File: webserver.hh

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 (314 lines) | stat: -rw-r--r-- 8,784 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
/*
 * 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.
 */
#pragma once

#include "config.h"

#ifdef RECURSOR
// Network facing/routing part of webserver is implemented in rust. We stil use a few classes from
// yahttp, but do not link to it.
#define RUST_WS
#endif

#include <boost/utility.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#include <utility>
#include <yahttp/yahttp.hpp>
#pragma GCC diagnostic pop

#include "json11.hpp"

#include "credentials.hh"
#include "namespaces.hh"
#ifndef REST_WS
#include "sstuff.hh"
#endif
#include "logging.hh"

class HttpRequest : public YaHTTP::Request {
public:
  HttpRequest(string logprefix_ = "") :
    YaHTTP::Request(), logprefix(std::move(logprefix_)) {};

  string logprefix;
  bool accept_yaml{false};
  bool accept_json{false};
  bool accept_html{false};
  bool complete{false};

  json11::Json json();

  // checks password _only_.
  bool compareAuthorization(const CredentialsHolder& expectedCredentials) const;
  bool compareHeader(const string &header_name, const CredentialsHolder& expectedCredentials) const;
  bool compareHeader(const string &header_name, const string &expected_value) const;

#ifdef RECURSOR
  void setSLog(Logr::log_t log)
  {
    d_slog = log;
  }
  std::shared_ptr<Logr::Logger> d_slog;
#endif
};

class HttpResponse: public YaHTTP::Response {
public:
  HttpResponse() : YaHTTP::Response() { };
  HttpResponse(const YaHTTP::Response &resp) : YaHTTP::Response(resp) { };

  void setPlainBody(const string& document);
  void setYamlBody(const string& document);
  void setJsonBody(const string& document);
  void setJsonBody(const json11::Json& document);
  void setErrorResult(const std::string& message, const int status);
  void setSuccessResult(const std::string& message, const int status = 200);

#ifdef RECURSOR
  void setSLog(Logr::log_t log)
  {
    d_slog = log;
  }
  std::shared_ptr<Logr::Logger> d_slog;
#endif
};


class HttpException
{
public:
  HttpException(int status) : d_response()
  {
    d_response.status = status;
  };

  HttpException(int status, const string& msg) : d_response()
  {
    d_response.setErrorResult(msg, status);
  };

  HttpResponse response()
  {
    return d_response;
  }

protected:
  HttpResponse d_response;
};

class HttpBadRequestException : public HttpException {
public:
  HttpBadRequestException() : HttpException(400) { };
  HttpBadRequestException(const string& msg) : HttpException(400, msg) { };
};

class HttpUnauthorizedException : public HttpException {
public:
  HttpUnauthorizedException(string const &scheme) : HttpException(401)
  {
    d_response.headers["WWW-Authenticate"] = scheme + " realm=\"PowerDNS\"";
  }
};

class HttpForbiddenException : public HttpException {
public:
  HttpForbiddenException() : HttpException(403) { };
  HttpForbiddenException(const string& msg) : HttpException(403, msg) { };
};

class HttpNotFoundException : public HttpException {
public:
  HttpNotFoundException() : HttpException(404) { };
  HttpNotFoundException(const string& msg) : HttpException(404, msg) { };
};

class HttpMethodNotAllowedException : public HttpException {
public:
  HttpMethodNotAllowedException() : HttpException(405) { };
  HttpMethodNotAllowedException(const string& msg) : HttpException(405, msg) { };
};

class HttpConflictException : public HttpException {
public:
  HttpConflictException() : HttpException(409) { };
  HttpConflictException(const string& msg) : HttpException(409, msg) { };
};

class HttpInternalServerErrorException : public HttpException {
public:
  HttpInternalServerErrorException() : HttpException(500) { };
  HttpInternalServerErrorException(const string& msg) : HttpException(500, msg) { };
};

class ApiException : public runtime_error
{
public:
  ApiException(const string& what_arg) : runtime_error(what_arg) {
  }
};

#ifndef RUST_WS

class Server
{
public:
  Server(const string &localaddress, int port) : d_local(localaddress.empty() ? "0.0.0.0" : localaddress, port), d_server_socket(d_local.sin4.sin_family, SOCK_STREAM, 0) {
    d_server_socket.setReuseAddr();
    d_server_socket.bind(d_local);
    d_server_socket.listen();
  }
  virtual ~Server() = default;

