2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "webserver.hh"
35 #include "arguments.hh"
36 #include <yahttp/router.hpp>
38 json11::Json
HttpRequest::json()
41 if(this->body
.empty()) {
42 L
<<Logger::Debug
<<"HTTP: JSON document expected in request body, but body was empty" << endl
;
43 throw HttpBadRequestException();
45 json11::Json doc
= json11::Json::parse(this->body
, err
);
47 L
<<Logger::Debug
<<"HTTP: parsing of JSON document failed:" << err
<< endl
;
48 throw HttpBadRequestException();
53 bool HttpRequest::compareAuthorization(const string
&expected_password
)
56 YaHTTP::strstr_map_t::iterator header
= headers
.find("authorization");
58 if (header
!= headers
.end() && toLower(header
->second
).find("basic ") == 0) {
59 string cookie
= header
->second
.substr(6);
62 B64Decode(cookie
, plain
);
64 vector
<string
> cparts
;
65 stringtok(cparts
, plain
, ":");
67 // this gets rid of terminating zeros
68 auth_ok
= (cparts
.size()==2 && (0==strcmp(cparts
[1].c_str(), expected_password
.c_str())));
73 bool HttpRequest::compareHeader(const string
&header_name
, const string
&expected_value
)
75 YaHTTP::strstr_map_t::iterator header
= headers
.find(header_name
);
76 if (header
== headers
.end())
79 // this gets rid of terminating zeros
80 return (0==strcmp(header
->second
.c_str(), expected_value
.c_str()));
84 void HttpResponse::setBody(const json11::Json
& document
)
86 document
.dump(this->body
);
89 void HttpResponse::setErrorResult(const std::string
& message
, const int status_
)
91 setBody(json11::Json::object
{ { "error", message
} });
92 this->status
= status_
;
95 void HttpResponse::setSuccessResult(const std::string
& message
, const int status_
)
97 setBody(json11::Json::object
{ { "result", message
} });
98 this->status
= status_
;
101 static void bareHandlerWrapper(WebServer::HandlerFunction handler
, YaHTTP::Request
* req
, YaHTTP::Response
* resp
)
103 // wrapper to convert from YaHTTP::* to our subclasses
104 handler(static_cast<HttpRequest
*>(req
), static_cast<HttpResponse
*>(resp
));
107 void WebServer::registerBareHandler(const string
& url
, HandlerFunction handler
)
109 YaHTTP::THandlerFunction f
= boost::bind(&bareHandlerWrapper
, handler
, _1
, _2
);
110 YaHTTP::Router::Any(url
, f
);
113 static bool optionsHandler(HttpRequest
* req
, HttpResponse
* resp
) {
114 if (req
->method
== "OPTIONS") {
115 resp
->headers
["access-control-allow-origin"] = "*";
116 resp
->headers
["access-control-allow-headers"] = "Content-Type, X-API-Key";
117 resp
->headers
["access-control-allow-methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS";
118 resp
->headers
["access-control-max-age"] = "3600";
120 resp
->headers
["content-type"]= "text/plain";
127 static void apiWrapper(WebServer::HandlerFunction handler
, HttpRequest
* req
, HttpResponse
* resp
) {
128 const string
& api_key
= arg()["api-key"];
130 if (optionsHandler(req
, resp
)) return;
132 resp
->headers
["access-control-allow-origin"] = "*";
134 if (api_key
.empty()) {
135 L
<<Logger::Error
<<"HTTP API Request \"" << req
->url
.path
<< "\": Authentication failed, API Key missing in config" << endl
;
136 throw HttpUnauthorizedException("X-API-Key");
138 bool auth_ok
= req
->compareHeader("x-api-key", api_key
) || req
->getvars
["api-key"]==api_key
;
141 L
<<Logger::Error
<<"HTTP Request \"" << req
->url
.path
<< "\": Authentication by API Key failed" << endl
;
142 throw HttpUnauthorizedException("X-API-Key");
145 resp
->headers
["Content-Type"] = "application/json";
148 resp
->headers
["X-Content-Type-Options"] = "nosniff";
149 resp
->headers
["X-Frame-Options"] = "deny";
150 resp
->headers
["X-Permitted-Cross-Domain-Policies"] = "none";
151 resp
->headers
["X-XSS-Protection"] = "1; mode=block";
152 resp
->headers
["Content-Security-Policy"] = "default-src 'self'; style-src 'self' 'unsafe-inline'";
154 req
->getvars
.erase("_"); // jQuery cache buster
159 } catch (ApiException
&e
) {
160 resp
->setErrorResult(e
.what(), 422);
162 } catch (JsonException
&e
) {
163 resp
->setErrorResult(e
.what(), 422);
167 if (resp
->status
== 204) {
168 // No Content -> no Content-Type.
169 resp
->headers
.erase("Content-Type");
173 void WebServer::registerApiHandler(const string
& url
, HandlerFunction handler
) {
174 HandlerFunction f
= boost::bind(&apiWrapper
, handler
, _1
, _2
);
175 registerBareHandler(url
, f
);
178 static void webWrapper(WebServer::HandlerFunction handler
, HttpRequest
* req
, HttpResponse
* resp
) {
179 const string
& web_password
= arg()["webserver-password"];
181 if (!web_password
.empty()) {
182 bool auth_ok
= req
->compareAuthorization(web_password
);
184 L
<<Logger::Debug
<<"HTTP Request \"" << req
->url
.path
<< "\": Web Authentication failed" << endl
;
185 throw HttpUnauthorizedException("Basic");
192 void WebServer::registerWebHandler(const string
& url
, HandlerFunction handler
) {
193 HandlerFunction f
= boost::bind(&webWrapper
, handler
, _1
, _2
);
194 registerBareHandler(url
, f
);
197 static void *WebServerConnectionThreadStart(const WebServer
* webServer
, std::shared_ptr
<Socket
> client
) {
198 webServer
->serveConnection(client
);
202 void WebServer::handleRequest(HttpRequest
& req
, HttpResponse
& resp
) const
204 // set default headers
205 resp
.headers
["Content-Type"] = "text/html; charset=utf-8";
209 L
<<Logger::Debug
<<"HTTP: Incomplete request" << endl
;
210 throw HttpBadRequestException();
213 L
<<Logger::Debug
<<"HTTP: Handling request \"" << req
.url
.path
<< "\"" << endl
;
215 YaHTTP::strstr_map_t::iterator header
;
217 if ((header
= req
.headers
.find("accept")) != req
.headers
.end()) {
218 // json wins over html
219 if (header
->second
.find("application/json") != std::string::npos
) {
220 req
.accept_json
= true;
221 } else if (header
->second
.find("text/html") != std::string::npos
) {
222 req
.accept_html
= true;
226 YaHTTP::THandlerFunction handler
;
227 if (!YaHTTP::Router::Route(&req
, handler
)) {
228 L
<<Logger::Debug
<<"HTTP: No route found for \"" << req
.url
.path
<< "\"" << endl
;
229 throw HttpNotFoundException();
233 handler(&req
, &resp
);
234 L
<<Logger::Debug
<<"HTTP: Result for \"" << req
.url
.path
<< "\": " << resp
.status
<< ", body length: " << resp
.body
.size() << endl
;
236 catch(HttpException
&) {
239 catch(PDNSException
&e
) {
240 L
<<Logger::Error
<<"HTTP ISE for \""<< req
.url
.path
<< "\": Exception: " << e
.reason
<< endl
;
241 throw HttpInternalServerErrorException();
243 catch(std::exception
&e
) {
244 L
<<Logger::Error
<<"HTTP ISE for \""<< req
.url
.path
<< "\": STL Exception: " << e
.what() << endl
;
245 throw HttpInternalServerErrorException();
248 L
<<Logger::Error
<<"HTTP ISE for \""<< req
.url
.path
<< "\": Unknown Exception" << endl
;
249 throw HttpInternalServerErrorException();
252 catch(HttpException
&e
) {
254 L
<<Logger::Debug
<<"HTTP: Error result for \"" << req
.url
.path
<< "\": " << resp
.status
<< endl
;
255 string what
= YaHTTP::Utility::status2text(resp
.status
);
256 if(req
.accept_html
) {
257 resp
.headers
["Content-Type"] = "text/html; charset=utf-8";
258 resp
.body
= "<!html><title>" + what
+ "</title><h1>" + what
+ "</h1>";
259 } else if (req
.accept_json
) {
260 resp
.headers
["Content-Type"] = "application/json";
261 resp
.setErrorResult(what
, resp
.status
);
263 resp
.headers
["Content-Type"] = "text/plain; charset=utf-8";
268 // always set these headers
269 resp
.headers
["Server"] = "PowerDNS/" VERSION
;
270 resp
.headers
["Connection"] = "close";
272 if (req
.method
== "HEAD") {
275 resp
.headers
["Content-Length"] = std::to_string(resp
.body
.size());
279 void WebServer::serveConnection(std::shared_ptr
<Socket
> client
) const
282 YaHTTP::AsyncRequestLoader yarl
;
283 yarl
.initialize(&req
);
285 client
->setNonBlocking();
288 while(!req
.complete
) {
291 bytes
= client
->readWithTimeout(buf
, sizeof(buf
), timeout
);
293 string data
= string(buf
, bytes
);
294 req
.complete
= yarl
.feed(data
);
301 } catch (YaHTTP::ParseError
&e
) {
302 // request stays incomplete
306 WebServer::handleRequest(req
, resp
);
309 string reply
= ss
.str();
311 client
->writenWithTimeout(reply
.c_str(), reply
.size(), timeout
);
313 catch(PDNSException
&e
) {
314 L
<<Logger::Error
<<"HTTP Exception: "<<e
.reason
<<endl
;
316 catch(std::exception
&e
) {
317 if(strstr(e
.what(), "timeout")==0)
318 L
<<Logger::Error
<<"HTTP STL Exception: "<<e
.what()<<endl
;
321 L
<<Logger::Error
<<"HTTP: Unknown exception"<<endl
;
324 WebServer::WebServer(const string
&listenaddress
, int port
) : d_server(nullptr)
326 d_listenaddress
=listenaddress
;
330 void WebServer::bind()
333 d_server
= createServer();
334 L
<<Logger::Warning
<<"Listening for HTTP requests on "<<d_server
->d_local
.toStringWithPort()<<endl
;
336 catch(NetworkError
&e
) {
337 L
<<Logger::Error
<<"Listening on HTTP socket failed: "<<e
.what()<<endl
;
348 acl
.toMasks(::arg()["webserver-allow-from"]);
352 auto client
= d_server
->accept();
356 if (client
->acl(acl
)) {
357 std::thread
webHandler(WebServerConnectionThreadStart
, this, client
);
361 if (client
->getRemote(remote
))
362 L
<<Logger::Error
<<"Webserver closing socket: remote ("<< remote
.toString() <<") does not match 'webserver-allow-from'"<<endl
;
365 catch(PDNSException
&e
) {
366 L
<<Logger::Error
<<"PDNSException while accepting a connection in main webserver thread: "<<e
.reason
<<endl
;
368 catch(std::exception
&e
) {
369 L
<<Logger::Error
<<"STL Exception while accepting a connection in main webserver thread: "<<e
.what()<<endl
;
372 L
<<Logger::Error
<<"Unknown exception while accepting a connection in main webserver thread"<<endl
;
376 catch(PDNSException
&e
) {
377 L
<<Logger::Error
<<"PDNSException in main webserver thread: "<<e
.reason
<<endl
;
379 catch(std::exception
&e
) {
380 L
<<Logger::Error
<<"STL Exception in main webserver thread: "<<e
.what()<<endl
;
383 L
<<Logger::Error
<<"Unknown exception in main webserver thread"<<endl
;