-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathhttp_utils.hpp
More file actions
504 lines (443 loc) · 20.1 KB
/
Copy pathhttp_utils.hpp
File metadata and controls
504 lines (443 loc) · 20.1 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
/*
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
*/
#if !defined (_HTTPSERVER_HPP_INSIDE_) && !defined (HTTPSERVER_COMPILATION)
#error "Only <httpserver.hpp> or <httpserverpp> can be included directly."
#endif
#ifndef SRC_HTTPSERVER_HTTP_UTILS_HPP_
#define SRC_HTTPSERVER_HTTP_UTILS_HPP_
// TASK-019 / TASK-020: backend headers (libmicrohttpd, GnuTLS, BSD-socket)
// are deliberately NOT included from this public header.
// The enums declared below previously took their integer values from
// upstream macros (MHD_USE_*, MHD_DIGEST_AUTH_ALGO3_*, MHD_DAUTH_*,
// GNUTLS_CRD_*), dragging the backend headers through the umbrella to
// every downstream consumer. Those values are now hard-coded to match
// the stable upstream ABI; static_assert blocks in src/webserver.cpp
// and src/http_request.cpp (where the upstream headers are reachable)
// pin the enum values to the upstream macros so any renumber breaks
// the build at the right place. `struct sockaddr` is forward-declared
// at file scope; the implementations live in src/http_utils.cpp where
// the BSD-socket header is included directly.
// needed to force Vista as a bare minimum to have inet_ntop (libmicro defines
// this to include XP support as a lower version).
#if defined(__MINGW32__) || defined(__CYGWIN32__)
#define _WINDOWS
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x600
#endif
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <cctype>
#include <iosfwd>
#include <map>
#include <string>
#include <vector>
#include "httpserver/constants.hpp"
#include "httpserver/http_arg_value.hpp"
// Forward-declare the BSD-socket address family. Only pointer-to-incomplete
// uses appear in this header; the .cpp side includes the BSD-socket header
// directly. MinGW/Windows uses winsock2.h; the same forward declaration is
// valid there since the canonical name `struct sockaddr` is the same across
// POSIX and Win32.
struct sockaddr;
namespace httpserver {
enum file_upload_target_T {
FILE_UPLOAD_MEMORY_ONLY,
FILE_UPLOAD_DISK_ONLY,
FILE_UPLOAD_MEMORY_AND_DISK,
};
typedef void(*unescaper_ptr)(std::string&);
namespace http {
struct generateFilenameException : public std::exception {
public:
explicit generateFilenameException(const std::string& message) noexcept : error_message(message) {
}
const char* what() const noexcept {
return error_message.c_str();
}
private:
std::string error_message;
};
class http_utils {
public:
// TASK-019: hard-coded values matching gnutls_credentials_type_t
// (a stable public ABI). Values pinned to the GnuTLS macros via
// static_assert in src/webserver.cpp so an upstream renumber would
// break the build. The enum is unconditional (PRD-FLG-REQ-001
// forbids gating public-header declarations on HAVE_GNUTLS); when
// GnuTLS is disabled at build time, selecting one of these via
// create_webserver().cred_type(...) hits the existing
// feature-unavailable path on use_ssl(true).
enum cred_type_T {
NONE = -1,
CERTIFICATE = 1, // GNUTLS_CRD_CERTIFICATE
ANON = 2, // GNUTLS_CRD_ANON
SRP = 3, // GNUTLS_CRD_SRP
PSK = 4, // GNUTLS_CRD_PSK
IA = 5 // GNUTLS_CRD_IA
};
// TASK-020: hard-coded values mirroring libmicrohttpd's MHD_FLAG enum
// (MHD_USE_AUTO=65536, MHD_USE_SELECT_INTERNALLY=8,
// MHD_USE_THREAD_PER_CONNECTION=4). Pinned to the upstream macros
// via static_assert in src/webserver.cpp so an upstream renumber
// breaks the build at the right place rather than silently mis-routing
// start-mode selection.
enum start_method_T {
INTERNAL_SELECT = 65544, // MHD_USE_SELECT_INTERNALLY | MHD_USE_AUTO
THREAD_PER_CONNECTION = 65540, // MHD_USE_THREAD_PER_CONNECTION | MHD_USE_AUTO
EXTERNAL_SELECT = 65536 // MHD_USE_AUTO
};
enum policy_T {
ACCEPT,
REJECT
};
enum IP_version_T {
IPV4 = 4,
IPV6 = 16
};
// TASK-020: hard-coded values mirroring libmicrohttpd's
// MHD_DigestAuthAlgo3 / MHD_DigestAuthResult enums. The integer
// values follow upstream's bitfield encoding
// (BASE_ALGO_X | NON_SESSION = X | 64 for the algorithms; the
// result codes are stable signed ints). Pinned via static_assert
// in src/http_request.cpp where <microhttpd.h> is reachable, so
// an upstream renumber breaks the build at the right place.
// The enums are unconditional (PRD-FLG-REQ-001 forbids gating
// public-header declarations on HAVE_DAUTH); when digest auth is
// disabled at build time, the corresponding methods on
// http_request hit the existing feature-unavailable path.
enum class digest_algorithm {
MD5 = 65, // MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION
SHA256 = 66, // MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION
SHA512_256 = 68 // MHD_DIGEST_BASE_ALGO_SHA512_256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION
};
enum class digest_auth_result {
OK = 1, // MHD_DAUTH_OK
// GENERIC_ERROR (not "ERROR") because <wingdi.h> on Windows
// unconditionally `#define`s ERROR to 0, which the preprocessor
// expands inside scoped-enum bodies just like anywhere else.
GENERIC_ERROR = 0, // MHD_DAUTH_ERROR ("general error")
WRONG_HEADER = -1, // MHD_DAUTH_WRONG_HEADER
WRONG_USERNAME = -2, // MHD_DAUTH_WRONG_USERNAME
WRONG_REALM = -3, // MHD_DAUTH_WRONG_REALM
WRONG_URI = -4, // MHD_DAUTH_WRONG_URI
WRONG_QOP = -5, // MHD_DAUTH_WRONG_QOP
WRONG_ALGO = -6, // MHD_DAUTH_WRONG_ALGO
TOO_LARGE = -15, // MHD_DAUTH_TOO_LARGE
NONCE_STALE = -17, // MHD_DAUTH_NONCE_STALE
NONCE_OTHER_COND = -18, // MHD_DAUTH_NONCE_OTHER_COND
NONCE_WRONG = -33, // MHD_DAUTH_NONCE_WRONG
RESPONSE_WRONG = -34 // MHD_DAUTH_RESPONSE_WRONG
};
static constexpr size_t md5_digest_size = 16;
static constexpr size_t sha256_digest_size = 32;
static constexpr size_t sha512_256_digest_size = 32;
static const uint16_t http_method_connect_code;
static const uint16_t http_method_delete_code;
static const uint16_t http_method_get_code;
static const uint16_t http_method_head_code;
static const uint16_t http_method_options_code;
static const uint16_t http_method_post_code;
static const uint16_t http_method_put_code;
static const uint16_t http_method_trace_code;
static const uint16_t http_method_patch_code;
static const uint16_t http_method_unknown_code;
static const int http_continue;
static const int http_switching_protocol;
static const int http_processing;
static const int http_ok;
static const int http_created;
static const int http_accepted;
static const int http_non_authoritative_information;
static const int http_no_content;
static const int http_reset_content;
static const int http_partial_content;
static const int http_multi_status;
static const int http_multiple_choices;
static const int http_moved_permanently;
static const int http_found;
static const int http_see_other;
static const int http_not_modified;
static const int http_use_proxy;
static const int http_switch_proxy;
static const int http_temporary_redirect;
static const int http_bad_request;
static const int http_unauthorized;
static const int http_payment_required;
static const int http_forbidden;
static const int http_not_found;
static const int http_method_not_allowed;
static const int http_method_not_acceptable;
static const int http_proxy_authentication_required;
static const int http_request_timeout;
static const int http_conflict;
static const int http_gone;
static const int http_length_required;
static const int http_precondition_failed;
static const int http_request_entity_too_large;
static const int http_request_uri_too_long;
static const int http_unsupported_media_type;
static const int http_requested_range_not_satisfiable;
static const int http_expectation_failed;
static const int http_unprocessable_entity;
static const int http_locked;
static const int http_failed_dependency;
static const int http_upgrade_required;
static const int http_retry_with;
static const int http_internal_server_error;
static const int http_not_implemented;
static const int http_bad_gateway;
static const int http_service_unavailable;
static const int http_gateway_timeout;
static const int http_version_not_supported;
static const int http_variant_also_negotiated;
static const int http_insufficient_storage;
static const int http_bandwidth_limit_exceeded;
static const int http_not_extended;
static const int shoutcast_response;
// See also: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
static const char* http_header_accept;
static const char* http_header_accept_charset;
static const char* http_header_accept_encoding;
static const char* http_header_accept_language;
static const char* http_header_accept_ranges;
static const char* http_header_age;
static const char* http_header_allow;
static const char* http_header_authorization;
static const char* http_header_cache_control;
static const char* http_header_connection;
static const char* http_header_content_encoding;
static const char* http_header_content_language;
static const char* http_header_content_length;
static const char* http_header_content_location;
static const char* http_header_content_md5;
static const char* http_header_content_range;
static const char* http_header_content_type;
static const char* http_header_date;
static const char* http_header_etag;
static const char* http_header_expect;
static const char* http_header_expires;
static const char* http_header_from;
static const char* http_header_host;
static const char* http_header_if_match;
static const char* http_header_if_modified_since;
static const char* http_header_if_none_match;
static const char* http_header_if_range;
static const char* http_header_if_unmodified_since;
static const char* http_header_last_modified;
static const char* http_header_location;
static const char* http_header_max_forwards;
static const char* http_header_pragma;
static const char* http_header_proxy_authenticate;
static const char* http_header_proxy_authentication;
static const char* http_header_range;
static const char* http_header_referer;
static const char* http_header_retry_after;
static const char* http_header_server;
static const char* http_header_te;
static const char* http_header_trailer;
static const char* http_header_transfer_encoding;
static const char* http_header_upgrade;
static const char* http_header_user_agent;
static const char* http_header_vary;
static const char* http_header_via;
static const char* http_header_warning;
static const char* http_header_www_authenticate;
static const char* http_version_1_0;
static const char* http_version_1_1;
static const char* http_method_connect;
static const char* http_method_delete;
static const char* http_method_head;
static const char* http_method_get;
static const char* http_method_options;
static const char* http_method_post;
static const char* http_method_put;
static const char* http_method_trace;
static const char* http_method_patch;
static const char* http_post_encoding_form_urlencoded;
static const char* http_post_encoding_multipart_formdata;
static const char* application_octet_stream;
static const char* text_plain;
static const char* upload_filename_template;
static const char path_separator;
static std::vector<std::string> tokenize_url(const std::string&, const char separator = '/');
static std::string standardize_url(const std::string&);
static const std::string generate_random_upload_filename(const std::string& directory);
static std::string sanitize_upload_filename(const std::string& filename);
static const char* reason_phrase(unsigned int status_code);
// TASK-020: parameter is the integer value of an `MHD_FEATURE`
// enumerator. The signature is `int` rather than `enum MHD_FEATURE`
// so this header doesn't have to drag in <microhttpd.h>; callers
// can still pass an `MHD_FEATURE_*` enumerator directly because the
// enum's underlying type implicitly converts to int.
static bool is_feature_supported(int feature);
static const char* get_mhd_version();
};
#define COMPARATOR(x, y, op) { \
size_t l1 = (x).size(); \
size_t l2 = (y).size(); \
if (l1 < l2) return true; \
if (l1 > l2) return false; \
\
for (size_t n = 0; n < l1; n++) { \
int xc = op((x)[n]); \
int yc = op((y)[n]); \
if (xc < yc) return true; \
if (xc > yc) return false; \
} \
return false; \
}
// ASCII-only uppercase helper for header name comparison.
// HTTP header names are defined to be US-ASCII (RFC 7230 §3.2), so using
// the locale-aware std::toupper on every character is unnecessary overhead.
// This branchless helper folds a-z to A-Z and leaves all other bytes unchanged.
// It is intentionally NOT locale-aware: non-ASCII bytes pass through as-is.
inline int http_header_toupper(char c) {
return (c >= 'a' && c <= 'z') ? c - ('a' - 'A') : static_cast<unsigned char>(c);
}
class header_comparator {
public:
// is_transparent enables heterogeneous lookup against header_map
// (std::map<std::string, std::string, header_comparator>): callers
// can pass std::string_view directly to find()/count() without
// constructing a std::string. Required by TASK-011's
// string_view-returning const accessors on http_response.
using is_transparent = std::true_type;
/**
* Case-insensitive less-than comparison.
* @param x first string to compare.
* @param y second string to compare.
* @return `true` iff @p x sorts before @p y under case-insensitive
* lexicographic order.
**/
bool operator()(std::string_view x, std::string_view y) const {
COMPARATOR(x, y, http_header_toupper);
}
/// @copydoc operator()(std::string_view, std::string_view) const
bool operator()(const std::string& x, const std::string& y) const {
COMPARATOR(x, y, http_header_toupper);
}
};
/**
* Operator Class that is used to compare two strings. The comparison can be sensitive or insensitive.
* The default comparison is case sensitive. To obtain insensitive comparison you have to pass in
* compilation phase the flag CASE_INSENSITIVE to the preprocessor.
**/
class arg_comparator {
public:
using is_transparent = std::true_type;
/**
* Less-than comparison between two argument keys.
*
* Defaults to case-sensitive byte-wise ordering; if the library was
* built with `-DCASE_INSENSITIVE` it folds upper-case before
* comparing, matching arg_map's documented contract.
*
* @param x first string to compare.
* @param y second string to compare.
* @return `true` iff @p x sorts before @p y under the active mode.
**/
bool operator()(std::string_view x, std::string_view y) const {
#ifdef CASE_INSENSITIVE
COMPARATOR(x, y, std::toupper);
#else
COMPARATOR(x, y,); // NOLINT(whitespace/comma)
#endif
}
/// @copydoc operator()(std::string_view, std::string_view) const
bool operator()(const std::string& x, const std::string& y) const {
return operator()(std::string_view(x), std::string_view(y));
}
/// @copydoc operator()(std::string_view, std::string_view) const
bool operator()(std::string_view x, const std::string& y) const {
return operator()(x, std::string_view(y));
}
/// @copydoc operator()(std::string_view, std::string_view) const
bool operator()(const std::string& x, std::string_view y) const {
return operator()(std::string_view(x), y);
}
};
using header_map = std::map<std::string, std::string, http::header_comparator>;
// WARNING: header_view_map keys and values are non-owning views (std::string_view).
// Callers MUST NOT store a header_view_map beyond the lifetime of the header_map
// whose strings it views, and MUST NOT mutate that source map while any view is
// in use. Storing a header_view_map across response mutations is a use-after-free
// bug (CWE-416). This type is used internally for diagnostic formatting only.
using header_view_map = std::map<std::string_view, std::string_view, http::header_comparator>;
using arg_map = std::map<std::string, http_arg_value, http::arg_comparator>;
using arg_view_map = std::map<std::string_view, http_arg_value, http::arg_comparator>;
} // namespace http
} // namespace httpserver
// ip_representation lives in its own header; included here so existing
// consumers of <httpserver/http_utils.hpp> still see the type.
#include "httpserver/ip_representation.hpp"
namespace httpserver {
namespace http {
/**
* Method used to get an ip in form of string from a sockaddr structure.
*
* The buffer length is computed internally from the address family; the
* v1 `maxlen` parameter was removed in v2.0.
*
* @param sa The sockaddr object to find the ip address from.
* @return string containing the ip address.
**/
std::string get_ip_str(const struct sockaddr *sa);
/**
* Method used to get a port from a sockaddr
* @param sa The sockaddr object to find the port from
* @return short representing the port
**/
uint16_t get_port(const struct sockaddr* sa);
/**
* Method to output the contents of a headers map to a std::ostream
* @param os The ostream
* @param prefix Prefix to identify the map
* @param map
**/
void dump_header_map(std::ostream& os, const std::string& prefix, const http::header_view_map& map);
/**
* Overload that accepts the owning header_map directly, avoiding an O(n)
* copy into a temporary header_view_map. Preferred for diagnostic output
* (operator<<) where the source map is immediately available.
* @param os The ostream
* @param prefix Prefix to identify the map
* @param map
**/
void dump_header_map(std::ostream& os, const std::string& prefix, const http::header_map& map);
/**
* Method to output the contents of an arguments map to a std::ostream
* @param os The ostream
* @param prefix Prefix to identify the map
* @param map
**/
void dump_arg_map(std::ostream& os, const std::string& prefix, const http::arg_view_map& map);
/**
* Process escape sequences ('+'=space, %HH) Updates val in place; the
* result should be UTF-8 encoded and cannot be larger than the input.
* The result must also still be 0-terminated.
*
* @param val the string to unescape
* @return length of the resulting val (strlen(val) maybe
* shorter afterwards due to elimination of escape sequences)
*/
size_t http_unescape(std::string* val);
const std::string load_file(const std::string& filename);
size_t base_unescaper(std::string*, unescaper_ptr unescaper);
} // namespace http
} // namespace httpserver
#endif // SRC_HTTPSERVER_HTTP_UTILS_HPP_