summaryrefslogtreecommitdiff
path: root/apt-pkg/contrib/configuration.cc
blob: 18dded669100721da838567927c7fc7924be1a83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
// -*- mode: cpp; mode: fold -*-
// Description								/*{{{*/
// $Id: configuration.cc,v 1.16 2001/03/03 23:29:55 jgg Exp $
/* ######################################################################

   Configuration Class
   
   This class provides a configuration file and command line parser
   for a tree-oriented configuration environment. All runtime configuration
   is stored in here.
   
   ##################################################################### */
									/*}}}*/
// Include files							/*{{{*/
#ifdef __GNUG__
#pragma implementation "apt-pkg/configuration.h"
#endif
#include <apt-pkg/configuration.h>
#include <apt-pkg/error.h>
#include <apt-pkg/strutl.h>
#include <apt-pkg/fileutl.h>
#include <apti18n.h>

#include <vector>
#include <algorithm>
#include <fstream>
    
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
									/*}}}*/

Configuration *_config = new Configuration;

// Configuration::Configuration - Constructor				/*{{{*/
// ---------------------------------------------------------------------
/* */
Configuration::Configuration() : ToFree(true)
{
   Root = new Item;
}
Configuration::Configuration(const Item *Root) : Root((Item *)Root), ToFree(false)
{
};

									/*}}}*/
// Configuration::~Configuration - Destructor				/*{{{*/
// ---------------------------------------------------------------------
/* */
Configuration::~Configuration()
{
   if (ToFree == false)
      return;
   
   Item *Top = Root;
   for (; Top != 0;)
   {
      if (Top->Child != 0)
      {
	 Top = Top->Child;
	 continue;
      }
            
      while (Top != 0 && Top->Next == 0)
      {
	 Item *Parent = Top->Parent;
	 delete Top;
	 Top = Parent;
      }      
      if (Top != 0)
      {
	 Item *Next = Top->Next;
	 delete Top;
	 Top = Next;
      }
   }
}
									/*}}}*/
// Configuration::Lookup - Lookup a single item				/*{{{*/
// ---------------------------------------------------------------------
/* This will lookup a single item by name below another item. It is a 
   helper function for the main lookup function */
Configuration::Item *Configuration::Lookup(Item *Head,const char *S,
					   unsigned long Len,bool Create)
{
   int Res = 1;
   Item *I = Head->Child;
   Item **Last = &Head->Child;
   
   // Empty strings match nothing. They are used for lists.
   if (Len != 0)
   {
      for (; I != 0; Last = &I->Next, I = I->Next)
	 if ((Res = stringcasecmp(I->Tag.begin(),I->Tag.end(),S,S + Len)) == 0)
	    break;
   }
   else
      for (; I != 0; Last = &I->Next, I = I->Next);
      
   if (Res == 0)
      return I;
   if (Create == false)
      return 0;
   
   I = new Item;
   I->Tag = string(S,Len);
   I->Next = *Last;
   I->Parent = Head;
   *Last = I;
   return I;
}
									/*}}}*/
// Configuration::Lookup - Lookup a fully scoped item			/*{{{*/
// ---------------------------------------------------------------------
/* This performs a fully scoped lookup of a given name, possibly creating
   new items */
Configuration::Item *Configuration::Lookup(const char *Name,bool Create)
{
   if (Name == 0)
      return Root->Child;
   
   const char *Start = Name;
   const char *End = Start + strlen(Name);
   const char *TagEnd = Name;
   Item *Itm = Root;
   for (; End - TagEnd >= 2; TagEnd++)
   {
      if (TagEnd[0] == ':' && TagEnd[1] == ':')
      {
	 Itm = Lookup(Itm,Start,TagEnd - Start,Create);
	 if (Itm == 0)
	    return 0;
	 TagEnd = Start = TagEnd + 2;	 
      }
   }   

   // This must be a trailing ::, we create unique items in a list
   if (End - Start == 0)
   {
      if (Create == false)
	 return 0;
   }
   
   Itm = Lookup(Itm,Start,End - Start,Create);
   return Itm;
}
									/*}}}*/
