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>
34 Configuration
*_config
= new Configuration
;
36 // Configuration::Configuration - Constructor /*{{{*/
37 // ---------------------------------------------------------------------
39 Configuration::Configuration() : ToFree(true)
43 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] == '/')
200 if (val
.length() >= 2 && (val
[0] == '~' || val
[0] == '.') && val
[1] == '/')
204 if (val
.length() >= 3 && val
[0] == '.' && val
[1] == '.' && val
[2] == '/')
207 if (Itm
->Parent
->Value
.end()[-1] != '/')
210 val
.insert(0, Itm
->Parent
->Value
);
216 // do some normalisation by removing // and /./ from the path
217 size_t found
= string::npos
;
218 while ((found
= result
.find("/./")) != string::npos
)
219 result
.replace(found
, 3, "/");
220 while ((found
= result
.find("//")) != string::npos
)
221 result
.replace(found
, 2, "/");
226 // Configuration::FindDir - Find a directory name /*{{{*/
227 // ---------------------------------------------------------------------
228 /* This is like findfile execept the result is terminated in a / */
229 string
Configuration::FindDir(const char *Name
,const char *Default
) const
231 string Res
= FindFile(Name
,Default
);
232 if (Res
.end()[-1] != '/')
237 // Configuration::FindVector - Find a vector of values /*{{{*/
238 // ---------------------------------------------------------------------
239 /* Returns a vector of config values under the given item */
240 vector
<string
> Configuration::FindVector(const char *Name
) const
243 const Item
*Top
= Lookup(Name
);
247 Item
*I
= Top
->Child
;
250 Vec
.push_back(I
->Value
);
256 // Configuration::FindI - Find an integer value /*{{{*/
257 // ---------------------------------------------------------------------
259 int Configuration::FindI(const char *Name
,int const &Default
) const
261 const Item
*Itm
= Lookup(Name
);
262 if (Itm
== 0 || Itm
->Value
.empty() == true)
266 int Res
= strtol(Itm
->Value
.c_str(),&End
,0);
267 if (End
== Itm
->Value
.c_str())
273 // Configuration::FindB - Find a boolean type /*{{{*/
274 // ---------------------------------------------------------------------
276 bool Configuration::FindB(const char *Name
,bool const &Default
) const
278 const Item
*Itm
= Lookup(Name
);
279 if (Itm
== 0 || Itm
->Value
.empty() == true)
282 return StringToBool(Itm
->Value
,Default
);
285 // Configuration::FindAny - Find an arbitrary type /*{{{*/
286 // ---------------------------------------------------------------------
287 /* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
288 string
Configuration::FindAny(const char *Name
,const char *Default
) const
293 if (key
.size() > 2 && key
.end()[-2] == '/')
295 type
= key
.end()[-1];
296 key
.resize(key
.size() - 2);
303 return FindFile(key
.c_str(), Default
);
307 return FindDir(key
.c_str(), Default
);
311 return FindB(key
, Default
) ? "true" : "false";
317 snprintf(buf
, sizeof(buf
)-1, "%d", FindI(key
, Default
? atoi(Default
) : 0 ));
323 return Find(Name
, Default
);
326 // Configuration::CndSet - Conditinal Set a value /*{{{*/
327 // ---------------------------------------------------------------------
328 /* This will not overwrite */
329 void Configuration::CndSet(const char *Name
,const string
&Value
)
331 Item
*Itm
= Lookup(Name
,true);
334 if (Itm
->Value
.empty() == true)
338 // Configuration::Set - Set an integer value /*{{{*/
339 // ---------------------------------------------------------------------
341 void Configuration::CndSet(const char *Name
,int const Value
)
343 Item
*Itm
= Lookup(Name
,true);
344 if (Itm
== 0 || Itm
->Value
.empty() == false)
347 snprintf(S
,sizeof(S
),"%i",Value
);
351 // Configuration::Set - Set a value /*{{{*/
352 // ---------------------------------------------------------------------
354 void Configuration::Set(const char *Name
,const string
&Value
)
356 Item
*Itm
= Lookup(Name
,true);
362 // Configuration::Set - Set an integer value /*{{{*/
363 // ---------------------------------------------------------------------
365 void Configuration::Set(const char *Name
,int const &Value
)
367 Item
*Itm
= Lookup(Name
,true);
371 snprintf(S
,sizeof(S
),"%i",Value
);
375 // Configuration::Clear - Clear an single value from a list /*{{{*/
376 // ---------------------------------------------------------------------
378 void Configuration::Clear(string
const &Name
, int const &Value
)
381 snprintf(S
,sizeof(S
),"%i",Value
);
385 // Configuration::Clear - Clear an single value from a list /*{{{*/
386 // ---------------------------------------------------------------------
388 void Configuration::Clear(string
const &Name
, string
const &Value
)
390 Item
*Top
= Lookup(Name
.c_str(),false);
391 if (Top
== 0 || Top
->Child
== 0)
394 Item
*Tmp
, *Prev
, *I
;
395 Prev
= I
= Top
->Child
;
399 if(I
->Value
== Value
)
402 // was first element, point parent to new first element
403 if(Top
->Child
== Tmp
)
404 Top
->Child
= I
->Next
;
416 // Configuration::Clear - Clear an entire tree /*{{{*/
417 // ---------------------------------------------------------------------
419 void Configuration::Clear(string
const &Name
)
421 Item
*Top
= Lookup(Name
.c_str(),false);
437 while (Top
!= 0 && Top
->Next
== 0)
454 // Configuration::Exists - Returns true if the Name exists /*{{{*/
455 // ---------------------------------------------------------------------
457 bool Configuration::Exists(const char *Name
) const
459 const Item
*Itm
= Lookup(Name
);
465 // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
466 // ---------------------------------------------------------------------
467 /* qualified by /[fdbi] exists */
468 bool Configuration::ExistsAny(const char *Name
) const
472 if (key
.size() > 2 && key
.end()[-2] == '/')
474 if (key
.find_first_of("fdbi",key
.size()-1) < key
.size())
476 key
.resize(key
.size() - 2);
477 if (Exists(key
.c_str()))
482 _error
->Warning(_("Unrecognized type abbreviation: '%c'"), key
.end()[-3]);
488 // Configuration::Dump - Dump the config /*{{{*/
489 // ---------------------------------------------------------------------
490 /* Dump the entire configuration space */
491 void Configuration::Dump(ostream
& str
)
493 Dump(str
, NULL
, "%f \"%v\";\n", true);
495 void Configuration::Dump(ostream
& str
, char const * const root
,
496 char const * const formatstr
, bool const emptyValue
)
498 const Configuration::Item
* Top
= Tree(root
);
501 const Configuration::Item
* const Root
= (root
== NULL
) ? NULL
: Top
;
502 std::vector
<std::string
> const format
= VectorizeString(formatstr
, '%');
504 /* Write out all of the configuration directives by walking the
505 configuration tree */
507 if (emptyValue
== true || Top
->Value
.empty() == emptyValue
)
509 std::vector
<std::string
>::const_iterator f
= format
.begin();
511 for (++f
; f
!= format
.end(); ++f
)
513 if (f
->empty() == true)
519 char const type
= (*f
)[0];
521 str
<< Top
->FullTag();
522 else if (type
== 't')
524 else if (type
== 'v')
526 else if (type
== 'F')
527 str
<< QuoteString(Top
->FullTag(), "=\"\n");
528 else if (type
== 'T')
529 str
<< QuoteString(Top
->Tag
, "=\"\n");
530 else if (type
== 'V')
531 str
<< QuoteString(Top
->Value
, "=\"\n");
532 else if (type
== 'n')
534 else if (type
== 'N')
538 str
<< f
->c_str() + 1;
548 while (Top
!= 0 && Top
->Next
== 0)
555 const Configuration::Item
* I
= Top
;
570 // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
571 // ---------------------------------------------------------------------
572 /* Stop sets an optional max recursion depth if this item is being viewed as
573 part of a sub tree. */
574 string
Configuration::Item::FullTag(const Item
*Stop
) const
576 if (Parent
== 0 || Parent
->Parent
== 0 || Parent
== Stop
)
578 return Parent
->FullTag(Stop
) + "::" + Tag
;
582 // ReadConfigFile - Read a configuration file /*{{{*/
583 // ---------------------------------------------------------------------
584 /* The configuration format is very much like the named.conf format
585 used in bind8, in fact this routine can parse most named.conf files.
586 Sectional config files are like bind's named.conf where there are
587 sections like 'zone "foo.org" { .. };' This causes each section to be
588 added in with a tag like "zone::foo.org" instead of being split
589 tag/value. AsSectional enables Sectional parsing.*/
590 bool ReadConfigFile(Configuration
&Conf
,const string
&FName
,bool const &AsSectional
,
591 unsigned const &Depth
)
593 // Open the stream for reading
594 ifstream
F(FName
.c_str(),ios::in
);
596 return _error
->Errno("ifstream::ifstream",_("Opening configuration file %s"),FName
.c_str());
600 unsigned int StackPos
= 0;
606 bool InComment
= false;
607 while (F
.eof() == false)
609 // The raw input line.
611 // The input line with comments stripped.
612 std::string Fragment
;
614 // Grab the next line of F and place it in Input.
617 char *Buffer
= new char[1024];
620 F
.getline(Buffer
,sizeof(Buffer
) / 2);
625 while (F
.fail() && !F
.eof());
627 // Expand tabs in the input line and remove leading and trailing
630 const int BufferSize
= Input
.size() * 8 + 1;
631 char *Buffer
= new char[BufferSize
];
634 memcpy(Buffer
, Input
.c_str(), Input
.size() + 1);
636 _strtabexpand(Buffer
, BufferSize
);
649 // Now strip comments; if the whole line is contained in a
650 // comment, skip this line.
652 // The first meaningful character in the current fragment; will
653 // be adjusted below as we remove bytes from the front.
654 std::string::const_iterator Start
= Input
.begin();
655 // The last meaningful character in the current fragment.
656 std::string::const_iterator End
= Input
.end();
658 // Multi line comment
659 if (InComment
== true)
661 for (std::string::const_iterator I
= Start
;
664 if (*I
== '*' && I
+ 1 != End
&& I
[1] == '/')
671 if (InComment
== true)
675 // Discard single line comments
676 bool InQuote
= false;
677 for (std::string::const_iterator I
= Start
;
685 if ((*I
== '/' && I
+ 1 != End
&& I
[1] == '/') ||
686 (*I
== '#' && strcmp(string(I
,I
+6).c_str(),"#clear") != 0 &&
687 strcmp(string(I
,I
+8).c_str(),"#include") != 0))
694 // Look for multi line comments and build up the
696 Fragment
.reserve(End
- Start
);
698 for (std::string::const_iterator I
= Start
;
704 Fragment
.push_back(*I
);
705 else if (*I
== '/' && I
+ 1 != End
&& I
[1] == '*')
708 for (std::string::const_iterator J
= I
;
711 if (*J
== '*' && J
+ 1 != End
&& J
[1] == '/')
713 // Pretend we just finished walking over the
714 // comment, and don't add anything to the output
722 if (InComment
== true)
726 Fragment
.push_back(*I
);
730 if (Fragment
.empty())
733 // The line has actual content; interpret what it means.
735 Start
= Fragment
.begin();
736 End
= Fragment
.end();
737 for (std::string::const_iterator I
= Start
;
743 if (InQuote
== false && (*I
== '{' || *I
== ';' || *I
== '}'))
745 // Put the last fragment into the buffer
746 std::string::const_iterator NonWhitespaceStart
= Start
;
747 std::string::const_iterator NonWhitespaceStop
= I
;
748 for (; NonWhitespaceStart
!= I
&& isspace(*NonWhitespaceStart
) != 0; ++NonWhitespaceStart
)
750 for (; NonWhitespaceStop
!= NonWhitespaceStart
&& isspace(NonWhitespaceStop
[-1]) != 0; --NonWhitespaceStop
)
752 if (LineBuffer
.empty() == false && NonWhitespaceStop
- NonWhitespaceStart
!= 0)
754 LineBuffer
+= string(NonWhitespaceStart
, NonWhitespaceStop
);
756 // Drop this from the input string, saving the character
757 // that terminated the construct we just closed. (i.e., a
758 // brace or a semicolon)
763 if (TermChar
== '{' && LineBuffer
.empty() == true)
764 return _error
->Error(_("Syntax error %s:%u: Block starts with no name."),FName
.c_str(),CurLine
);
766 // No string on this line
767 if (LineBuffer
.empty() == true)
772 ParentTag
= string();
774 ParentTag
= Stack
[--StackPos
];
781 const char *Pos
= LineBuffer
.c_str();
782 if (ParseQuoteWord(Pos
,Tag
) == false)
783 return _error
->Error(_("Syntax error %s:%u: Malformed tag"),FName
.c_str(),CurLine
);
785 // Parse off the word
788 if (ParseCWord(Pos
,Word
) == false &&
789 ParseQuoteWord(Pos
,Word
) == false)
799 if (strlen(Pos
) != 0)
800 return _error
->Error(_("Syntax error %s:%u: Extra junk after value"),FName
.c_str(),CurLine
);
806 Stack
[StackPos
++] = ParentTag
;
808 /* Make sectional tags incorperate the section into the
810 if (AsSectional
== true && Word
.empty() == false)
817 if (ParentTag
.empty() == true)
820 ParentTag
+= string("::") + Tag
;
824 // Generate the item name
826 if (ParentTag
.empty() == true)
830 if (TermChar
!= '{' || Tag
.empty() == false)
831 Item
= ParentTag
+ "::" + Tag
;
837 if (Tag
.length() >= 1 && Tag
[0] == '#')
839 if (ParentTag
.empty() == false)
840 return _error
->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName
.c_str(),CurLine
);
841 Tag
.erase(Tag
.begin());
844 else if (Tag
== "include")
847 return _error
->Error(_("Syntax error %s:%u: Too many nested includes"),FName
.c_str(),CurLine
);
848 if (Word
.length() > 2 && Word
.end()[-1] == '/')
850 if (ReadConfigDir(Conf
,Word
,AsSectional
,Depth
+1) == false)
851 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
855 if (ReadConfigFile(Conf
,Word
,AsSectional
,Depth
+1) == false)
856 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
860 return _error
->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName
.c_str(),CurLine
,Tag
.c_str());
862 else if (Tag
.empty() == true && NoWord
== false && Word
== "#clear")
863 return _error
->Error(_("Syntax error %s:%u: clear directive requires an option tree as argument"),FName
.c_str(),CurLine
);
866 // Set the item in the configuration class
874 // Move up a tag, but only if there is no bit to parse
880 ParentTag
= Stack
[--StackPos
];
886 // Store the remaining text, if any, in the current line buffer.
888 // NB: could change this to use string-based operations; I'm
889 // using strstrip now to ensure backwards compatibility.
890 // -- dburrows 2008-04-01
892 char *Buffer
= new char[End
- Start
+ 1];
895 std::copy(Start
, End
, Buffer
);
896 Buffer
[End
- Start
] = '\0';
898 const char *Stripd
= _strstrip(Buffer
);
899 if (*Stripd
!= 0 && LineBuffer
.empty() == false)
901 LineBuffer
+= Stripd
;
912 if (LineBuffer
.empty() == false)
913 return _error
->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName
.c_str(),CurLine
);
917 // ReadConfigDir - Read a directory of config files /*{{{*/
918 // ---------------------------------------------------------------------
920 bool ReadConfigDir(Configuration
&Conf
,const string
&Dir
,
921 bool const &AsSectional
, unsigned const &Depth
)
923 vector
<string
> const List
= GetListOfFilesInDir(Dir
, "conf", true, true);
926 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
927 if (ReadConfigFile(Conf
,*I
,AsSectional
,Depth
) == false)
932 // MatchAgainstConfig Constructor /*{{{*/
933 Configuration::MatchAgainstConfig::MatchAgainstConfig(char const * Config
)
935 std::vector
<std::string
> const strings
= _config
->FindVector(Config
);
936 for (std::vector
<std::string
>::const_iterator s
= strings
.begin();
937 s
!= strings
.end(); ++s
)
939 regex_t
*p
= new regex_t
;
940 if (regcomp(p
, s
->c_str(), REG_EXTENDED
| REG_ICASE
| REG_NOSUB
) == 0)
941 patterns
.push_back(p
);
946 _error
->Warning("Invalid regular expression '%s' in configuration "
947 "option '%s' will be ignored.",
952 if (strings
.size() == 0)
953 patterns
.push_back(NULL
);
956 // MatchAgainstConfig Destructor /*{{{*/
957 Configuration::MatchAgainstConfig::~MatchAgainstConfig()
961 void Configuration::MatchAgainstConfig::clearPatterns()
963 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
964 p
!= patterns
.end(); ++p
)
966 if (*p
== NULL
) continue;
973 // MatchAgainstConfig::Match - returns true if a pattern matches /*{{{*/
974 bool Configuration::MatchAgainstConfig::Match(char const * str
) const
976 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
977 p
!= patterns
.end(); ++p
)
978 if (*p
!= NULL
&& regexec(*p
, str
, 0, 0, 0) == 0)