File: zoneparser-tng.cc

package info (click to toggle)
pdns-recursor 4.4.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 7,756 kB
  • sloc: cpp: 68,610; javascript: 26,596; sh: 4,673; makefile: 591; xml: 37
file content (563 lines) | stat: -rw-r--r-- 16,292 bytes parent folder | download
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
/*
 * 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 "ascii.hh"
#include "dnsparser.hh"
#include "sstuff.hh"
#include "misc.hh"
#include "dnswriter.hh"
#include "dnsrecords.hh"
#include "misc.hh"
#include <fstream>
#include "dns.hh"
#include "zoneparser-tng.hh"
#include <deque>
#include <boost/algorithm/string.hpp>
#include <system_error>

static string g_INstr("IN");

ZoneParserTNG::ZoneParserTNG(const string& fname, const DNSName& zname, const string& reldir) : d_reldir(reldir), 
                                                                                               d_zonename(zname), d_defaultttl(3600), 
                                                                                               d_templatecounter(0), d_templatestop(0),
                                                                                               d_templatestep(0), d_havedollarttl(false){
  stackFile(fname);
}

ZoneParserTNG::ZoneParserTNG(const vector<string> zonedata, const DNSName& zname):
  d_zonename(zname), d_zonedata(zonedata), d_defaultttl(3600),
  d_templatecounter(0), d_templatestop(0), d_templatestep(0),
  d_havedollarttl(false), d_fromfile(false)
{
  d_zonedataline = d_zonedata.begin();
}

void ZoneParserTNG::stackFile(const std::string& fname)
{
  FILE *fp=fopen(fname.c_str(), "r");
  if(!fp) {
    std::error_code ec (errno,std::generic_category());
    throw std::system_error(ec, "Unable to open file '"+fname+"': "+stringerror());
  }

  filestate fs(fp, fname);
  d_filestates.push(fs);
  d_fromfile = true;
}

ZoneParserTNG::~ZoneParserTNG()
{
  while(!d_filestates.empty()) {
    fclose(d_filestates.top().d_fp);
    d_filestates.pop();
  }
}

static string makeString(const string& line, const pair<string::size_type, string::size_type>& range)
{
  return string(line.c_str() + range.first, range.second - range.first);
}

static bool isTimeSpec(const string& nextpart)
{
  if(nextpart.empty())
    return false;
  for(string::const_iterator iter = nextpart.begin(); iter != nextpart.end(); ++iter) {
    if(isdigit(*iter))
      continue;
    if(iter+1 != nextpart.end())
      return false;
    char c=tolower(*iter);
    return (c=='s' || c=='m' || c=='h' || c=='d' || c=='w' || c=='y');
  }
  return true;
}


unsigned int ZoneParserTNG::makeTTLFromZone(const string& str)
{
  if(str.empty())
    return 0;

  unsigned int val;
  try {
    val=pdns_stou(str);
  }
  catch (const std::out_of_range& oor) {
    throw PDNSException("Unable to parse time specification '"+str+"' "+getLineOfFile());
  }

  char lc=dns_tolower(str[str.length()-1]);
  if(!isdigit(lc))
    switch(lc) {
    case 's':
      break;
    case 'm':
      val*=60; // minutes, not months!
      break;
    case 'h':
      val*=3600;
      break;
    case 'd':
      val*=3600*24;
      break;
    case 'w':
      val*=3600*24*7;
      break;
    case 'y': // ? :-)
      val*=3600*24*365;
      break;

    default:
      throw PDNSException("Unable to parse time specification '"+str+"' "+getLineOfFile());
    }
  return val;
}

bool ZoneParserTNG::getTemplateLine()
{
  if(d_templateparts.empty() || d_templatecounter > d_templatestop) // no template, or done with
    return false;

  string retline;
  for(parts_t::const_iterator iter = d_templateparts.begin() ; iter != d_templateparts.end(); ++iter) {
    if(iter != d_templateparts.begin())
      retline+=" ";

    string part=makeString(d_templateline, *iter);
    
    /* a part can contain a 'naked' $, an escaped $ (\$), or ${offset,width,radix}, with width defaulting to 0, 
       and radix being 'd', 'o', 'x' or 'X', defaulting to 'd'. 

       The width is zero-padded, so if the counter is at 1, the offset is 15, with is 3, and the radix is 'x',
       output will be '010', from the input of ${15,3,x}
    */

    string outpart;
    outpart.reserve(part.size()+5);
    bool inescape=false;

    for(string::size_type pos = 0; pos < part.size() ; ++pos) {
      char c=part[pos];
      if(inescape) {
        outpart.append(1, c);
        inescape=false;
        continue;
      }
        
      if(part[pos]=='\\') {
        inescape=true;
        continue;
      }
      if(c=='$') {
        if(pos + 1 == part.size() || part[pos+1]!='{') {  // a trailing $, or not followed by {
          outpart.append(std::to_string(d_templatecounter));
          continue;
        }
        
        // need to deal with { case 
        
        pos+=2;
        string::size_type startPos=pos;
        for(; pos < part.size() && part[pos]!='}' ; ++pos)
          ;
        
        if(pos == part.size()) // partial spec
          break;

        // we are on the '}'

        string spec(part.c_str() + startPos, part.c_str() + pos);
        int offset=0, width=0;
        char radix='d';
        sscanf(spec.c_str(), "%d,%d,%c", &offset, &width, &radix);  // parse format specifier

        char tmp[80];
        switch (radix) {
        case 'o':
          snprintf(tmp, sizeof(tmp), "%0*o", width, d_templatecounter + offset);
          break;
        case 'x':
          snprintf(tmp, sizeof(tmp), "%0*x", width, d_templatecounter + offset);
          break;
        case 'X':
          snprintf(tmp, sizeof(tmp), "%0*X", width, d_templatecounter + offset);
          break;
        case 'd':
        default:
          snprintf(tmp, sizeof(tmp), "%0*d", width, d_templatecounter + offset);
          break;
        }
        outpart+=tmp;
      }
      else
        outpart.append(1, c);
    }
    retline+=outpart;
  }
  d_templatecounter+=d_templatestep;

  d_line = retline;
  return true;
}

