File: webserver.cc

package info (click to toggle)
pdns-recursor 3.6.2-2%2Bdeb8u4
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 1,584 kB
  • sloc: cpp: 18,941; ansic: 1,653; sh: 539; makefile: 130
file content (343 lines) | stat: -rw-r--r-- 10,256 bytes parent folder | download | duplicates (4)
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
/*
    PowerDNS Versatile Database Driven Nameserver
    Copyright (C) 2002-2012  PowerDNS.COM BV

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation

    Additionally, the license of this program contains a special
    exception which allows to distribute the program in binary form when
    it is linked against OpenSSL.

    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 St, Fifth Floor, Boston, MA  02110-1301  USA
*/
#include "utility.hh"
#include "arguments.hh"
#include "webserver.hh"
#include "misc.hh"
#include <vector>
#include "logger.hh"
#include <stdio.h>
#include "dns.hh"
#include "base64.hh"
#include "json.hh"
#include <yahttp/router.hpp>

struct connectionThreadData {
  WebServer* webServer;
  Socket* client;
};

void HttpRequest::json(rapidjson::Document& document)
{
  if(this->body.empty()) {
    L<<Logger::Debug<<"HTTP: JSON document expected in request body, but body was empty" << endl;
    throw HttpBadRequestException();
  }
  if(document.Parse<0>(this->body.c_str()).HasParseError()) {
    L<<Logger::Debug<<"HTTP: parsing of JSON document failed" << endl;
    throw HttpBadRequestException();
  }
}

bool HttpRequest::compareAuthorization(const string &expected_password)
{
  // validate password
  YaHTTP::strstr_map_t::iterator header = headers.find("authorization");
  bool auth_ok = false;
  if (header != headers.end() && toLower(header->second).find("basic ") == 0) {
    string cookie = header->second.substr(6);

    string plain;
    B64Decode(cookie, plain);

    vector<string> cparts;
    stringtok(cparts, plain, ":");

    // this gets rid of terminating zeros
    auth_ok = (cparts.size()==2 && (0==strcmp(cparts[1].c_str(), expected_password.c_str())));
  }
  return auth_ok;
}

bool HttpRequest::compareHeader(const string &header_name, const string &expected_value)
{
  YaHTTP::strstr_map_t::iterator header = headers.find(header_name);
  if (header == headers.end())
    return false;

  // this gets rid of terminating zeros
  return (0==strcmp(header->second.c_str(), expected_value.c_str()));
}


void HttpResponse::setBody(rapidjson::Document& document)
{
  this->body = makeStringFromDocument(document);
}

int WebServer::B64Decode(const std::string& strInput, std::string& strOutput)
{
  return ::B64Decode(strInput, strOutput);
}

static void bareHandlerWrapper(WebServer::HandlerFunction handler, YaHTTP::Request* req, YaHTTP::Response* resp)
{
  // wrapper to convert from YaHTTP::* to our subclasses
  handler(static_cast<HttpRequest*>(req), static_cast<HttpResponse*>(resp));
}

void WebServer::registerBareHandler(const string& url, HandlerFunction handler)
{
  YaHTTP::THandlerFunction f = boost::bind(&bareHandlerWrapper, handler, _1, _2);
  YaHTTP::Router::Any(url, f);
}

static void apiWrapper(WebServer::HandlerFunction handler, HttpRequest* req, HttpResponse* resp) {
  const string& api_key = ::arg()["experimental-api-key"];
  if (api_key.empty()) {
    L<<Logger::Debug<<"HTTP API Request \"" << req->url.path << "\": Authentication failed, API Key missing in config" << endl;
    throw HttpUnauthorizedException();
  }
  bool auth_ok = req->compareHeader("x-api-key", api_key);
  if (!auth_ok) {
    L<<Logger::Debug<<"HTTP Request \"" << req->url.path << "\": Authentication by API Key failed" << endl;
    throw HttpUnauthorizedException();
  }

  resp->headers["Access-Control-Allow-Origin"] = "*";
  resp->headers["Content-Type"] = "application/json";

  string callback;

  if(req->getvars.count("callback")) {
    callback=req->getvars["callback"];
    req->getvars.erase("callback");
  }

  req->getvars.erase("_"); // jQuery cache buster

  try {
    resp->status = 200;
    handler(req, resp);
  } catch (ApiException &e) {
    resp->body = returnJsonError(e.what());
    resp->status = 422;
    return;
  } catch (JsonException &e) {
    resp->body = returnJsonError(e.what());
    resp->status = 422;
    return;
  }

  if (resp->status == 204) {
    // No Content -> no Content-Type.
    resp->headers.erase("Content-Type");
  }

  if(!callback.empty()) {
    resp->body = callback + "(" + resp->body + ");";
  }
}

void WebServer::registerApiHandler(const string& url, HandlerFunction handler) {
  HandlerFunction f = boost::bind(&apiWrapper, handler, _1, _2);
  registerBareHandler(url, f);
}

static void webWrapper(WebServer::HandlerFunction handler, HttpRequest* req, HttpResponse* resp) {
  const string& web_password = arg()["webserver-password"];
  if (!web_password.empty()) {
    bool auth_ok = req->compareAuthorization(web_password);
    if (!auth_ok) {
      L<<Logger::Debug<<"HTTP Request \"" << req->url.path << "\": Web Authentication failed" << endl;
      throw HttpUnauthorizedException();
    }
  }

  handler(req, resp);
}

