configuration.cc 27 KB

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