File: arguments.cc

package info (click to toggle)
pdns-recursor 4.0.4-1+deb9u3~bpo8+1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 5,484 kB
  • sloc: cpp: 36,380; sh: 11,771; makefile: 305; xml: 37
file content (505 lines) | stat: -rw-r--r-- 12,540 bytes parent folder | download | duplicates (3)
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
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "arguments.hh"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/compare.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include "namespaces.hh"
#include "logger.hh"
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>

const ArgvMap::param_t::const_iterator ArgvMap::begin()
{
  return params.begin();
}

const ArgvMap::param_t::const_iterator ArgvMap::end()
{
  return params.end();
}

string & ArgvMap::set(const string &var)
{
  return params[var];
}

bool ArgvMap::mustDo(const string &var)
{
  return ((*this)[var]!="no") && ((*this)[var]!="off");
}

vector<string>ArgvMap::list()
{
  vector<string> ret;
  for(map<string,string>::const_iterator i=params.begin();i!=params.end();++i)
    ret.push_back(i->first);
  return ret;
}

string ArgvMap::getHelp(const string &item)
{
  return helpmap[item];
}

string & ArgvMap::set(const string &var, const string &help)
{
  helpmap[var]=help;
  d_typeMap[var]="Parameter";
  return set(var);
}

void ArgvMap::setCmd(const string &var, const string &help)
{
  helpmap[var]=help;
  d_typeMap[var]="Command";
  set(var)="no";
}

string & ArgvMap::setSwitch(const string &var, const string &help)
{
  helpmap[var]=help;
  d_typeMap[var]="Switch";
  return set(var);
}


bool ArgvMap::contains(const string &var, const string &val)
{
  params_t::const_iterator param = params.find(var);
  if(param == params.end() || param->second.empty())  {
    return false;
  }
  vector<string> parts;
  vector<string>::const_iterator i;
  
  stringtok( parts, param->second, ", \t" );
  for( i = parts.begin(); i != parts.end(); i++ ) {
    if( *i == val ) {
      return true;
    }
  }

  return false;
}

string ArgvMap::helpstring(string prefix)
{
  if(prefix=="no")
    prefix="";
  
  string help;
  
  for(map<string,string>::const_iterator i=helpmap.begin();
      i!=helpmap.end();
      i++)
    {
      if(!prefix.empty() && i->first.find(prefix)) // only print items with prefix
        continue;

      help+="  --";
      help+=i->first;
      
      string type=d_typeMap[i->first];

      if(type=="Parameter")
        help+="=...";
      else if(type=="Switch")
        {
          help+=" | --"+i->first+"=yes";
          help+=" | --"+i->first+"=no";
        }
      

      help+="\n\t";
      help+=i->second;
      help+="\n";

    }
  return help;
}

string ArgvMap::configstring(bool current)
{
  string help;

  if (current)
    help="# Autogenerated configuration file based on running instance\n";
  else
    help="# Autogenerated configuration file template\n";
  
  for(map<string,string>::const_iterator i=helpmap.begin(); i!=helpmap.end(); i++) {
    if(d_typeMap[i->first]=="Command")
      continue;

    help+="#################################\n";
    help+="# ";
    help+=i->first;
    help+="\t";
    help+=i->second;
    help+="\n#\n";
    if (current) {
      help+=i->first+"="+params[i->first]+"\n\n";
    } else {
      help+="# "+i->first+"="+params[i->first]+"\n\n";
    }
  }
  return help;
}

const string & ArgvMap::operator[](const string &arg)
{
  if(!parmIsset(arg))
    throw ArgException(string("Undefined but needed argument: '")+arg+"'");

  return params[arg];
}

mode_t ArgvMap::asMode(const string &arg) 
{
  mode_t mode;
  const char *cptr_orig;
  char *cptr_ret = NULL;

  if(!parmIsset(arg))
   throw ArgException(string("Undefined but needed argument: '")+arg+"'");

  cptr_orig = params[arg].c_str();
  mode = static_cast<mode_t>(strtol(cptr_orig, &cptr_ret, 8));
  if (mode == 0 && cptr_ret == cptr_orig) 
    throw ArgException("'" + arg + string("' contains invalid octal mode"));
   return mode;
}

