File: pipebackend.cc

package info (click to toggle)
pdns 5.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,824 kB
  • sloc: cpp: 101,240; sh: 5,616; makefile: 2,318; sql: 860; ansic: 675; python: 635; yacc: 245; perl: 161; lex: 131
file content (395 lines) | stat: -rw-r--r-- 10,876 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
/*
 * 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 <string>
#include <map>
#include <unistd.h>
#include <stdlib.h>
#include <sstream>
#include "coprocess.hh"

#include "pdns/namespaces.hh"

#include "pdns/dns.hh"
#include "pdns/dnsbackend.hh"
#include "pdns/dnspacket.hh"
#include "pdns/pdnsexception.hh"
#include "pdns/logger.hh"
#include "pdns/arguments.hh"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "pipebackend.hh"

// The following requirement guarantees UnknownDomainID will get output as "-1"
// for compatibility.
static_assert(std::is_signed<domainid_t>::value);

static const char* kBackendId = "[PIPEBackend]";

CoWrapper::CoWrapper(const string& command, int timeout, int abiVersion)
{
  d_command = command;
  d_timeout = timeout;
  d_abiVersion = abiVersion;
  launch(); // let exceptions fall through - if initial launch fails, we want to die
  // I think
}

CoWrapper::~CoWrapper() = default;

void CoWrapper::launch()
{
  if (d_cp)
    return;

  if (d_command.empty())
    throw ArgException("pipe-command is not specified");

  if (isUnixSocket(d_command)) {
    d_cp = std::make_unique<UnixRemote>(d_command);
  }
  else {
    auto coprocess = std::make_unique<CoProcess>(d_command, d_timeout);
    coprocess->launch();
    d_cp = std::move(coprocess);
  }

  d_cp->send("HELO\t" + std::to_string(d_abiVersion));
  string banner;
  d_cp->receive(banner);
  g_log << Logger::Error << "Backend launched with banner: " << banner << endl;
}

void CoWrapper::send(const string& line)
{
  launch();
  try {
    d_cp->send(line);
    return;
  }
  catch (PDNSException& ae) {
    d_cp.reset();
    throw;
  }
}
void CoWrapper::receive(string& line)
{
  launch();
  try {
    d_cp->receive(line);
    return;
  }
  catch (PDNSException& ae) {
    g_log << Logger::Warning << kBackendId << " Unable to receive data from coprocess. " << ae.reason << endl;
    d_cp.reset();
    throw;
  }
}

PipeBackend::PipeBackend(const string& suffix)
{
  d_disavow = false;
  signal(SIGCHLD, SIG_IGN);
  setArgPrefix("pipe" + suffix);
  try {
    launch();
  }
  catch (const ArgException& A) {
    g_log << Logger::Error << kBackendId << " Unable to launch, fatal argument error: " << A.reason << endl;
    throw;
  }
  catch (...) {
    throw;
  }
}

void PipeBackend::launch()
{
  if (d_coproc)
    return;

  try {
    if (!getArg("regex").empty()) {
      d_regex = std::make_unique<Regex>(getArg("regex"));
    }
    d_regexstr = getArg("regex");
    d_abiVersion = getArgAsNum("abi-version");
    d_coproc = std::make_unique<CoWrapper>(getArg("command"), getArgAsNum("timeout"), getArgAsNum("abi-version"));
  }

  catch (const ArgException& A) {
    cleanup();
    throw;
  }
}

/*
 * Cleans up the co-process wrapper
 */
void PipeBackend::cleanup()
{
  d_coproc.reset(nullptr);
  d_regex.reset();
  d_regexstr = string();
  d_abiVersion = 0;
}

void PipeBackend::lookup(const QType& qtype, const DNSName& qname, domainid_t zoneId, DNSPacket* pkt_p)
{
  try {
    launch();
    d_disavow = false;
    if (d_regex && !d_regex->match(qname.toStringRootDot())) {
      if (::arg().mustDo("query-logging"))
        g_log << Logger::Error << "Query for '" << qname << "' failed regex '" << d_regexstr << "'" << endl;
      d_disavow = true; // don't pass to backend
    }
    else {
      ostringstream query;
      string localIP = "0.0.0.0";
      string remoteIP = "0.0.0.0";
      Netmask realRemote("0.0.0.0/0");
      if (pkt_p) {
        localIP = pkt_p->getLocal().toString();
        realRemote = pkt_p->getRealRemote();
        remoteIP = pkt_p->getInnerRemote().toString();
      }
      // abi-version = 1
      // type    qname           qclass  qtype   id      remote-ip-address
      query << "Q\t" << qname.toStringRootDot() << "\tIN\t" << qtype.toString() << "\t" << zoneId << "\t" << remoteIP;

      // add the local-ip-address if abi-version is set to 2
      if (d_abiVersion >= 2)
        query << "\t" << localIP;
      if (d_abiVersion >= 3)
        query << "\t" << realRemote.toString();

      if (::arg().mustDo("query-logging"))
        g_log << Logger::Error << "Query: '" << query.str() << "'" << endl;
      d_coproc->send(query.str());
    }
  }
  catch (PDNSException& pe) {
    g_log << Logger::Error << kBackendId << " Error from coprocess: " << pe.reason << endl;
    d_disavow = true;
  }
  d_qtype = qtype;
  d_qname = qname;
}

