You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

786 lines
20 KiB

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