// Configuration::Find - Find a value					/*{{{*/
// ---------------------------------------------------------------------
/* */
string Configuration::Find(const char *Name,const char *Default) const
{
   const Item *Itm = Lookup(Name);
   if (Itm == 0 || Itm->Value.empty() == true)
   {
      if (Default == 0)
	 return string();
      else
	 return Default;
   }
   
   return Itm->Value;
}
									/*}}}*/
// Configuration::FindFile - Find a Filename				/*{{{*/
// ---------------------------------------------------------------------
/* Directories are stored as the base dir in the Parent node and the
   sub directory in sub nodes with the final node being the end filename
 */
string Configuration::FindFile(const char *Name,const char *Default) const
{
   const Item *Itm = Lookup(Name);
   if (Itm == 0 || Itm->Value.empty() == true)
   {
      if (Default == 0)
	 return string();
      else
	 return Default;
   }
   
   string val = Itm->Value;
   while (Itm->Parent != 0 && Itm->Parent->Value.empty() == false)
   {	 
      // Absolute
      if (val.length() >= 1 && val[0] == '/')
         break;

      // ~/foo or ./foo 
      if (val.length() >= 2 && (val[0] == '~' || val[0] == '.') && val[1] == '/')
	 break;
	 
      // ../foo 
      if (val.length() >= 3 && val[0] == '.' && val[1] == '.' && val[2] == '/')
	 break;
      
      if (Itm->Parent->Value.end()[-1] != '/')
	 val.insert(0, "/");

      val.insert(0, Itm->Parent->Value);
      Itm = Itm->Parent;
   }

   return val;
}
									/*}}}*/
// Configuration::FindDir - Find a directory name			/*{{{*/
// ---------------------------------------------------------------------
/* This is like findfile execept the result is terminated in a / */
string Configuration::FindDir(const char *Name,const char *Default) const
{
   string Res = FindFile(Name,Default);
   if (Res.end()[-1] != '/')
      return Res + '/';
   return Res;
}
									/*}}}*/
// Configuration::FindI - Find an integer value				/*{{{*/
// ---------------------------------------------------------------------
/* */
int Configuration::FindI(const char *Name,int Default) const
{
   const Item *Itm = Lookup(Name);
   if (Itm == 0 || Itm->Value.empty() == true)
      return Default;
   
   char *End;
   int Res = strtol(Itm->Value.c_str(),&End,0);
   if (End == Itm->Value.c_str())
      return Default;
   
   return Res;
}
									/*}}}*/
// Configuration::FindB - Find a boolean type				/*{{{*/
// ---------------------------------------------------------------------
/* */
bool Configuration::FindB(const char *Name,bool Default) const
{
   const Item *Itm = Lookup(Name);
   if (Itm == 0 || Itm->Value.empty() == true)
      return Default;
   
   return StringToBool(Itm->Value,Default);
}
									/*}}}*/
// Configuration::FindAny - Find an arbitrary type			/*{{{*/
// ---------------------------------------------------------------------
/* a key suffix of /f, /d, /b or /i calls Find{File,Dir,B,I} */
string Configuration::FindAny(const char *Name,const char *Default) const
{
   string key = Name;
   char type = 0;

   if (key.size() > 2 && key.end()[-2] == '/')
   {
      type = key.end()[-1];
      key.resize(key.size() - 2);
   }

   switch (type)
   {
      // file
      case 'f': 
      return FindFile(key.c_str(), Default);
      
      // directory
      case 'd': 
      return FindDir(key.c_str(), Default);
      
      // bool
      case 'b': 
      return FindB(key, Default) ? "true" : "false";
      
      // int
      case 'i': 
      {
	 char buf[16];
	 snprintf(buf, sizeof(buf)-1, "%d", FindI(key, Default));
	 return buf;
      }
   }

   // fallback
   return Find(Name, Default);
}
									/*}}}*/
// Configuration::CndSet - Conditinal Set a value			/*{{{*/
// ---------------------------------------------------------------------
/* This will not overwrite */
void Configuration::CndSet(const char *Name,string Value)
{
   Item *Itm = Lookup(Name,true);
   if (Itm == 0)
      return;
   if (Itm->Value.empty() == true)
      Itm->Value = Value;
}
									/*}}}*/
