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 /*{{{*/
20 #include <apt-pkg/configuration.h>
21 #include <apt-pkg/error.h>
22 #include <apt-pkg/strutl.h>
23 #include <apt-pkg/fileutl.h>
24 #include <apt-pkg/macros.h>
42 Configuration
*_config
= new Configuration
;
44 // Configuration::Configuration - Constructor /*{{{*/
45 // ---------------------------------------------------------------------
47 Configuration::Configuration() : ToFree(true)
51 Configuration::Configuration(const Item
*Root
) : Root((Item
*)Root
), ToFree(false)
55 // Configuration::~Configuration - Destructor /*{{{*/
56 // ---------------------------------------------------------------------
58 Configuration::~Configuration()
72 while (Top
!= 0 && Top
->Next
== 0)
74 Item
*Parent
= Top
->Parent
;
80 Item
*Next
= Top
->Next
;
87 // Configuration::Lookup - Lookup a single item /*{{{*/
88 // ---------------------------------------------------------------------
89 /* This will lookup a single item by name below another item. It is a
90 helper function for the main lookup function */
91 Configuration::Item
*Configuration::Lookup(Item
*Head
,const char *S
,
92 unsigned long const &Len
,bool const &Create
)
95 Item
*I
= Head
->Child
;
96 Item
**Last
= &Head
->Child
;
98 // Empty strings match nothing. They are used for lists.
101 for (; I
!= 0; Last
= &I
->Next
, I
= I
->Next
)
102 if ((Res
= stringcasecmp(I
->Tag
,S
,S
+ Len
)) == 0)
106 for (; I
!= 0; Last
= &I
->Next
, I
= I
->Next
);
114 I
->Tag
.assign(S
,Len
);
121 // Configuration::Lookup - Lookup a fully scoped item /*{{{*/
122 // ---------------------------------------------------------------------
123 /* This performs a fully scoped lookup of a given name, possibly creating
125 Configuration::Item
*Configuration::Lookup(const char *Name
,bool const &Create
)
130 const char *Start
= Name
;
131 const char *End
= Start
+ strlen(Name
);
132 const char *TagEnd
= Name
;
134 for (; End
- TagEnd
>= 2; TagEnd
++)
136 if (TagEnd
[0] == ':' && TagEnd
[1] == ':')
138 Itm
= Lookup(Itm
,Start
,TagEnd
- Start
,Create
);
141 TagEnd
= Start
= TagEnd
+ 2;
145 // This must be a trailing ::, we create unique items in a list
146 if (End
- Start
== 0)
152 Itm
= Lookup(Itm
,Start
,End
- Start
,Create
);
156 // Configuration::Find - Find a value /*{{{*/
157 // ---------------------------------------------------------------------
159 string
Configuration::Find(const char *Name
,const char *Default
) const
161 const Item
*Itm
= Lookup(Name
);
162 if (Itm
== 0 || Itm
->Value
.empty() == true)
173 // Configuration::FindFile - Find a Filename /*{{{*/
174 // ---------------------------------------------------------------------
175 /* Directories are stored as the base dir in the Parent node and the
176 sub directory in sub nodes with the final node being the end filename
178 string
Configuration::FindFile(const char *Name
,const char *Default
) const
180 const Item
*RootItem
= Lookup("RootDir");
181 std::string result
= (RootItem
== 0) ? "" : RootItem
->Value
;
182 if(result
.empty() == false && result
[result
.size() - 1] != '/')
183 result
.push_back('/');
185 const Item
*Itm
= Lookup(Name
);
186 if (Itm
== 0 || Itm
->Value
.empty() == true)
189 result
.append(Default
);
193 string val
= Itm
->Value
;
194 while (Itm
->Parent
!= 0)
196 if (Itm
->Parent
->Value
.empty() == true)
203 if (val
.length() >= 1 && val
[0] == '/')
205 if (val
.compare(0, 9, "/dev/null") == 0)
211 if (val
.length() >= 2 && (val
[0] == '~' || val
[0] == '.') && val
[1] == '/')
215 if (val
.length() >= 3 && val
[0] == '.' && val
[1] == '.' && val
[2] == '/')
218 if (Itm
->Parent
->Value
.end()[-1] != '/')
221 val
.insert(0, Itm
->Parent
->Value
);
227 // do some normalisation by removing // and /./ from the path
228 size_t found
= string::npos
;
229 while ((found
= result
.find("/./")) != string::npos
)
230 result
.replace(found
, 3, "/");
231 while ((found
= result
.find("//")) != string::npos
)
232 result
.replace(found
, 2, "/");
237 // Configuration::FindDir - Find a directory name /*{{{*/
238 // ---------------------------------------------------------------------
239 /* This is like findfile execept the result is terminated in a / */
240 string
Configuration::FindDir(const char *Name
,const char *Default
) const
242 string Res
= FindFile(Name
,Default
);
243 if (Res
.end()[-1] != '/')
245 size_t const found
= Res
.rfind("/dev/null");
246 if (found
!= string::npos
&& found
== Res
.size() - 9)
247 return Res
; // /dev/null returning
253 // Configuration::FindVector - Find a vector of values /*{{{*/
254 // ---------------------------------------------------------------------
255 /* Returns a vector of config values under the given item */
256 vector
<string
> Configuration::FindVector(const char *Name
, std::string
const &Default
, bool const Keys
) const
259 const Item
*Top
= Lookup(Name
);
261 return VectorizeString(Default
, ',');
263 if (Top
->Value
.empty() == false)
264 return VectorizeString(Top
->Value
, ',');
266 Item
*I
= Top
->Child
;
269 Vec
.push_back(Keys
? I
->Tag
: I
->Value
);
272 if (Vec
.empty() == true)
273 return VectorizeString(Default
, ',');
278 // Configuration::FindI - Find an integer value /*{{{*/
279 // ---------------------------------------------------------------------
281 int Configuration::FindI(const char *Name
,int const &Default
) const
283 const Item
*Itm
= Lookup(Name
);
284 if (Itm
== 0 || Itm
->Value
.empty() == true)
288 int Res
= strtol(Itm
->Value
.c_str(),&End
,0);
289 if (End
== Itm
->Value
.c_str())
295 // Configuration::FindB - Find a boolean type /*{{{*/
296 // ---------------------------------------------------------------------
298 bool Configuration::FindB(const char *Name
,bool const &Default
) const
300 const Item
*Itm
= Lookup(Name
);
301 if (Itm
== 0 || Itm
->Value
.empty() == true)
304 return StringToBool(Itm
->Value
,Default
);
307 // Configuration::FindAny - Find an arbitrary type /*{{{*/
308 // ---------------------------------------------------------------------
309 /* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
310 string
Configuration::FindAny(const char *Name
,const char *Default
) const
315 if (key
.size() > 2 && key
.end()[-2] == '/')
317 type
= key
.end()[-1];
318 key
.resize(key
.size() - 2);
325 return FindFile(key
.c_str(), Default
);
329 return FindDir(key
.c_str(), Default
);
333 return FindB(key
, Default
) ? "true" : "false";
339 snprintf(buf
, sizeof(buf
)-1, "%d", FindI(key
, Default
? atoi(Default
) : 0 ));
345 return Find(Name
, Default
);
348 // Configuration::CndSet - Conditinal Set a value /*{{{*/
349 // ---------------------------------------------------------------------
350 /* This will not overwrite */
351 void Configuration::CndSet(const char *Name
,const string
&Value
)
353 Item
*Itm
= Lookup(Name
,true);
356 if (Itm
->Value
.empty() == true)
360 // Configuration::Set - Set an integer value /*{{{*/
361 // ---------------------------------------------------------------------
363 void Configuration::CndSet(const char *Name
,int const Value
)
365 Item
*Itm
= Lookup(Name
,true);
366 if (Itm
== 0 || Itm
->Value
.empty() == false)
369 snprintf(S
,sizeof(S
),"%i",Value
);
373 // Configuration::Set - Set a value /*{{{*/
374 // ---------------------------------------------------------------------
376 void Configuration::Set(const char *Name
,const string
&Value
)
378 Item
*Itm
= Lookup(Name
,true);
384 // Configuration::Set - Set an integer value /*{{{*/
385 // ---------------------------------------------------------------------
387 void Configuration::Set(const char *Name
,int const &Value
)
389 Item
*Itm
= Lookup(Name
,true);
393 snprintf(S
,sizeof(S
),"%i",Value
);
397 // Configuration::Clear - Clear an single value from a list /*{{{*/
398 // ---------------------------------------------------------------------
400 void Configuration::Clear(string
const &Name
, int const &Value
)
403 snprintf(S
,sizeof(S
),"%i",Value
);
407 // Configuration::Clear - Clear an single value from a list /*{{{*/
408 // ---------------------------------------------------------------------
410 void Configuration::Clear(string
const &Name
, string
const &Value
)
412 Item
*Top
= Lookup(Name
.c_str(),false);
413 if (Top
== 0 || Top
->Child
== 0)
416 Item
*Tmp
, *Prev
, *I
;
417 Prev
= I
= Top
->Child
;
421 if(I
->Value
== Value
)
424 // was first element, point parent to new first element
425 if(Top
->Child
== Tmp
)
426 Top
->Child
= I
->Next
;
438 // Configuration::Clear - Clear everything /*{{{*/
439 // ---------------------------------------------------------------------
440 void Configuration::Clear()
442 const Configuration::Item
*Top
= Tree(0);
445 Clear(Top
->FullTag());
450 // Configuration::Clear - Clear an entire tree /*{{{*/
451 // ---------------------------------------------------------------------
453 void Configuration::Clear(string
const &Name
)
455 Item
*Top
= Lookup(Name
.c_str(),false);
471 while (Top
!= 0 && Top
->Next
== 0)
488 // Configuration::Exists - Returns true if the Name exists /*{{{*/
489 // ---------------------------------------------------------------------
491 bool Configuration::Exists(const char *Name
) const
493 const Item
*Itm
= Lookup(Name
);
499 // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
500 // ---------------------------------------------------------------------
501 /* qualified by /[fdbi] exists */
502 bool Configuration::ExistsAny(const char *Name
) const
506 if (key
.size() > 2 && key
.end()[-2] == '/')
508 if (key
.find_first_of("fdbi",key
.size()-1) < key
.size())
510 key
.resize(key
.size() - 2);
511 if (Exists(key
.c_str()))
516 _error
->Warning(_("Unrecognized type abbreviation: '%c'"), key
.end()[-3]);
522 // Configuration::Dump - Dump the config /*{{{*/
523 // ---------------------------------------------------------------------
524 /* Dump the entire configuration space */
525 void Configuration::Dump(ostream
& str
)
527 Dump(str
, NULL
, "%f \"%v\";\n", true);
529 void Configuration::Dump(ostream
& str
, char const * const root
,
530 char const * const formatstr
, bool const emptyValue
)
532 const Configuration::Item
* Top
= Tree(root
);
535 const Configuration::Item
* const Root
= (root
== NULL
) ? NULL
: Top
;
536 std::vector
<std::string
> const format
= VectorizeString(formatstr
, '%');
538 /* Write out all of the configuration directives by walking the
539 configuration tree */
541 if (emptyValue
== true || Top
->Value
.empty() == emptyValue
)
543 std::vector
<std::string
>::const_iterator f
= format
.begin();
545 for (++f
; f
!= format
.end(); ++f
)
547 if (f
->empty() == true)
553 char const type
= (*f
)[0];
555 str
<< Top
->FullTag();
556 else if (type
== 't')
558 else if (type
== 'v')
560 else if (type
== 'F')
561 str
<< QuoteString(Top
->FullTag(), "=\"\n");
562 else if (type
== 'T')
563 str
<< QuoteString(Top
->Tag
, "=\"\n");
564 else if (type
== 'V')
565 str
<< QuoteString(Top
->Value
, "=\"\n");
566 else if (type
== 'n')
568 else if (type
== 'N')
572 str
<< f
->c_str() + 1;
582 while (Top
!= 0 && Top
->Next
== 0)
589 const Configuration::Item
* I
= Top
;
604 // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
605 // ---------------------------------------------------------------------
606 /* Stop sets an optional max recursion depth if this item is being viewed as
607 part of a sub tree. */
608 string
Configuration::Item::FullTag(const Item
*Stop
) const
610 if (Parent
== 0 || Parent
->Parent
== 0 || Parent
== Stop
)
612 return Parent
->FullTag(Stop
) + "::" + Tag
;
616 // ReadConfigFile - Read a configuration file /*{{{*/
617 // ---------------------------------------------------------------------
618 /* The configuration format is very much like the named.conf format
619 used in bind8, in fact this routine can parse most named.conf files.
620 Sectional config files are like bind's named.conf where there are
621 sections like 'zone "foo.org" { .. };' This causes each section to be
622 added in with a tag like "zone::foo.org" instead of being split
623 tag/value. AsSectional enables Sectional parsing.*/
624 bool ReadConfigFile(Configuration
&Conf
,const string
&FName
,bool const &AsSectional
,
625 unsigned const &Depth
)
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());
634 unsigned int StackPos
= 0;
640 bool InComment
= false;
641 while (F
.eof() == false)
643 // The raw input line.
645 // The input line with comments stripped.
646 std::string Fragment
;
648 // Grab the next line of F and place it in Input.
651 char *Buffer
= new char[1024];
654 F
.getline(Buffer
,sizeof(Buffer
) / 2);
659 while (F
.fail() && !F
.eof());
661 // Expand tabs in the input line and remove leading and trailing
664 const int BufferSize
= Input
.size() * 8 + 1;
665 char *Buffer
= new char[BufferSize
];
668 memcpy(Buffer
, Input
.c_str(), Input
.size() + 1);
670 _strtabexpand(Buffer
, BufferSize
);
683 // Now strip comments; if the whole line is contained in a
684 // comment, skip this line.
686 // The first meaningful character in the current fragment; will
687 // be adjusted below as we remove bytes from the front.
688 std::string::const_iterator Start
= Input
.begin();
689 // The last meaningful character in the current fragment.
690 std::string::const_iterator End
= Input
.end();
692 // Multi line comment
693 if (InComment
== true)
695 for (std::string::const_iterator I
= Start
;
698 if (*I
== '*' && I
+ 1 != End
&& I
[1] == '/')
705 if (InComment
== true)
709 // Discard single line comments
710 bool InQuote
= false;
711 for (std::string::const_iterator I
= Start
;
719 if ((*I
== '/' && I
+ 1 != End
&& I
[1] == '/') ||
720 (*I
== '#' && strcmp(string(I
,I
+6).c_str(),"#clear") != 0 &&
721 strcmp(string(I
,I
+8).c_str(),"#include") != 0))
728 // Look for multi line comments and build up the
730 Fragment
.reserve(End
- Start
);
732 for (std::string::const_iterator I
= Start
;
738 Fragment
.push_back(*I
);
739 else if (*I
== '/' && I
+ 1 != End
&& I
[1] == '*')
742 for (std::string::const_iterator J
= I
;
745 if (*J
== '*' && J
+ 1 != End
&& J
[1] == '/')
747 // Pretend we just finished walking over the
748 // comment, and don't add anything to the output
756 if (InComment
== true)
760 Fragment
.push_back(*I
);
764 if (Fragment
.empty())
767 // The line has actual content; interpret what it means.
769 Start
= Fragment
.begin();
770 End
= Fragment
.end();
771 for (std::string::const_iterator I
= Start
;
777 if (InQuote
== false && (*I
== '{' || *I
== ';' || *I
== '}'))
779 // Put the last fragment into the buffer
780 std::string::const_iterator NonWhitespaceStart
= Start
;
781 std::string::const_iterator NonWhitespaceStop
= I
;
782 for (; NonWhitespaceStart
!= I
&& isspace(*NonWhitespaceStart
) != 0; ++NonWhitespaceStart
)
784 for (; NonWhitespaceStop
!= NonWhitespaceStart
&& isspace(NonWhitespaceStop
[-1]) != 0; --NonWhitespaceStop
)
786 if (LineBuffer
.empty() == false && NonWhitespaceStop
- NonWhitespaceStart
!= 0)
788 LineBuffer
+= string(NonWhitespaceStart
, NonWhitespaceStop
);
790 // Drop this from the input string, saving the character
791 // that terminated the construct we just closed. (i.e., a
792 // brace or a semicolon)
797 if (TermChar
== '{' && LineBuffer
.empty() == true)
798 return _error
->Error(_("Syntax error %s:%u: Block starts with no name."),FName
.c_str(),CurLine
);
800 // No string on this line
801 if (LineBuffer
.empty() == true)
806 ParentTag
= string();
808 ParentTag
= Stack
[--StackPos
];
815 const char *Pos
= LineBuffer
.c_str();
816 if (ParseQuoteWord(Pos
,Tag
) == false)
817 return _error
->Error(_("Syntax error %s:%u: Malformed tag"),FName
.c_str(),CurLine
);
819 // Parse off the word
822 if (ParseCWord(Pos
,Word
) == false &&
823 ParseQuoteWord(Pos
,Word
) == false)
833 if (strlen(Pos
) != 0)
834 return _error
->Error(_("Syntax error %s:%u: Extra junk after value"),FName
.c_str(),CurLine
);
839 if (StackPos
< sizeof(Stack
)/sizeof(std::string
))
840 Stack
[StackPos
++] = ParentTag
;
842 /* Make sectional tags incorperate the section into the
844 if (AsSectional
== true && Word
.empty() == false)
851 if (ParentTag
.empty() == true)
854 ParentTag
+= string("::") + Tag
;
858 // Generate the item name
860 if (ParentTag
.empty() == true)
864 if (TermChar
!= '{' || Tag
.empty() == false)
865 Item
= ParentTag
+ "::" + Tag
;
871 if (Tag
.length() >= 1 && Tag
[0] == '#')
873 if (ParentTag
.empty() == false)
874 return _error
->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName
.c_str(),CurLine
);
875 Tag
.erase(Tag
.begin());
878 else if (Tag
== "include")
881 return _error
->Error(_("Syntax error %s:%u: Too many nested includes"),FName
.c_str(),CurLine
);
882 if (Word
.length() > 2 && Word
.end()[-1] == '/')
884 if (ReadConfigDir(Conf
,Word
,AsSectional
,Depth
+1) == false)
885 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
889 if (ReadConfigFile(Conf
,Word
,AsSectional
,Depth
+1) == false)
890 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
894 return _error
->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName
.c_str(),CurLine
,Tag
.c_str());
896 else if (Tag
.empty() == true && NoWord
== false && Word
== "#clear")
897 return _error
->Error(_("Syntax error %s:%u: clear directive requires an option tree as argument"),FName
.c_str(),CurLine
);
900 // Set the item in the configuration class
908 // Move up a tag, but only if there is no bit to parse
914 ParentTag
= Stack
[--StackPos
];
920 // Store the remaining text, if any, in the current line buffer.
922 // NB: could change this to use string-based operations; I'm
923 // using strstrip now to ensure backwards compatibility.
924 // -- dburrows 2008-04-01
926 char *Buffer
= new char[End
- Start
+ 1];
929 std::copy(Start
, End
, Buffer
);
930 Buffer
[End
- Start
] = '\0';
932 const char *Stripd
= _strstrip(Buffer
);
933 if (*Stripd
!= 0 && LineBuffer
.empty() == false)
935 LineBuffer
+= Stripd
;
946 if (LineBuffer
.empty() == false)
947 return _error
->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName
.c_str(),CurLine
);
951 // ReadConfigDir - Read a directory of config files /*{{{*/
952 // ---------------------------------------------------------------------
954 bool ReadConfigDir(Configuration
&Conf
,const string
&Dir
,
955 bool const &AsSectional
, unsigned const &Depth
)
957 vector
<string
> const List
= GetListOfFilesInDir(Dir
, "conf", true, true);
960 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
961 if (ReadConfigFile(Conf
,*I
,AsSectional
,Depth
) == false)
966 // MatchAgainstConfig Constructor /*{{{*/
967 Configuration::MatchAgainstConfig::MatchAgainstConfig(char const * Config
)
969 std::vector
<std::string
> const strings
= _config
->FindVector(Config
);
970 for (std::vector
<std::string
>::const_iterator s
= strings
.begin();
971 s
!= strings
.end(); ++s
)
973 regex_t
*p
= new regex_t
;
974 if (regcomp(p
, s
->c_str(), REG_EXTENDED
| REG_ICASE
| REG_NOSUB
) == 0)
975 patterns
.push_back(p
);
980 _error
->Warning("Invalid regular expression '%s' in configuration "
981 "option '%s' will be ignored.",
986 if (strings
.empty() == true)
987 patterns
.push_back(NULL
);
990 // MatchAgainstConfig Destructor /*{{{*/
991 Configuration::MatchAgainstConfig::~MatchAgainstConfig()
995 void Configuration::MatchAgainstConfig::clearPatterns()
997 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
998 p
!= patterns
.end(); ++p
)
1000 if (*p
== NULL
) continue;
1007 // MatchAgainstConfig::Match - returns true if a pattern matches /*{{{*/
1008 bool Configuration::MatchAgainstConfig::Match(char const * str
) const
1010 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
1011 p
!= patterns
.end(); ++p
)
1012 if (*p
!= NULL
&& regexec(*p
, str
, 0, 0, 0) == 0)