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
|
/*
Copyright (C) 2025
Matthias P. Braendli, matthias.braendli@mpb.li
http://www.opendigitalradio.org
*/
/*
This file is part of the ODR-mmbTools.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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, see <https://www.gnu.org/licenses/>.
*/
#include "webserver.h"
#include <future>
#include "Log.h"
using namespace std;
static const char* http_ok = "HTTP/1.0 200 OK\r\n";
static const char* http_404 = "HTTP/1.0 404 Not Found\r\n";
/* unused:
static const char* http_400 = "HTTP/1.0 400 Bad Request\r\n";
static const char* http_405 = "HTTP/1.0 405 Method Not Allowed\r\n";
static const char* http_500 = "HTTP/1.0 500 Internal Server Error\r\n";
static const char* http_503 = "HTTP/1.0 503 Service Unavailable\r\n";
static const char* http_contenttype_data = "Content-Type: application/octet-stream\r\n";
static const char* http_contenttype_html = "Content-Type: text/html; charset=utf-8\r\n";
*/
static const char* http_contenttype_text = "Content-Type: text/plain\r\n";
static const char* http_contenttype_json = "Content-Type: application/json; charset=utf-8\r\n";
static const char* http_nocache = "Cache-Control: no-cache\r\n";
WebServer::WebServer(std::string listen_ip, uint16_t port, const std::string& index_content)
: index_content(index_content)
{
server_socket.listen(port, listen_ip);
handler_thread = thread(&WebServer::serve, this);
}
WebServer::~WebServer()
{
running = false;
if (handler_thread.joinable()) {
handler_thread.join();
}
server_socket.close();
}
void WebServer::update_stats_json(const std::string& new_stats_json)
{
unique_lock<mutex> lock(data_mutex);
stats_json = new_stats_json;
}
void WebServer::serve()
{
deque<future<bool> > running_connections;
while (running) {
auto sock = server_socket.accept(1000);
if (sock.valid()) {
running_connections.push_back(async(launch::async,
&WebServer::dispatch_client, this, std::move(sock)));
deque<future<bool> > still_running_connections;
for (auto& fut : running_connections) {
if (fut.valid()) {
switch (fut.wait_for(chrono::milliseconds(1))) {
case future_status::deferred:
case future_status::timeout:
still_running_connections.push_back(std::move(fut));
break;
case future_status::ready:
fut.get();
break;
}
}
}
running_connections = std::move(still_running_connections);
}
}
etiLog.level(info) << "WebServer draining connections";
while (running_connections.size() > 0) {
deque<future<bool> > still_running_connections;
for (auto& fut : running_connections) {
if (fut.valid()) {
switch (fut.wait_for(chrono::milliseconds(1))) {
case future_status::deferred:
case future_status::timeout:
still_running_connections.push_back(std::move(fut));
break;
case future_status::ready:
fut.get();
break;
}
}
}
running_connections = std::move(still_running_connections);
}
}
static string recv_line(Socket::TCPSocket& s) {
string line;
bool cr_seen = false;
while (true) {
char c = 0;
ssize_t ret = s.recv(&c, 1, 0);
if (ret == 0) {
return "";
}
else if (ret == -1) {
string errstr = strerror(errno);
etiLog.level(error) << "recv error " << errstr;
return "";
}
line += c;
if (c == '\r') {
cr_seen = true;
}
else if (cr_seen and c == '\n') {
return line;
}
}
}
static vector<char> recv_exactly(Socket::TCPSocket& s, size_t num_bytes)
{
vector<char> buf(num_bytes);
size_t rx = 0;
while (rx < num_bytes) {
const size_t remain = num_bytes - rx;
ssize_t ret = s.recv(buf.data() + rx, remain, 0);
if (ret == 0) {
break;
}
else if (ret == -1) {
string errstr = strerror(errno);
etiLog.level(error) << "recv error " << errstr;
return {};
}
else {
rx += ret;
}
}
return buf;
}
static vector<string> split(const string& str, char c = ' ')
{
const char *s = str.data();
vector<string> result;
do {
const char *begin = s;
while (*s != c && *s)
s++;
result.push_back(string(begin, s));
} while (0 != *s++);
return result;
}
struct http_request_t {
bool valid = false;
bool is_get = false;
bool is_post = false;
string url;
map<string, string> headers;
string post_data;
};
static http_request_t parse_http_headers(Socket::TCPSocket& s) {
http_request_t r;
const auto first_line = recv_line(s);
const auto request_type = split(first_line);
if (request_type.size() != 3) {
return r;
}
else if (request_type[0] == "GET") {
r.is_get = true;
}
else if (request_type[0] == "POST") {
r.is_post = true;
}
else {
return r;
}
r.url = request_type[1];
while (true) {
string header_line = recv_line(s);
if (header_line == "\r\n") {
break;
}
const auto header = split(header_line, ':');
if (header.size() == 2) {
r.headers.emplace(header[0], header[1]);
}
}
if (r.is_post) {
constexpr auto CONTENT_LENGTH = "Content-Length";
if (r.headers.count(CONTENT_LENGTH) == 1) {
try {
const int content_length = stoi(r.headers[CONTENT_LENGTH]);
if (content_length > 1024 * 1024) {
etiLog.level(warn) << "Unreasonable POST Content-Length: " << content_length;
return r;
}
const auto buf = recv_exactly(s, content_length);
r.post_data = string(buf.begin(), buf.end());
}
catch (const invalid_argument&) {
etiLog.level(warn) << "Cannot parse POST Content-Length: " << r.headers[CONTENT_LENGTH];
return r;
}
catch (const out_of_range&) {
etiLog.level(warn) << "Cannot represent POST Content-Length: " << r.headers[CONTENT_LENGTH];
return r;
}
}
}
r.valid = true;
return r;
}
static bool send_http_response(
Socket::TCPSocket& s,
const string& statuscode,
const string& data,
const string& content_type = http_contenttype_text)
{
string headers = statuscode;
headers += content_type;
headers += http_nocache;
headers += "\r\n";
headers += data;
ssize_t ret = s.send(headers.data(), headers.size(), MSG_NOSIGNAL);
if (ret == -1) {
etiLog.level(warn) << "Failed to send response " << statuscode << " " << data;
}
return ret != -1;
}
bool WebServer::dispatch_client(Socket::TCPSocket&& sock)
{
try {
Socket::TCPSocket s(std::move(sock));
bool success = false;
if (not s.valid()) {
etiLog.level(error) << "socket in dispatcher not valid!";
return false;
}
const auto req = parse_http_headers(s);
if (not req.valid) {
return false;
}
if (req.is_get) {
if (req.url == "/") {
success = send_index(s);
}
else if (req.url == "/stats.json") {
success = send_stats(s);
}
}
else if (req.is_post) {
if (req.url == "/rc") {
//success = handle_rc(s, req.post_data);
}
else {
etiLog.level(warn) << "Could not understand POST request " << req.url;
}
}
else {
throw logic_error("valid req is neither GET nor POST!");
}
if (not success) {
send_http_response(s, http_404, "Could not understand request.\r\n");
}
return success;
}
catch (const std::exception& e)
{
return false;
}
}
bool WebServer::send_index(Socket::TCPSocket& s)
{
if (not send_http_response(s, http_ok, "", http_contenttype_text)) {
return false;
}
ssize_t ret = s.send(index_content.c_str(), index_content.size(), MSG_NOSIGNAL);
if (ret == -1) {
etiLog.level(warn) << "Failed to send index";
return false;
}
return true;
}
bool WebServer::send_stats(Socket::TCPSocket& s)
{
if (not send_http_response(s, http_ok, "", http_contenttype_json)) {
return false;
}
std::string jsonstr = "{ }";
{
unique_lock<mutex> lock(data_mutex);
if (not stats_json.empty()) {
jsonstr = stats_json;
}
}
ssize_t ret = s.send(jsonstr.c_str(), jsonstr.size(), MSG_NOSIGNAL);
if (ret == -1) {
etiLog.level(warn) << "Failed to send index";
return false;
}
return true;
}
|