// Configuration::Set - Set a value					/*{{{*/
// ---------------------------------------------------------------------
/* */
void Configuration::Set(const char *Name,string Value)
{
   Item *Itm = Lookup(Name,true);
   if (Itm == 0)
      return;
   Itm->Value = Value;
}
									/*}}}*/
// Configuration::Set - Set an integer value				/*{{{*/
// ---------------------------------------------------------------------
/* */
void Configuration::Set(const char *Name,int Value)
{
   Item *Itm = Lookup(Name,true);
   if (Itm == 0)
      return;
   char S[300];
   snprintf(S,sizeof(S),"%i",Value);
   Itm->Value = S;
}
									/*}}}*/
// Configuration::Clear - Clear an entire tree				/*{{{*/
// ---------------------------------------------------------------------
/* */
void Configuration::Clear(string Name)
{
   Item *Top = Lookup(Name.c_str(),false);
   if (Top == 0)
      return;
   
   Top->Value = string();
   Item *Stop = Top;
   Top = Top->Child;
   Stop->Child = 0;
   for (; Top != 0;)
   {
      if (Top->Child != 0)
      {
	 Top = Top->Child;
	 continue;
      }

      while (Top != 0 && Top->Next == 0)
      {
	 Item *Tmp = Top;
	 Top = Top->Parent;
	 delete Tmp;
	 
	 if (Top == Stop)
	    return;
      }
      
      Item *Tmp = Top;
      if (Top != 0)
	 Top = Top->Next;
      delete Tmp;
   }
}
									/*}}}*/
// Configuration::Exists - Returns true if the Name exists		/*{{{*/
// ---------------------------------------------------------------------
/* */
bool Configuration::Exists(const char *Name) const
{
   const Item *Itm = Lookup(Name);
   if (Itm == 0)
      return false;
   return true;
}
									/*}}}*/
// Configuration::ExistsAny - Returns true if the Name, possibly	/*{{{*/
// ---------------------------------------------------------------------
/* qualified by /[fdbi] exists */
bool Configuration::ExistsAny(const char *Name) const
{
   string key = Name;

   if (key.size() > 2 && key.end()[-2] == '/' &&
       key.find_first_of("fdbi",key.size()-1) < key.size())
   {
      key.resize(key.size() - 2);
      if (Exists(key.c_str()))
	 return true;
   }

   return Exists(Name);
}
									/*}}}*/
// Configuration::Dump - Dump the config				/*{{{*/
// ---------------------------------------------------------------------
/* Dump the entire configuration space */
void Configuration::Dump()
{
   /* Write out all of the configuration directives by walking the 
      configuration tree */
   const Configuration::Item *Top = Tree(0);
   for (; Top != 0;)
   {
      clog << Top->FullTag() << " \"" << Top->Value << "\";" << endl;
      
      if (Top->Child != 0)
      {
	 Top = Top->Child;
	 continue;
      }
      
      while (Top != 0 && Top->Next == 0)
	 Top = Top->Parent;
      if (Top != 0)
	 Top = Top->Next;
   }
}
									/*}}}*/

// Configuration::Item::FullTag - Return the fully scoped tag		/*{{{*/
// ---------------------------------------------------------------------
/* Stop sets an optional max recursion depth if this item is being viewed as
   part of a sub tree. */
string Configuration::Item::FullTag(const Item *Stop) const
{
   if (Parent == 0 || Parent->Parent == 0 || Parent == Stop)
      return Tag;
   return Parent->FullTag(Stop) + "::" + Tag;
}
									/*}}}*/

// ReadConfigFile - Read a configuration file				/*{{{*/
// ---------------------------------------------------------------------
/* The configuration format is very much like the named.conf format
   used in bind8, in fact this routine can parse most named.conf files. 
   Sectional config files are like bind's named.conf where there are 
   sections like 'zone "foo.org" { .. };' This causes each section to be
   added in with a tag like "zone::foo.org" instead of being split 
   tag/value. */
