configuration.cc 28 KB

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