configuration.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: configuration.cc,v 1.22 2001/05/14 05:47:30 jgg 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. ##################################################################### */
  10. /*}}}*/
  11. // Include files /*{{{*/
  12. #ifdef __GNUG__
  13. #pragma implementation "apt-pkg/configuration.h"
  14. #endif
  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 <apti18n.h>
  20. #include <vector>
  21. #include <algorithm>
  22. #include <fstream>
  23. #include <iostream>
  24. #include <stdio.h>
  25. #include <dirent.h>
  26. #include <sys/stat.h>
  27. #include <unistd.h>
  28. using namespace std;
  29. /*}}}*/
  30. Configuration *_config = new Configuration;
  31. // Configuration::Configuration - Constructor /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* */
  34. Configuration::Configuration() : ToFree(true)
  35. {
  36. Root = new Item;
  37. }
  38. Configuration::Configuration(const Item *Root) : Root((Item *)Root), ToFree(false)
  39. {
  40. };
  41. /*}}}*/
  42. // Configuration::~Configuration - Destructor /*{{{*/
  43. // ---------------------------------------------------------------------
  44. /* */
  45. Configuration::~Configuration()
  46. {
  47. if (ToFree == false)
  48. return;
  49. Item *Top = Root;
  50. for (; Top != 0;)
  51. {
  52. if (Top->Child != 0)
  53. {
  54. Top = Top->Child;
  55. continue;
  56. }
  57. while (Top != 0 && Top->Next == 0)
  58. {
  59. Item *Parent = Top->Parent;
  60. delete Top;
  61. Top = Parent;
  62. }
  63. if (Top != 0)
  64. {
  65. Item *Next = Top->Next;
  66. delete Top;
  67. Top = Next;
  68. }
  69. }
  70. }
  71. /*}}}*/
  72. // Configuration::Lookup - Lookup a single item /*{{{*/
  73. // ---------------------------------------------------------------------
  74. /* This will lookup a single item by name below another item. It is a
  75. helper function for the main lookup function */
  76. Configuration::Item *Configuration::Lookup(Item *Head,const char *S,
  77. unsigned long Len,bool Create)
  78. {
  79. int Res = 1;
  80. Item *I = Head->Child;
  81. Item **Last = &Head->Child;
  82. // Empty strings match nothing. They are used for lists.
  83. if (Len != 0)
  84. {
  85. for (; I != 0; Last = &I->Next, I = I->Next)
  86. if ((Res = stringcasecmp(I->Tag,S,S + Len)) == 0)
  87. break;
  88. }
  89. else
  90. for (; I != 0; Last = &I->Next, I = I->Next);
  91. if (Res == 0)
  92. return I;
  93. if (Create == false)
  94. return 0;
  95. I = new Item;
  96. I->Tag = string(S,Len);
  97. I->Next = *Last;
  98. I->Parent = Head;
  99. *Last = I;
  100. return I;
  101. }
  102. /*}}}*/
  103. // Configuration::Lookup - Lookup a fully scoped item /*{{{*/
  104. // ---------------------------------------------------------------------
  105. /* This performs a fully scoped lookup of a given name, possibly creating
  106. new items */
  107. Configuration::Item *Configuration::Lookup(const char *Name,bool Create)
  108. {
  109. if (Name == 0)
  110. return Root->Child;
  111. const char *Start = Name;
  112. const char *End = Start + strlen(Name);
  113. const char *TagEnd = Name;
  114. Item *Itm = Root;
  115. for (; End - TagEnd >= 2; TagEnd++)
  116. {
  117. if (TagEnd[0] == ':' && TagEnd[1] == ':')
  118. {
  119. Itm = Lookup(Itm,Start,TagEnd - Start,Create);
  120. if (Itm == 0)
  121. return 0;
  122. TagEnd = Start = TagEnd + 2;
  123. }
  124. }
  125. // This must be a trailing ::, we create unique items in a list
  126. if (End - Start == 0)
  127. {
  128. if (Create == false)
  129. return 0;
  130. }
  131. Itm = Lookup(Itm,Start,End - Start,Create);
  132. return Itm;
  133. }
  134. /*}}}*/
  135. // Configuration::Find - Find a value /*{{{*/
  136. // ---------------------------------------------------------------------
  137. /* */
  138. string Configuration::Find(const char *Name,const char *Default) const
  139. {
  140. const Item *Itm = Lookup(Name);
  141. if (Itm == 0 || Itm->Value.empty() == true)
  142. {
  143. if (Default == 0)
  144. return string();
  145. else
  146. return Default;
  147. }
  148. return Itm->Value;
  149. }
  150. /*}}}*/
  151. // Configuration::FindFile - Find a Filename /*{{{*/
  152. // ---------------------------------------------------------------------
  153. /* Directories are stored as the base dir in the Parent node and the
  154. sub directory in sub nodes with the final node being the end filename
  155. */
  156. string Configuration::FindFile(const char *Name,const char *Default) const
  157. {
  158. const Item *Itm = Lookup(Name);
  159. if (Itm == 0 || Itm->Value.empty() == true)
  160. {
  161. if (Default == 0)
  162. return string();
  163. else
  164. return Default;
  165. }
  166. string val = Itm->Value;
  167. while (Itm->Parent != 0 && Itm->Parent->Value.empty() == false)
  168. {
  169. // Absolute
  170. if (val.length() >= 1 && val[0] == '/')
  171. break;
  172. // ~/foo or ./foo
  173. if (val.length() >= 2 && (val[0] == '~' || val[0] == '.') && val[1] == '/')
  174. break;
  175. // ../foo
  176. if (val.length() >= 3 && val[0] == '.' && val[1] == '.' && val[2] == '/')
  177. break;
  178. if (Itm->Parent->Value.end()[-1] != '/')
  179. val.insert(0, "/");
  180. val.insert(0, Itm->Parent->Value);
  181. Itm = Itm->Parent;
  182. }
  183. return val;
  184. }
  185. /*}}}*/
  186. // Configuration::FindDir - Find a directory name /*{{{*/
  187. // ---------------------------------------------------------------------
  188. /* This is like findfile execept the result is terminated in a / */
  189. string Configuration::FindDir(const char *Name,const char *Default) const
  190. {
  191. string Res = FindFile(Name,Default);
  192. if (Res.end()[-1] != '/')
  193. return Res + '/';
  194. return Res;
  195. }
  196. /*}}}*/
  197. // Configuration::FindI - Find an integer value /*{{{*/
  198. // ---------------------------------------------------------------------
  199. /* */
  200. int Configuration::FindI(const char *Name,int Default) const
  201. {
  202. const Item *Itm = Lookup(Name);
  203. if (Itm == 0 || Itm->Value.empty() == true)
  204. return Default;
  205. char *End;
  206. int Res = strtol(Itm->Value.c_str(),&End,0);
  207. if (End == Itm->Value.c_str())
  208. return Default;
  209. return Res;
  210. }
  211. /*}}}*/
  212. // Configuration::FindB - Find a boolean type /*{{{*/
  213. // ---------------------------------------------------------------------
  214. /* */
  215. bool Configuration::FindB(const char *Name,bool Default) const
  216. {
  217. const Item *Itm = Lookup(Name);
  218. if (Itm == 0 || Itm->Value.empty() == true)
  219. return Default;
  220. return StringToBool(Itm->Value,Default);
  221. }
  222. /*}}}*/
  223. // Configuration::FindAny - Find an arbitrary type /*{{{*/
  224. // ---------------------------------------------------------------------
  225. /* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
  226. string Configuration::FindAny(const char *Name,const char *Default) const
  227. {
  228. string key = Name;
  229. char type = 0;
  230. if (key.size() > 2 && key.end()[-2] == '/')
  231. {
  232. type = key.end()[-1];
  233. key.resize(key.size() - 2);
  234. }
  235. switch (type)
  236. {
  237. // file
  238. case 'f':
  239. return FindFile(key.c_str(), Default);
  240. // directory
  241. case 'd':
  242. return FindDir(key.c_str(), Default);
  243. // bool
  244. case 'b':
  245. return FindB(key, Default) ? "true" : "false";
  246. // int
  247. case 'i':
  248. {
  249. char buf[16];
  250. snprintf(buf, sizeof(buf)-1, "%d", FindI(key, atoi(Default)));
  251. return buf;
  252. }
  253. }
  254. // fallback
  255. return Find(Name, Default);
  256. }
  257. /*}}}*/
  258. // Configuration::CndSet - Conditinal Set a value /*{{{*/
  259. // ---------------------------------------------------------------------
  260. /* This will not overwrite */
  261. void Configuration::CndSet(const char *Name,string Value)
  262. {
  263. Item *Itm = Lookup(Name,true);
  264. if (Itm == 0)
  265. return;
  266. if (Itm->Value.empty() == true)
  267. Itm->Value = Value;
  268. }
  269. /*}}}*/
  270. // Configuration::Set - Set a value /*{{{*/
  271. // ---------------------------------------------------------------------
  272. /* */
  273. void Configuration::Set(const char *Name,string Value)
  274. {
  275. Item *Itm = Lookup(Name,true);
  276. if (Itm == 0)
  277. return;
  278. Itm->Value = Value;
  279. }
  280. /*}}}*/
  281. // Configuration::Set - Set an integer value /*{{{*/
  282. // ---------------------------------------------------------------------
  283. /* */
  284. void Configuration::Set(const char *Name,int Value)
  285. {
  286. Item *Itm = Lookup(Name,true);
  287. if (Itm == 0)
  288. return;
  289. char S[300];
  290. snprintf(S,sizeof(S),"%i",Value);
  291. Itm->Value = S;
  292. }
  293. /*}}}*/
  294. // Configuration::Clear - Clear an entire tree /*{{{*/
  295. // ---------------------------------------------------------------------
  296. /* */
  297. void Configuration::Clear(string Name)
  298. {
  299. Item *Top = Lookup(Name.c_str(),false);
  300. if (Top == 0)
  301. return;
  302. Top->Value = string();
  303. Item *Stop = Top;
  304. Top = Top->Child;
  305. Stop->Child = 0;
  306. for (; Top != 0;)
  307. {
  308. if (Top->Child != 0)
  309. {
  310. Top = Top->Child;
  311. continue;
  312. }
  313. while (Top != 0 && Top->Next == 0)
  314. {
  315. Item *Tmp = Top;
  316. Top = Top->Parent;
  317. delete Tmp;
  318. if (Top == Stop)
  319. return;
  320. }
  321. Item *Tmp = Top;
  322. if (Top != 0)
  323. Top = Top->Next;
  324. delete Tmp;
  325. }
  326. }
  327. /*}}}*/
  328. // Configuration::Exists - Returns true if the Name exists /*{{{*/
  329. // ---------------------------------------------------------------------
  330. /* */
  331. bool Configuration::Exists(const char *Name) const
  332. {
  333. const Item *Itm = Lookup(Name);
  334. if (Itm == 0)
  335. return false;
  336. return true;
  337. }
  338. /*}}}*/
  339. // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
  340. // ---------------------------------------------------------------------
  341. /* qualified by /[fdbi] exists */
  342. bool Configuration::ExistsAny(const char *Name) const
  343. {
  344. string key = Name;
  345. if (key.size() > 2 && key.end()[-2] == '/' &&
  346. key.find_first_of("fdbi",key.size()-1) < key.size())
  347. {
  348. key.resize(key.size() - 2);
  349. if (Exists(key.c_str()))
  350. return true;
  351. }
  352. return Exists(Name);
  353. }
  354. /*}}}*/
  355. // Configuration::Dump - Dump the config /*{{{*/
  356. // ---------------------------------------------------------------------
  357. /* Dump the entire configuration space */
  358. void Configuration::Dump()
  359. {
  360. /* Write out all of the configuration directives by walking the
  361. configuration tree */
  362. const Configuration::Item *Top = Tree(0);
  363. for (; Top != 0;)
  364. {
  365. clog << Top->FullTag() << " \"" << Top->Value << "\";" << endl;
  366. if (Top->Child != 0)
  367. {
  368. Top = Top->Child;
  369. continue;
  370. }
  371. while (Top != 0 && Top->Next == 0)
  372. Top = Top->Parent;
  373. if (Top != 0)
  374. Top = Top->Next;
  375. }
  376. }
  377. /*}}}*/
  378. // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
  379. // ---------------------------------------------------------------------
  380. /* Stop sets an optional max recursion depth if this item is being viewed as
  381. part of a sub tree. */
  382. string Configuration::Item::FullTag(const Item *Stop) const
  383. {
  384. if (Parent == 0 || Parent->Parent == 0 || Parent == Stop)
  385. return Tag;
  386. return Parent->FullTag(Stop) + "::" + Tag;
  387. }
  388. /*}}}*/
  389. // ReadConfigFile - Read a configuration file /*{{{*/
  390. // ---------------------------------------------------------------------
  391. /* The configuration format is very much like the named.conf format
  392. used in bind8, in fact this routine can parse most named.conf files.
  393. Sectional config files are like bind's named.conf where there are
  394. sections like 'zone "foo.org" { .. };' This causes each section to be
  395. added in with a tag like "zone::foo.org" instead of being split
  396. tag/value. AsSectional enables Sectional parsing.*/
  397. bool ReadConfigFile(Configuration &Conf,string FName,bool AsSectional,
  398. unsigned Depth)
  399. {
  400. // Open the stream for reading
  401. ifstream F(FName.c_str(),ios::in);
  402. if (!F != 0)
  403. return _error->Errno("ifstream::ifstream",_("Opening configuration file %s"),FName.c_str());
  404. char Buffer[300];
  405. string LineBuffer;
  406. string Stack[100];
  407. unsigned int StackPos = 0;
  408. // Parser state
  409. string ParentTag;
  410. int CurLine = 0;
  411. bool InComment = false;
  412. while (F.eof() == false)
  413. {
  414. F.getline(Buffer,sizeof(Buffer));
  415. CurLine++;
  416. _strtabexpand(Buffer,sizeof(Buffer));
  417. _strstrip(Buffer);
  418. // Multi line comment
  419. if (InComment == true)
  420. {
  421. for (const char *I = Buffer; *I != 0; I++)
  422. {
  423. if (*I == '*' && I[1] == '/')
  424. {
  425. memmove(Buffer,I+2,strlen(I+2) + 1);
  426. InComment = false;
  427. break;
  428. }
  429. }
  430. if (InComment == true)
  431. continue;
  432. }
  433. // Discard single line comments
  434. bool InQuote = false;
  435. for (char *I = Buffer; *I != 0; I++)
  436. {
  437. if (*I == '"')
  438. InQuote = !InQuote;
  439. if (InQuote == true)
  440. continue;
  441. if (*I == '/' && I[1] == '/')
  442. {
  443. *I = 0;
  444. break;
  445. }
  446. }
  447. // Look for multi line comments
  448. InQuote = false;
  449. for (char *I = Buffer; *I != 0; I++)
  450. {
  451. if (*I == '"')
  452. InQuote = !InQuote;
  453. if (InQuote == true)
  454. continue;
  455. if (*I == '/' && I[1] == '*')
  456. {
  457. InComment = true;
  458. for (char *J = Buffer; *J != 0; J++)
  459. {
  460. if (*J == '*' && J[1] == '/')
  461. {
  462. memmove(I,J+2,strlen(J+2) + 1);
  463. InComment = false;
  464. break;
  465. }
  466. }
  467. if (InComment == true)
  468. {
  469. *I = 0;
  470. break;
  471. }
  472. }
  473. }
  474. // Blank
  475. if (Buffer[0] == 0)
  476. continue;
  477. // We now have a valid line fragment
  478. InQuote = false;
  479. for (char *I = Buffer; *I != 0;)
  480. {
  481. if (*I == '"')
  482. InQuote = !InQuote;
  483. if (InQuote == false && (*I == '{' || *I == ';' || *I == '}'))
  484. {
  485. // Put the last fragment into the buffer
  486. char *Start = Buffer;
  487. char *Stop = I;
  488. for (; Start != I && isspace(*Start) != 0; Start++);
  489. for (; Stop != Start && isspace(Stop[-1]) != 0; Stop--);
  490. if (LineBuffer.empty() == false && Stop - Start != 0)
  491. LineBuffer += ' ';
  492. LineBuffer += string(Start,Stop - Start);
  493. // Remove the fragment
  494. char TermChar = *I;
  495. memmove(Buffer,I + 1,strlen(I + 1) + 1);
  496. I = Buffer;
  497. // Syntax Error
  498. if (TermChar == '{' && LineBuffer.empty() == true)
  499. return _error->Error(_("Syntax error %s:%u: Block starts with no name."),FName.c_str(),CurLine);
  500. // No string on this line
  501. if (LineBuffer.empty() == true)
  502. {
  503. if (TermChar == '}')
  504. {
  505. if (StackPos == 0)
  506. ParentTag = string();
  507. else
  508. ParentTag = Stack[--StackPos];
  509. }
  510. continue;
  511. }
  512. // Parse off the tag
  513. string Tag;
  514. const char *Pos = LineBuffer.c_str();
  515. if (ParseQuoteWord(Pos,Tag) == false)
  516. return _error->Error(_("Syntax error %s:%u: Malformed Tag"),FName.c_str(),CurLine);
  517. // Parse off the word
  518. string Word;
  519. bool NoWord = false;
  520. if (ParseCWord(Pos,Word) == false &&
  521. ParseQuoteWord(Pos,Word) == false)
  522. {
  523. if (TermChar != '{')
  524. {
  525. Word = Tag;
  526. Tag = "";
  527. }
  528. else
  529. NoWord = true;
  530. }
  531. if (strlen(Pos) != 0)
  532. return _error->Error(_("Syntax error %s:%u: Extra junk after value"),FName.c_str(),CurLine);
  533. // Go down a level
  534. if (TermChar == '{')
  535. {
  536. if (StackPos <= 100)
  537. Stack[StackPos++] = ParentTag;
  538. /* Make sectional tags incorperate the section into the
  539. tag string */
  540. if (AsSectional == true && Word.empty() == false)
  541. {
  542. Tag += "::" ;
  543. Tag += Word;
  544. Word = "";
  545. }
  546. if (ParentTag.empty() == true)
  547. ParentTag = Tag;
  548. else
  549. ParentTag += string("::") + Tag;
  550. Tag = string();
  551. }
  552. // Generate the item name
  553. string Item;
  554. if (ParentTag.empty() == true)
  555. Item = Tag;
  556. else
  557. {
  558. if (TermChar != '{' || Tag.empty() == false)
  559. Item = ParentTag + "::" + Tag;
  560. else
  561. Item = ParentTag;
  562. }
  563. // Specials
  564. if (Tag.length() >= 1 && Tag[0] == '#')
  565. {
  566. if (ParentTag.empty() == false)
  567. return _error->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName.c_str(),CurLine);
  568. Tag.erase(Tag.begin());
  569. if (Tag == "clear")
  570. Conf.Clear(Word);
  571. else if (Tag == "include")
  572. {
  573. if (Depth > 10)
  574. return _error->Error(_("Syntax error %s:%u: Too many nested includes"),FName.c_str(),CurLine);
  575. if (Word.length() > 2 && Word.end()[-1] == '/')
  576. {
  577. if (ReadConfigDir(Conf,Word,AsSectional,Depth+1) == false)
  578. return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
  579. }
  580. else
  581. {
  582. if (ReadConfigFile(Conf,Word,AsSectional,Depth+1) == false)
  583. return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
  584. }
  585. }
  586. else
  587. return _error->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName.c_str(),CurLine,Tag.c_str());
  588. }
  589. else
  590. {
  591. // Set the item in the configuration class
  592. if (NoWord == false)
  593. Conf.Set(Item,Word);
  594. }
  595. // Empty the buffer
  596. LineBuffer = string();
  597. // Move up a tag, but only if there is no bit to parse
  598. if (TermChar == '}')
  599. {
  600. if (StackPos == 0)
  601. ParentTag = string();
  602. else
  603. ParentTag = Stack[--StackPos];
  604. }
  605. }
  606. else
  607. I++;
  608. }
  609. // Store the fragment
  610. const char *Stripd = _strstrip(Buffer);
  611. if (*Stripd != 0 && LineBuffer.empty() == false)
  612. LineBuffer += " ";
  613. LineBuffer += Stripd;
  614. }
  615. if (LineBuffer.empty() == false)
  616. return _error->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName.c_str(),CurLine);
  617. return true;
  618. }
  619. /*}}}*/
  620. // ReadConfigDir - Read a directory of config files /*{{{*/
  621. // ---------------------------------------------------------------------
  622. /* */
  623. bool ReadConfigDir(Configuration &Conf,string Dir,bool AsSectional,
  624. unsigned Depth)
  625. {
  626. DIR *D = opendir(Dir.c_str());
  627. if (D == 0)
  628. return _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  629. vector<string> List;
  630. for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
  631. {
  632. if (Ent->d_name[0] == '.')
  633. continue;
  634. // Skip bad file names ala run-parts
  635. const char *C = Ent->d_name;
  636. for (; *C != 0; C++)
  637. if (isalpha(*C) == 0 && isdigit(*C) == 0 && *C != '_' && *C != '-')
  638. break;
  639. if (*C != 0)
  640. continue;
  641. // Make sure it is a file and not something else
  642. string File = flCombine(Dir,Ent->d_name);
  643. struct stat St;
  644. if (stat(File.c_str(),&St) != 0 || S_ISREG(St.st_mode) == 0)
  645. continue;
  646. List.push_back(File);
  647. }
  648. closedir(D);
  649. sort(List.begin(),List.end());
  650. // Read the files
  651. for (vector<string>::const_iterator I = List.begin(); I != List.end(); I++)
  652. if (ReadConfigFile(Conf,*I,AsSectional,Depth) == false)
  653. return false;
  654. return true;
  655. }
  656. /*}}}*/