configuration.cc 19 KB

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