gid_t ArgvMap::asGid(const string &arg)
{
  gid_t gid;
  const char *cptr_orig;
  char *cptr_ret = NULL;

  if(!parmIsset(arg))
   throw ArgException(string("Undefined but needed argument: '")+arg+"'");

  cptr_orig = params[arg].c_str();
  gid = static_cast<gid_t>(strtol(cptr_orig, &cptr_ret, 0));
  if (gid == 0 && cptr_ret == cptr_orig) {
    // try to resolve
    struct group *group = getgrnam(params[arg].c_str());
    if (group == NULL)
     throw ArgException("'" + arg + string("' contains invalid group"));
    gid = group->gr_gid;
   }
   return gid;
}

uid_t ArgvMap::asUid(const string &arg)
{
  uid_t uid;
  const char *cptr_orig;
  char *cptr_ret = NULL;

  if(!parmIsset(arg))
   throw ArgException(string("Undefined but needed argument: '")+arg+"'");

  cptr_orig = params[arg].c_str();
  uid = static_cast<uid_t>(strtol(cptr_orig, &cptr_ret, 0));
  if (uid == 0 && cptr_ret == cptr_orig) {
    // try to resolve
    struct passwd *pwent = getpwnam(params[arg].c_str());
    if (pwent == NULL)
     throw ArgException("'" + arg + string("' contains invalid group"));
    uid = pwent->pw_uid;
   }
   return uid;
}

int ArgvMap::asNum(const string &arg, int def)
{
  int retval;
  const char *cptr_orig;
  char *cptr_ret = NULL;

  if(!parmIsset(arg))
    throw ArgException(string("Undefined but needed argument: '")+arg+"'");

  // use default for empty values
  if (params[arg].empty())
   return def;

  cptr_orig = params[arg].c_str();
  retval = static_cast<int>(strtol(cptr_orig, &cptr_ret, 0));
  if (!retval && cptr_ret == cptr_orig)
   throw ArgException("'"+arg+"' value '"+string(cptr_orig) + string( "' is not a valid number"));

  return retval;
}

bool ArgvMap::isEmpty(const string &arg) 
{
   if(!parmIsset(arg))
    return true;
   return params[arg].empty();
}

double ArgvMap::asDouble(const string &arg)
{
  double retval;
  const char *cptr_orig;
  char *cptr_ret = NULL;

  if(!parmIsset(arg))
    throw ArgException(string("Undefined but needed argument: '")+arg+"'");

  if (params[arg].empty())
   return 0.0;

  cptr_orig = params[arg].c_str();
  retval = strtod(cptr_orig, &cptr_ret);
 
  if (retval == 0 && cptr_ret == cptr_orig)
   throw ArgException("'"+arg+string("' is not valid double"));

  return retval;
}

ArgvMap::ArgvMap()
{

}

bool ArgvMap::parmIsset(const string &var)
{
  return (params.find(var)!=params.end());
}

void ArgvMap::parseOne(const string &arg, const string &parseOnly, bool lax)
{
  string var, val;
  string::size_type pos;
  bool incremental = false;

  if(!arg.find("--") && (pos=arg.find("+="))!=string::npos) // this is a --port+=25 case
  {
    var=arg.substr(2,pos-2);
    val=arg.substr(pos+2);
    incremental = true;
  }
  else if(!arg.find("--") && (pos=arg.find("="))!=string::npos)  // this is a --port=25 case
  {
    var=arg.substr(2,pos-2);
    val=arg.substr(pos+1);
  }
  else if(!arg.find("--") && (arg.find("=")==string::npos))  // this is a --daemon case
  {
    var=arg.substr(2);
    val="";
  }
  else if(arg[0]=='-')
  {
    var=arg.substr(1);
    val="";
  }
  else // command
    d_cmds.push_back(arg);
 
  boost::trim(var);

  if(var!="" && (parseOnly.empty() || var==parseOnly)) {
    pos=val.find_first_not_of(" \t");  // strip leading whitespace
    if(pos && pos!=string::npos)
      val=val.substr(pos);
    if(parmIsset(var))
    {
      if(incremental)
      {
        if(params[var].empty())
        {
          if(!d_cleared.count(var))
            throw ArgException("Incremental parameter '"+var+"' without a parent");
          params[var]=val;
        }
        else
          params[var]+=", " + val;
      }
      else
      {
        params[var]=val;
        d_cleared.insert(var);
      }
    }
    else if(!lax)
      throw ArgException("Trying to set unknown parameter '"+var+"'");
  }
}