static void chopComment(string& line)
{
  if(line.find(';')==string::npos)
    return;
  string::size_type pos, len = line.length();
  bool inQuote=false;
  for(pos = 0 ; pos < len; ++pos) {
    if(line[pos]=='\\') 
      pos++;
    else if(line[pos]=='"') 
      inQuote=!inQuote;
    else if(line[pos]==';' && !inQuote)
      break;
  }
  if(pos != len)
    line.resize(pos);
}

static bool findAndElide(string& line, char c)
{
  string::size_type pos, len = line.length();
  bool inQuote=false;
  for(pos = 0 ; pos < len; ++pos) {
    if(line[pos]=='\\') 
      pos++;
    else if(line[pos]=='"') 
      inQuote=!inQuote;
    else if(line[pos]==c && !inQuote)
      break;
  }
  if(pos != len) {
    line.erase(pos, 1);
    return true;
  }
  return false;
}

DNSName ZoneParserTNG::getZoneName()
{
  return d_zonename;
}

string ZoneParserTNG::getLineOfFile()
{
  if (d_zonedata.size() > 0)
    return "on line "+std::to_string(std::distance(d_zonedata.begin(), d_zonedataline))+" of given string";

  if (d_filestates.empty())
    return "";

  return "on line "+std::to_string(d_filestates.top().d_lineno)+" of file '"+d_filestates.top().d_filename+"'";
}

pair<string,int> ZoneParserTNG::getLineNumAndFile()
{
  if (d_filestates.empty())
    return {"", 0};
  else
    return {d_filestates.top().d_filename, d_filestates.top().d_lineno};
}