  SockaddrWrapper d_local;

  std::shared_ptr<Socket> accept() {
    return std::shared_ptr<Socket>(d_server_socket.accept());
  }

protected:
  Socket d_server_socket;
};

class WebServer : public boost::noncopyable
{
public:
  WebServer(string listenaddress, int port);
  virtual ~WebServer() = default;

#ifdef RECURSOR
  void setSLog(Logr::log_t log)
  {
    d_slog = log;
  }
#endif

  void setApiKey(const string &apikey, bool hashPlaintext) {
    if (!apikey.empty()) {
      d_apikey = make_unique<CredentialsHolder>(std::string(apikey), hashPlaintext);
    }
    else {
      d_apikey.reset();
    }
  }

  void setPassword(const string &password, bool hashPlaintext) {
    if (!password.empty()) {
      d_webserverPassword = make_unique<CredentialsHolder>(std::string(password), hashPlaintext);
    }
    else {
      d_webserverPassword.reset();
    }
  }

  void setMaxBodySize(ssize_t s) { // in megabytes
    d_maxbodysize = s * 1024 * 1024;
  }

  void setConnectionTimeout(int t) { // in seconds
    d_connectiontimeout = t;
  }

  void setACL(const NetmaskGroup &nmg) {
    d_acl = nmg;
  }

  static bool validURL(const YaHTTP::URL& url);

  void bind();
  void go();

  void serveConnection(const std::shared_ptr<Socket>& client) const;
  void handleRequest(HttpRequest& request, HttpResponse& resp) const;

  typedef std::function<void(HttpRequest* req, HttpResponse* resp)> HandlerFunction;
  void registerApiHandler(const string& url, const HandlerFunction& handler, const std::string& method = "", bool allowPassword=false);
  void registerWebHandler(const string& url, const HandlerFunction& handler, const std::string& method = "");

  enum class LogLevel : uint8_t {
    None = 0,                // No logs from requests at all
    Normal = 10,             // A "common log format"-like line e.g. '127.0.0.1 "GET /apache_pb.gif HTTP/1.0" 200 2326'
    Detailed = 20,           // The full request headers and body, and the full response headers and body
  };

  void setLogLevel(const string& level) {
    if (level == "none") {
      d_loglevel = LogLevel::None;
      return;
    }

    if (level == "normal") {
      d_loglevel = LogLevel::Normal;
      return;
    }

    if (level == "detailed") {
      d_loglevel = LogLevel::Detailed;
      return;
    }

    throw PDNSException("Unknown webserver log level: " + level);
  }

  void setLogLevel(const LogLevel level) {
    d_loglevel = level;
  };

  LogLevel getLogLevel() {
    return d_loglevel;
  };

#ifdef RECURSOR
  std::shared_ptr<Logr::Logger> d_slog;
#endif

protected:
  static void registerBareHandler(const string& url, const HandlerFunction& handler, const std::string& method);
  void logRequest(const HttpRequest& req, const ComboAddress& remote) const;
  void logResponse(const HttpResponse& resp, const ComboAddress& remote, const string& logprefix) const;

  virtual std::shared_ptr<Server> createServer() {
    return std::make_shared<Server>(d_listenaddress, d_port);
  }

  void apiWrapper(const WebServer::HandlerFunction& handler, HttpRequest* req, HttpResponse* resp, bool allowPassword);
  void webWrapper(const WebServer::HandlerFunction& handler, HttpRequest* req, HttpResponse* resp);

  string d_listenaddress;
  int d_port;
  std::shared_ptr<Server> d_server;

  std::unique_ptr<CredentialsHolder> d_apikey{nullptr};
  std::unique_ptr<CredentialsHolder> d_webserverPassword{nullptr};

  ssize_t d_maxbodysize; // in bytes
  int d_connectiontimeout{5}; // in seconds

  NetmaskGroup d_acl;

  const string d_logprefix = "[webserver] ";

  // Describes the amount of logging the webserver does
  WebServer::LogLevel d_loglevel{WebServer::LogLevel::Detailed};
};

#endif // !RUST_WS