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/init.h>
35 Configuration
*_config
= new Configuration
;
37 // Configuration::Configuration - Constructor /*{{{*/
38 // ---------------------------------------------------------------------
40 Configuration::Configuration() : ToFree(true)
44 Configuration::Configuration(const Item
*Root
) : Root((Item
*)Root
), ToFree(false)
48 // Configuration::~Configuration - Destructor /*{{{*/
49 // ---------------------------------------------------------------------
51 Configuration::~Configuration()
65 while (Top
!= 0 && Top
->Next
== 0)
67 Item
*Parent
= Top
->Parent
;
73 Item
*Next
= Top
->Next
;
80 // Configuration::Lookup - Lookup a single item /*{{{*/
81 // ---------------------------------------------------------------------
82 /* This will lookup a single item by name below another item. It is a
83 helper function for the main lookup function */
84 Configuration::Item
*Configuration::Lookup(Item
*Head
,const char *S
,
85 unsigned long const &Len
,bool const &Create
)
88 Item
*I
= Head
->Child
;
89 Item
**Last
= &Head
->Child
;
91 // Empty strings match nothing. They are used for lists.
94 for (; I
!= 0; Last
= &I
->Next
, I
= I
->Next
)
95 if ((Res
= stringcasecmp(I
->Tag
,S
,S
+ Len
)) == 0)
99 for (; I
!= 0; Last
= &I
->Next
, I
= I
->Next
);
107 I
->Tag
.assign(S
,Len
);
114 // Configuration::Lookup - Lookup a fully scoped item /*{{{*/
115 // ---------------------------------------------------------------------
116 /* This performs a fully scoped lookup of a given name, possibly creating
118 Configuration::Item
*Configuration::Lookup(const char *Name
,bool const &Create
)
123 const char *Start
= Name
;
124 const char *End
= Start
+ strlen(Name
);
125 const char *TagEnd
= Name
;
127 for (; End
- TagEnd
>= 2; TagEnd
++)
129 if (TagEnd
[0] == ':' && TagEnd
[1] == ':')
131 Itm
= Lookup(Itm
,Start
,TagEnd
- Start
,Create
);
134 TagEnd
= Start
= TagEnd
+ 2;
138 // This must be a trailing ::, we create unique items in a list
139 if (End
- Start
== 0)
145 Itm
= Lookup(Itm
,Start
,End
- Start
,Create
);
149 // Configuration::Find - Find a value /*{{{*/
150 // ---------------------------------------------------------------------
152 string
Configuration::Find(const char *Name
,const char *Default
) const
154 const Item
*Itm
= Lookup(Name
);
155 if (Itm
== 0 || Itm
->Value
.empty() == true)
166 // Configuration::FindFile - Find a Filename /*{{{*/
167 // ---------------------------------------------------------------------
168 /* Directories are stored as the base dir in the Parent node and the
169 sub directory in sub nodes with the final node being the end filename
171 string
Configuration::FindFile(const char *Name
,const char *Default
) const
173 const Item
*RootItem
= Lookup("RootDir");
174 std::string result
= (RootItem
== 0) ? "" : RootItem
->Value
;
175 if(result
.empty() == false && result
[result
.size() - 1] != '/')
176 result
.push_back('/');
178 const Item
*Itm
= Lookup(Name
);
179 if (Itm
== 0 || Itm
->Value
.empty() == true)
182 result
.append(Default
);
186 string val
= Itm
->Value
;
187 while (Itm
->Parent
!= 0)
189 if (Itm
->Parent
->Value
.empty() == true)
196 if (val
.length() >= 1 && val
[0] == '/')
198 if (val
.compare(0, 9, "/dev/null") == 0)
204 if (val
.length() >= 2 && (val
[0] == '~' || val
[0] == '.') && val
[1] == '/')
208 if (val
.length() >= 3 && val
[0] == '.' && val
[1] == '.' && val
[2] == '/')
211 if (Itm
->Parent
->Value
.end()[-1] != '/')
214 val
.insert(0, Itm
->Parent
->Value
);
220 // do some normalisation by removing // and /./ from the path
221 size_t found
= string::npos
;
222 while ((found
= result
.find("/./")) != string::npos
)
223 result
.replace(found
, 3, "/");
224 while ((found
= result
.find("//")) != string::npos
)
225 result
.replace(found
, 2, "/");
230 // Configuration::FindDir - Find a directory name /*{{{*/
231 // ---------------------------------------------------------------------
232 /* This is like findfile execept the result is terminated in a / */
233 string
Configuration::FindDir(const char *Name
,const char *Default
) const
235 string Res
= FindFile(Name
,Default
);
236 if (Res
.end()[-1] != '/')
238 size_t const found
= Res
.rfind("/dev/null");
239 if (found
!= string::npos
&& found
== Res
.size() - 9)
240 return Res
; // /dev/null returning
246 // Configuration::FindVector - Find a vector of values /*{{{*/
247 // ---------------------------------------------------------------------
248 /* Returns a vector of config values under the given item */
249 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
250 vector
<string
> Configuration::FindVector(const char *Name
) const { return FindVector(Name
, ""); }
252 vector
<string
> Configuration::FindVector(const char *Name
, std::string
const &Default
) const
255 const Item
*Top
= Lookup(Name
);
257 return VectorizeString(Default
, ',');
259 if (Top
->Value
.empty() == false)
260 return VectorizeString(Top
->Value
, ',');
262 Item
*I
= Top
->Child
;
265 Vec
.push_back(I
->Value
);
268 if (Vec
.empty() == true)
269 return VectorizeString(Default
, ',');
274 // Configuration::FindI - Find an integer value /*{{{*/
275 // ---------------------------------------------------------------------
277 int Configuration::FindI(const char *Name
,int const &Default
) const
279 const Item
*Itm
= Lookup(Name
);
280 if (Itm
== 0 || Itm
->Value
.empty() == true)
284 int Res
= strtol(Itm
->Value
.c_str(),&End
,0);
285 if (End
== Itm
->Value
.c_str())
291 // Configuration::FindB - Find a boolean type /*{{{*/
292 // ---------------------------------------------------------------------
294 bool Configuration::FindB(const char *Name
,bool const &Default
) const
296 const Item
*Itm
= Lookup(Name
);
297 if (Itm
== 0 || Itm
->Value
.empty() == true)
300 return StringToBool(Itm
->Value
,Default
);
303 // Configuration::FindAny - Find an arbitrary type /*{{{*/
304 // ---------------------------------------------------------------------
305 /* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
306 string
Configuration::FindAny(const char *Name
,const char *Default
) const
311 if (key
.size() > 2 && key
.end()[-2] == '/')
313 type
= key
.end()[-1];
314 key
.resize(key
.size() - 2);
321 return FindFile(key
.c_str(), Default
);
325 return FindDir(key
.c_str(), Default
);
329 return FindB(key
, Default
) ? "true" : "false";
335 snprintf(buf
, sizeof(buf
)-1, "%d", FindI(key
, Default
? atoi(Default
) : 0 ));
341 return Find(Name
, Default
);
344 // Configuration::CndSet - Conditinal Set a value /*{{{*/
345 // ---------------------------------------------------------------------
346 /* This will not overwrite */
347 void Configuration::CndSet(const char *Name
,const string
&Value
)
349 Item
*Itm
= Lookup(Name
,true);
352 if (Itm
->Value
.empty() == true)
356 // Configuration::Set - Set an integer value /*{{{*/
357 // ---------------------------------------------------------------------
359 void Configuration::CndSet(const char *Name
,int const Value
)
361 Item
*Itm
= Lookup(Name
,true);
362 if (Itm
== 0 || Itm
->Value
.empty() == false)
365 snprintf(S
,sizeof(S
),"%i",Value
);
369 // Configuration::Set - Set a value /*{{{*/
370 // ---------------------------------------------------------------------
372 void Configuration::Set(const char *Name
,const string
&Value
)
374 Item
*Itm
= Lookup(Name
,true);
380 // Configuration::Set - Set an integer value /*{{{*/
381 // ---------------------------------------------------------------------
383 void Configuration::Set(const char *Name
,int const &Value
)
385 Item
*Itm
= Lookup(Name
,true);
389 snprintf(S
,sizeof(S
),"%i",Value
);
393 // Configuration::Clear - Clear an single value from a list /*{{{*/
394 // ---------------------------------------------------------------------
396 void Configuration::Clear(string
const &Name
, int const &Value
)
399 snprintf(S
,sizeof(S
),"%i",Value
);
403 // Configuration::Clear - Clear an single value from a list /*{{{*/
404 // ---------------------------------------------------------------------
406 void Configuration::Clear(string
const &Name
, string
const &Value
)
408 Item
*Top
= Lookup(Name
.c_str(),false);
409 if (Top
== 0 || Top
->Child
== 0)
412 Item
*Tmp
, *Prev
, *I
;
413 Prev
= I
= Top
->Child
;
417 if(I
->Value
== Value
)
420 // was first element, point parent to new first element
421 if(Top
->Child
== Tmp
)
422 Top
->Child
= I
->Next
;
434 // Configuration::Clear - Clear everything /*{{{*/
435 // ---------------------------------------------------------------------
436 void Configuration::Clear()
438 const Configuration::Item
*Top
= Tree(0);
441 Clear(Top
->FullTag());
446 // Configuration::Clear - Clear an entire tree /*{{{*/
447 // ---------------------------------------------------------------------
449 void Configuration::Clear(string
const &Name
)
451 Item
*Top
= Lookup(Name
.c_str(),false);
467 while (Top
!= 0 && Top
->Next
== 0)
484 // Configuration::Exists - Returns true if the Name exists /*{{{*/
485 // ---------------------------------------------------------------------
487 bool Configuration::Exists(const char *Name
) const
489 const Item
*Itm
= Lookup(Name
);
495 // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
496 // ---------------------------------------------------------------------
497 /* qualified by /[fdbi] exists */
498 bool Configuration::ExistsAny(const char *Name
) const
502 if (key
.size() > 2 && key
.end()[-2] == '/')
504 if (key
.find_first_of("fdbi",key
.size()-1) < key
.size())
506 key
.resize(key
.size() - 2);
507 if (Exists(key
.c_str()))
512 _error
->Warning(_("Unrecognized type abbreviation: '%c'"), key
.end()[-3]);
518 // Configuration::Dump - Dump the config /*{{{*/
519 // ---------------------------------------------------------------------
520 /* Dump the entire configuration space */
521 void Configuration::Dump(ostream
& str
)
523 Dump(str
, NULL
, "%f \"%v\";\n", true);
525 void Configuration::Dump(ostream
& str
, char const * const root
,
526 char const * const formatstr
, bool const emptyValue
)
528 const Configuration::Item
* Top
= Tree(root
);
531 const Configuration::Item
* const Root
= (root
== NULL
) ? NULL
: Top
;
532 std::vector
<std::string
> const format
= VectorizeString(formatstr
, '%');
534 /* Write out all of the configuration directives by walking the
535 configuration tree */
537 if (emptyValue
== true || Top
->Value
.empty() == emptyValue
)
539 std::vector
<std::string
>::const_iterator f
= format
.begin();
541 for (++f
; f
!= format
.end(); ++f
)
543 if (f
->empty() == true)
549 char const type
= (*f
)[0];
551 str
<< Top
->FullTag();
552 else if (type
== 't')
554 else if (type
== 'v')
556 else if (type
== 'F')
557 str
<< QuoteString(Top
->FullTag(), "=\"\n");
558 else if (type
== 'T')
559 str
<< QuoteString(Top
->Tag
, "=\"\n");
560 else if (type
== 'V')
561 str
<< QuoteString(Top
->Value
, "=\"\n");
562 else if (type
== 'n')
564 else if (type
== 'N')
568 str
<< f
->c_str() + 1;
578 while (Top
!= 0 && Top
->Next
== 0)
585 const Configuration::Item
* I
= Top
;
600 // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
601 // ---------------------------------------------------------------------
602 /* Stop sets an optional max recursion depth if this item is being viewed as
603 part of a sub tree. */
604 string
Configuration::Item::FullTag(const Item
*Stop
) const
606 if (Parent
== 0 || Parent
->Parent
== 0 || Parent
== Stop
)
608 return Parent
->FullTag(Stop
) + "::" + Tag
;
612 // ReadConfigFile - Read a configuration file /*{{{*/
613 // ---------------------------------------------------------------------
614 /* The configuration format is very much like the named.conf format
615 used in bind8, in fact this routine can parse most named.conf files.
616 Sectional config files are like bind's named.conf where there are
617 sections like 'zone "foo.org" { .. };' This causes each section to be
618 added in with a tag like "zone::foo.org" instead of being split
619 tag/value. AsSectional enables Sectional parsing.*/
620 bool ReadConfigFile(Configuration
&Conf
,const string
&FName
,bool const &AsSectional
,
621 unsigned const &Depth
)
623 // Open the stream for reading
624 ifstream
F(FName
.c_str(),ios::in
);
626 return _error
->Errno("ifstream::ifstream",_("Opening configuration file %s"),FName
.c_str());
630 unsigned int StackPos
= 0;
636 bool InComment
= false;
637 while (F
.eof() == false)
639 // The raw input line.
641 // The input line with comments stripped.
642 std::string Fragment
;
644 // Grab the next line of F and place it in Input.
647 char *Buffer
= new char[1024];
650 F
.getline(Buffer
,sizeof(Buffer
) / 2);
655 while (F
.fail() && !F
.eof());
657 // Expand tabs in the input line and remove leading and trailing
660 const int BufferSize
= Input
.size() * 8 + 1;
661 char *Buffer
= new char[BufferSize
];
664 memcpy(Buffer
, Input
.c_str(), Input
.size() + 1);
666 _strtabexpand(Buffer
, BufferSize
);
679 // Now strip comments; if the whole line is contained in a
680 // comment, skip this line.
682 // The first meaningful character in the current fragment; will
683 // be adjusted below as we remove bytes from the front.
684 std::string::const_iterator Start
= Input
.begin();
685 // The last meaningful character in the current fragment.
686 std::string::const_iterator End
= Input
.end();
688 // Multi line comment
689 if (InComment
== true)
691 for (std::string::const_iterator I
= Start
;
694 if (*I
== '*' && I
+ 1 != End
&& I
[1] == '/')
701 if (InComment
== true)
705 // Discard single line comments
706 bool InQuote
= false;
707 for (std::string::const_iterator I
= Start
;
715 if ((*I
== '/' && I
+ 1 != End
&& I
[1] == '/') ||
716 (*I
== '#' && strcmp(string(I
,I
+6).c_str(),"#clear") != 0 &&
717 strcmp(string(I
,I
+8).c_str(),"#include") != 0))
724 // Look for multi line comments and build up the
726 Fragment
.reserve(End
- Start
);
728 for (std::string::const_iterator I
= Start
;
734 Fragment
.push_back(*I
);
735 else if (*I
== '/' && I
+ 1 != End
&& I
[1] == '*')
738 for (std::string::const_iterator J
= I
;
741 if (*J
== '*' && J
+ 1 != End
&& J
[1] == '/')
743 // Pretend we just finished walking over the
744 // comment, and don't add anything to the output
752 if (InComment
== true)
756 Fragment
.push_back(*I
);
760 if (Fragment
.empty())
763 // The line has actual content; interpret what it means.
765 Start
= Fragment
.begin();
766 End
= Fragment
.end();
767 for (std::string::const_iterator I
= Start
;
773 if (InQuote
== false && (*I
== '{' || *I
== ';' || *I
== '}'))
775 // Put the last fragment into the buffer
776 std::string::const_iterator NonWhitespaceStart
= Start
;
777 std::string::const_iterator NonWhitespaceStop
= I
;
778 for (; NonWhitespaceStart
!= I
&& isspace(*NonWhitespaceStart
) != 0; ++NonWhitespaceStart
)
780 for (; NonWhitespaceStop
!= NonWhitespaceStart
&& isspace(NonWhitespaceStop
[-1]) != 0; --NonWhitespaceStop
)
782 if (LineBuffer
.empty() == false && NonWhitespaceStop
- NonWhitespaceStart
!= 0)
784 LineBuffer
+= string(NonWhitespaceStart
, NonWhitespaceStop
);
786 // Drop this from the input string, saving the character
787 // that terminated the construct we just closed. (i.e., a
788 // brace or a semicolon)
793 if (TermChar
== '{' && LineBuffer
.empty() == true)
794 return _error
->Error(_("Syntax error %s:%u: Block starts with no name."),FName
.c_str(),CurLine
);
796 // No string on this line
797 if (LineBuffer
.empty() == true)
802 ParentTag
= string();
804 ParentTag
= Stack
[--StackPos
];
811 const char *Pos
= LineBuffer
.c_str();
812 if (ParseQuoteWord(Pos
,Tag
) == false)
813 return _error
->Error(_("Syntax error %s:%u: Malformed tag"),FName
.c_str(),CurLine
);
815 // Parse off the word
818 if (ParseCWord(Pos
,Word
) == false &&
819 ParseQuoteWord(Pos
,Word
) == false)
829 if (strlen(Pos
) != 0)
830 return _error
->Error(_("Syntax error %s:%u: Extra junk after value"),FName
.c_str(),CurLine
);
835 if (StackPos
< sizeof(Stack
)/sizeof(std::string
))
836 Stack
[StackPos
++] = ParentTag
;
838 /* Make sectional tags incorperate the section into the
840 if (AsSectional
== true && Word
.empty() == false)
847 if (ParentTag
.empty() == true)
850 ParentTag
+= string("::") + Tag
;
854 // Generate the item name
856 if (ParentTag
.empty() == true)
860 if (TermChar
!= '{' || Tag
.empty() == false)
861 Item
= ParentTag
+ "::" + Tag
;
867 if (Tag
.length() >= 1 && Tag
[0] == '#')
869 if (ParentTag
.empty() == false)
870 return _error
->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName
.c_str(),CurLine
);
871 Tag
.erase(Tag
.begin());
874 else if (Tag
== "include")
877 return _error
->Error(_("Syntax error %s:%u: Too many nested includes"),FName
.c_str(),CurLine
);
878 if (Word
.length() > 2 && Word
.end()[-1] == '/')
880 if (ReadConfigDir(Conf
,Word
,AsSectional
,Depth
+1) == false)
881 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
885 if (ReadConfigFile(Conf
,Word
,AsSectional
,Depth
+1) == false)
886 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
890 return _error
->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName
.c_str(),CurLine
,Tag
.c_str());
892 else if (Tag
.empty() == true && NoWord
== false && Word
== "#clear")
893 return _error
->Error(_("Syntax error %s:%u: clear directive requires an option tree as argument"),FName
.c_str(),CurLine
);
896 // Set the item in the configuration class
904 // Move up a tag, but only if there is no bit to parse
910 ParentTag
= Stack
[--StackPos
];
916 // Store the remaining text, if any, in the current line buffer.
918 // NB: could change this to use string-based operations; I'm
919 // using strstrip now to ensure backwards compatibility.
920 // -- dburrows 2008-04-01
922 char *Buffer
= new char[End
- Start
+ 1];
925 std::copy(Start
, End
, Buffer
);
926 Buffer
[End
- Start
] = '\0';
928 const char *Stripd
= _strstrip(Buffer
);
929 if (*Stripd
!= 0 && LineBuffer
.empty() == false)
931 LineBuffer
+= Stripd
;
942 if (LineBuffer
.empty() == false)
943 return _error
->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName
.c_str(),CurLine
);
947 // ReadConfigDir - Read a directory of config files /*{{{*/
948 // ---------------------------------------------------------------------
950 bool ReadConfigDir(Configuration
&Conf
,const string
&Dir
,
951 bool const &AsSectional
, unsigned const &Depth
)
953 vector
<string
> const List
= GetListOfFilesInDir(Dir
, "conf", true, true);
956 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
957 if (ReadConfigFile(Conf
,*I
,AsSectional
,Depth
) == false)
962 // MatchAgainstConfig Constructor /*{{{*/
963 Configuration::MatchAgainstConfig::MatchAgainstConfig(char const * Config
)
965 std::vector
<std::string
> const strings
= _config
->FindVector(Config
);
966 for (std::vector
<std::string
>::const_iterator s
= strings
.begin();
967 s
!= strings
.end(); ++s
)
969 regex_t
*p
= new regex_t
;
970 if (regcomp(p
, s
->c_str(), REG_EXTENDED
| REG_ICASE
| REG_NOSUB
) == 0)
971 patterns
.push_back(p
);
976 _error
->Warning("Invalid regular expression '%s' in configuration "
977 "option '%s' will be ignored.",
982 if (strings
.empty() == true)
983 patterns
.push_back(NULL
);
986 // MatchAgainstConfig Destructor /*{{{*/
987 Configuration::MatchAgainstConfig::~MatchAgainstConfig()
991 void Configuration::MatchAgainstConfig::clearPatterns()
993 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
994 p
!= patterns
.end(); ++p
)
996 if (*p
== NULL
) continue;
1003 // MatchAgainstConfig::Match - returns true if a pattern matches /*{{{*/
1004 bool Configuration::MatchAgainstConfig::Match(char const * str
) const
1006 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
1007 p
!= patterns
.end(); ++p
)
1008 if (*p
!= NULL
&& regexec(*p
, str
, 0, 0, 0) == 0)