configuration.cc 26 KB

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