configuration.cc 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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) 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(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. // Configuration::Exists - Returns true if the Name exists /*{{{*/
  443. // ---------------------------------------------------------------------
  444. /* */
  445. bool Configuration::Exists(const char *Name) const
  446. {
  447. const Item *Itm = Lookup(Name);
  448. if (Itm == 0)
  449. return false;
  450. return true;
  451. }
  452. /*}}}*/
  453. // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
  454. // ---------------------------------------------------------------------
  455. /* qualified by /[fdbi] exists */
  456. bool Configuration::ExistsAny(const char *Name) const
  457. {
  458. string key = Name;
  459. if (key.size() > 2 && key.end()[-2] == '/')
  460. {
  461. if (key.find_first_of("fdbi",key.size()-1) < key.size())
  462. {
  463. key.resize(key.size() - 2);
  464. if (Exists(key.c_str()))
  465. return true;
  466. }
  467. else
  468. {
  469. _error->Warning(_("Unrecognized type abbreviation: '%c'"), key.end()[-3]);
  470. }
  471. }
  472. return Exists(Name);
  473. }
  474. /*}}}*/
  475. // Configuration::Dump - Dump the config /*{{{*/
  476. // ---------------------------------------------------------------------
  477. /* Dump the entire configuration space */
  478. void Configuration::Dump(ostream& str)
  479. {
  480. Dump(str, NULL, "%f \"%v\";\n", true);
  481. }
  482. void Configuration::Dump(ostream& str, char const * const root,
  483. char const * const formatstr, bool const emptyValue)
  484. {
  485. const Configuration::Item* Top = Tree(root);
  486. if (Top == 0)
  487. return;
  488. const Configuration::Item* const Root = (root == NULL) ? NULL : Top;
  489. std::vector<std::string> const format = VectorizeString(formatstr, '%');
  490. /* Write out all of the configuration directives by walking the
  491. configuration tree */
  492. do {
  493. if (emptyValue == true || Top->Value.empty() == emptyValue)
  494. {
  495. std::vector<std::string>::const_iterator f = format.begin();
  496. str << *f;
  497. for (++f; f != format.end(); ++f)
  498. {
  499. if (f->empty() == true)
  500. {
  501. ++f;
  502. str << '%' << *f;
  503. continue;
  504. }
  505. char const type = (*f)[0];
  506. if (type == 'f')
  507. str << Top->FullTag();
  508. else if (type == 't')
  509. str << Top->Tag;
  510. else if (type == 'v')
  511. str << Top->Value;
  512. else if (type == 'F')
  513. str << QuoteString(Top->FullTag(), "=\"\n");
  514. else if (type == 'T')
  515. str << QuoteString(Top->Tag, "=\"\n");
  516. else if (type == 'V')
  517. str << QuoteString(Top->Value, "=\"\n");
  518. else if (type == 'n')
  519. str << "\n";
  520. else if (type == 'N')
  521. str << "\t";
  522. else
  523. str << '%' << type;
  524. str << f->c_str() + 1;
  525. }
  526. }
  527. if (Top->Child != 0)
  528. {
  529. Top = Top->Child;
  530. continue;
  531. }
  532. while (Top != 0 && Top->Next == 0)
  533. Top = Top->Parent;
  534. if (Top != 0)
  535. Top = Top->Next;
  536. if (Root != NULL)
  537. {
  538. const Configuration::Item* I = Top;
  539. while(I != 0)
  540. {
  541. if (I == Root)
  542. break;
  543. else
  544. I = I->Parent;
  545. }
  546. if (I == 0)
  547. break;
  548. }
  549. } while (Top != 0);
  550. }
  551. /*}}}*/
  552. // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
  553. // ---------------------------------------------------------------------
  554. /* Stop sets an optional max recursion depth if this item is being viewed as
  555. part of a sub tree. */
  556. string Configuration::Item::FullTag(const Item *Stop) const
  557. {
  558. if (Parent == 0 || Parent->Parent == 0 || Parent == Stop)
  559. return Tag;
  560. return Parent->FullTag(Stop) + "::" + Tag;
  561. }
  562. /*}}}*/
  563. // ReadConfigFile - Read a configuration file /*{{{*/
  564. // ---------------------------------------------------------------------
  565. /* The configuration format is very much like the named.conf format
  566. used in bind8, in fact this routine can parse most named.conf files.
  567. Sectional config files are like bind's named.conf where there are
  568. sections like 'zone "foo.org" { .. };' This causes each section to be
  569. added in with a tag like "zone::foo.org" instead of being split
  570. tag/value. AsSectional enables Sectional parsing.*/
  571. bool ReadConfigFile(Configuration &Conf,const string &FName,bool const &AsSectional,
  572. unsigned const &Depth)
  573. {
  574. // Open the stream for reading
  575. ifstream F(FName.c_str(),ios::in);
  576. if (!F != 0)
  577. return _error->Errno("ifstream::ifstream",_("Opening configuration file %s"),FName.c_str());
  578. string LineBuffer;
  579. string Stack[100];
  580. unsigned int StackPos = 0;
  581. // Parser state
  582. string ParentTag;
  583. int CurLine = 0;
  584. bool InComment = false;
  585. while (F.eof() == false)
  586. {
  587. // The raw input line.
  588. std::string Input;
  589. // The input line with comments stripped.
  590. std::string Fragment;
  591. // Grab the next line of F and place it in Input.
  592. do
  593. {
  594. char *Buffer = new char[1024];
  595. F.clear();
  596. F.getline(Buffer,sizeof(Buffer) / 2);
  597. Input += Buffer;
  598. delete[] Buffer;
  599. }
  600. while (F.fail() && !F.eof());
  601. // Expand tabs in the input line and remove leading and trailing
  602. // whitespace.
  603. {
  604. const int BufferSize = Input.size() * 8 + 1;
  605. char *Buffer = new char[BufferSize];
  606. try
  607. {
  608. memcpy(Buffer, Input.c_str(), Input.size() + 1);
  609. _strtabexpand(Buffer, BufferSize);
  610. _strstrip(Buffer);
  611. Input = Buffer;
  612. }
  613. catch(...)
  614. {
  615. delete[] Buffer;
  616. throw;
  617. }
  618. delete[] Buffer;
  619. }
  620. CurLine++;
  621. // Now strip comments; if the whole line is contained in a
  622. // comment, skip this line.
  623. // The first meaningful character in the current fragment; will
  624. // be adjusted below as we remove bytes from the front.
  625. std::string::const_iterator Start = Input.begin();
  626. // The last meaningful character in the current fragment.
  627. std::string::const_iterator End = Input.end();
  628. // Multi line comment
  629. if (InComment == true)
  630. {
  631. for (std::string::const_iterator I = Start;
  632. I != End; ++I)
  633. {
  634. if (*I == '*' && I + 1 != End && I[1] == '/')
  635. {
  636. Start = I + 2;
  637. InComment = false;
  638. break;
  639. }
  640. }
  641. if (InComment == true)
  642. continue;
  643. }
  644. // Discard single line comments
  645. bool InQuote = false;
  646. for (std::string::const_iterator I = Start;
  647. I != End; ++I)
  648. {
  649. if (*I == '"')
  650. InQuote = !InQuote;
  651. if (InQuote == true)
  652. continue;
  653. if ((*I == '/' && I + 1 != End && I[1] == '/') ||
  654. (*I == '#' && strcmp(string(I,I+6).c_str(),"#clear") != 0 &&
  655. strcmp(string(I,I+8).c_str(),"#include") != 0))
  656. {
  657. End = I;
  658. break;
  659. }
  660. }
  661. // Look for multi line comments and build up the
  662. // fragment.
  663. Fragment.reserve(End - Start);
  664. InQuote = false;
  665. for (std::string::const_iterator I = Start;
  666. I != End; ++I)
  667. {
  668. if (*I == '"')
  669. InQuote = !InQuote;
  670. if (InQuote == true)
  671. Fragment.push_back(*I);
  672. else if (*I == '/' && I + 1 != End && I[1] == '*')
  673. {
  674. InComment = true;
  675. for (std::string::const_iterator J = I;
  676. J != End; ++J)
  677. {
  678. if (*J == '*' && J + 1 != End && J[1] == '/')
  679. {
  680. // Pretend we just finished walking over the
  681. // comment, and don't add anything to the output
  682. // fragment.
  683. I = J + 1;
  684. InComment = false;
  685. break;
  686. }
  687. }
  688. if (InComment == true)
  689. break;
  690. }
  691. else
  692. Fragment.push_back(*I);
  693. }
  694. // Skip blank lines.
  695. if (Fragment.empty())
  696. continue;
  697. // The line has actual content; interpret what it means.
  698. InQuote = false;
  699. Start = Fragment.begin();
  700. End = Fragment.end();
  701. for (std::string::const_iterator I = Start;
  702. I != End; ++I)
  703. {
  704. if (*I == '"')
  705. InQuote = !InQuote;
  706. if (InQuote == false && (*I == '{' || *I == ';' || *I == '}'))
  707. {
  708. // Put the last fragment into the buffer
  709. std::string::const_iterator NonWhitespaceStart = Start;
  710. std::string::const_iterator NonWhitespaceStop = I;
  711. for (; NonWhitespaceStart != I && isspace(*NonWhitespaceStart) != 0; ++NonWhitespaceStart)
  712. ;
  713. for (; NonWhitespaceStop != NonWhitespaceStart && isspace(NonWhitespaceStop[-1]) != 0; --NonWhitespaceStop)
  714. ;
  715. if (LineBuffer.empty() == false && NonWhitespaceStop - NonWhitespaceStart != 0)
  716. LineBuffer += ' ';
  717. LineBuffer += string(NonWhitespaceStart, NonWhitespaceStop);
  718. // Drop this from the input string, saving the character
  719. // that terminated the construct we just closed. (i.e., a
  720. // brace or a semicolon)
  721. char TermChar = *I;
  722. Start = I + 1;
  723. // Syntax Error
  724. if (TermChar == '{' && LineBuffer.empty() == true)
  725. return _error->Error(_("Syntax error %s:%u: Block starts with no name."),FName.c_str(),CurLine);
  726. // No string on this line
  727. if (LineBuffer.empty() == true)
  728. {
  729. if (TermChar == '}')
  730. {
  731. if (StackPos == 0)
  732. ParentTag = string();
  733. else
  734. ParentTag = Stack[--StackPos];
  735. }
  736. continue;
  737. }
  738. // Parse off the tag
  739. string Tag;
  740. const char *Pos = LineBuffer.c_str();
  741. if (ParseQuoteWord(Pos,Tag) == false)
  742. return _error->Error(_("Syntax error %s:%u: Malformed tag"),FName.c_str(),CurLine);
  743. // Parse off the word
  744. string Word;
  745. bool NoWord = false;
  746. if (ParseCWord(Pos,Word) == false &&
  747. ParseQuoteWord(Pos,Word) == false)
  748. {
  749. if (TermChar != '{')
  750. {
  751. Word = Tag;
  752. Tag = "";
  753. }
  754. else
  755. NoWord = true;
  756. }
  757. if (strlen(Pos) != 0)
  758. return _error->Error(_("Syntax error %s:%u: Extra junk after value"),FName.c_str(),CurLine);
  759. // Go down a level
  760. if (TermChar == '{')
  761. {
  762. if (StackPos < sizeof(Stack)/sizeof(std::string))
  763. Stack[StackPos++] = ParentTag;
  764. /* Make sectional tags incorperate the section into the
  765. tag string */
  766. if (AsSectional == true && Word.empty() == false)
  767. {
  768. Tag += "::" ;
  769. Tag += Word;
  770. Word = "";
  771. }
  772. if (ParentTag.empty() == true)
  773. ParentTag = Tag;
  774. else
  775. ParentTag += string("::") + Tag;
  776. Tag = string();
  777. }
  778. // Generate the item name
  779. string Item;
  780. if (ParentTag.empty() == true)
  781. Item = Tag;
  782. else
  783. {
  784. if (TermChar != '{' || Tag.empty() == false)
  785. Item = ParentTag + "::" + Tag;
  786. else
  787. Item = ParentTag;
  788. }
  789. // Specials
  790. if (Tag.length() >= 1 && Tag[0] == '#')
  791. {
  792. if (ParentTag.empty() == false)
  793. return _error->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName.c_str(),CurLine);
  794. Tag.erase(Tag.begin());
  795. if (Tag == "clear")
  796. Conf.Clear(Word);
  797. else if (Tag == "include")
  798. {
  799. if (Depth > 10)
  800. return _error->Error(_("Syntax error %s:%u: Too many nested includes"),FName.c_str(),CurLine);
  801. if (Word.length() > 2 && Word.end()[-1] == '/')
  802. {
  803. if (ReadConfigDir(Conf,Word,AsSectional,Depth+1) == false)
  804. return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
  805. }
  806. else
  807. {
  808. if (ReadConfigFile(Conf,Word,AsSectional,Depth+1) == false)
  809. return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
  810. }
  811. }
  812. else
  813. return _error->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName.c_str(),CurLine,Tag.c_str());
  814. }
  815. else if (Tag.empty() == true && NoWord == false && Word == "#clear")
  816. return _error->Error(_("Syntax error %s:%u: clear directive requires an option tree as argument"),FName.c_str(),CurLine);
  817. else
  818. {
  819. // Set the item in the configuration class
  820. if (NoWord == false)
  821. Conf.Set(Item,Word);
  822. }
  823. // Empty the buffer
  824. LineBuffer.clear();
  825. // Move up a tag, but only if there is no bit to parse
  826. if (TermChar == '}')
  827. {
  828. if (StackPos == 0)
  829. ParentTag.clear();
  830. else
  831. ParentTag = Stack[--StackPos];
  832. }
  833. }
  834. }
  835. // Store the remaining text, if any, in the current line buffer.
  836. // NB: could change this to use string-based operations; I'm
  837. // using strstrip now to ensure backwards compatibility.
  838. // -- dburrows 2008-04-01
  839. {
  840. char *Buffer = new char[End - Start + 1];
  841. try
  842. {
  843. std::copy(Start, End, Buffer);
  844. Buffer[End - Start] = '\0';
  845. const char *Stripd = _strstrip(Buffer);
  846. if (*Stripd != 0 && LineBuffer.empty() == false)
  847. LineBuffer += " ";
  848. LineBuffer += Stripd;
  849. }
  850. catch(...)
  851. {
  852. delete[] Buffer;
  853. throw;
  854. }
  855. delete[] Buffer;
  856. }
  857. }
  858. if (LineBuffer.empty() == false)
  859. return _error->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName.c_str(),CurLine);
  860. return true;
  861. }
  862. /*}}}*/
  863. // ReadConfigDir - Read a directory of config files /*{{{*/
  864. // ---------------------------------------------------------------------
  865. /* */
  866. bool ReadConfigDir(Configuration &Conf,const string &Dir,
  867. bool const &AsSectional, unsigned const &Depth)
  868. {
  869. vector<string> const List = GetListOfFilesInDir(Dir, "conf", true, true);
  870. // Read the files
  871. for (vector<string>::const_iterator I = List.begin(); I != List.end(); ++I)
  872. if (ReadConfigFile(Conf,*I,AsSectional,Depth) == false)
  873. return false;
  874. return true;
  875. }
  876. /*}}}*/
  877. // MatchAgainstConfig Constructor /*{{{*/
  878. Configuration::MatchAgainstConfig::MatchAgainstConfig(char const * Config)
  879. {
  880. std::vector<std::string> const strings = _config->FindVector(Config);
  881. for (std::vector<std::string>::const_iterator s = strings.begin();
  882. s != strings.end(); ++s)
  883. {
  884. regex_t *p = new regex_t;
  885. if (regcomp(p, s->c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB) == 0)
  886. patterns.push_back(p);
  887. else
  888. {
  889. regfree(p);
  890. delete p;
  891. _error->Warning("Invalid regular expression '%s' in configuration "
  892. "option '%s' will be ignored.",
  893. s->c_str(), Config);
  894. continue;
  895. }
  896. }
  897. if (strings.empty() == true)
  898. patterns.push_back(NULL);
  899. }
  900. /*}}}*/
  901. // MatchAgainstConfig Destructor /*{{{*/
  902. Configuration::MatchAgainstConfig::~MatchAgainstConfig()
  903. {
  904. clearPatterns();
  905. }
  906. void Configuration::MatchAgainstConfig::clearPatterns()
  907. {
  908. for(std::vector<regex_t *>::const_iterator p = patterns.begin();
  909. p != patterns.end(); ++p)
  910. {
  911. if (*p == NULL) continue;
  912. regfree(*p);
  913. delete *p;
  914. }
  915. patterns.clear();
  916. }
  917. /*}}}*/
  918. // MatchAgainstConfig::Match - returns true if a pattern matches /*{{{*/
  919. bool Configuration::MatchAgainstConfig::Match(char const * str) const
  920. {
  921. for(std::vector<regex_t *>::const_iterator p = patterns.begin();
  922. p != patterns.end(); ++p)
  923. if (*p != NULL && regexec(*p, str, 0, 0, 0) == 0)
  924. return true;
  925. return false;
  926. }
  927. /*}}}*/