RESTHttpsServer.cpp 10.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * RESTHttpsServer.cpp
 *
 *  Created on: 20.05.2019
 *      Author: Micha Mueller
 */

#include "RESTHttpsServer.h"

#include <string>

#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>
#include <boost/archive/iterators/transform_width.hpp>

// This is the C++11 equivalent of a generic lambda.
// The function object is used to send an HTTP message.
template<class Stream>
struct send_lambda {
    Stream& stream_;
    bool& close_;
22
    boost::beast::error_code& ec_;
23

24
    explicit send_lambda(Stream& stream, bool& close, boost::beast::error_code& ec) :
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
            stream_(stream),
            close_(close),
            ec_(ec) {
    }

    template<bool isRequest, class Body, class Fields>
    void operator()(http::message<isRequest, Body, Fields>&& msg) const {
        // Determine if we should close the connection after
        close_ = msg.need_eof();

        // We need the serializer here because the serializer requires
        // a non-const file_body, and the message oriented version of
        // http::write only works with const messages.
        http::serializer<isRequest, Body, Fields> sr{msg};
        http::write(stream_, sr, ec_);
    }
};

RESTHttpsServer::RESTHttpsServer(serverSettings_t settings) :
    _isRunning(false) {

    _io = std::unique_ptr<boost::asio::io_context>(
            new boost::asio::io_context(1));

    _ctx = std::unique_ptr<ssl::context>(new ssl::context(ssl::context::tls_server));

    _ctx->set_options(ssl::context::default_workarounds |
                      ssl::context::no_tlsv1 |
                      ssl::context::single_dh_use);

    // Password callback needs to be set before setting cert and key.
    /*
    _ctx->set_password_callback([](std::size_t max_length,
                                  ssl::context::password_purpose purpose)
    {
        return "password";
    });
    */

64
    //TODO make more robust if certificate not found
65
66
67
68
    _ctx->use_certificate_chain_file(settings.certificate);
    _ctx->use_private_key_file(settings.privateKey, ssl::context::pem);
    _ctx->use_tmp_dh_file(settings.dhFile);

69
70
71
72
73
74
75
76
77
78
79
80
81
    // This will receive the new connection
    _socket = std::unique_ptr<tcp::socket>(new tcp::socket(*_io));

    try {
        auto const address = boost::asio::ip::make_address(settings.host);
        auto const port    = static_cast<unsigned short>(std::stoul(settings.port));

        _acceptor = std::unique_ptr<tcp::acceptor>(new tcp::acceptor(*_io, {address, port}));
        _acceptor->set_option(tcp::acceptor::reuse_address(true));
    } catch (const std::exception& e) {
        LOG(fatal) << "RestAPI address invalid! Please make sure IP address and port are valid!";
        throw;
    }
82
83
84
}


85
void RESTHttpsServer::handle_session(tcp::socket& socket, ssl::context& ctx) {
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    ServerLOG(info) << _remoteEndpoint.address().to_string() << ":"
                    << _remoteEndpoint.port() << " connecting";

    bool close = false;
    boost::beast::error_code ec;

    // Construct the stream around the socket
    boost::beast::ssl_stream<tcp::socket&> stream{socket, ctx};

    // Perform the SSL handshake
    stream.handshake(ssl::stream_base::server, ec);
    if(ec) {
        ServerLOG(error) << "handshake: " << ec.message();
        goto serverError;
    }

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
    {//scope, so any goto before does not cross variable initialization
        // This buffer is required to persist across reads
        boost::beast::flat_buffer buffer;

        // This lambda is used to send messages
        send_lambda<boost::beast::ssl_stream<tcp::socket&>> lambda{stream, close, ec};

        while(true) {
            // Read a request
            http::request<http::string_body> req;
            http::read(stream, buffer, req, ec);
            if(ec == http::error::end_of_stream) {
                break;
            }
            if(ec) {
                ServerLOG(error) << "read: " << ec.message();
                goto serverError;
            }

            if(!validateUser(req, lambda)) {
                break;
            }

            // Send the response
            handle_request(req, lambda);

            if(ec) {
                ServerLOG(error) << "write: " << ec.message();
                goto serverError;
            }
            if(close) {
                // This means we should close the connection, usually because
                // the response indicated the "Connection: close" semantic.
                break;
            }
137
138
139
140
141
        }
    }

    // Perform the SSL shutdown
    stream.shutdown(ec);
142
143
144
145
146
    if(ec) { ServerLOG(error) << "stream shutdown: " << ec.message(); }

serverError:
    socket.shutdown(tcp::socket::shutdown_both, ec);
    if(ec) { ServerLOG(error) << "socket shutdown: " << ec.message(); }
147

148
149
    socket.close(ec);
    if(ec) { ServerLOG(error) << "socket close: " << ec.message(); }
150
151
152
153
    startAccept();
}

