File: arguments.cc

package info (click to toggle)
pdns-recursor 5.3.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,116 kB
  • sloc: cpp: 109,650; javascript: 20,651; python: 5,657; sh: 5,094; makefile: 780; ansic: 582; xml: 37
file content (608 lines) | stat: -rw-r--r-- 16,876 bytes parent folder | download | duplicates (2)
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
/*
 * 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 <climits>

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

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

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

void ArgvMap::setDefault(const string& var, const string& value)
{
  if (defaultmap.count(var) == 0) {
    defaultmap.insert(pair<string, string>(var, value));
  }
}

void ArgvMap::setDefaults()
{
  for (const auto& param : d_params) {
    if (defaultmap.count(param.first) == 0) {
      defaultmap.insert(param);
    }
  }
}

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

vector<string> ArgvMap::list()
{
  vector<string> ret;
  ret.reserve(d_params.size());
  for (const auto& param : d_params) {
    ret.push_back(param.first);
  }
  return ret;
}

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)
{
  const auto& param = d_params.find(var);
  if (param == d_params.end() || param->second.empty()) {
    return false;
  }
  vector<string> parts;

  stringtok(parts, param->second, ", \t");
  return std::find(parts.begin(), parts.end(), val) != parts.end();
}

string ArgvMap::helpstring(string prefix)
{
  if (prefix == "no") {
    prefix = "";
  }

  string help;

  for (const auto& helpitem : helpmap) {
    if (!prefix.empty() && helpitem.first.find(prefix) != 0) { // only print items with prefix
      continue;
    }

    help += "  --";
    help += helpitem.first;

    string type = d_typeMap[helpitem.first];

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

    help += "\n\t";
    help += helpitem.second;
    help += "\n";
  }
  return help;
}

string ArgvMap::formatOne(bool running, bool full, const string& var, const string& help, const string& theDefault, const string& current)
{
  string out;

  if (!running || full) {
    out += "#################################\n";
    out += "# ";
    out += var;
    out += "\t";
    out += help;
    out += "\n#\n";
  }
  else {
    if (theDefault == current) {
      return "";
    }
  }

  if (!running || theDefault == current) {
    out += "# ";
  }

  if (running) {
    out += var + "=" + current + "\n";
    if (full) {
      out += "\n";
    }
  }
  else {
    out += var + "=" + theDefault + "\n\n";
  }

  return out;
}

// If running and full, only changed settings are returned.
string ArgvMap::configstring(bool running, bool full)
{
  string help;

  if (running) {
    help = "# Autogenerated configuration file based on running instance (" + nowTime() + ")\n\n";
  }
  else {
    help = "# Autogenerated configuration file template\n\n";
  }

  // Affects parsing, should come first.
  help += formatOne(running, full, "ignore-unknown-settings", helpmap["ignore-unknown-settings"], defaultmap["ignore-unknown-settings"], d_params["ignore-unknown-settings"]);

  for (const auto& helpitem : helpmap) {
    if (d_typeMap[helpitem.first] == "Command") {
      continue;
    }
    if (helpitem.first == "ignore-unknown-settings") {
      continue;
    }

    if (defaultmap.count(helpitem.first) == 0) {
      throw ArgException(string("Default for setting '") + helpitem.first + "' not set");
    }

    help += formatOne(running, full, helpitem.first, helpitem.second, defaultmap[helpitem.first], d_params[helpitem.first]);
  }

  if (running) {
    for (const auto& unknown : d_unknownParams) {
      help += formatOne(running, full, unknown.first, "unknown setting", "", unknown.second);
    }
  }

  return help;
}

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

  return d_params[arg];
}

mode_t ArgvMap::asMode(const string& arg)
{
  if (!parmIsset(arg)) {
    throw ArgException(string("Undefined but needed argument: '") + arg + "'");
  }

  const auto* const cptr_orig = d_params[arg].c_str();
  char* cptr_ret = nullptr;

  auto 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)
{
  if (!parmIsset(arg)) {
    throw ArgException(string("Undefined but needed argument: '") + arg + "'");
  }

  const auto* cptr_orig = d_params[arg].c_str();
  char* cptr_ret = nullptr;
  auto 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(d_params[arg].c_str()); // NOLINT: called before going multi-threaded
    if (group == nullptr) {
      throw ArgException("'" + arg + string("' contains invalid group"));
    }
    gid = group->gr_gid;
  }
  return gid;
}

uid_t ArgvMap::asUid(const string& arg)
{
  if (!parmIsset(arg)) {
    throw ArgException(string("Undefined but needed argument: '") + arg + "'");
  }

  const auto* cptr_orig = d_params[arg].c_str();
  char* cptr_ret = nullptr;

  auto 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(d_params[arg].c_str()); // NOLINT: called before going multi-threaded
    if (pwent == nullptr) {
      throw ArgException("'" + arg + string("' contains invalid group"));
    }
    uid = pwent->pw_uid;
  }
  return uid;
}

int ArgvMap::asNum(const string& arg, int def)
{
  if (!parmIsset(arg)) {
    throw ArgException(string("Undefined but needed argument: '") + arg + "'");
  }

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

  const auto* cptr_orig = d_params[arg].c_str();
  char* cptr_ret = nullptr;
  auto retval = static_cast<int>(strtol(cptr_orig, &cptr_ret, 0));
  if (retval == 0 && 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 d_params[arg].empty();
}

double ArgvMap::asDouble(const string& arg)
{
  if (!parmIsset(arg)) {
    throw ArgException(string("Undefined but needed argument: '") + arg + "'");
  }

  if (d_params[arg].empty()) {
    return 0.0;
  }

  const auto* cptr_orig = d_params[arg].c_str();
  char* cptr_ret = nullptr;
  auto 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()
{
  set("ignore-unknown-settings", "Configuration settings to ignore if they are unknown") = "";
}

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

// ATM Shared between Recursor and Auth, is that a good idea?
static const map<string, string> deprecateList = {
  {"stats-api-blacklist", "stats-api-disabled-list"},
  {"stats-carbon-blacklist", "stats-carbon-disabled-list"},
  {"stats-rec-control-blacklist", "stats-rec-control-disabled-list"},
  {"stats-snmp-blacklist", "stats-snmp-disabled-list"},
  {"edns-subnet-whitelist", "edns-subnet-allow-list"},
  {"new-domain-whitelist", "new-domain-ignore-list"},
  {"snmp-master-socket", "snmp-daemon-socket"},
  {"xpf-allow-from", "Proxy Protocol"},
  {"xpf-rr-code", "Proxy Protocol"},
  {"domain-metadata-cache-ttl", "zone-metadata-cache-ttl"},
};

// NOLINTNEXTLINE(readability-convert-member-functions-to-static): accesses d_log (compiled out in auth, hence clang-tidy message)
void ArgvMap::warnIfDeprecated(const string& var) const
{
  const auto msg = deprecateList.find(var);
  if (msg != deprecateList.end()) {
    SLOG(g_log << Logger::Warning << "'" << var << "' is deprecated and will be removed in a future release, use '" << msg->second << "' instead" << endl,
         d_log->info(Logr::Warning, "Option is deprecated and will be removed in a future release", "deprecatedName", Logging::Loggable(var), "alternative", Logging::Loggable(msg->second)));
  }
}

string ArgvMap::isDeprecated(const string& var)
{
  const auto msg = deprecateList.find(var);
  return msg != deprecateList.end() ? msg->second : "";
}

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

  if (arg.find("--") == 0 && (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("--") == 0 && (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("--") == 0 && (arg.find('=') == string::npos)) // this is a --daemon case
  {
    var = arg.substr(2);
    val = "";
  }
  else if (arg[0] == '-' && arg.length() > 1) {
    var = arg.substr(1);
    val = "";
  }
  else { // command
    d_cmds.push_back(arg);
  }

  boost::trim(var);

  if (!var.empty() && (parseOnly.empty() || var == parseOnly)) {
    if (!lax) {
      warnIfDeprecated(var);
    }
    pos = val.find_first_not_of(" \t"); // strip leading whitespace
    if (pos != 0 && pos != string::npos) {
      val = val.substr(pos);
    }
    if (parmIsset(var)) {
      if (incremental) {
        if (d_params[var].empty()) {
          if (d_cleared.count(var) == 0) {
            throw ArgException("Incremental setting '" + var + "' without a parent");
          }
          d_params[var] = val;
        }
        else {
          d_params[var] += ", " + val;
        }
      }
      else {
        d_params[var] = val;
        d_cleared.insert(std::move(var));
      }
    }
    else {
      // unknown setting encountered. see if its on the ignore list before throwing.
      vector<string> parts;
      stringtok(parts, d_params["ignore-unknown-settings"], " ,\t\n\r");
      if (find(parts.begin(), parts.end(), var) != parts.end()) {
        d_unknownParams[var] = std::move(val);
        SLOG(g_log << Logger::Warning << "Ignoring unknown setting '" << var << "' as requested" << endl,
             d_log->info(Logr::Warning, "Ignoring unknown setting as requested", "name", Logging::Loggable(var)));
        return;
      }

      if (!lax) {
        throw ArgException("Trying to set unknown setting '" + 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 i = 1; i < argc; i++) {
    parseOne(argv[i], "", lax); // NOLINT: Posix argument parsing
  }
}

void ArgvMap::preParse(int& argc, char** argv, const string& arg)
{
  for (int i = 1; i < argc; i++) {
    string varval = argv[i]; // NOLINT: Posix argument parsing
    if (varval.find("--" + arg) == 0) {
      parseOne(argv[i]); // NOLINT:  Posix argument parsing
    }
  }
}

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

  std::ifstream configFileStream(fname);
  if (!configFileStream) {
    return false;
  }

  while (getline(configFileStream, pline)) {
    boost::trim_right(pline);

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

    line += pline;

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

    // strip trailing spaces
    boost::trim_right(line);

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

    // gpgsql-basic-query=sdfsdfs dfsdfsdf sdfsdfsfd

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

  return true;
}

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

  return parseFile(fname, arg, false);
}

bool ArgvMap::file(const string& fname, bool lax)
{
  return file(fname, lax, false);
}

bool ArgvMap::file(const string& 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)) {
    SLOG(g_log << Logger::Warning << "Unable to open " << fname << std::endl,
         d_log->error(Logr::Warning, "Unable to open file", "name", Logging::Loggable(fname)));
    return false;
  }

  // handle include here (avoid re-include)
  if (!included && !d_params["include-dir"].empty()) {
    std::vector<std::string> extraConfigs;
    gatherIncludes(d_params["include-dir"], ".conf", extraConfigs);
    for (const std::string& filename : extraConfigs) {
      if (!file(filename.c_str(), lax, true)) {
        SLOG(g_log << Logger::Error << filename << " could not be parsed" << std::endl,
             d_log->info(Logr::Error, "Unable to parse config file", "name", Logging::Loggable(filename)));
        throw ArgException(filename + " could not be parsed");
      }
    }
  }

  return true;
}

// NOLINTNEXTLINE(readability-convert-member-functions-to-static): accesses d_log (compiled out in auth, hence clang-tidy message)
void ArgvMap::gatherIncludes(const std::string& directory, const std::string& suffix, std::vector<std::string>& extraConfigs)
{
  if (directory.empty()) {
    return; // nothing to do
  }

  std::vector<std::string> vec;
  auto directoryError = pdns::visit_directory(directory, [this, &directory, &suffix, &vec]([[maybe_unused]] ino_t inodeNumber, const std::string_view& name) {
    (void)this;
    if (boost::starts_with(name, ".")) {
      return true; // skip any dots
    }
    if (boost::ends_with(name, suffix)) {
      // build name
      string fullName = directory + "/" + std::string(name);
      // ensure it's readable file
      struct stat statInfo{};
      if (stat(fullName.c_str(), &statInfo) != 0 || !S_ISREG(statInfo.st_mode)) {
        string msg = fullName + " is not a regular file";
        SLOG(g_log << Logger::Error << msg << std::endl,
             d_log->info(Logr::Error, "Unable to open non-regular file", "name", Logging::Loggable(fullName)));
        throw ArgException(std::move(msg));
      }
      vec.emplace_back(fullName);
    }
    return true;
  });

  if (directoryError) {
    int err = errno;
    string msg = directory + " is not accessible: " + stringerror(err);
    SLOG(g_log << Logger::Error << msg << std::endl,
         d_log->error(Logr::Error, err, "Directory is not accessible", "name", Logging::Loggable(directory)));
    throw ArgException(std::move(msg));
  }

  std::sort(vec.begin(), vec.end(), CIStringComparePOSIX());
  extraConfigs.insert(extraConfigs.end(), vec.begin(), vec.end());
}