bool ZoneParserTNG::get(DNSResourceRecord& rr, std::string* comment)
{
 retry:;
  if(!getTemplateLine() && !getLine())
    return false;

  boost::trim_right_if(d_line, is_any_of(" \t\r\n\x1a"));
  if(comment)
    comment->clear();
  if(comment && d_line.find(';') != string::npos)
    *comment = d_line.substr(d_line.find(';'));

  d_parts.clear();
  vstringtok(d_parts, d_line);

  if(d_parts.empty())
    goto retry;

  if(d_parts[0].first != d_parts[0].second && d_line[d_parts[0].first]==';') // line consisting of nothing but comments
    goto retry;

  if(d_line[0]=='$') { 
    string command=makeString(d_line, d_parts[0]);
    if(pdns_iequals(command,"$TTL") && d_parts.size() > 1) {
      d_defaultttl=makeTTLFromZone(trim_right_copy_if(makeString(d_line, d_parts[1]), is_any_of(";")));
      d_havedollarttl=true;
    }
    else if(pdns_iequals(command,"$INCLUDE") && d_parts.size() > 1 && d_fromfile) {
      string fname=unquotify(makeString(d_line, d_parts[1]));
      if(!fname.empty() && fname[0]!='/' && !d_reldir.empty())
        fname=d_reldir+"/"+fname;
      stackFile(fname);
    }
    else if(pdns_iequals(command, "$ORIGIN") && d_parts.size() > 1) {
      d_zonename = DNSName(makeString(d_line, d_parts[1]));
    }
    else if(pdns_iequals(command, "$GENERATE") && d_parts.size() > 2) {
      if (!d_generateEnabled) {
        throw exception("$GENERATE is not allowed in this zone");
      }
      // $GENERATE 1-127 $ CNAME $.0
      string range=makeString(d_line, d_parts[1]);
      d_templatestep=1;
      d_templatestop=0;
      sscanf(range.c_str(),"%u-%u/%u", &d_templatecounter, &d_templatestop, &d_templatestep);
      if (d_templatestep < 1 ||
          d_templatestop < d_templatecounter) {
        throw exception("Invalid $GENERATE parameters");
      }
      if (d_maxGenerateSteps != 0) {
        size_t numberOfSteps = (d_templatestop - d_templatecounter) / d_templatestep;
        if (numberOfSteps > d_maxGenerateSteps) {
          throw exception("The number of $GENERATE steps (" + std::to_string(numberOfSteps) + ") is too high, the maximum is set to " + std::to_string(d_maxGenerateSteps));
        }
      }
      d_templateline=d_line;
      d_parts.pop_front();
      d_parts.pop_front();

      d_templateparts=d_parts;
      goto retry;
    }
    else
      throw exception("Can't parse zone line '"+d_line+"' "+getLineOfFile());
    goto retry;
  }

  bool prevqname=false;
  string qname = makeString(d_line, d_parts[0]); // Don't use DNSName here!
  if(dns_isspace(d_line[0])) {
    rr.qname=d_prevqname;
    prevqname=true;
  }else {
    rr.qname=DNSName(qname); 
    d_parts.pop_front();
    if(qname.empty() || qname[0]==';')
      goto retry;
  }
  if(qname=="@")
    rr.qname=d_zonename;
  else if(!prevqname && !isCanonical(qname))
    rr.qname += d_zonename;
  d_prevqname=rr.qname;

  if(d_parts.empty())
    throw exception("Line with too little parts "+getLineOfFile());

  string nextpart;
  
  rr.ttl=d_defaultttl;
  bool haveTTL=0, haveQTYPE=0;
  pair<string::size_type, string::size_type> range;

  while(!d_parts.empty()) {
    range=d_parts.front();
    d_parts.pop_front();
    nextpart=makeString(d_line, range);
    if(nextpart.empty())
      break;

    if(nextpart.find(';')!=string::npos) {
      break;
    }

    // cout<<"Next part: '"<<nextpart<<"'"<<endl;

    if(pdns_iequals(nextpart, g_INstr)) {
      // cout<<"Ignoring 'IN'\n";
      continue;
    }
    if(!haveTTL && !haveQTYPE && isTimeSpec(nextpart)) {
      rr.ttl=makeTTLFromZone(nextpart);
      if(!d_havedollarttl)
        d_defaultttl = rr.ttl;
      haveTTL=true;
      // cout<<"ttl is probably: "<<rr.ttl<<endl;
      continue;
    }
    if(haveQTYPE) 
      break;

    try {
      rr.qtype=DNSRecordContent::TypeToNumber(nextpart);
      // cout<<"Got qtype ("<<rr.qtype.getCode()<<")\n";
      haveQTYPE=1;
      continue;
    }
    catch(...) {
      throw runtime_error("Parsing zone content "+getLineOfFile()+
                          ": '"+nextpart+
                          "' doesn't look like a qtype, stopping loop");
    }
  }
  if(!haveQTYPE) 
    throw exception("Malformed line "+getLineOfFile()+": '"+d_line+"'");

  //  rr.content=d_line.substr(range.first);
  rr.content.assign(d_line, range.first, string::npos);
  chopComment(rr.content);
  trim_if(rr.content, is_any_of(" \r\n\t\x1a"));

  if(rr.content.size()==1 && rr.content[0]=='@')
    rr.content=d_zonename.toString();

  if(findAndElide(rr.content, '(')) {      // have found a ( and elided it
    if(!findAndElide(rr.content, ')')) {
      while(getLine()) {
        trim_right(d_line);
        chopComment(d_line);
        trim(d_line);
        
        bool ended = findAndElide(d_line, ')');
        rr.content+=" "+d_line;
        if(ended)
          break;
      }
    }
  }
  trim_if(rr.content, is_any_of(" \r\n\t\x1a"));

  vector<string> recparts;
  switch(rr.qtype.getCode()) {
  case QType::MX:
    stringtok(recparts, rr.content);
    if(recparts.size()==2) {
      if (recparts[1]!=".") {
        try {
          recparts[1] = toCanonic(d_zonename, recparts[1]).toStringRootDot();
        } catch (std::exception &e) {
          throw PDNSException("Error in record '" + rr.qname.toLogString() + " " + rr.qtype.getName() + "': " + e.what());
        }
      }
      rr.content=recparts[0]+" "+recparts[1];
    }
    break;
  
  case QType::RP:
    stringtok(recparts, rr.content);
    if(recparts.size()==2) {
      recparts[0] = toCanonic(d_zonename, recparts[0]).toStringRootDot();
      recparts[1] = toCanonic(d_zonename, recparts[1]).toStringRootDot();
      rr.content=recparts[0]+" "+recparts[1];
    }
    break;

  case QType::SRV:
    stringtok(recparts, rr.content);
    if(recparts.size()==4) {
      if(recparts[3]!=".") {
        try {
          recparts[3] = toCanonic(d_zonename, recparts[3]).toStringRootDot();
        } catch (std::exception &e) {
          throw PDNSException("Error in record '" + rr.qname.toLogString() + " " + rr.qtype.getName() + "': " + e.what());
        }
      }
      rr.content=recparts[0]+" "+recparts[1]+" "+recparts[2]+" "+recparts[3];
    }
    break;
  
    
  case QType::NS:
  case QType::CNAME:
  case QType::DNAME:
  case QType::PTR:
    try {
      rr.content = toCanonic(d_zonename, rr.content).toStringRootDot();
    } catch (std::exception &e) {
      throw PDNSException("Error in record '" + rr.qname.toLogString() + " " + rr.qtype.getName() + "': " + e.what());
    }
    break;
  case QType::AFSDB:
    stringtok(recparts, rr.content);
    if(recparts.size() == 2) {
      try {
        recparts[1]=toCanonic(d_zonename, recparts[1]).toStringRootDot();
      } catch (std::exception &e) {
        throw PDNSException("Error in record '" + rr.qname.toLogString() + " " + rr.qtype.getName() + "': " + e.what());
      }
    } else {
      throw PDNSException("AFSDB record for "+rr.qname.toLogString()+" invalid");
    }
    rr.content.clear();
    for(string::size_type n = 0; n < recparts.size(); ++n) {
      if(n)
        rr.content.append(1,' ');

      rr.content+=recparts[n];
    }
    break;
  case QType::SOA:
    stringtok(recparts, rr.content);
    if(recparts.size() > 7)
      throw PDNSException("SOA record contents for "+rr.qname.toLogString()+" contains too many parts");
    if(recparts.size() > 1) {
      try {
        recparts[0]=toCanonic(d_zonename, recparts[0]).toStringRootDot();
        recparts[1]=toCanonic(d_zonename, recparts[1]).toStringRootDot();
      } catch (std::exception &e) {
        throw PDNSException("Error in record '" + rr.qname.toLogString() + " " + rr.qtype.getName() + "': " + e.what());
      }
    }
    rr.content.clear();
    for(string::size_type n = 0; n < recparts.size(); ++n) {
      if(n)
        rr.content.append(1,' ');

      if(n > 1)
        rr.content+=std::to_string(makeTTLFromZone(recparts[n]));
      else
        rr.content+=recparts[n];
    }
    break;
  default:;
  }
  return true;
}


bool ZoneParserTNG::getLine()
{
  if (d_zonedata.size() > 0) {
    if (d_zonedataline != d_zonedata.end()) {
      d_line = *d_zonedataline;
      ++d_zonedataline;
      return true;
    }
    return false;
  }
  while(!d_filestates.empty()) {
    if(stringfgets(d_filestates.top().d_fp, d_line)) {
      d_filestates.top().d_lineno++;
      return true;
    }
    fclose(d_filestates.top().d_fp);
    d_filestates.pop();
  }
  return false;
}