template<class Body, class Send>
154
void RESTHttpsServer::handle_request(http::request<Body>& req, Send&& send) {
155
156
157
158
159
160
161
162

    http::response<http::string_body> res {http::status::internal_server_error, req.version()};
    res.set(http::field::server, SERVER_STRING);
    res.set(http::field::content_type, "text/plain");
    res.keep_alive(req.keep_alive());
    res.body() = "Unknown error occurred\n";

    //split target and find matching endpoint handler
163
    queries_t queries;
164
    const std::string endpointName = splitUri(req.target().to_string(), queries);
165
166
167

    //Look up the endpoint
    try {
168
        apiEndpoint_t endpoint = _endpoints.at(endpointName);
169
170
171

        if (endpoint.first == req.method()) {
            //Everything matches --> call the endpoint function
172
            ServerLOG(info) << req.method_string() << " " << endpointName << " requested";
173
            endpoint.second(res, queries);
174
        } else {
175
176
            const std::string msg = "Request method " + req.method_string().to_string() +
                                    " does not match endpoint " + endpointName + "\n";
177
178
179
            ServerLOG(info) << msg;
            res.result(http::status::bad_request);
            res.body() = msg;
180
181
182
183
        }
    } catch (const std::out_of_range& e) {
        ServerLOG(info) << "Requested endpoint " << endpointName << " not found";
        res.result(http::status::not_implemented);
184
        res.body() = "Invalid endpoint\n";
185
186
    }

187
    ServerLOG(info) << "Responding:\n" << res.body();
188

189
190
191
192
193
194
195
196
    res.prepare_payload();
    send(std::move(res));
    return;
}

template<class Body, class Send>
bool RESTHttpsServer::validateUser(const http::request<Body>& req, Send&& send) {

197
198
199
200
201
202
    http::response<http::string_body> res {http::status::unauthorized, req.version()};
    res.set(http::field::server, SERVER_STRING);
    res.set(http::field::content_type, "text/plain");
    res.keep_alive(req.keep_alive());
    res.body() = "Unauthorized access!\n";
    res.prepare_payload();
203
204
205
206
207
208
209
210
211
212

    //GET /help does not need any authorization
    if (req.target() == "/help" && req.method() == http::verb::get) {
        return true;
    }

    std::string auth;
    std::string credentials;

    try {
213
        auth = req.base().at(http::field::authorization).to_string();
214
215
    } catch (const std::out_of_range& e) {
        ServerLOG(info) << "No credentials were provided";
216
        send(std::move(res));
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
        return false;
    }

    //Remove the substring "Basic" and decode the credentials.
    auth.erase(0,6);
    using namespace boost::archive::iterators;
    using ItBinaryT =
            transform_width<binary_from_base64<remove_whitespace<std::string::const_iterator>>, 8, 6>;

    try {
        // If the input isn't a multiple of 4, pad with =
        size_t num_pad_chars((4 - auth.size() % 4) % 4);
        auth.append(num_pad_chars, '=');

        size_t pad_chars(std::count(auth.begin(), auth.end(), '='));
        std::replace(auth.begin(), auth.end(), '=', 'A');
        std::string output(ItBinaryT(auth.begin()), ItBinaryT(auth.end()));
        output.erase(output.end() - pad_chars, output.end());
        credentials = output;
    } catch (std::exception const&) {
        credentials = std::string("");
    }

    size_t pos = credentials.find(':');
    const std::string usr = credentials.substr(0, pos);
    const std::string pwd = credentials.substr(pos+1, credentials.length());

    //Check credentials
    userAttributes_t userData;
    try {
        userData = _users.at(usr);
    } catch (const std::out_of_range& e) {
        ServerLOG(warning) << "User does not exist: " << usr;
250
        send(std::move(res));
251
252
253
254
255
        return false;
    }

    if (pwd != userData.first) {
        ServerLOG(warning) << "Invalid password provided: " << usr << ":" << pwd;
256
        send(std::move(res));
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
        return false;
    }

    permission perm;

    switch (req.method()) {
        case http::verb::get:
            perm = permission::GET;
            break;
        case http::verb::put:
            perm = permission::PUT;
            break;
        case http::verb::post:
            perm = permission::POST;
            break;
        case http::verb::delete_:
            perm = permission::DELETE;
            break;
        default:
            perm = permission::NUM_PERMISSIONS;
            break;
    }

    try {
        if (!userData.second.test(perm)) {
            ServerLOG(warning) << "User " << usr << " has insufficient permissions";
283
284
285
286
            res.result(http::status::forbidden);
            res.body() = "Insufficient permissions\n";
            res.prepare_payload();
            send(std::move(res));
287
288
289
290
            return false;
        }
    } catch (const std::out_of_range& e) {
        ServerLOG(error) << "Permission out of range (method not supported)";
291
292
293
294
        res.result(http::status::not_implemented);
        res.body() = "Request method not supported!\n";
        res.prepare_payload();
        send(std::move(res));
295
296
297
298
299
300
        return false;
    }

    return true;
}

301
std::string RESTHttpsServer::splitUri(const std::string& uri, queries_t& queries) {
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
    //split into path and query
    std::string path;
    std::string query;

    size_t pos = uri.find('?');
    path = uri.substr(0, pos);
    query = uri.substr(pos+1, uri.length());

    //split query part into the individual queries (key-value pairs)
    std::vector<std::string> queryStrs;
    std::stringstream stream(query);
    std::string part;

    while(std::getline(stream, part, ';')) {
        queryStrs.push_back(part);
    }
318

319
320
321
    for(auto& key : queryStrs) {
        size_t pos = key.find("=");
        if (pos != std::string::npos) {
322
            const std::string value = key.substr(pos+1);
323
            key.erase(pos);
324
            queries[key] = value;
325
326
        }
    }
327
328

    return path;
329
330
}