1 // -*- mode: cpp; mode: fold -*-
3 // $Id: configuration.cc,v 1.28 2004/04/30 04:00:15 mdz Exp $
4 /* ######################################################################
8 This class provides a configuration file and command line parser
9 for a tree-oriented configuration environment. All runtime configuration
12 This source is placed in the Public Domain, do with it what you will
13 It was originally written by Jason Gunthorpe <jgg@debian.org>.
15 ##################################################################### */
17 // Include files /*{{{*/
18 #include <apt-pkg/configuration.h>
19 #include <apt-pkg/error.h>
20 #include <apt-pkg/strutl.h>
21 #include <apt-pkg/fileutl.h>
37 Configuration
*_config
= new Configuration
;
39 // Configuration::Configuration - Constructor /*{{{*/
40 // ---------------------------------------------------------------------
42 Configuration::Configuration() : ToFree(true)
46 Configuration::Configuration(const Item
*Root
) : Root((Item
*)Root
), ToFree(false)
51 // Configuration::~Configuration - Destructor /*{{{*/
52 // ---------------------------------------------------------------------
54 Configuration::~Configuration()
68 while (Top
!= 0 && Top
->Next
== 0)
70 Item
*Parent
= Top
->Parent
;
76 Item
*Next
= Top
->Next
;
83 // Configuration::Lookup - Lookup a single item /*{{{*/
84 // ---------------------------------------------------------------------
85 /* This will lookup a single item by name below another item. It is a
86 helper function for the main lookup function */
87 Configuration::Item
*Configuration::Lookup(Item
*Head
,const char *S
,
88 unsigned long Len
,bool Create
)
91 Item
*I
= Head
->Child
;
92 Item
**Last
= &Head
->Child
;
94 // Empty strings match nothing. They are used for lists.
97 for (; I
!= 0; Last
= &I
->Next
, I
= I
->Next
)
98 if ((Res
= stringcasecmp(I
->Tag
,S
,S
+ Len
)) == 0)
102 for (; I
!= 0; Last
= &I
->Next
, I
= I
->Next
);
110 I
->Tag
.assign(S
,Len
);
117 // Configuration::Lookup - Lookup a fully scoped item /*{{{*/
118 // ---------------------------------------------------------------------
119 /* This performs a fully scoped lookup of a given name, possibly creating
121 Configuration::Item
*Configuration::Lookup(const char *Name
,bool Create
)
126 const char *Start
= Name
;
127 const char *End
= Start
+ strlen(Name
);
128 const char *TagEnd
= Name
;
130 for (; End
- TagEnd
>= 2; TagEnd
++)
132 if (TagEnd
[0] == ':' && TagEnd
[1] == ':')
134 Itm
= Lookup(Itm
,Start
,TagEnd
- Start
,Create
);
137 TagEnd
= Start
= TagEnd
+ 2;
141 // This must be a trailing ::, we create unique items in a list
142 if (End
- Start
== 0)
148 Itm
= Lookup(Itm
,Start
,End
- Start
,Create
);
152 // Configuration::Find - Find a value /*{{{*/
153 // ---------------------------------------------------------------------
155 string
Configuration::Find(const char *Name
,const char *Default
) const
157 const Item
*Itm
= Lookup(Name
);
158 if (Itm
== 0 || Itm
->Value
.empty() == true)
169 // Configuration::FindFile - Find a Filename /*{{{*/
170 // ---------------------------------------------------------------------
171 /* Directories are stored as the base dir in the Parent node and the
172 sub directory in sub nodes with the final node being the end filename
174 string
Configuration::FindFile(const char *Name
,const char *Default
) const
176 const Item
*RootItem
= Lookup("RootDir");
177 std::string rootDir
= (RootItem
== 0) ? "" : RootItem
->Value
;
178 if(rootDir
.size() > 0 && rootDir
[rootDir
.size() - 1] != '/')
179 rootDir
.push_back('/');
181 const Item
*Itm
= Lookup(Name
);
182 if (Itm
== 0 || Itm
->Value
.empty() == true)
187 return rootDir
+ Default
;
190 string val
= Itm
->Value
;
191 while (Itm
->Parent
!= 0 && Itm
->Parent
->Value
.empty() == false)
194 if (val
.length() >= 1 && val
[0] == '/')
198 if (val
.length() >= 2 && (val
[0] == '~' || val
[0] == '.') && val
[1] == '/')
202 if (val
.length() >= 3 && val
[0] == '.' && val
[1] == '.' && val
[2] == '/')
205 if (Itm
->Parent
->Value
.end()[-1] != '/')
208 val
.insert(0, Itm
->Parent
->Value
);
212 return rootDir
+ val
;
215 // Configuration::FindDir - Find a directory name /*{{{*/
216 // ---------------------------------------------------------------------
217 /* This is like findfile execept the result is terminated in a / */
218 string
Configuration::FindDir(const char *Name
,const char *Default
) const
220 string Res
= FindFile(Name
,Default
);
221 if (Res
.end()[-1] != '/')
226 // Configuration::FindVector - Find a vector of values /*{{{*/
227 // ---------------------------------------------------------------------
228 /* Returns a vector of config values under the given item */
229 vector
<string
> Configuration::FindVector(const char *Name
) const
232 const Item
*Top
= Lookup(Name
);
236 Item
*I
= Top
->Child
;
239 Vec
.push_back(I
->Value
);
245 // Configuration::FindI - Find an integer value /*{{{*/
246 // ---------------------------------------------------------------------
248 int Configuration::FindI(const char *Name
,int Default
) const
250 const Item
*Itm
= Lookup(Name
);
251 if (Itm
== 0 || Itm
->Value
.empty() == true)
255 int Res
= strtol(Itm
->Value
.c_str(),&End
,0);
256 if (End
== Itm
->Value
.c_str())
262 // Configuration::FindB - Find a boolean type /*{{{*/
263 // ---------------------------------------------------------------------
265 bool Configuration::FindB(const char *Name
,bool Default
) const
267 const Item
*Itm
= Lookup(Name
);
268 if (Itm
== 0 || Itm
->Value
.empty() == true)
271 return StringToBool(Itm
->Value
,Default
);
274 // Configuration::FindAny - Find an arbitrary type /*{{{*/
275 // ---------------------------------------------------------------------
276 /* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
277 string
Configuration::FindAny(const char *Name
,const char *Default
) const
282 if (key
.size() > 2 && key
.end()[-2] == '/')
284 type
= key
.end()[-1];
285 key
.resize(key
.size() - 2);
292 return FindFile(key
.c_str(), Default
);
296 return FindDir(key
.c_str(), Default
);
300 return FindB(key
, Default
) ? "true" : "false";
306 snprintf(buf
, sizeof(buf
)-1, "%d", FindI(key
, Default
? atoi(Default
) : 0 ));
312 return Find(Name
, Default
);
315 // Configuration::CndSet - Conditinal Set a value /*{{{*/
316 // ---------------------------------------------------------------------
317 /* This will not overwrite */
318 void Configuration::CndSet(const char *Name
,const string
&Value
)
320 Item
*Itm
= Lookup(Name
,true);
323 if (Itm
->Value
.empty() == true)
327 // Configuration::Set - Set a value /*{{{*/
328 // ---------------------------------------------------------------------
330 void Configuration::Set(const char *Name
,const string
&Value
)
332 Item
*Itm
= Lookup(Name
,true);
338 // Configuration::Set - Set an integer value /*{{{*/
339 // ---------------------------------------------------------------------
341 void Configuration::Set(const char *Name
,int Value
)
343 Item
*Itm
= Lookup(Name
,true);
347 snprintf(S
,sizeof(S
),"%i",Value
);
351 // Configuration::Clear - Clear an single value from a list /*{{{*/
352 // ---------------------------------------------------------------------
354 void Configuration::Clear(const string Name
, int Value
)
357 snprintf(S
,sizeof(S
),"%i",Value
);
361 // Configuration::Clear - Clear an single value from a list /*{{{*/
362 // ---------------------------------------------------------------------
364 void Configuration::Clear(const string Name
, string Value
)
366 Item
*Top
= Lookup(Name
.c_str(),false);
367 if (Top
== 0 || Top
->Child
== 0)
370 Item
*Tmp
, *Prev
, *I
;
371 Prev
= I
= Top
->Child
;
375 if(I
->Value
== Value
)
378 // was first element, point parent to new first element
379 if(Top
->Child
== Tmp
)
380 Top
->Child
= I
->Next
;
392 // Configuration::Clear - Clear an entire tree /*{{{*/
393 // ---------------------------------------------------------------------
395 void Configuration::Clear(string Name
)
397 Item
*Top
= Lookup(Name
.c_str(),false);
413 while (Top
!= 0 && Top
->Next
== 0)
430 // Configuration::Exists - Returns true if the Name exists /*{{{*/
431 // ---------------------------------------------------------------------
433 bool Configuration::Exists(const char *Name
) const
435 const Item
*Itm
= Lookup(Name
);
441 // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
442 // ---------------------------------------------------------------------
443 /* qualified by /[fdbi] exists */
444 bool Configuration::ExistsAny(const char *Name
) const
448 if (key
.size() > 2 && key
.end()[-2] == '/')
450 if (key
.find_first_of("fdbi",key
.size()-1) < key
.size())
452 key
.resize(key
.size() - 2);
453 if (Exists(key
.c_str()))
458 _error
->Warning(_("Unrecognized type abbreviation: '%c'"), key
.end()[-3]);
464 // Configuration::Dump - Dump the config /*{{{*/
465 // ---------------------------------------------------------------------
466 /* Dump the entire configuration space */
467 void Configuration::Dump(ostream
& str
)
469 /* Write out all of the configuration directives by walking the
470 configuration tree */
471 const Configuration::Item
*Top
= Tree(0);
474 str
<< Top
->FullTag() << " \"" << Top
->Value
<< "\";" << endl
;
482 while (Top
!= 0 && Top
->Next
== 0)
490 // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
491 // ---------------------------------------------------------------------
492 /* Stop sets an optional max recursion depth if this item is being viewed as
493 part of a sub tree. */
494 string
Configuration::Item::FullTag(const Item
*Stop
) const
496 if (Parent
== 0 || Parent
->Parent
== 0 || Parent
== Stop
)
498 return Parent
->FullTag(Stop
) + "::" + Tag
;
502 // ReadConfigFile - Read a configuration file /*{{{*/
503 // ---------------------------------------------------------------------
504 /* The configuration format is very much like the named.conf format
505 used in bind8, in fact this routine can parse most named.conf files.
506 Sectional config files are like bind's named.conf where there are
507 sections like 'zone "foo.org" { .. };' This causes each section to be
508 added in with a tag like "zone::foo.org" instead of being split
509 tag/value. AsSectional enables Sectional parsing.*/
510 bool ReadConfigFile(Configuration
&Conf
,const string
&FName
,bool AsSectional
,
513 // Open the stream for reading
514 ifstream
F(FName
.c_str(),ios::in
);
516 return _error
->Errno("ifstream::ifstream",_("Opening configuration file %s"),FName
.c_str());
520 unsigned int StackPos
= 0;
526 bool InComment
= false;
527 while (F
.eof() == false)
529 // The raw input line.
531 // The input line with comments stripped.
532 std::string Fragment
;
534 // Grab the next line of F and place it in Input.
537 char *Buffer
= new char[1024];
540 F
.getline(Buffer
,sizeof(Buffer
) / 2);
545 while (F
.fail() && !F
.eof());
547 // Expand tabs in the input line and remove leading and trailing
550 const int BufferSize
= Input
.size() * 8 + 1;
551 char *Buffer
= new char[BufferSize
];
554 memcpy(Buffer
, Input
.c_str(), Input
.size() + 1);
556 _strtabexpand(Buffer
, BufferSize
);
569 // Now strip comments; if the whole line is contained in a
570 // comment, skip this line.
572 // The first meaningful character in the current fragment; will
573 // be adjusted below as we remove bytes from the front.
574 std::string::const_iterator Start
= Input
.begin();
575 // The last meaningful character in the current fragment.
576 std::string::const_iterator End
= Input
.end();
578 // Multi line comment
579 if (InComment
== true)
581 for (std::string::const_iterator I
= Start
;
584 if (*I
== '*' && I
+ 1 != End
&& I
[1] == '/')
591 if (InComment
== true)
595 // Discard single line comments
596 bool InQuote
= false;
597 for (std::string::const_iterator I
= Start
;
605 if ((*I
== '/' && I
+ 1 != End
&& I
[1] == '/') ||
606 (*I
== '#' && strcmp(string(I
,I
+6).c_str(),"#clear") != 0 &&
607 strcmp(string(I
,I
+8).c_str(),"#include") != 0))
614 // Look for multi line comments and build up the
616 Fragment
.reserve(End
- Start
);
618 for (std::string::const_iterator I
= Start
;
624 Fragment
.push_back(*I
);
625 else if (*I
== '/' && I
+ 1 != End
&& I
[1] == '*')
628 for (std::string::const_iterator J
= I
;
631 if (*J
== '*' && J
+ 1 != End
&& J
[1] == '/')
633 // Pretend we just finished walking over the
634 // comment, and don't add anything to the output
642 if (InComment
== true)
646 Fragment
.push_back(*I
);
650 if (Fragment
.empty())
653 // The line has actual content; interpret what it means.
655 Start
= Fragment
.begin();
656 End
= Fragment
.end();
657 for (std::string::const_iterator I
= Start
;
663 if (InQuote
== false && (*I
== '{' || *I
== ';' || *I
== '}'))
665 // Put the last fragment into the buffer
666 std::string::const_iterator NonWhitespaceStart
= Start
;
667 std::string::const_iterator NonWhitespaceStop
= I
;
668 for (; NonWhitespaceStart
!= I
&& isspace(*NonWhitespaceStart
) != 0; NonWhitespaceStart
++)
670 for (; NonWhitespaceStop
!= NonWhitespaceStart
&& isspace(NonWhitespaceStop
[-1]) != 0; NonWhitespaceStop
--)
672 if (LineBuffer
.empty() == false && NonWhitespaceStop
- NonWhitespaceStart
!= 0)
674 LineBuffer
+= string(NonWhitespaceStart
, NonWhitespaceStop
);
676 // Drop this from the input string, saving the character
677 // that terminated the construct we just closed. (i.e., a
678 // brace or a semicolon)
683 if (TermChar
== '{' && LineBuffer
.empty() == true)
684 return _error
->Error(_("Syntax error %s:%u: Block starts with no name."),FName
.c_str(),CurLine
);
686 // No string on this line
687 if (LineBuffer
.empty() == true)
692 ParentTag
= string();
694 ParentTag
= Stack
[--StackPos
];
701 const char *Pos
= LineBuffer
.c_str();
702 if (ParseQuoteWord(Pos
,Tag
) == false)
703 return _error
->Error(_("Syntax error %s:%u: Malformed tag"),FName
.c_str(),CurLine
);
705 // Parse off the word
708 if (ParseCWord(Pos
,Word
) == false &&
709 ParseQuoteWord(Pos
,Word
) == false)
719 if (strlen(Pos
) != 0)
720 return _error
->Error(_("Syntax error %s:%u: Extra junk after value"),FName
.c_str(),CurLine
);
726 Stack
[StackPos
++] = ParentTag
;
728 /* Make sectional tags incorperate the section into the
730 if (AsSectional
== true && Word
.empty() == false)
737 if (ParentTag
.empty() == true)
740 ParentTag
+= string("::") + Tag
;
744 // Generate the item name
746 if (ParentTag
.empty() == true)
750 if (TermChar
!= '{' || Tag
.empty() == false)
751 Item
= ParentTag
+ "::" + Tag
;
757 if (Tag
.length() >= 1 && Tag
[0] == '#')
759 if (ParentTag
.empty() == false)
760 return _error
->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName
.c_str(),CurLine
);
761 Tag
.erase(Tag
.begin());
764 else if (Tag
== "include")
767 return _error
->Error(_("Syntax error %s:%u: Too many nested includes"),FName
.c_str(),CurLine
);
768 if (Word
.length() > 2 && Word
.end()[-1] == '/')
770 if (ReadConfigDir(Conf
,Word
,AsSectional
,Depth
+1) == false)
771 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
775 if (ReadConfigFile(Conf
,Word
,AsSectional
,Depth
+1) == false)
776 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
780 return _error
->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName
.c_str(),CurLine
,Tag
.c_str());
784 // Set the item in the configuration class
792 // Move up a tag, but only if there is no bit to parse
798 ParentTag
= Stack
[--StackPos
];
804 // Store the remaining text, if any, in the current line buffer.
806 // NB: could change this to use string-based operations; I'm
807 // using strstrip now to ensure backwards compatibility.
808 // -- dburrows 2008-04-01
810 char *Buffer
= new char[End
- Start
+ 1];
813 std::copy(Start
, End
, Buffer
);
814 Buffer
[End
- Start
] = '\0';
816 const char *Stripd
= _strstrip(Buffer
);
817 if (*Stripd
!= 0 && LineBuffer
.empty() == false)
819 LineBuffer
+= Stripd
;
830 if (LineBuffer
.empty() == false)
831 return _error
->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName
.c_str(),CurLine
);
835 // ReadConfigDir - Read a directory of config files /*{{{*/
836 // ---------------------------------------------------------------------
838 bool ReadConfigDir(Configuration
&Conf
,const string
&Dir
,bool AsSectional
,
841 DIR *D
= opendir(Dir
.c_str());
843 return _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
847 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
849 if (Ent
->d_name
[0] == '.')
852 // Skip bad file names ala run-parts
853 const char *C
= Ent
->d_name
;
855 if (isalpha(*C
) == 0 && isdigit(*C
) == 0 && *C
!= '_' && *C
!= '-')
860 // Make sure it is a file and not something else
861 string File
= flCombine(Dir
,Ent
->d_name
);
863 if (stat(File
.c_str(),&St
) != 0 || S_ISREG(St
.st_mode
) == 0)
866 List
.push_back(File
);
870 sort(List
.begin(),List
.end());
873 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); I
++)
874 if (ReadConfigFile(Conf
,*I
,AsSectional
,Depth
) == false)