bool ReadConfigFile(Configuration &Conf,string FName,bool AsSectional,
		    unsigned Depth)
{   
   // Open the stream for reading
   ifstream F(FName.c_str(),ios::in | ios::nocreate);
   if (!F != 0)
      return _error->Errno("ifstream::ifstream",_("Opening configuration file %s"),FName.c_str());
   
   char Buffer[300];
   string LineBuffer;
   string Stack[100];
   unsigned int StackPos = 0;
   
   // Parser state
   string ParentTag;
   
   int CurLine = 0;
   bool InComment = false;
   while (F.eof() == false)
   {
      F.getline(Buffer,sizeof(Buffer));
      CurLine++;
      _strtabexpand(Buffer,sizeof(Buffer));
      _strstrip(Buffer);

      // Multi line comment
      if (InComment == true)
      {
	 for (const char *I = Buffer; *I != 0; I++)
	 {
	    if (*I == '*' && I[1] == '/')
	    {
	       memmove(Buffer,I+2,strlen(I+2) + 1);
	       InComment = false;
	       break;
	    }	    
	 }
	 if (InComment == true)
	    continue;
      }
      
      // Discard single line comments
      bool InQuote = false;
      for (char *I = Buffer; *I != 0; I++)
      {
	 if (*I == '"')
	    InQuote = !InQuote;
	 if (InQuote == true)
	    continue;
	 
	 if (*I == '/' && I[1] == '/')
         {
	    *I = 0;
	    break;
	 }
      }

      // Look for multi line comments
      InQuote = false;
      for (char *I = Buffer; *I != 0; I++)
      {
	 if (*I == '"')
	    InQuote = !InQuote;
	 if (InQuote == true)
	    continue;
	 
	 if (*I == '/' && I[1] == '*')
         {
	    InComment = true;
	    for (char *J = Buffer; *J != 0; J++)
	    {
	       if (*J == '*' && J[1] == '/')
	       {
		  memmove(I,J+2,strlen(J+2) + 1);
		  InComment = false;
		  break;
	       }	       
	    }
	    
	    if (InComment == true)
	    {
	       *I = 0;
	       break;
	    }	    
	 }
      }
      
      // Blank
      if (Buffer[0] == 0)
	 continue;
      
      // We now have a valid line fragment
      InQuote = false;
      for (char *I = Buffer; *I != 0;)
      {
	 if (*I == '"')
	    InQuote = !InQuote;
	 
	 if (InQuote == false && (*I == '{' || *I == ';' || *I == '}'))
	 {
	    // Put the last fragment into the buffer
	    char *Start = Buffer;
	    char *Stop = I;
	    for (; Start != I && isspace(*Start) != 0; Start++);
	    for (; Stop != Start && isspace(Stop[-1]) != 0; Stop--);
	    if (LineBuffer.empty() == false && Stop - Start != 0)
	       LineBuffer += ' ';
	    LineBuffer += string(Start,Stop - Start);
	    
	    // Remove the fragment
	    char TermChar = *I;
	    memmove(Buffer,I + 1,strlen(I + 1) + 1);
	    I = Buffer;
	    
	    // Syntax Error
	    if (TermChar == '{' && LineBuffer.empty() == true)
	       return _error->Error(_("Syntax error %s:%u: Block starts with no name."),FName.c_str(),CurLine);
	    
	    // No string on this line
	    if (LineBuffer.empty() == true)
	    {
	       if (TermChar == '}')
	       {
		  if (StackPos == 0)
		     ParentTag = string();
		  else
		     ParentTag = Stack[--StackPos];
	       }
	       continue;
	    }
	    
	    // Parse off the tag
	    string Tag;
	    const char *Pos = LineBuffer.c_str();
	    if (ParseQuoteWord(Pos,Tag) == false)
	       return _error->Error(_("Syntax error %s:%u: Malformed Tag"),FName.c_str(),CurLine);

	    // Parse off the word
	    string Word;
	    if (ParseCWord(Pos,Word) == false &&
		ParseQuoteWord(Pos,Word) == false)
	    {
	       if (TermChar != '{')
	       {
		  Word = Tag;
		  Tag = "";
	       }	       
	    }
	    if (strlen(Pos) != 0)
	       return _error->Error(_("Syntax error %s:%u: Extra junk after value"),FName.c_str(),CurLine);

	    // Go down a level
	    if (TermChar == '{')
	    {
	       if (StackPos <= 100)
		  Stack[StackPos++] = ParentTag;
	       
	       /* Make sectional tags incorperate the section into the
	          tag string */
	       if (AsSectional == true && Word.empty() == false)
	       {
		  Tag += "::" ;
		  Tag += Word;
		  Word = "";
	       }
	       
	       if (ParentTag.empty() == true)
		  ParentTag = Tag;
	       else
		  ParentTag += string("::") + Tag;
	       Tag = string();
	    }
	    
	    // Generate the item name
	    string Item;
	    if (ParentTag.empty() == true)
	       Item = Tag;
	    else
	    {
	       if (TermChar != '{' || Tag.empty() == false)
		  Item = ParentTag + "::" + Tag;
	       else
		  Item = ParentTag;
	    }
	    
	    // Specials
	    if (Tag.length() >= 1 && Tag[0] == '#')
	    {
	       if (ParentTag.empty() == false)
		  return _error->Error(_("Syntax error %s:%u: Directives can only be done at the top level"),FName.c_str(),CurLine);
	       Tag.erase(Tag.begin());
	       if (Tag == "clear")
		  Conf.Clear(Word);
	       else if (Tag == "include")
	       {
		  if (Depth > 10)
		     return _error->Error(_("Syntax error %s:%u: Too many nested includes"),FName.c_str(),CurLine);
		  if (Word.length() > 2 && Word.end()[-1] == '/')
		  {
		     if (ReadConfigDir(Conf,Word,AsSectional,Depth+1) == false)
			return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
		  }
		  else
		  {
		     if (ReadConfigFile(Conf,Word,AsSectional,Depth+1) == false)
			return _error->Error(_("Syntax error %s:%u: Included from here"),FName.c_str(),CurLine);
		  }		  
	       }
	       else
		  return _error->Error(_("Syntax error %s:%u: Unsupported directive '%s'"),FName.c_str(),CurLine,Tag.c_str());
	    }
	    else
	    {
	       // Set the item in the configuration class
	       Conf.Set(Item,Word);
	    }
	    
	    // Empty the buffer
	    LineBuffer = string();
	    
	    // Move up a tag, but only if there is no bit to parse
	    if (TermChar == '}')
	    {
	       if (StackPos == 0)
		  ParentTag = string();
	       else
		  ParentTag = Stack[--StackPos];
	    }
	    
	 }
	 else
	    I++;
      }

      // Store the fragment
      const char *Stripd = _strstrip(Buffer);
      if (*Stripd != 0 && LineBuffer.empty() == false)
	 LineBuffer += " ";
      LineBuffer += Stripd;
   }

   if (LineBuffer.empty() == false)
      return _error->Error(_("Syntax error %s:%u: Extra junk at end of file"),FName.c_str(),CurLine);
   return true;
}
									/*}}}*/
