-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathhttp_request.cpp
More file actions
594 lines (467 loc) · 16.9 KB
/
http_request.cpp
File metadata and controls
594 lines (467 loc) · 16.9 KB
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/*
This file is part of libhttpserver
Copyright (C) 2011-2019 Sebastiano Merlino
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include "httpserver/http_request.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "httpserver/http_utils.hpp"
#include "httpserver/string_utilities.hpp"
#ifdef HAVE_GNUTLS
#include <gnutls/x509.h>
// RAII wrapper for gnutls_x509_crt_t to ensure proper cleanup
class scoped_x509_cert {
public:
scoped_x509_cert() : cert_(nullptr), valid_(false) {}
~scoped_x509_cert() {
if (cert_ != nullptr) {
gnutls_x509_crt_deinit(cert_);
}
}
// Initialize from a TLS session's peer certificate
// Returns true if certificate was successfully loaded
bool init_from_session(gnutls_session_t session) {
unsigned int list_size = 0;
const gnutls_datum_t* cert_list = gnutls_certificate_get_peers(session, &list_size);
if (cert_list == nullptr || list_size == 0) {
return false;
}
if (gnutls_x509_crt_init(&cert_) != GNUTLS_E_SUCCESS) {
cert_ = nullptr;
return false;
}
if (gnutls_x509_crt_import(cert_, &cert_list[0], GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
gnutls_x509_crt_deinit(cert_);
cert_ = nullptr;
return false;
}
valid_ = true;
return true;
}
bool is_valid() const { return valid_; }
gnutls_x509_crt_t get() const { return cert_; }
// Non-copyable
scoped_x509_cert(const scoped_x509_cert&) = delete;
scoped_x509_cert& operator=(const scoped_x509_cert&) = delete;
private:
gnutls_x509_crt_t cert_;
bool valid_;
};
#endif // HAVE_GNUTLS
namespace httpserver {
const char http_request::EMPTY[] = "";
struct arguments_accumulator {
unescaper_ptr unescaper;
std::map<std::string, std::vector<std::string>, http::arg_comparator>* arguments;
};
void http_request::set_method(const std::string& method) {
this->method = string_utilities::to_upper_copy(method);
}
#ifdef HAVE_DAUTH
bool http_request::check_digest_auth(const std::string& realm, const std::string& password, int nonce_timeout, bool* reload_nonce) const {
std::string_view digested_user = get_digested_user();
int val = MHD_digest_auth_check(underlying_connection, realm.c_str(), digested_user.data(), password.c_str(), nonce_timeout);
if (val == MHD_INVALID_NONCE) {
*reload_nonce = true;
return false;
} else if (val == MHD_NO) {
*reload_nonce = false;
return false;
}
*reload_nonce = false;
return true;
}
bool http_request::check_digest_auth_ha1(
const std::string& realm,
const unsigned char* digest,
size_t digest_size,
int nonce_timeout,
bool* reload_nonce,
http::http_utils::digest_algorithm algo) const {
std::string_view digested_user = get_digested_user();
int val = MHD_digest_auth_check_digest2(
underlying_connection,
realm.c_str(),
digested_user.data(),
digest,
digest_size,
nonce_timeout,
static_cast<MHD_DigestAuthAlgorithm>(algo));
if (val == MHD_INVALID_NONCE) {
*reload_nonce = true;
return false;
} else if (val == MHD_NO) {
*reload_nonce = false;
return false;
}
*reload_nonce = false;
return true;
}
#endif // HAVE_DAUTH
std::string_view http_request::get_connection_value(std::string_view key, enum MHD_ValueKind kind) const {
const char* header_c = MHD_lookup_connection_value(underlying_connection, kind, key.data());
if (header_c == nullptr) return EMPTY;
return header_c;
}
MHD_Result http_request::build_request_header(void *cls, enum MHD_ValueKind kind, const char *key, const char *value) {
// Parameters needed to respect MHD interface, but not used in the implementation.
std::ignore = kind;
http::header_view_map* dhr = static_cast<http::header_view_map*>(cls);
(*dhr)[key] = value;
return MHD_YES;
}
const http::header_view_map http_request::get_headerlike_values(enum MHD_ValueKind kind) const {
http::header_view_map headers;
MHD_get_connection_values(underlying_connection, kind, &build_request_header, reinterpret_cast<void*>(&headers));
return headers;
}
std::string_view http_request::get_header(std::string_view key) const {
return get_connection_value(key, MHD_HEADER_KIND);
}
const http::header_view_map http_request::get_headers() const {
return get_headerlike_values(MHD_HEADER_KIND);
}
std::string_view http_request::get_footer(std::string_view key) const {
return get_connection_value(key, MHD_FOOTER_KIND);
}
const http::header_view_map http_request::get_footers() const {
return get_headerlike_values(MHD_FOOTER_KIND);
}
std::string_view http_request::get_cookie(std::string_view key) const {
return get_connection_value(key, MHD_COOKIE_KIND);
}
const http::header_view_map http_request::get_cookies() const {
return get_headerlike_values(MHD_COOKIE_KIND);
}
void http_request::populate_args() const {
if (cache->args_populated) {
return;
}
arguments_accumulator aa;
aa.unescaper = unescaper;
aa.arguments = &cache->unescaped_args;
MHD_get_connection_values(underlying_connection, MHD_GET_ARGUMENT_KIND, &build_request_args, reinterpret_cast<void*>(&aa));
cache->args_populated = true;
}
void http_request::grow_last_arg(const std::string& key, const std::string& value) {
auto it = cache->unescaped_args.find(key);
if (it != cache->unescaped_args.end()) {
if (!it->second.empty()) {
it->second.back() += value;
} else {
it->second.push_back(value);
}
} else {
cache->unescaped_args[key] = {value};
}
}
http_arg_value http_request::get_arg(std::string_view key) const {
populate_args();
auto it = cache->unescaped_args.find(key);
if (it != cache->unescaped_args.end()) {
http_arg_value arg;
arg.values.reserve(it->second.size());
for (const auto& value : it->second) {
arg.values.push_back(value);
}
return arg;
}
return http_arg_value();
}
std::string_view http_request::get_arg_flat(std::string_view key) const {
auto const it = cache->unescaped_args.find(key);
if (it != cache->unescaped_args.end()) {
return it->second[0];
}
return get_connection_value(key, MHD_GET_ARGUMENT_KIND);
}
const http::arg_view_map http_request::get_args() const {
populate_args();
http::arg_view_map arguments;
for (const auto& [key, value] : cache->unescaped_args) {
auto& arg_values = arguments[key];
for (const auto& v : value) {
arg_values.values.push_back(v);
}
}
return arguments;
}
const std::map<std::string_view, std::string_view, http::arg_comparator> http_request::get_args_flat() const {
populate_args();
std::map<std::string_view, std::string_view, http::arg_comparator> ret;
for (const auto&[key, val] : cache->unescaped_args) {
ret[key] = val[0];
}
return ret;
}
http::file_info& http_request::get_or_create_file_info(const std::string& key, const std::string& upload_file_name) {
return files[key][upload_file_name];
}
std::string_view http_request::get_querystring() const {
if (!cache->querystring.empty()) {
return cache->querystring;
}
MHD_get_connection_values(underlying_connection, MHD_GET_ARGUMENT_KIND, &build_request_querystring, reinterpret_cast<void*>(&cache->querystring));
return cache->querystring;
}
MHD_Result http_request::build_request_args(void *cls, enum MHD_ValueKind kind, const char *key, const char *arg_value) {
// Parameters needed to respect MHD interface, but not used in the implementation.
std::ignore = kind;
arguments_accumulator* aa = static_cast<arguments_accumulator*>(cls);
std::string value = ((arg_value == nullptr) ? "" : arg_value);
http::base_unescaper(&value, aa->unescaper);
(*aa->arguments)[key].push_back(value);
return MHD_YES;
}
MHD_Result http_request::build_request_querystring(void *cls, enum MHD_ValueKind kind, const char *key_value, const char *arg_value) {
// Parameters needed to respect MHD interface, but not used in the implementation.
std::ignore = kind;
std::string* querystring = static_cast<std::string*>(cls);
std::string_view key = key_value;
std::string_view value = ((arg_value == nullptr) ? "" : arg_value);
// Limit to a single allocation.
querystring->reserve(querystring->size() + key.size() + value.size() + 3);
*querystring += ((*querystring == "") ? "?" : "&");
*querystring += key;
*querystring += "=";
*querystring += value;
return MHD_YES;
}
void http_request::fetch_user_pass() const {
char* password = nullptr;
auto* username = MHD_basic_auth_get_username_password(underlying_connection, &password);
if (username != nullptr) {
cache->username = username;
MHD_free(username);
}
if (password != nullptr) {
cache->password = password;
MHD_free(password);
}
}
std::string_view http_request::get_user() const {
if (!cache->username.empty()) {
return cache->username;
}
fetch_user_pass();
return cache->username;
}
std::string_view http_request::get_pass() const {
if (!cache->password.empty()) {
return cache->password;
}
fetch_user_pass();
return cache->password;
}
#ifdef HAVE_DAUTH
std::string_view http_request::get_digested_user() const {
if (!cache->digested_user.empty()) {
return cache->digested_user;
}
char* digested_user_c = MHD_digest_auth_get_username(underlying_connection);
cache->digested_user = EMPTY;
if (digested_user_c != nullptr) {
cache->digested_user = digested_user_c;
free(digested_user_c);
}
return cache->digested_user;
}
#endif // HAVE_DAUTH
#ifdef HAVE_GNUTLS
bool http_request::has_tls_session() const {
const MHD_ConnectionInfo * conninfo = MHD_get_connection_info(underlying_connection, MHD_CONNECTION_INFO_GNUTLS_SESSION);
return (conninfo != nullptr);
}
gnutls_session_t http_request::get_tls_session() const {
const MHD_ConnectionInfo * conninfo = MHD_get_connection_info(underlying_connection, MHD_CONNECTION_INFO_GNUTLS_SESSION);
if (conninfo == nullptr) {
return nullptr;
}
return static_cast<gnutls_session_t>(conninfo->tls_session);
}
bool http_request::has_client_certificate() const {
if (!has_tls_session()) {
return false;
}
gnutls_session_t session = get_tls_session();
unsigned int list_size = 0;
const gnutls_datum_t* cert_list = gnutls_certificate_get_peers(session, &list_size);
return (cert_list != nullptr && list_size > 0);
}
std::string http_request::get_client_cert_dn() const {
if (!has_tls_session()) {
return "";
}
scoped_x509_cert cert;
if (!cert.init_from_session(get_tls_session())) {
return "";
}
size_t dn_size = 0;
gnutls_x509_crt_get_dn(cert.get(), nullptr, &dn_size);
std::string dn(dn_size, '\0');
if (gnutls_x509_crt_get_dn(cert.get(), &dn[0], &dn_size) != GNUTLS_E_SUCCESS) {
return "";
}
// Remove trailing null if present
if (!dn.empty() && dn.back() == '\0') {
dn.pop_back();
}
return dn;
}
std::string http_request::get_client_cert_issuer_dn() const {
if (!has_tls_session()) {
return "";
}
scoped_x509_cert cert;
if (!cert.init_from_session(get_tls_session())) {
return "";
}
size_t dn_size = 0;
gnutls_x509_crt_get_issuer_dn(cert.get(), nullptr, &dn_size);
std::string dn(dn_size, '\0');
if (gnutls_x509_crt_get_issuer_dn(cert.get(), &dn[0], &dn_size) != GNUTLS_E_SUCCESS) {
return "";
}
// Remove trailing null if present
if (!dn.empty() && dn.back() == '\0') {
dn.pop_back();
}
return dn;
}
std::string http_request::get_client_cert_cn() const {
if (!has_tls_session()) {
return "";
}
scoped_x509_cert cert;
if (!cert.init_from_session(get_tls_session())) {
return "";
}
size_t cn_size = 0;
gnutls_x509_crt_get_dn_by_oid(cert.get(), GNUTLS_OID_X520_COMMON_NAME, 0, 0, nullptr, &cn_size);
if (cn_size == 0) {
return "";
}
std::string cn(cn_size, '\0');
if (gnutls_x509_crt_get_dn_by_oid(cert.get(), GNUTLS_OID_X520_COMMON_NAME, 0, 0, &cn[0], &cn_size) != GNUTLS_E_SUCCESS) {
return "";
}
// Remove trailing null if present
if (!cn.empty() && cn.back() == '\0') {
cn.pop_back();
}
return cn;
}
bool http_request::is_client_cert_verified() const {
if (!has_tls_session()) {
return false;
}
gnutls_session_t session = get_tls_session();
unsigned int status = 0;
if (gnutls_certificate_verify_peers2(session, &status) != GNUTLS_E_SUCCESS) {
return false;
}
return (status == 0);
}
std::string http_request::get_client_cert_fingerprint_sha256() const {
if (!has_tls_session()) {
return "";
}
scoped_x509_cert cert;
if (!cert.init_from_session(get_tls_session())) {
return "";
}
unsigned char fingerprint[32]; // SHA-256 is 32 bytes
size_t fingerprint_size = sizeof(fingerprint);
if (gnutls_x509_crt_get_fingerprint(cert.get(), GNUTLS_DIG_SHA256, fingerprint, &fingerprint_size) != GNUTLS_E_SUCCESS) {
return "";
}
// Convert to hex string
std::string hex_fingerprint;
hex_fingerprint.reserve(fingerprint_size * 2);
for (size_t i = 0; i < fingerprint_size; ++i) {
char hex[3];
snprintf(hex, sizeof(hex), "%02x", fingerprint[i]);
hex_fingerprint += hex;
}
return hex_fingerprint;
}
time_t http_request::get_client_cert_not_before() const {
if (!has_tls_session()) {
return -1;
}
scoped_x509_cert cert;
if (!cert.init_from_session(get_tls_session())) {
return -1;
}
return gnutls_x509_crt_get_activation_time(cert.get());
}
time_t http_request::get_client_cert_not_after() const {
if (!has_tls_session()) {
return -1;
}
scoped_x509_cert cert;
if (!cert.init_from_session(get_tls_session())) {
return -1;
}
return gnutls_x509_crt_get_expiration_time(cert.get());
}
#endif // HAVE_GNUTLS
std::string_view http_request::get_requestor() const {
if (!cache->requestor_ip.empty()) {
return cache->requestor_ip;
}
const MHD_ConnectionInfo * conninfo = MHD_get_connection_info(underlying_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS);
cache->requestor_ip = http::get_ip_str(conninfo->client_addr);
return cache->requestor_ip;
}
uint16_t http_request::get_requestor_port() const {
const MHD_ConnectionInfo * conninfo = MHD_get_connection_info(underlying_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS);
return http::get_port(conninfo->client_addr);
}
std::ostream &operator<< (std::ostream &os, const http_request &r) {
os << r.get_method() << " Request [user:\"" << r.get_user() << "\" pass:\"" << r.get_pass() << "\"] path:\""
<< r.get_path() << "\"" << std::endl;
http::dump_header_map(os, "Headers", r.get_headers());
http::dump_header_map(os, "Footers", r.get_footers());
http::dump_header_map(os, "Cookies", r.get_cookies());
http::dump_arg_map(os, "Query Args", r.get_args());
os << " Version [ " << r.get_version() << " ] Requestor [ " << r.get_requestor()
<< " ] Port [ " << r.get_requestor_port() << " ]" << std::endl;
return os;
}
http_request::~http_request() {
for (const auto& file_key : get_files()) {
for (const auto& files : file_key.second) {
bool should_delete = true;
if (file_cleanup_callback != nullptr) {
try {
should_delete = file_cleanup_callback(file_key.first, files.first, files.second);
} catch (...) {
// If callback throws, default to deleting the file
should_delete = true;
}
}
if (should_delete) {
// C++17 has std::filesystem::remove()
remove(files.second.get_file_system_file_name().c_str());
}
}
}
}
} // namespace httpserver