configuration.cc 28 KB

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