const vector<string>&ArgvMap::getCommands()
{
  return d_cmds;
}

void ArgvMap::parse(int &argc, char **argv, bool lax)
{
  d_cmds.clear();
  d_cleared.clear();
  for(int n=1;n<argc;n++) {
    parseOne(argv[n],"",lax);
  }
}

void ArgvMap::preParse(int &argc, char **argv, const string &arg)
{
  for(int n=1;n<argc;n++) {
    string varval=argv[n];
    if(!varval.find("--"+arg))
      parseOne(argv[n]);
  }
}

bool ArgvMap::parseFile(const char *fname, const string& arg, bool lax) {
  string line;
  string pline;
  string::size_type pos;

  ifstream f(fname);
  if(!f)
    return false;

  while(getline(f,pline)) {
    trim_right(pline);
    
    if(!pline.empty() && pline[pline.size()-1]=='\\') {
      line+=pline.substr(0,pline.length()-1);
      continue;
    }
    else
      line+=pline;

    // strip everything after a #
    if((pos=line.find("#"))!=string::npos) {
      // make sure it's either first char or has whitespace before
      // fixes issue #354
      if (pos == 0 || std::isspace(line[pos-1]))
        line=line.substr(0,pos);
    }

    // strip trailing spaces
    trim_right(line);

    // strip leading spaces
    if((pos=line.find_first_not_of(" \t\r\n"))!=string::npos)
      line=line.substr(pos);

    // gpgsql-basic-query=sdfsdfs dfsdfsdf sdfsdfsfd

    parseOne( string("--") + line, arg, lax );
    line="";
  }

  return true;
}


bool ArgvMap::preParseFile(const char *fname, const string &arg, const string& theDefault)
{
  params[arg]=theDefault;

  return parseFile(fname, arg, false);
}

bool ArgvMap::file(const char *fname, bool lax)
{
   return file(fname,lax,false);
}

bool ArgvMap::file(const char *fname, bool lax, bool included)
{
  if (!parmIsset("include-dir"))  // inject include-dir
    set("include-dir","Directory to include configuration files from");

  if(!parseFile(fname, "", lax)) {
    L << Logger::Warning << "Unable to open " << fname << std::endl;
    return false;
  }

  // handle include here (avoid re-include)
  if (!included && !params["include-dir"].empty()) {
    std::vector<std::string> extraConfigs;
    gatherIncludes(extraConfigs); 
    for(const std::string& fn :  extraConfigs) {
      if (!file(fn.c_str(), lax, true)) {
        L << Logger::Error << fn << " could not be parsed" << std::endl;
        throw ArgException(fn + " could not be parsed");
      }
    }
  }

  return true;
}

void ArgvMap::gatherIncludes(std::vector<std::string> &extraConfigs) {
  extraConfigs.clear();
  if (params["include-dir"].empty()) return; // nothing to do
    struct stat st;
    DIR *dir;
    struct dirent *ent;

    // stat
    if (stat(params["include-dir"].c_str(), &st)) {
       L << Logger::Error << params["include-dir"] << " does not exist!" << std::endl;
       throw ArgException(params["include-dir"] + " does not exist!");
    }

    // wonder if it's accessible directory
    if (!S_ISDIR(st.st_mode)) {
       L << Logger::Error << params["include-dir"] << " is not a directory" << std::endl;
       throw ArgException(params["include-dir"] + " is not a directory");
    }

    if (!(dir = opendir(params["include-dir"].c_str()))) {
       L << Logger::Error << params["include-dir"] << " is not accessible" << std::endl;
       throw ArgException(params["include-dir"] + " is not accessible");
    }

    while((ent = readdir(dir)) != NULL) {
      if (ent->d_name[0] == '.') continue; // skip any dots
      if (boost::ends_with(ent->d_name, ".conf")) {
        // build name
        std::ostringstream namebuf;
        namebuf << params["include-dir"].c_str() << "/" << ent->d_name; // FIXME: Use some path separator
        // ensure it's readable file
        if (stat(namebuf.str().c_str(), &st) || !S_ISREG(st.st_mode)) {
          L << Logger::Error << namebuf.str() << " is not a file" << std::endl;
          throw ArgException(namebuf.str() + " does not exist!");
        }
        extraConfigs.push_back(namebuf.str());
      }
    }
    std::sort(extraConfigs.begin(), extraConfigs.end(), CIStringComparePOSIX()); 
    closedir(dir);
}