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 rootDir
= (RootItem
== 0) ? "" : RootItem
->Value
;
175 if(rootDir
.size() > 0 && rootDir
[rootDir
.size() - 1] != '/')
176 rootDir
.push_back('/');
178 const Item
*Itm
= Lookup(Name
);
179 if (Itm
== 0 || Itm
->Value
.empty() == true)
184 return rootDir
+ Default
;
187 string val
= Itm
->Value
;
188 while (Itm
->Parent
!= 0 && Itm
->Parent
->Value
.empty() == false)
191 if (val
.length() >= 1 && val
[0] == '/')
195 if (val
.length() >= 2 && (val
[0] == '~' || val
[0] == '.') && val
[1] == '/')
199 if (val
.length() >= 3 && val
[0] == '.' && val
[1] == '.' && val
[2] == '/')
202 if (Itm
->Parent
->Value
.end()[-1] != '/')
205 val
.insert(0, Itm
->Parent
->Value
);
209 return rootDir
+ val
;
212 // Configuration::FindDir - Find a directory name /*{{{*/
213 // ---------------------------------------------------------------------
214 /* This is like findfile execept the result is terminated in a / */
215 string
Configuration::FindDir(const char *Name
,const char *Default
) const
217 string Res
= FindFile(Name
,Default
);
218 if (Res
.end()[-1] != '/')
223 // Configuration::FindVector - Find a vector of values /*{{{*/
224 // ---------------------------------------------------------------------
225 /* Returns a vector of config values under the given item */
226 vector
<string
> Configuration::FindVector(const char *Name
) const
229 const Item
*Top
= Lookup(Name
);
233 Item
*I
= Top
->Child
;
236 Vec
.push_back(I
->Value
);
242 // Configuration::FindI - Find an integer value /*{{{*/
243 // ---------------------------------------------------------------------
245 int Configuration::FindI(const char *Name
,int const &Default
) const
247 const Item
*Itm
= Lookup(Name
);
248 if (Itm
== 0 || Itm
->Value
.empty() == true)
252 int Res
= strtol(Itm
->Value
.c_str(),&End
,0);
253 if (End
== Itm
->Value
.c_str())
259 // Configuration::FindB - Find a boolean type /*{{{*/
260 // ---------------------------------------------------------------------
262 bool Configuration::FindB(const char *Name
,bool const &Default
) const
264 const Item
*Itm
= Lookup(Name
);
265 if (Itm
== 0 || Itm
->Value
.empty() == true)
268 return StringToBool(Itm
->Value
,Default
);
271 // Configuration::FindAny - Find an arbitrary type /*{{{*/
272 // ---------------------------------------------------------------------
273 /* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
274 string
Configuration::FindAny(const char *Name
,const char *Default
) const
279 if (key
.size() > 2 && key
.end()[-2] == '/')
281 type
= key
.end()[-1];
282 key
.resize(key
.size() - 2);
289 return FindFile(key
.c_str(), Default
);
293 return FindDir(key
.c_str(), Default
);
297 return FindB(key
, Default
) ? "true" : "false";
303 snprintf(buf
, sizeof(buf
)-1, "%d", FindI(key
, Default
? atoi(Default
) : 0 ));
309 return Find(Name
, Default
);
312 // Configuration::CndSet - Conditinal Set a value /*{{{*/
313 // ---------------------------------------------------------------------
314 /* This will not overwrite */
315 void Configuration::CndSet(const char *Name
,const string
&Value
)
317 Item
*Itm
= Lookup(Name
,true);
320 if (Itm
->Value
.empty() == true)
324 // Configuration::Set - Set an integer value /*{{{*/
325 // ---------------------------------------------------------------------
327 void Configuration::CndSet(const char *Name
,int const Value
)
329 Item
*Itm
= Lookup(Name
,true);
330 if (Itm
== 0 || Itm
->Value
.empty() == false)
333 snprintf(S
,sizeof(S
),"%i",Value
);
337 // Configuration::Set - Set a value /*{{{*/
338 // ---------------------------------------------------------------------
340 void Configuration::Set(const char *Name
,const string
&Value
)
342 Item
*Itm
= Lookup(Name
,true);
348 // Configuration::Set - Set an integer value /*{{{*/
349 // ---------------------------------------------------------------------
351 void Configuration::Set(const char *Name
,int const &Value
)
353 Item
*Itm
= Lookup(Name
,true);
357 snprintf(S
,sizeof(S
),"%i",Value
);
361 // Configuration::Clear - Clear an single value from a list /*{{{*/
362 // ---------------------------------------------------------------------
364 void Configuration::Clear(string
const &Name
, int const &Value
)
367 snprintf(S
,sizeof(S
),"%i",Value
);
371 // Configuration::Clear - Clear an single value from a list /*{{{*/
372 // ---------------------------------------------------------------------
374 void Configuration::Clear(string
const &Name
, string
const &Value
)
376 Item
*Top
= Lookup(Name
.c_str(),false);
377 if (Top
== 0 || Top
->Child
== 0)
380 Item
*Tmp
, *Prev
, *I
;
381 Prev
= I
= Top
->Child
;
385 if(I
->Value
== Value
)
388 // was first element, point parent to new first element
389 if(Top
->Child
== Tmp
)
390 Top
->Child
= I
->Next
;
402 // Configuration::Clear - Clear an entire tree /*{{{*/
403 // ---------------------------------------------------------------------
405 void Configuration::Clear(string
const &Name
)
407 Item
*Top
= Lookup(Name
.c_str(),false);
423 while (Top
!= 0 && Top
->Next
== 0)
440 // Configuration::Exists - Returns true if the Name exists /*{{{*/
441 // ---------------------------------------------------------------------
443 bool Configuration::Exists(const char *Name
) const
445 const Item
*Itm
= Lookup(Name
);
451 // Configuration::ExistsAny - Returns true if the Name, possibly /*{{{*/
452 // ---------------------------------------------------------------------
453 /* qualified by /[fdbi] exists */
454 bool Configuration::ExistsAny(const char *Name
) const
458 if (key
.size() > 2 && key
.end()[-2] == '/')
460 if (key
.find_first_of("fdbi",key
.size()-1) < key
.size())
462 key
.resize(key
.size() - 2);
463 if (Exists(key
.c_str()))
468 _error
->Warning(_("Unrecognized type abbreviation: '%c'"), key
.end()[-3]);
474 // Configuration::Dump - Dump the config /*{{{*/
475 // ---------------------------------------------------------------------
476 /* Dump the entire configuration space */
477 void Configuration::Dump(ostream
& str
)
479 /* Write out all of the configuration directives by walking the
480 configuration tree */
481 const Configuration::Item
*Top
= Tree(0);
484 str
<< Top
->FullTag() << " \"" << Top
->Value
<< "\";" << endl
;
492 while (Top
!= 0 && Top
->Next
== 0)
500 // Configuration::Item::FullTag - Return the fully scoped tag /*{{{*/
501 // ---------------------------------------------------------------------
502 /* Stop sets an optional max recursion depth if this item is being viewed as
503 part of a sub tree. */
504 string
Configuration::Item::FullTag(const Item
*Stop
) const
506 if (Parent
== 0 || Parent
->Parent
== 0 || Parent
== Stop
)
508 return Parent
->FullTag(Stop
) + "::" + Tag
;
512 // ReadConfigFile - Read a configuration file /*{{{*/
513 // ---------------------------------------------------------------------
514 /* The configuration format is very much like the named.conf format
515 used in bind8, in fact this routine can parse most named.conf files.
516 Sectional config files are like bind's named.conf where there are
517 sections like 'zone "foo.org" { .. };' This causes each section to be
518 added in with a tag like "zone::foo.org" instead of being split
519 tag/value. AsSectional enables Sectional parsing.*/
520 bool ReadConfigFile(Configuration
&Conf
,const string
&FName
,bool const &AsSectional
,
521 unsigned const &Depth
)
523 // Open the stream for reading
524 ifstream
F(FName
.c_str(),ios::in
);
526 return _error
->Errno("ifstream::ifstream",_("Opening configuration file %s"),FName
.c_str());
530 unsigned int StackPos
= 0;
536 bool InComment
= false;
537 while (F
.eof() == false)
539 // The raw input line.
541 // The input line with comments stripped.
542 std::string Fragment
;
544 // Grab the next line of F and place it in Input.
547 char *Buffer
= new char[1024];
550 F
.getline(Buffer
,sizeof(Buffer
) / 2);
555 while (F
.fail() && !F
.eof());
557 // Expand tabs in the input line and remove leading and trailing
560 const int BufferSize
= Input
.size() * 8 + 1;
561 char *Buffer
= new char[BufferSize
];
564 memcpy(Buffer
, Input
.c_str(), Input
.size() + 1);
566 _strtabexpand(Buffer
, BufferSize
);
579 // Now strip comments; if the whole line is contained in a
580 // comment, skip this line.
582 // The first meaningful character in the current fragment; will
583 // be adjusted below as we remove bytes from the front.
584 std::string::const_iterator Start
= Input
.begin();
585 // The last meaningful character in the current fragment.
586 std::string::const_iterator End
= Input
.end();
588 // Multi line comment
589 if (InComment
== true)
591 for (std::string::const_iterator I
= Start
;
594 if (*I
== '*' && I
+ 1 != End
&& I
[1] == '/')
601 if (InComment
== true)
605 // Discard single line comments
606 bool InQuote
= false;
607 for (std::string::const_iterator I
= Start
;
615 if ((*I
== '/' && I
+ 1 != End
&& I
[1] == '/') ||
616 (*I
== '#' && strcmp(string(I
,I
+6).c_str(),"#clear") != 0 &&
617 strcmp(string(I
,I
+8).c_str(),"#include") != 0))
624 // Look for multi line comments and build up the
626 Fragment
.reserve(End
- Start
);
628 for (std::string::const_iterator I
= Start
;
634 Fragment
.push_back(*I
);
635 else if (*I
== '/' && I
+ 1 != End
&& I
[1] == '*')
638 for (std::string::const_iterator J
= I
;
641 if (*J
== '*' && J
+ 1 != End
&& J
[1] == '/')
643 // Pretend we just finished walking over the
644 // comment, and don't add anything to the output
652 if (InComment
== true)
656 Fragment
.push_back(*I
);
660 if (Fragment
.empty())
663 // The line has actual content; interpret what it means.
665 Start
= Fragment
.begin();
666 End
= Fragment
.end();
667 for (std::string::const_iterator I
= Start
;
673 if (InQuote
== false && (*I
== '{' || *I
== ';' || *I
== '}'))
675 // Put the last fragment into the buffer
676 std::string::const_iterator NonWhitespaceStart
= Start
;
677 std::string::const_iterator NonWhitespaceStop
= I
;
678 for (; NonWhitespaceStart
!= I
&& isspace(*NonWhitespaceStart
) != 0; ++NonWhitespaceStart
)
680 for (; NonWhitespaceStop
!= NonWhitespaceStart
&& isspace(NonWhitespaceStop
[-1]) != 0; --NonWhitespaceStop
)
682 if (LineBuffer
.empty() == false && NonWhitespaceStop
- NonWhitespaceStart
!= 0)
684 LineBuffer
+= string(NonWhitespaceStart
, NonWhitespaceStop
);
686 // Drop this from the input string, saving the character
687 // that terminated the construct we just closed. (i.e., a
688 // brace or a semicolon)
693 if (TermChar
== '{' && LineBuffer
.empty() == true)
694 return _error
->Error(_("Syntax error %s:%u: Block starts with no name."),FName
.c_str(),CurLine
);
696 // No string on this line
697 if (LineBuffer
.empty() == true)
702 ParentTag
= string();
704 ParentTag
= Stack
[--StackPos
];
711 const char *Pos
= LineBuffer
.c_str();
712 if (ParseQuoteWord(Pos
,Tag
) == false)
713 return _error
->Error(_("Syntax error %s:%u: Malformed tag"),FName
.c_str(),CurLine
);
715 // Parse off the word
718 if (ParseCWord(Pos
,Word
) == false &&
719 ParseQuoteWord(Pos
,Word
) == false)
729 if (strlen(Pos
) != 0)
730 return _error
->Error(_("Syntax error %s:%u: Extra junk after value"),FName
.c_str(),CurLine
);
736 Stack
[StackPos
++] = ParentTag
;
738 /* Make sectional tags incorperate the section into the
740 if (AsSectional
== true && Word
.empty() == false)
747 if (ParentTag
.empty() == true)
750 ParentTag
+= string("::") + Tag
;
754 // Generate the item name
756 if (ParentTag
.empty() == true)
760 if (TermChar
!= '{' || Tag
.empty() == false)
761 Item
= ParentTag
+ "::" + Tag
;
767 if (Tag
.length() >= 1 && Tag
[0] == '#')
769 if (ParentTag
.empty() == false)
770 return _error
->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName
.c_str(),CurLine
);
771 Tag
.erase(Tag
.begin());
774 else if (Tag
== "include")
777 return _error
->Error(_("Syntax error %s:%u: Too many nested includes"),FName
.c_str(),CurLine
);
778 if (Word
.length() > 2 && Word
.end()[-1] == '/')
780 if (ReadConfigDir(Conf
,Word
,AsSectional
,Depth
+1) == false)
781 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
785 if (ReadConfigFile(Conf
,Word
,AsSectional
,Depth
+1) == false)
786 return _error
->Error(_("Syntax error %s:%u: Included from here"),FName
.c_str(),CurLine
);
790 return _error
->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName
.c_str(),CurLine
,Tag
.c_str());
792 else if (Tag
.empty() == true && NoWord
== false && Word
== "#clear")
793 return _error
->Error(_("Syntax error %s:%u: clear directive requires an option tree as argument"),FName
.c_str(),CurLine
);
796 // Set the item in the configuration class
804 // Move up a tag, but only if there is no bit to parse
810 ParentTag
= Stack
[--StackPos
];
816 // Store the remaining text, if any, in the current line buffer.
818 // NB: could change this to use string-based operations; I'm
819 // using strstrip now to ensure backwards compatibility.
820 // -- dburrows 2008-04-01
822 char *Buffer
= new char[End
- Start
+ 1];
825 std::copy(Start
, End
, Buffer
);
826 Buffer
[End
- Start
] = '\0';
828 const char *Stripd
= _strstrip(Buffer
);
829 if (*Stripd
!= 0 && LineBuffer
.empty() == false)
831 LineBuffer
+= Stripd
;
842 if (LineBuffer
.empty() == false)
843 return _error
->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName
.c_str(),CurLine
);
847 // ReadConfigDir - Read a directory of config files /*{{{*/
848 // ---------------------------------------------------------------------
850 bool ReadConfigDir(Configuration
&Conf
,const string
&Dir
,
851 bool const &AsSectional
, unsigned const &Depth
)
853 vector
<string
> const List
= GetListOfFilesInDir(Dir
, "conf", true, true);
856 for (vector
<string
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
857 if (ReadConfigFile(Conf
,*I
,AsSectional
,Depth
) == false)
862 // MatchAgainstConfig Constructor /*{{{*/
863 Configuration::MatchAgainstConfig::MatchAgainstConfig(char const * Config
)
865 std::vector
<std::string
> const strings
= _config
->FindVector(Config
);
866 for (std::vector
<std::string
>::const_iterator s
= strings
.begin();
867 s
!= strings
.end(); ++s
)
869 regex_t
*p
= new regex_t
;
870 if (regcomp(p
, s
->c_str(), REG_EXTENDED
| REG_ICASE
| REG_NOSUB
) == 0)
871 patterns
.push_back(p
);
876 _error
->Warning("Invalid regular expression '%s' in configuration "
877 "option '%s' will be ignored.",
882 if (strings
.size() == 0)
883 patterns
.push_back(NULL
);
886 // MatchAgainstConfig Destructor /*{{{*/
887 Configuration::MatchAgainstConfig::~MatchAgainstConfig()
891 void Configuration::MatchAgainstConfig::clearPatterns()
893 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
894 p
!= patterns
.end(); ++p
)
896 if (*p
== NULL
) continue;
903 // MatchAgainstConfig::Match - returns true if a pattern matches /*{{{*/
904 bool Configuration::MatchAgainstConfig::Match(char const * str
) const
906 for(std::vector
<regex_t
*>::const_iterator p
= patterns
.begin();
907 p
!= patterns
.end(); ++p
)
908 if (*p
!= NULL
&& regexec(*p
, str
, 0, 0, 0) == 0)