void WebServer::registerWebHandler(const string& url, HandlerFunction handler) {
  HandlerFunction f = boost::bind(&webWrapper, handler, _1, _2);
  registerBareHandler(url, f);
}

static void *WebServerConnectionThreadStart(void *p) {
  connectionThreadData* data = static_cast<connectionThreadData*>(p);
  pthread_detach(pthread_self());
  data->webServer->serveConnection(data->client);

  delete data->client; // close socket
  delete data;

  return NULL;
}

HttpResponse WebServer::handleRequest(HttpRequest req)
{
  HttpResponse resp;

  // set default headers
  resp.headers["Content-Type"] = "text/html; charset=utf-8";

  try {
    if (!req.complete) {
      L<<Logger::Debug<<"HTTP: Incomplete request" << endl;
      throw HttpBadRequestException();
    }

    L<<Logger::Debug<<"HTTP: Handling request \"" << req.url.path << "\"" << endl;

    YaHTTP::strstr_map_t::iterator header;

    if ((header = req.headers.find("accept")) != req.headers.end()) {
      // json wins over html
      if (header->second.find("application/json") != std::string::npos) {
        req.accept_json = true;
      } else if (header->second.find("text/html") != std::string::npos) {
        req.accept_html = true;
      }
    }

    YaHTTP::THandlerFunction handler;
    if (!YaHTTP::Router::Route(&req, handler)) {
      L<<Logger::Debug<<"HTTP: No route found for \"" << req.url.path << "\"" << endl;
      throw HttpNotFoundException();
    }

    try {
      handler(&req, &resp);
      L<<Logger::Debug<<"HTTP: Result for \"" << req.url.path << "\": " << resp.status << ", body length: " << resp.body.size() << endl;
    }
    catch(HttpException) {
      throw;
    }
    catch(PDNSException &e) {
      L<<Logger::Error<<"HTTP ISE for \""<< req.url.path << "\": Exception: " << e.reason << endl;
      throw HttpInternalServerErrorException();
    }
    catch(std::exception &e) {
      L<<Logger::Error<<"HTTP ISE for \""<< req.url.path << "\": STL Exception: " << e.what() << endl;
      throw HttpInternalServerErrorException();
    }
    catch(...) {
      L<<Logger::Error<<"HTTP ISE for \""<< req.url.path << "\": Unknown Exception" << endl;
      throw HttpInternalServerErrorException();
    }
  }
  catch(HttpException &e) {
    resp = e.response();
    L<<Logger::Debug<<"HTTP: Error result for \"" << req.url.path << "\": " << resp.status << endl;
    string what = YaHTTP::Utility::status2text(resp.status);
    if(req.accept_html) {
      resp.headers["Content-Type"] = "text/html; charset=utf-8";
      resp.body = "<!html><title>" + what + "</title><h1>" + what + "</h1>";
    } else if (req.accept_json) {
      resp.headers["Content-Type"] = "application/json";
      resp.body = returnJsonError(what);
    } else {
      resp.headers["Content-Type"] = "text/plain; charset=utf-8";
      resp.body = what;
    }
  }

  // always set these headers
  resp.headers["Server"] = "PowerDNS/"VERSION;
  resp.headers["Connection"] = "close";

  return resp;
}

void WebServer::serveConnection(Socket *client)
try {
  HttpRequest req;
  YaHTTP::AsyncRequestLoader yarl;
  yarl.initialize(&req);
  int timeout = 5;
  client->setNonBlocking();

  try {
    while(!req.complete) {
      int bytes;
      char buf[1024];
      bytes = client->readWithTimeout(buf, sizeof(buf), timeout);
      if (bytes > 0) {
        string data = string(buf, bytes);
        req.complete = yarl.feed(data);
      } else {
        // read error OR EOF
        break;
      }
    }
    yarl.finalize();
  } catch (YaHTTP::ParseError &e) {
    // request stays incomplete
  }

  HttpResponse resp = WebServer::handleRequest(req);
  ostringstream ss;
  resp.write(ss);
  string reply = ss.str();

  client->writenWithTimeout(reply.c_str(), reply.size(), timeout);
}
catch(PDNSException &e) {
  L<<Logger::Error<<"HTTP Exception: "<<e.reason<<endl;
}
catch(std::exception &e) {
  L<<Logger::Error<<"HTTP STL Exception: "<<e.what()<<endl;
}
catch(...) {
  L<<Logger::Error<<"HTTP: Unknown exception"<<endl;
}

WebServer::WebServer(const string &listenaddress, int port) : d_server(NULL)
{
  d_listenaddress=listenaddress;
  d_port=port;
}

void WebServer::bind()
{
  try {
    d_server = createServer();
    L<<Logger::Warning<<"Listening for HTTP requests on "<<d_server->d_local.toStringWithPort()<<endl;
  }
  catch(NetworkError &e) {
    L<<Logger::Error<<"Listening on HTTP socket failed: "<<e.what()<<endl;
    d_server = NULL;
  }
}

void WebServer::go()
{
  if(!d_server)
    return;
  try {
    pthread_t tid;

    while(true) {
      // data and data->client will be freed by thread
      connectionThreadData *data = new connectionThreadData;
      data->webServer = this;
      data->client = d_server->accept();
      pthread_create(&tid, 0, &WebServerConnectionThreadStart, (void *)data);
    }
  }
  catch(std::exception &e) {
    L<<Logger::Error<<"STL Exception in main webserver thread: "<<e.what()<<endl;
  }
  catch(...) {
    L<<Logger::Error<<"Unknown exception in main webserver thread"<<endl;
  }
  exit(1);
}