// ReadConfigDir - Read a directory of config files			/*{{{*/
// ---------------------------------------------------------------------
/* */
bool ReadConfigDir(Configuration &Conf,string Dir,bool AsSectional,
		    unsigned Depth)
{   
   static const char *BadExts[] = {".disabled",".dpkg-old",".dpkg-dist",
   				   ".rpmsave",".rpmorig","~",",v",0};
   
   DIR *D = opendir(Dir.c_str());
   if (D == 0)
      return _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());

   vector<string> List;
   
   for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
   {
      if (Ent->d_name[0] == '.')
	 continue;
      
      // Skip bad extensions
      const char **I;
      for (I = BadExts; *I != 0; I++)
      {
	 if (strcmp(Ent->d_name + strlen(Ent->d_name) - strlen(*I),*I) == 0)
	    break;
      }
      
      if (*I != 0)
	 continue;
      
      // Make sure it is a file and not something else
      string File = flCombine(Dir,Ent->d_name);
      struct stat St;
      if (stat(File.c_str(),&St) != 0 || S_ISREG(St.st_mode) == 0)
	 continue;
      
      List.push_back(File);      
   }   
   closedir(D);
   
   sort(List.begin(),List.end());

   // Read the files
   for (vector<string>::const_iterator I = List.begin(); I != List.end(); I++)
      if (ReadConfigFile(Conf,*I,AsSectional,Depth) == false)
	 return false;
   return true;
}
									/*}}}*/