bool PipeBackend::list(const ZoneName& target, domainid_t domain_id, bool /* include_disabled */)
{
  try {
    launch();
    d_disavow = false;
    ostringstream query;
    // The question format:

    // type    qname           qclass  qtype   id      ip-address
    if (d_abiVersion >= 4)
      query << "AXFR\t" << domain_id << "\t" << target.toStringRootDot();
    else
      query << "AXFR\t" << domain_id;

    d_coproc->send(query.str());
  }
  catch (PDNSException& ae) {
    g_log << Logger::Error << kBackendId << " Error from coprocess: " << ae.reason << endl;
  }
  d_qname = DNSName(std::to_string(domain_id)); // why do we store a number here??
  return true;
}

string PipeBackend::directBackendCmd(const string& query)
{
  if (d_abiVersion < 5)
    return "not supported on ABI version " + std::to_string(d_abiVersion) + " (use ABI version 5 or later)\n";

  try {
    launch();
    ostringstream oss;
    oss << "CMD\t" << query;
    d_coproc->send(oss.str());
  }
  catch (PDNSException& ae) {
    g_log << Logger::Error << kBackendId << " Error from coprocess: " << ae.reason << endl;
    cleanup();
  }

  ostringstream oss;
  while (true) {
    string line;
    d_coproc->receive(line);
    if (line == "END")
      break;
    oss << line << std::endl;
  };

  return oss.str();
}

//! For the dynamic loader
DNSBackend* PipeBackend::maker()
{
  try {
    return new PipeBackend();
  }
  catch (...) {
    g_log << Logger::Error << kBackendId << " Unable to instantiate a pipebackend!" << endl;
    return nullptr;
  }
}

PipeBackend::~PipeBackend()
{
  cleanup();
}

bool PipeBackend::get(DNSResourceRecord& r)
{
  if (d_disavow) // this query has been blocked
    return false;

  string line;

  // The answer format:
  // DATA    qname           qclass  qtype   ttl     id      content
  unsigned int extraFields = 0;
  if (d_abiVersion >= 3)
    extraFields = 2;

  try {
    launch();
    for (;;) {
      d_coproc->receive(line);
      vector<string> parts;
      stringtok(parts, line, "\t");
      if (parts.empty()) {
        g_log << Logger::Error << kBackendId << " Coprocess returned empty line in query for " << d_qname << endl;
        throw PDNSException("Format error communicating with coprocess");
      }
      else if (parts[0] == "FAIL") {
        throw DBException("coprocess returned a FAIL");
      }
      else if (parts[0] == "END") {
        return false;
      }
      else if (parts[0] == "LOG") {
        g_log << Logger::Error << "Coprocess: " << line.substr(4) << endl;
        continue;
      }
      else if (parts[0] == "DATA") { // yay
        if (parts.size() < 7 + extraFields) {
          g_log << Logger::Error << kBackendId << " Coprocess returned incomplete or empty line in data section for query for " << d_qname << endl;
          throw PDNSException("Format error communicating with coprocess in data section");
          // now what?
        }

        if (d_abiVersion >= 3) {
          r.scopeMask = std::stoi(parts[1]);
          r.auth = (parts[2] == "1");
        }
        else {
          r.scopeMask = 0;
          r.auth = true;
        }
        r.qname = DNSName(parts[1 + extraFields]);
        r.qtype = parts[3 + extraFields];
        pdns::checked_stoi_into(r.ttl, parts[4 + extraFields]);
        pdns::checked_stoi_into(r.domain_id, parts[5 + extraFields]);

        if (r.qtype.getCode() != QType::MX && r.qtype.getCode() != QType::SRV) {
          r.content.clear();
          for (unsigned int n = 6 + extraFields; n < parts.size(); ++n) {
            if (n != 6 + extraFields)
              r.content.append(1, ' ');
            r.content.append(parts[n]);
          }
        }
        else {
          if (parts.size() < 8 + extraFields) {
            g_log << Logger::Error << kBackendId << " Coprocess returned incomplete MX/SRV line in data section for query for " << d_qname << endl;
            throw PDNSException("Format error communicating with coprocess in data section of MX/SRV record");
          }

          r.content = parts[6 + extraFields] + " " + parts[7 + extraFields];
        }
        break;
      }
      else
        throw PDNSException("Coprocess backend sent incorrect response '" + line + "'");
    }
  }
  catch (DBException& dbe) {
    g_log << Logger::Error << kBackendId << " " << dbe.reason << endl;
    throw;
  }
  catch (PDNSException& pe) {
    g_log << Logger::Error << kBackendId << " " << pe.reason << endl;
    cleanup();
    throw;
  }
  return true;
}

//
// Magic class that is activated when the dynamic library is loaded
//

class PipeFactory : public BackendFactory
{
public:
  PipeFactory() :
    BackendFactory("pipe") {}

  void declareArguments(const string& suffix = "") override
  {
    declare(suffix, "command", "Command to execute for piping questions to", "");
    declare(suffix, "timeout", "Number of milliseconds to wait for an answer", "2000");
    declare(suffix, "regex", "Regular expression of queries to pass to coprocess", "");
    declare(suffix, "abi-version", "Version of the pipe backend ABI", "1");
  }

  DNSBackend* make(const string& suffix = "") override
  {
    return new PipeBackend(suffix);
  }
};

class PipeLoader
{
public:
  PipeLoader()
  {
    BackendMakers().report(std::make_unique<PipeFactory>());
    g_log << Logger::Info << kBackendId << " This is the pipe backend version " VERSION
#ifndef REPRODUCIBLE
          << " (" __DATE__ " " __TIME__ ")"
#endif
          << " reporting" << endl;
  }
};

static PipeLoader pipeloader;