You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1210 lines
33 KiB

  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. /* ######################################################################
  4. Configuration Class
  5. This class provides a configuration file and command line parser
  6. for a tree-oriented configuration environment. All runtime configuration
  7. is stored in here.
  8. This source is placed in the Public Domain, do with it what you will
  9. It was originally written by Jason Gunthorpe <jgg@debian.org>.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include files /*{{{*/
  13. #include <config.h>
  14. #include <apt-pkg/configuration.h>
  15. #include <apt-pkg/error.h>
  16. #include <apt-pkg/fileutl.h>
  17. #include <apt-pkg/macros.h>
  18. #include <apt-pkg/strutl.h>
  19. #include <ctype.h>
  20. #include <regex.h>
  21. #include <stddef.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <algorithm>
  26. #include <fstream>
  27. #include <iterator>
  28. #include <sstream>
  29. #include <stack>
  30. #include <string>
  31. #include <unordered_map>
  32. #include <vector>
  33. #include <apti18n.h>
  34. using namespace std;
  35. /*}}}*/
  36. Configuration *_config = new Configuration;
  37. /* TODO: This config verification shouldn't be using a static variable
  38. but a Cnf-member – but that would need ABI breaks and stuff and for now
  39. that really is an apt-dev-only tool, so it isn't that bad that it is
  40. unusable and allaround a bit strange */
  41. enum class APT_HIDDEN ConfigType { UNDEFINED, INT, BOOL, STRING, STRING_OR_BOOL, STRING_OR_LIST, FILE, DIR, LIST, PROGRAM_PATH = FILE };
  42. APT_HIDDEN std::unordered_map<std::string, ConfigType> apt_known_config {};
  43. static std::string getConfigTypeString(ConfigType const type) /*{{{*/
  44. {
  45. switch (type)
  46. {
  47. case ConfigType::UNDEFINED: return "UNDEFINED";
  48. case ConfigType::INT: return "INT";
  49. case ConfigType::BOOL: return "BOOL";
  50. case ConfigType::STRING: return "STRING";
  51. case ConfigType::STRING_OR_BOOL: return "STRING_OR_BOOL";
  52. case ConfigType::FILE: return "FILE";
  53. case ConfigType::DIR: return "DIR";
  54. case ConfigType::LIST: return "LIST";
  55. case ConfigType::STRING_OR_LIST: return "STRING_OR_LIST";
  56. }
  57. return "UNKNOWN";
  58. }
  59. /*}}}*/
  60. static ConfigType getConfigType(std::string const &type) /*{{{*/
  61. {
  62. if (type == "<INT>")
  63. return ConfigType::INT;
  64. else if (type == "<BOOL>")
  65. return ConfigType::BOOL;
  66. else if (type == "<STRING>")
  67. return ConfigType::STRING;
  68. else if (type == "<STRING_OR_BOOL>")
  69. return ConfigType::STRING_OR_BOOL;
  70. else if (type == "<FILE>")
  71. return ConfigType::FILE;
  72. else if (type == "<DIR>")
  73. return ConfigType::DIR;
  74. else if (type == "<LIST>")
  75. return ConfigType::LIST;
  76. else if (type == "<STRING_OR_LIST>")
  77. return ConfigType::STRING_OR_LIST;
  78. else if (type == "<PROGRAM_PATH>")
  79. return ConfigType::PROGRAM_PATH;
  80. return ConfigType::UNDEFINED;
  81. }
  82. /*}}}*/
  83. // checkFindConfigOptionType - workhorse of option checking /*{{{*/
  84. static void checkFindConfigOptionTypeInternal(std::string name, ConfigType const type)
  85. {
  86. std::transform(name.begin(), name.end(), name.begin(), ::tolower);
  87. auto known = apt_known_config.find(name);
  88. if (known == apt_known_config.cend())
  89. {
  90. auto const rcolon = name.rfind(':');
  91. if (rcolon != std::string::npos)
  92. {
  93. known = apt_known_config.find(name.substr(0, rcolon) + ":*");
  94. if (known == apt_known_config.cend())
  95. {
  96. auto const parts = StringSplit(name, "::");
  97. size_t psize = parts.size();
  98. if (psize > 1)
  99. {
  100. for (size_t max = psize; max != 1; --max)
  101. {
  102. std::ostringstream os;
  103. std::copy(parts.begin(), parts.begin() + max, std::ostream_iterator<std::string>(os, "::"));
  104. os << "**";
  105. known = apt_known_config.find(os.str());
  106. if (known != apt_known_config.cend() && known->second == ConfigType::UNDEFINED)
  107. return;
  108. }
  109. for (size_t max = psize - 1; max != 1; --max)
  110. {
  111. std::ostringstream os;
  112. std::copy(parts.begin(), parts.begin() + max - 1, std::ostream_iterator<std::string>(os, "::"));
  113. os << "*::";
  114. std::copy(parts.begin() + max + 1, parts.end() - 1, std::ostream_iterator<std::string>(os, "::"));
  115. os << *(parts.end() - 1);
  116. known = apt_known_config.find(os.str());
  117. if (known != apt_known_config.cend())
  118. break;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. if (known == apt_known_config.cend())
  125. _error->Warning("Using unknown config option »%s« of type %s",
  126. name.c_str(), getConfigTypeString(type).c_str());
  127. else if (known->second != type)
  128. {
  129. if (known->second == ConfigType::DIR && type == ConfigType::FILE)
  130. ; // implementation detail
  131. else if (type == ConfigType::STRING && (known->second == ConfigType::FILE || known->second == ConfigType::DIR))
  132. ; // TODO: that might be an error or not, we will figure this out later
  133. else if (known->second == ConfigType::STRING_OR_BOOL && (type == ConfigType::BOOL || type == ConfigType::STRING))
  134. ;
  135. else if (known->second == ConfigType::STRING_OR_LIST && (type == ConfigType::LIST || type == ConfigType::STRING))
  136. ;
  137. else
  138. _error->Warning("Using config option »%s« of type %s as a type %s",
  139. name.c_str(), getConfigTypeString(known->second).c_str(), getConfigTypeString(type).c_str());
  140. }
  141. }
  142. static void checkFindConfigOptionType(char const * const name, ConfigType const type)
  143. {
  144. if (apt_known_config.empty())
  145. return;
  146. checkFindConfigOptionTypeInternal(name, type);
  147. }
  148. /*}}}*/
  149. static bool LoadConfigurationIndex(std::string const &filename) /*{{{*/
  150. {
  151. apt_known_config.clear();
  152. if (filename.empty())
  153. return true;
  154. Configuration Idx;
  155. if (ReadConfigFile(Idx, filename) == false)
  156. return false;
  157. Configuration::Item const * Top = Idx.Tree(nullptr);
  158. if (unlikely(Top == nullptr))
  159. return false;
  160. do {
  161. if (Top->Value.empty() == false)
  162. {
  163. std::string fulltag = Top->FullTag();
  164. std::transform(fulltag.begin(), fulltag.end(), fulltag.begin(), ::tolower);
  165. apt_known_config.emplace(std::move(fulltag), getConfigType(Top->Value));
  166. }
  167. if (Top->Child != nullptr)
  168. {
  169. Top = Top->Child;
  170. continue;
  171. }
  172. while (Top != nullptr && Top->Next == nullptr)
  173. Top = Top->Parent;
  174. if (Top != nullptr)
  175. Top = Top->Next;
  176. } while (Top != nullptr);
  177. return true;
  178. }
  179. /*}}}*/
  180. // Configuration::Configuration - Constructor /*{{{*/
  181. // ---------------------------------------------------------------------
  182. /* */
  183. Configuration::Configuration() : ToFree(true)
  184. {
  185. Root = new Item;
  186. }
  187. Configuration::Configuration(const Item *Root) : Root((Item *)Root), ToFree(false)
  188. {
  189. }
  190. /*}}}*/
  191. // Configuration::~Configuration - Destructor /*{{{*/
  192. // ---------------------------------------------------------------------
  193. /* */
  194. Configuration::~Configuration()
  195. {
  196. if (ToFree == false)
  197. return;
  198. Item *Top = Root;
  199. for (; Top != 0;)
  200. {
  201. if (Top->Child != 0)
  202. {
  203. Top = Top->Child;
  204. continue;
  205. }
  206. while (Top != 0 && Top->Next == 0)
  207. {
  208. Item *Parent = Top->Parent;
  209. delete Top;
  210. Top = Parent;
  211. }
  212. if (Top != 0)
  213. {
  214. Item *Next = Top->Next;
  215. delete Top;
  216. Top = Next;
  217. }
  218. }
  219. }
  220. /*}}}*/
  221. // Configuration::Lookup - Lookup a single item /*{{{*/
  222. // ---------------------------------------------------------------------
  223. /* This will lookup a single item by name below another item. It is a
  224. helper function for the main lookup function */
  225. Configuration::Item *Configuration::Lookup(Item *Head,const char *S,
  226. unsigned long const &Len,bool const &Create)
  227. {
  228. int Res = 1;
  229. Item *I = Head->Child;
  230. Item **Last = &Head->Child;
  231. // Empty strings match nothing. They are used for lists.
  232. if (Len != 0)
  233. {
  234. for (; I != 0; Last = &I->Next, I = I->Next)
  235. if ((Res = stringcasecmp(I->Tag,S,S + Len)) == 0)
  236. break;
  237. }
  238. else
  239. for (; I != 0; Last = &I->Next, I = I->Next);
  240. if (Res == 0)
  241. return I;
  242. if (Create == false)
  243. return 0;
  244. I = new Item;
  245. I->Tag.assign(S,Len);
  246. I->Next = *Last;
  247. I->Parent = Head;
  248. *Last = I;
  249. return I;
  250. }
  251. /*}}}*/
  252. // Configuration::Lookup - Lookup a fully scoped item /*{{{*/
  253. // ---------------------------------------------------------------------
  254. /* This performs a fully scoped lookup of a given name, possibly creating
  255. new items */
  256. Configuration::Item *Configuration::Lookup(const char *Name,bool const &Create)
  257. {
  258. if (Name == 0)
  259. return Root->Child;
  260. const char *Start = Name;
  261. const char *End = Start + strlen(Name);
  262. const char *TagEnd = Name;
  263. Item *Itm = Root;
  264. for (; End - TagEnd >= 2; TagEnd++)
  265. {
  266. if (TagEnd[0] == ':' && TagEnd[1] == ':')
  267. {
  268. Itm = Lookup(Itm,Start,TagEnd - Start,Create);
  269. if (Itm == 0)
  270. return 0;
  271. TagEnd = Start = TagEnd + 2;
  272. }
  273. }
  274. // This must be a trailing ::, we create unique items in a list
  275. if (End - Start == 0)
  276. {
  277. if (Create == false)
  278. return 0;
  279. }
  280. Itm = Lookup(Itm,Start,End - Start,Create);
  281. return Itm;
  282. }
  283. /*}}}*/
  284. // Configuration::Find - Find a value /*{{{*/
  285. // ---------------------------------------------------------------------
  286. /* */
  287. string Configuration::Find(const char *Name,const char *Default) const
  288. {
  289. checkFindConfigOptionType(Name, ConfigType::STRING);
  290. const Item *Itm = Lookup(Name);
  291. if (Itm == 0 || Itm->Value.empty() == true)
  292. {
  293. if (Default == 0)
  294. return "";
  295. else
  296. return Default;
  297. }
  298. return Itm->Value;
  299. }
  300. /*}}}*/
  301. // Configuration::FindFile - Find a Filename /*{{{*/
  302. // ---------------------------------------------------------------------
  303. /* Directories are stored as the base dir in the Parent node and the
  304. sub directory in sub nodes with the final node being the end filename
  305. */
  306. string Configuration::FindFile(const char *Name,const char *Default) const
  307. {
  308. checkFindConfigOptionType(Name, ConfigType::FILE);
  309. const Item *RootItem = Lookup("RootDir");
  310. std::string result = (RootItem == 0) ? "" : RootItem->Value;
  311. if(result.empty() == false && result[result.size() - 1] != '/')
  312. result.push_back('/');
  313. const Item *Itm = Lookup(Name);
  314. if (Itm == 0 || Itm->Value.empty() == true)
  315. {
  316. if (Default != 0)
  317. result.append(Default);
  318. }
  319. else
  320. {
  321. string val = Itm->Value;
  322. while (Itm->Parent != 0)
  323. {
  324. if (Itm->Parent->Value.empty() == true)
  325. {
  326. Itm = Itm->Parent;
  327. continue;
  328. }
  329. // Absolute
  330. if (val.length() >= 1 && val[0] == '/')
  331. {
  332. if (val.compare(0, 9, "/dev/null") == 0)
  333. val.erase(9);
  334. break;
  335. }
  336. // ~/foo or ./foo
  337. if (val.length() >= 2 && (val[0] == '~' || val[0] == '.') && val[1] == '/')
  338. break;
  339. // ../foo
  340. if (val.length() >= 3 && val[0] == '.' && val[1] == '.' && val[2] == '/')
  341. break;
  342. if (Itm->Parent->Value.end()[-1] != '/')
  343. val.insert(0, "/");
  344. val.insert(0, Itm->Parent->Value);
  345. Itm = Itm->Parent;
  346. }
  347. result.append(val);
  348. }
  349. return flNormalize(result);
  350. }
  351. /*}}}*/
  352. // Configuration::FindDir - Find a directory name /*{{{*/
  353. // ---------------------------------------------------------------------
  354. /* This is like findfile execept the result is terminated in a / */
  355. string Configuration::FindDir(const char *Name,const char *Default) const
  356. {
  357. checkFindConfigOptionType(Name, ConfigType::DIR);
  358. string Res = FindFile(Name,Default);
  359. if (Res.end()[-1] != '/')
  360. {
  361. size_t const found = Res.rfind("/dev/null");
  362. if (found != string::npos && found == Res.size() - 9)
  363. return Res; // /dev/null returning
  364. return Res + '/';
  365. }
  366. return Res;
  367. }
  368. /*}}}*/
  369. // Configuration::FindVector - Find a vector of values /*{{{*/
  370. // ---------------------------------------------------------------------
  371. /* Returns a vector of config values under the given item */
  372. vector<string> Configuration::FindVector(const char *Name, std::string const &Default, bool const Keys) const
  373. {
  374. checkFindConfigOptionType(Name, ConfigType::LIST);
  375. vector<string> Vec;
  376. const Item *Top = Lookup(Name);
  377. if (Top == NULL)
  378. return VectorizeString(Default, ',');
  379. if (Top->Value.empty() == false)
  380. return VectorizeString(Top->Value, ',');
  381. Item *I = Top->Child;
  382. while(I != NULL)
  383. {
  384. Vec.push_back(Keys ? I->Tag : I->Value);
  385. I = I->Next;
  386. }
  387. if (Vec.empty() == true)
  388. return VectorizeString(Default, ',');
  389. return Vec;
  390. }
  391. /*}}}*/
  392. // Configuration::FindI - Find an integer value /*{{{*/
  393. // ---------------------------------------------------------------------
  394. /* */
  395. int Configuration::FindI(const char *Name,int const &Default) const
  396. {
  397. checkFindConfigOptionType(Name, ConfigType::INT);
  398. const Item *Itm = Lookup(Name);
  399. if (Itm == 0 || Itm->Value.empty() == true)
  400. return Default;
  401. char *End;
  402. int Res = strtol(Itm->Value.c_str(),&End,0);
  403. if (End == Itm->Value.c_str())
  404. return Default;
  405. return Res;
  406. }
  407. /*}}}*/
  408. // Configuration::FindB - Find a boolean type /*{{{*/
  409. // ---------------------------------------------------------------------
  410. /* */
  411. bool Configuration::FindB(const char *Name,bool const &Default) const
  412. {
  413. checkFindConfigOptionType(Name, ConfigType::BOOL);
  414. const Item *Itm = Lookup(Name);
  415. if (Itm == 0 || Itm->Value.empty() == true)
  416. return Default;
  417. return StringToBool(Itm->Value,Default);
  418. }
  419. /*}}}*/
  420. // Configuration::FindAny - Find an arbitrary type /*{{{*/
  421. // ---------------------------------------------------------------------
  422. /* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
  423. string Configuration::FindAny(const char *Name,const char *Default) const
  424. {
  425. string key = Name;
  426. char type = 0;
  427. if (key.size() > 2 && key.end()[-2] == '/')
  428. {
  429. type = key.end()[-1];
  430. key.resize(key.size() - 2);
  431. }
  432. switch (type)
  433. {
  434. // file
  435. case 'f':
  436. return FindFile(key.c_str(), Default);
  437. // directory
  438. case 'd':
  439. return FindDir(key.c_str(), Default);
  440. // bool
  441. case 'b':
  442. return FindB(key, Default) ? "true" : "false";
  443. // int
  444. case 'i':
  445. {
  446. char buf[16];
  447. snprintf(buf, sizeof(buf)-1, "%d", FindI(key, Default ? atoi(Default) : 0 ));
  448. return buf;
  449. }
  450. }
  451. // fallback
  452. return Find(Name, Default);
  453. }
  454. /*}}}*/
  455. // Configuration::CndSet - Conditinal Set a value /*{{{*/
  456. // ---------------------------------------------------------------------
  457. /* This will not overwrite */
  458. void Configuration::CndSet(const char *Name,const string &Value)
  459. {
  460. Item *Itm = Lookup(Name,true);
  461. if (Itm == 0)
  462. return;
  463. if (Itm->Value.empty() == true)
  464. Itm->Value = Value;
  465. }
  466. /*}}}*/
  467. // Configuration::Set - Set an integer value /*{{{*/
  468. // ---------------------------------------------------------------------
  469. /* */
  470. void Configuration::CndSet(const char *Name,int const Value)
  471. {
  472. Item *Itm = Lookup(Name,true);
  473. if (Itm == 0 || Itm->Value.empty() == false)
  474. return;
  475. char S[300];
  476. snprintf(S,sizeof(S),"%i",Value);
  477. Itm->Value = S;
  478. }
  479. /*}}}*/
  480. // Configuration::Set - Set a value /*{{{*/
  481. // ---------------------------------------------------------------------
  482. /* */
  483. void Configuration::Set(const char *Name,const string &Value)
  484. {
  485. Item *Itm = Lookup(Name,true);
  486. if (Itm == 0)
  487. return;
  488. Itm->Value = Value;
  489. }
  490. /*}}}*/
  491. // Configuration::Set - Set an integer value /*{{{*/
  492. // ---------------------------------------------------------------------
  493. /* */
  494. void Configuration::Set(const char *Name,int const &Value)
  495. {
  496. Item *Itm = Lookup(Name,true);
  497. if (Itm == 0)
  498. return;
  499. char S[300];
  500. snprintf(S,sizeof(S),"%i",Value);
  501. Itm->Value = S;
  502. }
  503. /*}}}*/
  504. // Configuration::Clear - Clear an single value from a list /*{{{*/
  505. // ---------------------------------------------------------------------
  506. /* */
  507. void Configuration::Clear(string const &Name, int const &Value)
  508. {
  509. char S[300];
  510. snprintf(S,sizeof(S),"%i",Value);
  511. Clear(Name, S);
  512. }
  513. /*}}}*/
  514. // Configuration::Clear - Clear an single value from a list /*{{{*/
  515. // ---------------------------------------------------------------------
  516. /* */
  517. void Configuration::Clear(string const &Name, string const &Value)
  518. {
  519. Item *Top = Lookup(Name.c_str(),false);
  520. if (Top == 0 || Top->Child == 0)
  521. return;
  522. Item *Tmp, *Prev, *I;
  523. Prev = I = Top->Child;
  524. while(I != NULL)
  525. {
  526. if(I->Value == Value)
  527. {
  528. Tmp = I;
  529. // was first element, point parent to new first element
  530. if(Top->Child == Tmp)
  531. Top->Child = I->Next;
  532. I = I->Next;
  533. Prev->Next = I;
  534. delete Tmp;
  535. } else {
  536. Prev = I;
  537. I = I->Next;
  538. }
  539. }
  540. }
  541. /*}}}*/
  542. // Configuration::Clear - Clear everything /*{{{*/
  543. // ---------------------------------------------------------------------
  544. void Configuration::Clear()
  545. {
  546. const Configuration::Item *Top = Tree(0);
  547. while( Top != 0 )
  548. {
  549. Clear(Top->FullTag());
  550. Top = Top->Next;
  551. }
  552. }
  553. /*}}}*/
  554. // Configuration::Clear - Clear an entire tree /*{{{*/
  555. // ---------------------------------------------------------------------
  556. /* */
  557. void Configuration::Clear(string const &Name)
  558. {
  559. Item *Top = Lookup(Name.c_str(),false);
  560. if (Top == 0)
  561. return;
  562. Top->Value.clear();
  563. Item *Stop = Top;
  564. Top = Top->Child;
  565. Stop->Child = 0;
  566. for (; Top != 0;)
  567. {
  568. if (Top->Child != 0)
  569. {
  570. Top = Top->Child;
  571. continue;
  572. }
  573. while (Top != 0 && Top->Next == 0)
  574. {
  575. Item *Tmp = Top;
  576. Top = Top->Parent;
  577. delete Tmp;
  578. if (Top == Stop)
  579. return;
  580. }
  581. Item *Tmp = Top;
  582. if (Top != 0)
  583. Top = Top->Next;
  584. delete Tmp;
  585. }
  586. }
  587. /*}}}*/
  588. void Configuration::MoveSubTree(char const * const OldRootName, char const * const NewRootName)/*{{{*/
  589. {
  590. // prevent NewRoot being a subtree of OldRoot
  591. if (OldRootName == nullptr)
  592. return;
  593. if (NewRootName != nullptr)
  594. {
  595. if (strcmp(OldRootName, NewRootName) == 0)
  596. return;
  597. std::string const oldroot = std::string(OldRootName) + "::";
  598. if (strcasestr(NewRootName, oldroot.c_str()) != NULL)
  599. return;
  600. }
  601. Item * Top;
  602. Item const * const OldRoot = Top = Lookup(OldRootName, false);
  603. if (Top == nullptr)
  604. return;
  605. std::string NewRoot;
  606. if (NewRootName != nullptr)
  607. NewRoot.append(NewRootName).append("::");
  608. Top->Value.clear();
  609. Item * const Stop = Top;
  610. Top = Top->Child;
  611. Stop->Child = 0;
  612. for (; Top != 0;)
  613. {
  614. if (Top->Child != 0)
  615. {
  616. Top = Top->Child;
  617. continue;
  618. }
  619. while (Top != 0 && Top->Next == 0)
  620. {
  621. Set(NewRoot + Top->FullTag(OldRoot), Top->Value);
  622. Item const * const Tmp = Top;
  623. Top = Top->Parent;
  624. delete Tmp;
  625. if (Top == Stop)
  626. return;
  627. }
  628. Set(NewRoot + Top->FullTag(OldRoot), Top->Value);
  629. Item const * const Tmp = Top;
  630. if (Top != 0)
  631. Top = Top->Next;
  632. delete Tmp;
  633. }
  634. }
  635. /*}}}*/
  636. // Configuration::Exists - Returns true if the Name exists /*{{{*/
  637. // ---------------------------------------------------------------------
  638. /* */
  639. bool Configuration::Exists(const char *Name) const
  640. {
  641. const Item *Itm = Lookup(Name);
  642. if (Itm == 0)
  643. return false;
  644. return true;
  645. }
  646. /*}}}*/
  647. // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
  648. // ---------------------------------------------------------------------
  649. /* qualified by /[fdbi] exists */
  650. bool Configuration::ExistsAny(const char *Name) const
  651. {
  652. string key = Name;
  653. if (key.size() > 2 && key.end()[-2] == '/')
  654. {
  655. if (key.find_first_of("fdbi",key.size()-1) < key.size())
  656. {
  657. key.resize(key.size() - 2);
  658. if (Exists(key.c_str()))
  659. return true;
  660. }
  661. else
  662. {
  663. _error->Warning(_("Unrecognized type abbreviation: '%c'"), key.end()[-3]);
  664. }
  665. }
  666. return Exists(Name);
  667. }
  668. /*}}}*/
  669. // Configuration::Dump - Dump the config /*{{{*/
  670. // ---------------------------------------------------------------------
  671. /* Dump the entire configuration space */
  672. void Configuration::Dump(ostream& str)
  673. {
  674. Dump(str, NULL, "%F \"%v\";\n", true);
  675. }
  676. void Configuration::Dump(ostream& str, char const * const root,
  677. char const * const formatstr, bool const emptyValue)
  678. {
  679. const Configuration::Item* Top = Tree(root);
  680. if (Top == 0)
  681. return;
  682. const Configuration::Item* const Root = (root == NULL) ? NULL : Top;
  683. std::vector<std::string> const format = VectorizeString(formatstr, '%');
  684. /* Write out all of the configuration directives by walking the
  685. configuration tree */
  686. do {
  687. if (emptyValue == true || Top->Value.empty() == emptyValue)
  688. {
  689. std::vector<std::string>::const_iterator f = format.begin();
  690. str << *f;
  691. for (++f; f != format.end(); ++f)
  692. {
  693. if (f->empty() == true)
  694. {
  695. ++f;
  696. str << '%' << *f;
  697. continue;
  698. }
  699. char const type = (*f)[0];
  700. if (type == 'f')
  701. str << Top->FullTag();
  702. else if (type == 't')
  703. str << Top->Tag;
  704. else if (type == 'v')
  705. str << Top->Value;
  706. else if (type == 'F')
  707. str << QuoteString(Top->FullTag(), "=\"\n");
  708. else if (type == 'T')
  709. str << QuoteString(Top->Tag, "=\"\n");
  710. else if (type == 'V')
  711. str << QuoteString(Top->Value, "=\"\n");
  712. else if (type == 'n')
  713. str << "\n";
  714. else if (type == 'N')
  715. str << "\t";
  716. else
  717. str << '%' << type;
  718. str << f->c_str() + 1;
  719. }
  720. }
  721. if (Top->Child != 0)
  722. {
  723. Top = Top->Child;
  724. continue;
  725. }
  726. while (Top != 0 && Top->Next == 0)
  727. Top = Top->Parent;
  728. if (Top != 0)
  729. Top = Top->Next;
  730. if (Root != NULL)
  731. {
  732. const Configuration::Item* I = Top;
  733. while(I != 0)
  734. {
  735. if (I == Root)
  736. break;
  737. else
  738. I = I->Parent;
  739. }
  740. if (I == 0)
  741. break;
  742. }
  743. } while (Top != 0);
  744. }
  745. /*}}}*/
  746. // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
  747. // ---------------------------------------------------------------------
  748. /* Stop sets an optional max recursion depth if this item is being viewed as
  749. part of a sub tree. */
  750. string Configuration::Item::FullTag(const Item *Stop) const
  751. {
  752. if (Parent == 0 || Parent->Parent == 0 || Parent == Stop)
  753. return Tag;
  754. return Parent->FullTag(Stop) + "::" + Tag;
  755. }
  756. /*}}}*/
  757. // ReadConfigFile - Read a configuration file /*{{{*/
  758. // ---------------------------------------------------------------------
  759. /* The configuration format is very much like the named.conf format
  760. used in bind8, in fact this routine can parse most named.conf files.
  761. Sectional config files are like bind's named.conf where there are
  762. sections like 'zone "foo.org" { .. };' This causes each section to be
  763. added in with a tag like "zone::foo.org" instead of being split
  764. tag/value. AsSectional enables Sectional parsing.*/
  765. static void leaveCurrentScope(std::stack<std::string> &Stack, std::string &ParentTag)
  766. {
  767. if (Stack.empty())
  768. ParentTag.clear();
  769. else
  770. {
  771. ParentTag = Stack.top();
  772. Stack.pop();
  773. }
  774. }
  775. bool ReadConfigFile(Configuration &Conf,const string &FName,bool const &AsSectional,
  776. unsigned const &Depth)
  777. {
  778. // Open the stream for reading
  779. FileFd F;
  780. if (OpenConfigurationFileFd(FName, F) == false)
  781. return false;
  782. string LineBuffer;
  783. std::stack<std::string> Stack;
  784. // Parser state
  785. string ParentTag;
  786. int CurLine = 0;
  787. bool InComment = false;
  788. while (F.Eof() == false)
  789. {
  790. // The raw input line.
  791. std::string Input;
  792. if (F.ReadLine(Input) == false)
  793. Input.clear();
  794. // The input line with comments stripped.
  795. std::string Fragment;
  796. // Expand tabs in the input line and remove leading and trailing
  797. // whitespace.
  798. {
  799. const int BufferSize = Input.size() * 8 + 1;
  800. char *Buffer = new char[BufferSize];
  801. try
  802. {
  803. memcpy(Buffer, Input.c_str(), Input.size() + 1);
  804. _strtabexpand(Buffer, BufferSize);
  805. _strstrip(Buffer);
  806. Input = Buffer;
  807. }
  808. catch(...)
  809. {
  810. delete[] Buffer;
  811. throw;
  812. }
  813. delete[] Buffer;
  814. }
  815. CurLine++;
  816. // Now strip comments; if the whole line is contained in a
  817. // comment, skip this line.
  818. // The first meaningful character in the current fragment; will
  819. // be adjusted below as we remove bytes from the front.
  820. std::string::const_iterator Start = Input.begin();
  821. // The last meaningful character in the current fragment.
  822. std::string::const_iterator End = Input.end();
  823. // Multi line comment
  824. if (InComment == true)
  825. {
  826. for (std::string::const_iterator I = Start;
  827. I != End; ++I)
  828. {
  829. if (*I == '*' && I + 1 != End && I[1] == '/')
  830. {
  831. Start = I + 2;
  832. InComment = false;
  833. break;
  834. }
  835. }
  836. if (InComment == true)
  837. continue;
  838. }
  839. // Discard single line comments
  840. bool InQuote = false;
  841. for (std::string::const_iterator I = Start;
  842. I != End; ++I)
  843. {
  844. if (*I == '"')
  845. InQuote = !InQuote;
  846. if (InQuote == true)
  847. continue;
  848. if ((*I == '/' && I + 1 != End && I[1] == '/') ||
  849. (*I == '#' && strcmp(string(I,I+6).c_str(),"#clear") != 0 &&
  850. strcmp(string(I,I+8).c_str(),"#include") != 0 &&
  851. strcmp(string(I,I+strlen("#x-apt-configure-index")).c_str(), "#x-apt-configure-index") != 0))
  852. {
  853. End = I;
  854. break;
  855. }
  856. }
  857. // Look for multi line comments and build up the
  858. // fragment.
  859. Fragment.reserve(End - Start);
  860. InQuote = false;
  861. for (std::string::const_iterator I = Start;
  862. I != End; ++I)
  863. {
  864. if (*I == '"')
  865. InQuote = !InQuote;
  866. if (InQuote == true)
  867. Fragment.push_back(*I);
  868. else if (*I == '/' && I + 1 != End && I[1] == '*')
  869. {
  870. InComment = true;
  871. for (std::string::const_iterator J = I;
  872. J != End; ++J)
  873. {
  874. if (*J == '*' && J + 1 != End && J[1] == '/')
  875. {
  876. // Pretend we just finished walking over the
  877. // comment, and don't add anything to the output
  878. // fragment.
  879. I = J + 1;
  880. InComment = false;
  881. break;
  882. }
  883. }
  884. if (InComment == true)
  885. break;
  886. }
  887. else
  888. Fragment.push_back(*I);
  889. }
  890. // Skip blank lines.
  891. if (Fragment.empty())
  892. continue;
  893. // The line has actual content; interpret what it means.
  894. InQuote = false;
  895. Start = Fragment.begin();
  896. End = Fragment.end();
  897. for (std::string::const_iterator I = Start;
  898. I != End; ++I)
  899. {
  900. if (*I == '"')
  901. InQuote = !InQuote;
  902. if (InQuote == false && (*I == '{' || *I == ';' || *I == '}'))
  903. {
  904. // Put the last fragment into the buffer
  905. std::string::const_iterator NonWhitespaceStart = Start;
  906. std::string::const_iterator NonWhitespaceStop = I;
  907. for (; NonWhitespaceStart != I && isspace(*NonWhitespaceStart) != 0; ++NonWhitespaceStart)
  908. ;
  909. for (; NonWhitespaceStop != NonWhitespaceStart && isspace(NonWhitespaceStop[-1]) != 0; --NonWhitespaceStop)
  910. ;
  911. if (LineBuffer.empty() == false && NonWhitespaceStop - NonWhitespaceStart != 0)
  912. LineBuffer += ' ';
  913. LineBuffer += string(NonWhitespaceStart, NonWhitespaceStop);
  914. // Drop this from the input string, saving the character
  915. // that terminated the construct we just closed. (i.e., a
  916. // brace or a semicolon)
  917. char TermChar = *I;
  918. Start = I + 1;
  919. // Syntax Error
  920. if (TermChar == '{' && LineBuffer.empty() == true)
  921. return _error->Error(_("Syntax error %s:%u: Block starts with no name."),FName.c_str(),CurLine);
  922. // No string on this line
  923. if (LineBuffer.empty() == true)
  924. {
  925. if (TermChar == '}')
  926. leaveCurrentScope(Stack, ParentTag);
  927. continue;
  928. }
  929. // Parse off the tag
  930. string Tag;
  931. const char *Pos = LineBuffer.c_str();
  932. if (ParseQuoteWord(Pos,Tag) == false)
  933. return _error->Error(_("Syntax error %s:%u: Malformed tag"),FName.c_str(),CurLine);
  934. // Parse off the word
  935. string Word;
  936. bool NoWord = false;
  937. if (ParseCWord(Pos,Word) == false &&
  938. ParseQuoteWord(Pos,Word) == false)
  939. {
  940. if (TermChar != '{')
  941. {
  942. Word = Tag;
  943. Tag = "";
  944. }
  945. else
  946. NoWord = true;
  947. }
  948. if (strlen(Pos) != 0)
  949. return _error->Error(_("Syntax error %s:%u: Extra junk after value"),FName.c_str(),CurLine);
  950. // Go down a level
  951. if (TermChar == '{')
  952. {
  953. Stack.push(ParentTag);
  954. /* Make sectional tags incorporate the section into the
  955. tag string */
  956. if (AsSectional == true && Word.empty() == false)
  957. {
  958. Tag.append("::").append(Word);
  959. Word.clear();
  960. }
  961. if (ParentTag.empty() == true)
  962. ParentTag = Tag;
  963. else
  964. ParentTag.append("::").append(Tag);
  965. Tag.clear();
  966. }
  967. // Generate the item name
  968. string Item;
  969. if (ParentTag.empty() == true)
  970. Item = Tag;
  971. else
  972. {
  973. if (TermChar != '{' || Tag.empty() == false)
  974. Item = ParentTag + "::" + Tag;
  975. else
  976. Item = ParentTag;
  977. }
  978. // Specials
  979. if (Tag.length() >= 1 && Tag[0] == '#')
  980. {
  981. if (ParentTag.empty() == false)
  982. return _error->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName.c_str(),CurLine);
  983. Tag.erase(Tag.begin());
  984. if (Tag == "clear")
  985. Conf.Clear(Word);
  986. else if (Tag == "include")
  987. {
  988. if (Depth > 10)
  989. return _error->Error(_("Syntax error %s:%u: Too many nested includes"),FName.c_str(),CurLine);
  990. if (Word.length() > 2 && Word.end()[-1] == '/')
  991. {
  992. if (ReadConfigDir(Conf,Word,AsSectional,Depth+1) == false)
  993. return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
  994. }
  995. else
  996. {
  997. if (ReadConfigFile(Conf,Word,AsSectional,Depth+1) == false)
  998. return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
  999. }
  1000. }
  1001. else if (Tag == "x-apt-configure-index")
  1002. {
  1003. if (LoadConfigurationIndex(Word) == false)
  1004. return _error->Warning("Loading the configure index %s in file %s:%u failed!", Word.c_str(), FName.c_str(), CurLine);
  1005. }
  1006. else
  1007. return _error->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName.c_str(),CurLine,Tag.c_str());
  1008. }
  1009. else if (Tag.empty() == true && NoWord == false && Word == "#clear")
  1010. return _error->Error(_("Syntax error %s:%u: clear directive requires an option tree as argument"),FName.c_str(),CurLine);
  1011. else
  1012. {
  1013. // Set the item in the configuration class
  1014. if (NoWord == false)
  1015. Conf.Set(Item,Word);
  1016. }
  1017. // Empty the buffer
  1018. LineBuffer.clear();
  1019. // Move up a tag, but only if there is no bit to parse
  1020. if (TermChar == '}')
  1021. leaveCurrentScope(Stack, ParentTag);
  1022. }
  1023. }
  1024. // Store the remaining text, if any, in the current line buffer.
  1025. // NB: could change this to use string-based operations; I'm
  1026. // using strstrip now to ensure backwards compatibility.
  1027. // -- dburrows 2008-04-01
  1028. {
  1029. char *Buffer = new char[End - Start + 1];
  1030. try
  1031. {
  1032. std::copy(Start, End, Buffer);
  1033. Buffer[End - Start] = '\0';
  1034. const char *Stripd = _strstrip(Buffer);
  1035. if (*Stripd != 0 && LineBuffer.empty() == false)
  1036. LineBuffer += " ";
  1037. LineBuffer += Stripd;
  1038. }
  1039. catch(...)
  1040. {
  1041. delete[] Buffer;
  1042. throw;
  1043. }
  1044. delete[] Buffer;
  1045. }
  1046. }
  1047. if (LineBuffer.empty() == false)
  1048. return _error->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName.c_str(),CurLine);
  1049. return true;
  1050. }
  1051. /*}}}*/
  1052. // ReadConfigDir - Read a directory of config files /*{{{*/
  1053. // ---------------------------------------------------------------------
  1054. /* */
  1055. bool ReadConfigDir(Configuration &Conf,const string &Dir,
  1056. bool const &AsSectional, unsigned const &Depth)
  1057. {
  1058. bool good = true;
  1059. for (auto const &I : GetListOfFilesInDir(Dir, "conf", true, true))
  1060. good = ReadConfigFile(Conf, I, AsSectional, Depth) && good;
  1061. return good;
  1062. }
  1063. /*}}}*/
  1064. // MatchAgainstConfig Constructor /*{{{*/
  1065. Configuration::MatchAgainstConfig::MatchAgainstConfig(char const * Config)
  1066. {
  1067. std::vector<std::string> const strings = _config->FindVector(Config);
  1068. for (std::vector<std::string>::const_iterator s = strings.begin();
  1069. s != strings.end(); ++s)
  1070. {
  1071. regex_t *p = new regex_t;
  1072. if (regcomp(p, s->c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB) == 0)
  1073. patterns.push_back(p);
  1074. else
  1075. {
  1076. regfree(p);
  1077. delete p;
  1078. _error->Warning("Invalid regular expression '%s' in configuration "
  1079. "option '%s' will be ignored.",
  1080. s->c_str(), Config);
  1081. continue;
  1082. }
  1083. }
  1084. if (strings.empty() == true)
  1085. patterns.push_back(NULL);
  1086. }
  1087. /*}}}*/
  1088. // MatchAgainstConfig Destructor /*{{{*/
  1089. Configuration::MatchAgainstConfig::~MatchAgainstConfig()
  1090. {
  1091. clearPatterns();
  1092. }
  1093. void Configuration::MatchAgainstConfig::clearPatterns()
  1094. {
  1095. for(std::vector<regex_t *>::const_iterator p = patterns.begin();
  1096. p != patterns.end(); ++p)
  1097. {
  1098. if (*p == NULL) continue;
  1099. regfree(*p);
  1100. delete *p;
  1101. }
  1102. patterns.clear();
  1103. }
  1104. /*}}}*/
  1105. // MatchAgainstConfig::Match - returns true if a pattern matches /*{{{*/
  1106. bool Configuration::MatchAgainstConfig::Match(char const * str) const
  1107. {
  1108. for(std::vector<regex_t *>::const_iterator p = patterns.begin();
  1109. p != patterns.end(); ++p)
  1110. if (*p != NULL && regexec(*p, str, 0, 0, 0) == 0)
  1111. return true;
  1112. return false;
  1113. }
  1114. /*}}}*/