-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHttp.h
More file actions
415 lines (381 loc) · 18 KB
/
Copy pathHttp.h
File metadata and controls
415 lines (381 loc) · 18 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
/// file : parsers/http.h
/// author : Siddharth Mishra (admin@brightprogrammer.in)
/// This is free and unencumbered software released into the public domain.
///
/// HTTP/1.1 request + response primitives. Pure parsing / serialization;
/// no socket dependency. The serializer renders a response into a `Str`
/// which the caller is free to write to any transport (sockets, files,
/// in-memory mocks).
#ifndef MISRA_PARSERS_HTTP_H
#define MISRA_PARSERS_HTTP_H
#include <Misra/Parsers/Http/Private.h>
#include <Misra/Std.h>
#include <Misra/Types.h>
typedef enum HttpRequestMethod {
HTTP_REQUEST_METHOD_UNKNOWN = 0,
HTTP_REQUEST_METHOD_GET,
HTTP_REQUEST_METHOD_POST,
HTTP_REQUEST_METHOD_DELETE,
HTTP_REQUEST_METHOD_PUT,
HTTP_REQUEST_METHOD_PATCH,
HTTP_REQUEST_METHOD_HEAD,
HTTP_REQUEST_METHOD_OPTIONS,
HTTP_REQUEST_METHOD_CONNECT,
HTTP_REQUEST_METHOD_TRACE,
} HttpRequestMethod;
///
/// A single `Key: Value` HTTP header. `key` and `value` are both `Str`
/// objects that own their backing storage through their stored
/// allocator. When kept inside a `Vec(HttpHeader)`, the deep-copy
/// callbacks installed via `HttpHeaderInit` handle duplication and
/// cleanup automatically.
///
/// TAGS: Http, Type, Header
///
typedef struct HttpHeader {
Str key;
Str value;
} HttpHeader;
///
/// Initialize an empty `HttpHeader`. Inside a `Scope` the allocator
/// argument may be omitted (uses `MisraScope`).
///
/// SUCCESS : Returns an `HttpHeader` whose `key` and `value` are empty
/// `Str`s backed by the resolved allocator.
/// FAILURE : Macro cannot fail (pure literal expansion).
///
/// TAGS: Http, Header, Init
///
#define HttpHeaderInit(...) OVERLOAD(HttpHeaderInit, __VA_ARGS__)
#define HttpHeaderInit_0() HttpHeaderInit_1(MisraScope)
#define HttpHeaderInit_1(alloc_ptr) ((HttpHeader) {.key = StrInit_1(alloc_ptr), .value = StrInit_1(alloc_ptr)})
typedef Vec(HttpHeader) HttpHeaders;
///
/// User-facing deinit. Releases the backing storage owned by
/// `header->key` and `header->value`, then zeros the struct.
///
/// SUCCESS : Returns to the caller. `*header` is zeroed.
/// FAILURE : Aborts via `LOG_FATAL` when `header` is NULL.
///
/// TAGS: Http, Deinit, Header, Init
///
void HttpHeaderDeinit(HttpHeader *header);
///
/// Container-callback shape of the same operation, matching
/// `GenericCopyDeinit`. Plumb this into `VecInitWithDeepCopy` so a
/// `Vec(HttpHeader)` automatically deinits each entry on removal.
///
/// SUCCESS : Returns to the caller. `*(HttpHeader *)header` is zeroed.
/// FAILURE : Function cannot fail. The container guarantees `header` is
/// non-NULL and a valid entry slot.
///
/// TAGS: Http, Deinit, Header, Init
///
///
/// Find a header by key (case-sensitive comparison).
///
/// Two call shapes via `OVERLOAD` + `_Generic` on `key`:
/// `HttpHeadersFind(headers, key)` -- `key` is `Str *` / `Zstr`.
/// `HttpHeadersFind(headers, key, key_len)` -- `key` is a counted view
/// (`Zstr`, `size`).
///
/// headers[in] : Caller's `Vec(HttpHeader)` to search.
/// key[in] : Key to look up.
/// key_len[in] : Length of `key` for the 3-arg counted form.
///
/// SUCCESS : Returns a pointer to the matching header inside the
/// vector. The pointer is valid until `*headers` is mutated
/// or deinitialized.
/// FAILURE : Returns `NULL` if no header matches; `*headers` is
/// unchanged.
///
/// TAGS: Http, Find, Header
///
HttpHeader *http_headers_find_zstr(HttpHeaders *headers, Zstr key);
HttpHeader *http_headers_find_str(HttpHeaders *headers, const Str *key);
HttpHeader *http_headers_find_cstr(HttpHeaders *headers, Zstr key, size key_len);
#define HttpHeadersFind(...) OVERLOAD(HttpHeadersFind, __VA_ARGS__)
#define HttpHeadersFind_2(headers, key) \
_Generic((key), Str *: http_headers_find_str, Zstr: http_headers_find_zstr, char *: http_headers_find_zstr)( \
(headers), \
(key) \
)
#define HttpHeadersFind_3(headers, key, key_len) http_headers_find_cstr((headers), (Zstr)(key), (key_len))
typedef enum HttpResponseCode {
HTTP_RESPONSE_CODE_INVALID = 0,
HTTP_RESPONSE_CODE_CONTINUE = 100,
HTTP_RESPONSE_CODE_SWITCHING_PROTOCOLS = 101,
HTTP_RESPONSE_CODE_PROCESSING = 102,
HTTP_RESPONSE_CODE_EARLY_HINTS = 103,
HTTP_RESPONSE_CODE_OK = 200,
HTTP_RESPONSE_CODE_CREATED = 201,
HTTP_RESPONSE_CODE_ACCEPTED = 202,
HTTP_RESPONSE_CODE_NON_AUTHORITATIVE_INFORMATION = 203,
HTTP_RESPONSE_CODE_NO_CONTENT = 204,
HTTP_RESPONSE_CODE_RESET_CONTENT = 205,
HTTP_RESPONSE_CODE_PARTIAL_CONTENT = 206,
HTTP_RESPONSE_CODE_MULTI_STATUS = 207,
HTTP_RESPONSE_CODE_ALREADY_REPORTED = 208,
HTTP_RESPONSE_CODE_IM_USED = 226,
HTTP_RESPONSE_CODE_MULTIPLE_CHOICES = 300,
HTTP_RESPONSE_CODE_MOVED_PERMANENTLY = 301,
HTTP_RESPONSE_CODE_FOUND = 302,
HTTP_RESPONSE_CODE_SEE_OTHER = 303,
HTTP_RESPONSE_CODE_NOT_MODIFIED = 304,
HTTP_RESPONSE_CODE_USE_PROXY = 305,
HTTP_RESPONSE_CODE_TEMPORARY_REDIRECT = 307,
HTTP_RESPONSE_CODE_PERMANENT_REDIRECT = 308,
HTTP_RESPONSE_CODE_BAD_REQUEST = 400,
HTTP_RESPONSE_CODE_UNAUTHORIZED = 401,
HTTP_RESPONSE_CODE_PAYMENT_REQUIRED = 402,
HTTP_RESPONSE_CODE_FORBIDDEN = 403,
HTTP_RESPONSE_CODE_NOT_FOUND = 404,
HTTP_RESPONSE_CODE_METHOD_NOT_ALLOWED = 405,
HTTP_RESPONSE_CODE_NOT_ACCEPTABLE = 406,
HTTP_RESPONSE_CODE_PROXY_AUTHENTICATION_REQUIRED = 407,
HTTP_RESPONSE_CODE_REQUEST_TIMEOUT = 408,
HTTP_RESPONSE_CODE_CONFLICT = 409,
HTTP_RESPONSE_CODE_GONE = 410,
HTTP_RESPONSE_CODE_LENGTH_REQUIRED = 411,
HTTP_RESPONSE_CODE_PRECONDITION_FAILED = 412,
HTTP_RESPONSE_CODE_PAYLOAD_TOO_LARGE = 413,
HTTP_RESPONSE_CODE_URI_TOO_LONG = 414,
HTTP_RESPONSE_CODE_UNSUPPORTED_MEDIA_TYPE = 415,
HTTP_RESPONSE_CODE_RANGE_NOT_SATISFIABLE = 416,
HTTP_RESPONSE_CODE_EXPECTATION_FAILED = 417,
HTTP_RESPONSE_CODE_IM_A_TEAPOT = 418,
HTTP_RESPONSE_CODE_MISDIRECTED_REQUEST = 421,
HTTP_RESPONSE_CODE_UNPROCESSABLE_ENTITY = 422,
HTTP_RESPONSE_CODE_LOCKED = 423,
HTTP_RESPONSE_CODE_FAILED_DEPENDENCY = 424,
HTTP_RESPONSE_CODE_TOO_EARLY = 425,
HTTP_RESPONSE_CODE_UPGRADE_REQUIRED = 426,
HTTP_RESPONSE_CODE_PRECONDITION_REQUIRED = 428,
HTTP_RESPONSE_CODE_TOO_MANY_REQUESTS = 429,
HTTP_RESPONSE_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
HTTP_RESPONSE_CODE_UNAVAILABLE_FOR_LEGAL_REASONS = 451,
HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR = 500,
HTTP_RESPONSE_CODE_NOT_IMPLEMENTED = 501,
HTTP_RESPONSE_CODE_BAD_GATEWAY = 502,
HTTP_RESPONSE_CODE_SERVICE_UNAVAILABLE = 503,
HTTP_RESPONSE_CODE_GATEWAY_TIMEOUT = 504,
HTTP_RESPONSE_CODE_HTTP_VERSION_NOT_SUPPORTED = 505,
HTTP_RESPONSE_CODE_VARIANT_ALSO_NEGOTIATES = 506,
HTTP_RESPONSE_CODE_INSUFFICIENT_STORAGE = 507,
HTTP_RESPONSE_CODE_LOOP_DETECTED = 508,
HTTP_RESPONSE_CODE_NOT_EXTENDED = 510,
HTTP_RESPONSE_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511,
} HttpResponseCode;
typedef enum HttpContentType {
HTTP_CONTENT_TYPE_INVALID = 0,
HTTP_CONTENT_TYPE_TEXT_HTML,
HTTP_CONTENT_TYPE_TEXT_PLAIN,
HTTP_CONTENT_TYPE_TEXT_CSS,
HTTP_CONTENT_TYPE_TEXT_JAVASCRIPT,
HTTP_CONTENT_TYPE_TEXT_CSV,
HTTP_CONTENT_TYPE_APPLICATION_JSON,
HTTP_CONTENT_TYPE_APPLICATION_XML,
HTTP_CONTENT_TYPE_APPLICATION_JAVASCRIPT,
HTTP_CONTENT_TYPE_APPLICATION_PDF,
HTTP_CONTENT_TYPE_APPLICATION_OCTET_STREAM,
HTTP_CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED,
HTTP_CONTENT_TYPE_APPLICATION_ZIP,
HTTP_CONTENT_TYPE_APPLICATION_MS_EXCEL,
HTTP_CONTENT_TYPE_APPLICATION_OPENXML_SPREADSHEET,
HTTP_CONTENT_TYPE_APPLICATION_LD_JSON,
HTTP_CONTENT_TYPE_APPLICATION_GRAPHQL,
HTTP_CONTENT_TYPE_APPLICATION_FONT_WOFF,
HTTP_CONTENT_TYPE_IMAGE_JPEG,
HTTP_CONTENT_TYPE_IMAGE_PNG,
HTTP_CONTENT_TYPE_IMAGE_GIF,
HTTP_CONTENT_TYPE_IMAGE_BMP,
HTTP_CONTENT_TYPE_IMAGE_WEBP,
HTTP_CONTENT_TYPE_IMAGE_SVG_XML,
HTTP_CONTENT_TYPE_AUDIO_MPEG,
HTTP_CONTENT_TYPE_AUDIO_OGG,
HTTP_CONTENT_TYPE_AUDIO_WAV,
HTTP_CONTENT_TYPE_VIDEO_MP4,
HTTP_CONTENT_TYPE_VIDEO_OGG,
HTTP_CONTENT_TYPE_VIDEO_WEBM,
HTTP_CONTENT_TYPE_MULTIPART_FORM_DATA,
HTTP_CONTENT_TYPE_MULTIPART_BYTERANGES,
HTTP_CONTENT_TYPE_FONT_WOFF,
HTTP_CONTENT_TYPE_FONT_WOFF2,
} HttpContentType;
///
/// Parsed HTTP request. Carries the allocator that owns `url` and
/// `headers`; all sub-allocations route through the same handle.
///
/// TAGS: Http, Type, Request
///
typedef struct HttpRequest {
Allocator *allocator;
HttpRequestMethod method;
Str url;
HttpHeaders headers;
} HttpRequest;
///
/// Initialize an empty `HttpRequest`. Inside a `Scope` the allocator
/// argument may be omitted (uses `MisraScope`).
///
/// SUCCESS : Returns an `HttpRequest` with `method` set to
/// `HTTP_REQUEST_METHOD_UNKNOWN`, empty `url`, and an empty
/// `headers` Vec that takes ownership of inserted headers by
/// move (freed per-element by `HttpRequestDeinit`).
/// FAILURE : Macro cannot fail (pure literal expansion).
///
/// TAGS: Http, Request, Init
///
#define HttpRequestInit(...) OVERLOAD(HttpRequestInit, __VA_ARGS__)
#define HttpRequestInit_0() HttpRequestInit_1(MisraScope)
#define HttpRequestInit_1(alloc_ptr) \
((HttpRequest) {.allocator = ALLOCATOR_OF(alloc_ptr), \
.method = HTTP_REQUEST_METHOD_UNKNOWN, \
.url = StrInit_1(alloc_ptr), \
.headers = VecInitWithDeepCopy_3(NULL, http_header_deinit, alloc_ptr)})
///
/// Parse an HTTP/1.1 request out of `in` into `req`. `req` must already
/// be initialized with `HttpRequestInit(...)` so the parser has an
/// allocator to write into.
///
/// Two call shapes via `OVERLOAD` + `_Generic` on `in`:
/// `HttpRequestParse(req, in)` -- `in` is `Str *` / `Zstr`.
/// `HttpRequestParse(req, in, in_len)` -- `in` is a counted view
/// (`Zstr`, `size`).
///
/// SUCCESS : Returns a pointer past the parsed request line + headers
/// (start of the body), pointing into the caller's `in`.
/// FAILURE : Returns `in` unchanged when the input is malformed.
///
/// TAGS: Http, Parse, Request
///
#define HttpRequestParse(...) OVERLOAD(HttpRequestParse, __VA_ARGS__)
#define HttpRequestParse_2(req, in) \
_Generic( \
(in), \
Str *: http_request_parse_str((req), (const Str *)(in)), \
Zstr: http_request_parse_zstr((req), (Zstr)(in)), \
char *: http_request_parse_zstr((req), (Zstr)(in)) \
)
#define HttpRequestParse_3(req, in, in_len) http_request_parse_cstr((req), (Zstr)(in), (in_len))
///
/// Release storage owned by `req` and zero the struct. Safe to call on
/// a partially-parsed request.
///
/// SUCCESS : Returns to the caller. `*req` is zeroed.
/// FAILURE : Aborts via `LOG_FATAL` when `req` is NULL.
///
/// TAGS: Http, Request, Deinit, Init
///
void HttpRequestDeinit(HttpRequest *req);
///
/// HTTP response under construction. Same allocator-ownership story as
/// `HttpRequest`.
///
/// TAGS: Http, Type, Response
///
typedef struct HttpResponse {
Allocator *allocator;
HttpContentType content_type;
HttpResponseCode status_code;
HttpHeaders headers;
Str body;
} HttpResponse;
///
/// Initialize an empty `HttpResponse`. Inside a `Scope` the allocator
/// argument may be omitted (uses `MisraScope`).
///
/// SUCCESS : Returns an `HttpResponse` with `content_type` and
/// `status_code` set to their invalid sentinels, an empty
/// `headers` Vec that takes ownership of inserted headers by
/// move (freed per-element by `HttpResponseDeinit`), and
/// an empty `body`.
/// FAILURE : Macro cannot fail (pure literal expansion).
///
/// TAGS: Http, Response, Init
///
#define HttpResponseInit(...) OVERLOAD(HttpResponseInit, __VA_ARGS__)
#define HttpResponseInit_0() HttpResponseInit_1(MisraScope)
#define HttpResponseInit_1(alloc_ptr) \
((HttpResponse) {.allocator = ALLOCATOR_OF(alloc_ptr), \
.content_type = HTTP_CONTENT_TYPE_INVALID, \
.status_code = HTTP_RESPONSE_CODE_INVALID, \
.headers = VecInitWithDeepCopy_3(NULL, http_header_deinit, alloc_ptr), \
.body = StrInit_1(alloc_ptr)})
///
/// Wire-format lookup tables.
///
/// SUCCESS : Returns the canonical HTTP/1.1 reason-phrase string for
/// the given code / content type. The pointer is to static
/// storage and is valid for the lifetime of the program.
/// FAILURE : Returns `"Unknown"` for codes / content types outside the
/// recognised enum range. Cannot fail.
///
/// TAGS: Http, ResponseCode, Response, Convert, Zstr
///
Zstr HttpResponseCodeToZstr(HttpResponseCode code);
Zstr HttpContentTypeToZstr(HttpContentType content_type);
///
/// Populate `response` as an HTML reply. The body is a deep copy of
/// `html` allocated through `response->allocator`.
///
/// SUCCESS : Returns `response` with `status_code`, `content_type`, and
/// `body` updated.
/// FAILURE : Does not return - aborts on NULL arguments.
///
/// TAGS: Http, Respond, Html
///
HttpResponse *HttpRespondWithHtml(HttpResponse *response, HttpResponseCode status, const Str *html);
#if FEATURE_FILE
///
/// Populate `response` from a file on disk. The file's bytes are read
/// through `response->allocator`. Only available when the `file`
/// feature is enabled.
///
/// Two call shapes via `OVERLOAD` + `_Generic` on `filepath`:
/// `HttpRespondWithFile(response, status, content_type, filepath)`
/// -- `filepath` is `Str *` / `Zstr`.
/// `HttpRespondWithFile(response, status, content_type, filepath, filepath_len)`
/// -- `filepath` is a counted view (`Zstr`, `size`).
///
/// SUCCESS : Returns `response` with body filled.
/// FAILURE : Returns NULL on I/O or allocation failure.
///
/// TAGS: Http, Respond, File
///
# define HttpRespondWithFile(...) OVERLOAD(HttpRespondWithFile, __VA_ARGS__)
# define HttpRespondWithFile_4(response, status, content_type, filepath) \
_Generic( \
(filepath), \
Str *: http_respond_with_file_str((response), (status), (content_type), (const Str *)(filepath)), \
Zstr: http_respond_with_file_zstr((response), (status), (content_type), (Zstr)(filepath)), \
char *: http_respond_with_file_zstr((response), (status), (content_type), (Zstr)(filepath)) \
)
# define HttpRespondWithFile_5(response, status, content_type, filepath, filepath_len) \
http_respond_with_file_cstr((response), (status), (content_type), (Zstr)(filepath), (filepath_len))
#endif
///
/// Serialize `response` to its on-wire HTTP/1.1 form. Caller owns the
/// returned `Str` and must deinit it. The result is exactly the bytes
/// that should land on the transport (sockets / files / etc.) — no
/// transport call is made.
///
/// SUCCESS : Returns a populated `Str`.
/// FAILURE : Returns an empty `Str` and logs the failing condition
/// (unknown response code, unknown content type, etc.).
///
/// TAGS: Http, Serialize, Response
///
#define HttpResponseSerialize(...) OVERLOAD(HttpResponseSerialize, __VA_ARGS__)
#define HttpResponseSerialize_1(response) http_response_serialize((response), MisraScope)
#define HttpResponseSerialize_2(response, alloc) http_response_serialize((response), ALLOCATOR_OF(alloc))
///
/// Release storage owned by `response` and zero the struct.
///
/// SUCCESS : Returns to the caller. `*response` is zeroed.
/// FAILURE : Aborts via `LOG_FATAL` when `response` is NULL.
///
/// TAGS: Http, Response, Deinit, Init
///
void HttpResponseDeinit(HttpResponse *response);
#endif // MISRA_PARSERS_HTTP_H