A low-key HTTP micro-framework for people who hate web bloat
git clone git://soophie.de/tpee
blob: a6d3a3b3a624943963f4cc41c5a8b0b92cf9eb86 (36241 bytes)[doc][blame][raw]
1
/*2
* Copyright (C) 2026 Sophie Sitzler3
*4
* This program is free software: you can redistribute it and/or modify5
* it under the terms of the GNU General Public License as published by6
* the Free Software Foundation, either version 3 of the License, or7
* (at your option) any later version.8
*9
* This program is distributed in the hope that it will be useful,10
* but WITHOUT ANY WARRANTY; without even the implied warranty of11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12
* GNU General Public License for more details.13
*14
* You should have received a copy of the GNU General Public License15
* along with this program. If not, see <https://www.gnu.org/licenses/>.16
*/18
// @file http.h20
#ifndef _SO_HTTP_H21
#define _SO_HTTP_H23
#include <stdbool.h>24
#include <sys/socket.h>26
// @include <openssl/ssl.h>27
// @desc OpenSSL library handling TLS/SSL.28
#include <openssl/ssl.h>30
#ifdef SO_HTTP_IMPL31
#define SO_SOCK_IMPL32
#endif // SO_HTTP_IMPL34
// @include <so/sock.h>35
// @desc so/sock library handling server/client communication and multi-threading.36
#include <so/sock.h>38
// @enum http_err_t39
// @desc Error code.40
typedef enum {41
HTTP_ERR_OK = SOCK_ERR_OK,42
HTTP_ERR__COUNT,43
} http_err_t;45
// @enum http_status_t46
// @desc HTTP status code.47
typedef enum {48
HTTP_STATUS_CONTINUE = 100,49
HTTP_STATUS_SWITCHING_PROTOCOLS = 101,50
HTTP_STATUS_PROCESSING = 102,51
HTTP_STATUS_EARLY_HINTS = 103,52
HTTP_STATUS_OK = 200,53
HTTP_STATUS_CREATED = 201,54
HTTP_STATUS_ACCEPTED = 202,55
HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,56
HTTP_STATUS_NO_CONTENT = 204,57
HTTP_STATUS_RESET_CONTENT = 205,58
HTTP_STATUS_PARTIAL_CONTENT = 206,59
HTTP_STATUS_MULTI_STATUS = 207,60
HTTP_STATUS_ALREADY_REPORTED = 208,61
HTTP_STATUS_IM_USED = 226,62
HTTP_STATUS_MULTIPLE_CHOICES = 300,63
HTTP_STATUS_MOVED_PERMANENTLY = 301,64
HTTP_STATUS_FOUND = 302,65
HTTP_STATUS_SEE_OTHER = 303,66
HTTP_STATUS_NOT_MODIFIED = 304,67
HTTP_STATUS_TEMPORARY_REDIRECT = 307,68
HTTP_STATUS_PERMANENT_REDIRECT = 308,69
HTTP_STATUS_BAD_REQUEST = 400,70
HTTP_STATUS_UNAUTHORIZED = 401,71
HTTP_STATUS_PAYMENT_REQUIRED = 402,72
HTTP_STATUS_FORBIDDEN = 403,73
HTTP_STATUS_NOT_FOUND = 404,74
HTTP_STATUS_METHOD_NOT_ALLOWED = 405,75
HTTP_STATUS_NOT_ACCEPTABLE = 406,76
HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,77
HTTP_STATUS_REQUEST_TIMEOUT = 408,78
HTTP_STATUS_CONFLICT = 409,79
HTTP_STATUS_GONE = 410,80
HTTP_STATUS_LENGTH_REQUIRED = 411,81
HTTP_STATUS_PRECONDITION_FAILED = 412,82
HTTP_STATUS_PAYLOAD_TOO_LARGE = 413,83
HTTP_STATUS_URI_TOO_LONG = 414,84
HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,85
HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416,86
HTTP_STATUS_EXPECTATION_FAILED = 417,87
HTTP_STATUS_I_AM_A_TEAPOT = 418,88
HTTP_STATUS_MISDIRECTED_REQUEST = 421,89
HTTP_STATUS_UNPROCESSABLE_CONTENT = 422,90
HTTP_STATUS_LOCKED = 423,91
HTTP_STATUS_FAILED_DEPENDENCY = 424,92
HTTP_STATUS_TOO_EARLY = 425,93
HTTP_STATUS_UPGRADE_REQUIRED = 426,94
HTTP_STATUS_PRECONDITION_REQUIRED = 428,95
HTTP_STATUS_TOO_MANY_REQUESTS = 429,96
HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,97
HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,98
HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,99
HTTP_STATUS_NOT_IMPLEMENTED = 501,100
HTTP_STATUS_BAD_GATEWAY = 502,101
HTTP_STATUS_SERVICE_UNAVAILABLE = 503,102
HTTP_STATUS_GATEWAY_TIMEOUT = 504,103
HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,104
HTTP_STATUS_VARIANT_ALSO_NEGOTITATES = 506,105
HTTP_STATUS_INSUFFICIENT_STORAGE = 507,106
HTTP_STATUS_LOOP_DETECTED = 508,107
HTTP_STATUS_NOT_EXTENDED = 510,108
HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,109
__HTTP_STATUS_HANDLED = 999,110
} http_status_t;112
// @type http_t113
// @groupdef http_t114
// @desc Global context struct. Implemented here {http}.115
typedef struct http http_t;117
// @type http_host_t118
// @desc Represents a the host.119
typedef sock_host_t http_host_t;121
// @type http_bind_t122
// @desc Represents a the binding (port).123
typedef sock_bind_t http_bind_t;125
// @type http_conn_t126
// @groupdef http_conn_t127
// @desc Represents a client connection.128
typedef sock_conn_t http_conn_t;130
// @struct http_header_t131
// @desc A HTTP header.132
typedef struct {133
char *key;134
char *value;135
} http_header_t;137
// @struct http_req_t138
// @groupdef http_req_t139
// @desc A HTTP request struct.140
typedef struct {141
http_conn_t *conn;142
char *method;143
char *url;144
char *version;145
http_header_t *headers;146
int headers_len;147
char *body;148
long body_len;149
void *ext_data;150
} http_req_t;152
// @struct http_resp_t153
// @groupdef http_resp_t154
// @desc A HTTP response struct.155
typedef struct {156
char *version;157
http_status_t status;158
http_header_t *headers;159
int headers_len;160
char *body;161
long body_len;162
} http_resp_t;164
// @type http_global_fn_t165
// @desc A function type for a global route handler.166
typedef http_resp_t (*http_global_fn_t)(http_t *, http_req_t *);168
// @type http_handle_fn_t169
// @desc A function type for a route handler.170
typedef http_resp_t (*http_handle_fn_t)(http_req_t *);172
// @type http_hook_fn_t173
// @desc A function type for a hook handler.174
typedef void (*http_hook_fn_t)(http_req_t *);176
// @struct http_route_t177
// @desc A route.178
typedef struct {179
char *method;180
char *path;181
http_handle_fn_t fn;182
} http_route_t;184
// @struct http_pair_t185
typedef struct {186
char *key;187
char *value;188
} http_pair_t;190
// @struct http_pairs_t191
// @groupdef http_pairs_t192
typedef struct {193
http_pair_t *pairs;194
size_t len;195
} http_pairs_t;197
// @struct http198
// @group http_t199
// @desc Implementation of the global context struct. Type here {http_t}.200
struct http {201
sock_t *sock;202
http_global_fn_t fn;203
};205
// @func http_init206
// @group http_t207
// @desc Initializes global library context {http_t}. Free with {http_cleanup}.208
// @return {http_t} * - Returns the global library context.209
http_t *http_init(void);211
// @func http_cleanup212
// @group http_t213
// @desc Cleans up {http_t}.214
// @param {http_t} *self - The global library context.215
void http_cleanup(http_t *self);217
// @func http_on_global218
// @group http_t219
// @desc Set and override the default global route handler {_http_on_global}.220
// @param {http_t} *self - The global library context.221
// @param {http_global_fn_t} fn - The global route handler.222
void http_on_global(http_t *self, http_global_fn_t fn);224
// @func http_on_route225
// @note Use macros like {HTTP_GET} and others to register routes more easily.226
// @desc Registers a new route.227
// @param char *method - The HTTP method.228
// @param char *url - The HTTP URL (path).229
// @param {http_handle_fn_t} fn - The route handler.230
void http_on_route(char *method, char *url, http_handle_fn_t fn);232
// @func http_on_default233
// @note Use macro {HTTP_DEFAULT} instead.234
// @desc Registers a fallback handler.235
// @param {http_handle_fn_t} fn - The route handler.236
void http_on_default(http_handle_fn_t fn);238
// @func http_on_pre_route239
// @note Use macro {HTTP_PRE_HOOK} instead.240
// @desc Registers a hook handler which is performed before the route handler is executed.241
// @param {http_hook_fn_t} fn - The hook handler.242
void http_on_pre_route(http_hook_fn_t fn);244
// @func http_on_post_route245
// @note Use macro {HTTP_POST_HOOK} instead.246
// @desc Registers a hook handler which is performed after the route handler is executed.247
// @param {http_hook_fn_t} fn - The hook handler.248
void http_on_post_route(http_hook_fn_t fn);250
// @func http_req_path251
// @group http_req_t252
// @param {http_req_t} *req - The HTTP request.253
// @return char * - Returns the request path.254
char *http_req_path(http_req_t *req);256
// @func http_req_body257
// @group http_req_t258
// @param {http_req_t} *req - The HTTP request.259
// @return char * - Returns the request body.260
char *http_req_body(http_req_t *req);262
// @func http_req_queries263
// @group http_req_t264
// @param {http_req_t} *req - The HTTP request.265
// @return {http_pairs_t} - Returns the request queries.266
http_pairs_t http_req_queries(http_req_t *req);268
// @func http_req_params269
// @group http_req_t270
// @param {http_req_t} *req - The HTTP request.271
// @return {http_pairs_t} - Returns the request params.272
http_pairs_t http_req_params(http_req_t *req);274
// @func http_pairs_get275
// @group http_pairs_t276
char *http_pairs_get(http_pairs_t *self, char *key);278
// @func http_pairs_has279
// @group http_pairs_t280
bool http_pairs_has(http_pairs_t *self, char *key);282
// @func http_pairs_free283
// @group http_pairs_t284
void http_pairs_free(http_pairs_t *self);286
// @func http_req_header287
// @group http_req_t288
// @param {http_req_t} *req - The HTTP request.289
// @param char *key - The header key.290
// @return char * - Returns a header value.291
char *http_req_header(http_req_t *req, char *key);293
// @func http_resp_header294
// @group http_resp_t295
// @desc Writes a header to the response. The header content is consumed and can be freed afterward.296
// @param {http_resp_t} *resp - The HTTP response.297
// @param char *key - The header key.298
// @param char *value - The header value.299
void http_resp_header(http_resp_t *resp, char *key, char *value);301
// @func http_resp_create302
// @group http_resp_t303
// @desc Creates a new response with a given HTTP status. Freed with {http_resp_free}.304
// @param {http_status_t} status - The HTTP status code.305
// @return {http_resp_t} - Returns a HTTP response.306
http_resp_t http_resp_create(http_status_t status);308
// @func http_resp_body309
// @group http_resp_t310
// @desc Writes body content to the response. The body content is consumed and can be freed afterward.311
// @param {http_resp_t} *resp - The HTTP response.312
// @param char *body - The body content.313
// @param long len - The body length.314
void http_resp_body(http_resp_t *resp, char *body, long len);316
// @func http_req_free317
// @group http_req_t318
// @desc Frees a request.319
// @param {http_req_t} *req - The HTTP request.320
void http_req_free(http_req_t *req);322
// @func http_resp_write_head323
// @group http_resp_t324
// @desc Writes a response header to the socket stream.325
// @param {http_resp_t} *resp - The HTTP response.326
// @param {http_conn_t} *conn - The HTTP connection.327
void http_resp_write_head(http_resp_t *resp, http_conn_t *conn);329
// @func http_resp_write_body330
// @group http_resp_t331
// @desc Writes a response body to the socket stream.332
// @param {http_resp_t} *resp - The HTTP response.333
// @param {http_conn_t} *conn - The HTTP connection.334
void http_resp_write_body(http_resp_t *resp, http_conn_t *conn);336
// @func http_resp_write337
// @group http_resp_t338
// @desc Writes a response to the socket stream.339
// @param {http_resp_t} *resp - The HTTP response.340
// @param {http_conn_t} *conn - The HTTP connection.341
void http_resp_write(http_resp_t *resp, http_conn_t *conn);343
// @func http_resp_free344
// @group http_resp_t345
// @desc Frees a response.346
// @param {http_resp_t} *resp - The HTTP response.347
void http_resp_free(http_resp_t *resp);349
// @func http_bind350
// @group http_t351
// @param {http_t} *self - The global library context.352
// @param char *hostname - The hostname.353
// @param int port - The port.354
// @param {http_host_t} *hosts - The host to bind to.355
// @param int hosts_len - The host length of to be bound host.356
http_err_t http_bind(http_t *self, char *hostname, int port, http_host_t *hosts, int hosts_len);358
// @func http_listen359
// @group http_t360
// @param {http_t} *self - The global library context.361
http_err_t http_listen(http_t *self);363
// @func http_bind_listen364
// @group http_t365
// @param {http_t} *self - The global library context.366
// @param char *hostname - The hostname.367
// @param int port - The port.368
http_err_t http_bind_listen(http_t *self, char *hostname, int port);370
// @func http_close371
// @group http_t372
// @param {http_t} *self - The global library context.373
void http_close(http_t *self);375
// @func _http_req_read376
// @group http_req_t377
// @internal378
// @param {http_req_t} *req - The HTTP request.379
// @param {http_conn_t} *conn - The HTTP connection.380
// @return {http_err_t} - Returns an HTTP error code.381
http_err_t _http_req_read(http_req_t *req, http_conn_t *conn);383
#ifdef SO_HTTP_IMPL385
#include <stdio.h>386
#include <stdlib.h>387
#include <string.h>388
#include <ctype.h>389
#include <time.h>390
#include <unistd.h>391
#include <pthread.h>392
#include <netdb.h>393
#include <poll.h>394
#include <errno.h>395
#include <signal.h>397
// @macro HTTP_VERSION398
// @internal399
#define HTTP_VERSION "HTTP/1.1"401
// @macro HTTP_MAX_REQUEST_HEAD_SIZE402
// @internal403
#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000405
// @macro HTTP_RESP_HANDLED406
// @group http_resp_t407
// @desc Handled {http_resp_t}.408
#define HTTP_RESP_HANDLED (http_resp_t) { .status = __HTTP_STATUS_HANDLED }410
// @macro _HTTP_ON411
// @internal412
#define _HTTP_ON(method, path, fn_name) \413
static http_resp_t fn_name(http_req_t *req); \414
__attribute__((constructor)) \415
static void __macro_http_fn_register_##fn_name() { \416
http_on_route(method, path, &fn_name); \417
} \418
static http_resp_t fn_name(http_req_t *req)420
// @macro HTTP_GET421
#define HTTP_GET(path, fn_name) _HTTP_ON("GET", path, fn_name)423
// @macro HTTP_GET424
#define HTTP_HEAD(path, fn_name) _HTTP_ON("HEAD", path, fn_name)426
// @macro HTTP_POST427
#define HTTP_POST(path, fn_name) _HTTP_ON("POST", path, fn_name)429
// @macro HTTP_PUT430
#define HTTP_PUT(path, fn_name) _HTTP_ON("PUT", path, fn_name)432
// @macro HTTP_DELETE433
#define HTTP_DELETE(path, fn_name) _HTTP_ON("DELETE", path, fn_name)435
// @macro HTTP_CONNECT436
#define HTTP_CONNECT(path, fn_name) _HTTP_ON("CONNECT", path, fn_name)438
// @macro HTTP_OPTIONS439
#define HTTP_OPTIONS(path, fn_name) _HTTP_ON("OPTIONS", path, fn_name)441
// @macro HTTP_TRACE442
#define HTTP_TRACE(path, fn_name) _HTTP_ON("TRACE", path, fn_name)444
// @macro HTTP_PATCH445
#define HTTP_PATCH(path, fn_name) _HTTP_ON("PATCH", path, fn_name)447
// @macro HTTP_DEFAULT448
#define HTTP_DEFAULT(fn_name) \449
static http_resp_t fn_name(http_req_t *req); \450
__attribute__((constructor)) \451
static void __macro_http_fn_register_##fn_name() { \452
http_on_default(&fn_name); \453
} \454
static http_resp_t fn_name(http_req_t *req)456
// @macro HTTP_PRE_HOOK457
#define HTTP_PRE_HOOK(fn_name) \458
static void fn_name(http_req_t *req); \459
__attribute__((constructor)) \460
static void __macro_http_fn_register_##fn_name() { \461
http_on_pre_route(&fn_name); \462
} \463
static void fn_name(http_req_t *req)465
// @macro HTTP_POST_HOOK466
#define HTTP_POST_HOOK(fn_name) \467
static void fn_name(http_req_t *req); \468
__attribute__((constructor)) \469
static void __macro_http_fn_register_##fn_name() { \470
http_on_post_route(&fn_name); \471
} \472
static void fn_name(http_req_t *req)474
// @global _http_routes475
// @internal476
http_route_t *_http_routes = NULL;478
// @global _http_routes_len479
// @internal480
size_t _http_routes_len = 0;482
// @global _http_default_route483
// @internal484
http_handle_fn_t _http_default_route;486
// @global _http_pre_route487
// @internal488
http_hook_fn_t _http_pre_route;490
// @global _http_post_route491
// @internal492
http_hook_fn_t _http_post_route;494
// @func _http_on_global495
// @group http_t496
// @internal497
// @desc The default route handler. Can be overwritten with {http_on_global}.498
// @param {http_t} *self - The global library context.499
// @param {http_req_t} *req - The HTTP request.500
// @return {http_resp_t} - Returns a HTTP response.501
http_resp_t _http_on_global(http_t *self, http_req_t *req) {502
http_resp_t resp = http_resp_create(HTTP_STATUS_NOT_FOUND);503
if (_http_pre_route != NULL) {504
_http_pre_route(req);505
}506
for (size_t i = 0; i < _http_routes_len; i++) {507
http_route_t *route = &_http_routes[i];508
char *path = http_req_path(req);509
if (strcmp(route->method, req->method) == 0) {510
size_t len = strlen(route->path);511
char c = route->path[len - 1];512
if (c == '*') {513
if (strncmp(route->path, path, len - 1) == 0) {514
http_resp_free(&resp);515
resp = route->fn(req);516
}517
}518
else {519
if (strcmp(route->path, path) == 0) {520
http_resp_free(&resp);521
resp = route->fn(req);522
}523
}524
}525
free(path);526
if (resp.status != HTTP_STATUS_NOT_FOUND) {527
if (_http_post_route != NULL) {528
_http_post_route(req);529
}530
return resp;531
}532
}533
if (_http_default_route != NULL) {534
http_resp_free(&resp);535
resp = _http_default_route(req);536
}537
if (_http_post_route != NULL) {538
_http_post_route(req);539
}540
return resp;541
}543
// @func _http_on_handle544
// @internal545
sock_err_t _http_on_handle(sock_t *sock, http_conn_t *conn) {546
http_t *self= (http_t *) sock->ext;547
http_req_t req;548
http_err_t err = _http_req_read(&req, conn);549
if (err != HTTP_ERR_OK) {550
return err;551
}552
if (req.method != NULL && req.url != NULL) {553
if (self->fn != NULL) {554
http_resp_t resp = self->fn(self, &req);555
http_resp_write(&resp, conn);556
http_resp_free(&resp);557
}558
}559
http_req_free(&req);560
return HTTP_ERR_OK;561
}563
// @impl http_init564
http_t *http_init(void) {565
http_t *self = (http_t *) malloc(sizeof(http_t));566
*self = (http_t) {567
.sock = sock_init(),568
.fn = &_http_on_global,569
};570
sock_set_ext(self->sock, self);571
sock_on_global(self->sock, _http_on_handle);572
return self;573
}575
// @impl http_cleanup576
void http_cleanup(http_t *self) {577
if (self->sock != NULL) {578
sock_cleanup(self->sock);579
}580
free(self);581
}583
// @impl http_on_global584
void http_on_global(http_t *self, http_global_fn_t fn) {585
self->fn = fn;586
}588
// @impl http_on_route589
void http_on_route(char *method, char *path, http_handle_fn_t fn) {590
_http_routes = realloc(_http_routes, sizeof(http_route_t) * (_http_routes_len + 1));591
_http_routes[_http_routes_len] = (http_route_t) {592
.method = method,593
.path = path,594
.fn = fn,595
};596
_http_routes_len++;597
}599
// @impl http_on_default600
void http_on_default(http_handle_fn_t fn) {601
_http_default_route = fn;602
}604
// @impl http_on_pre_route605
void http_on_pre_route(http_hook_fn_t fn) {606
_http_pre_route = fn;607
}609
// @impl http_on_post_route610
void http_on_post_route(http_hook_fn_t fn) {611
_http_post_route = fn;612
}614
// @impl http_req_path615
char *http_req_path(http_req_t *req) {616
char *uri = req->url;617
size_t url_len = strlen(uri);618
size_t i = 0;619
for (; i < url_len; i++) {620
size_t c = uri[i];621
if (c == '?') {622
break;623
}624
}625
size_t len = i;626
char *path = malloc(len + 1);627
memcpy(path, uri, len);628
path[len] = '\0';629
return path;630
}632
// @impl http_req_body633
char *http_req_body(http_req_t *req) {634
return req->body;635
}637
// @func _http_pair_decode638
// @internal639
char *_http_pair_decode(char *str, size_t len) {640
size_t j = 0;641
size_t k = 0;642
char decoded[len + 1];643
while (j < len) {644
if (str[j] == '%') {645
if (j + 2 < len && isxdigit(str[j + 1]) && isxdigit(str[j + 2])) {646
char hex[3] = { str[j + 1], str[j + 2], '\0' };647
decoded[k++] = (char) strtol(hex, NULL, 16);648
j += 3;649
continue;650
}651
decoded[k++] = '%';652
j++;653
continue;654
}655
if (str[j] == '+') {656
decoded[k++] = ' ';657
j++;658
continue;659
}660
decoded[k++] = str[j++];661
}662
decoded[k] = '\0';663
size_t ret_len = strlen(decoded);664
char *ret = malloc(ret_len + 1);665
memcpy(ret, decoded, ret_len);666
ret[ret_len] = '\0';667
return ret;668
}670
// @func _http_pairs_init671
// @group http_pairs_t672
// @internal673
http_pairs_t _http_pairs_init(char *uri) {674
http_pairs_t self = (http_pairs_t) {675
.pairs = NULL,676
.len = 0,677
};678
int url_len = strlen(uri);679
size_t set = 0;680
size_t lim = 0;681
for (size_t i = 0; i < url_len + 1; i++) {682
char c = uri[i];683
// find 'key=value' pair684
if (i == url_len || uri[i] == '&') {685
size_t key_len = i - set;686
if (key_len > 0) {687
if (lim > set) {688
key_len = lim - set;689
}690
self.pairs = realloc(self.pairs, sizeof(http_pair_t) * (self.len + 1));691
http_pair_t *pair = &self.pairs[self.len];692
// read key693
pair->key = _http_pair_decode(uri + set, key_len);694
pair->value = NULL;695
if (i > set + key_len + 1) {696
// read value697
size_t value_len = i - (set + key_len + 1);698
pair->value = _http_pair_decode(uri + set + key_len + 1, value_len);699
}700
self.len++;701
}702
set = i + 1;703
}704
// find '=' delimiter705
if (uri[i] == '=') {706
lim = i;707
}708
}709
return self;710
}712
// @impl http_req_queries713
http_pairs_t http_req_queries(http_req_t *req) {714
size_t url_len = strlen(req->url);715
// skip path716
for (size_t i = 0; i < url_len; i++) {717
if (req->url[i] == '?') {718
return _http_pairs_init(req->url + i + 1);719
}720
}721
return (http_pairs_t) {722
.pairs = NULL,723
.len = 0,724
};725
}727
// @impl http_req_params728
http_pairs_t http_req_params(http_req_t *req) {729
return _http_pairs_init(req->body);730
}732
// @impl http_pairs_get733
char *http_pairs_get(http_pairs_t *self, char *key) {734
if (self && self->len > 0) {735
for (size_t i = 0; i < self->len; i++) {736
http_pair_t *pair = &self->pairs[i];737
if (strcmp(pair->key, key) == 0) {738
return pair->value;739
}740
}741
}742
return NULL;743
}745
// @impl http_pairs_has746
bool http_pairs_has(http_pairs_t *self, char *key) {747
if (self && self->len > 0) {748
for (size_t i = 0; i < self->len; i++) {749
http_pair_t *pair = &self->pairs[i];750
if (strcmp(pair->key, key) == 0) {751
return true;752
}753
}754
}755
return false;756
}758
// @impl http_pairs_free759
void http_pairs_free(http_pairs_t *self) {760
if (self == NULL) {761
return;762
}763
if (self->len > 0) {764
for (size_t i = 0; i < self->len; i++) {765
http_pair_t *pair = &self->pairs[i];766
free(pair->key);767
if (pair->value) {768
free(pair->value);769
}770
}771
free(self->pairs);772
}773
}775
// @func _http_status_str776
// @internal777
const char *_http_status_str(http_status_t status) {778
switch (status) {779
case HTTP_STATUS_CONTINUE:780
return "Continue";781
case HTTP_STATUS_SWITCHING_PROTOCOLS:782
return "Switching Protocols";783
case HTTP_STATUS_PROCESSING:784
return "Processing";785
case HTTP_STATUS_EARLY_HINTS:786
return "Early Hints";787
case HTTP_STATUS_OK:788
return "OK";789
case HTTP_STATUS_CREATED:790
return "Created";791
case HTTP_STATUS_ACCEPTED:792
return "Accepted";793
case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:794
return "Non-Authoritative Information";795
case HTTP_STATUS_NO_CONTENT:796
return "No Content";797
case HTTP_STATUS_RESET_CONTENT:798
return "Reset Content";799
case HTTP_STATUS_PARTIAL_CONTENT:800
return "Partial Content";801
case HTTP_STATUS_MULTI_STATUS:802
return "Multi-Status";803
case HTTP_STATUS_ALREADY_REPORTED:804
return "Already Reported";805
case HTTP_STATUS_IM_USED:806
return "IM Used";807
case HTTP_STATUS_MULTIPLE_CHOICES:808
return "Multiple Choices";809
case HTTP_STATUS_MOVED_PERMANENTLY:810
return "Moved Permanently";811
case HTTP_STATUS_FOUND:812
return "Found";813
case HTTP_STATUS_SEE_OTHER:814
return "See Other";815
case HTTP_STATUS_NOT_MODIFIED:816
return "Not Modified";817
case HTTP_STATUS_TEMPORARY_REDIRECT:818
return "Temporary Redirect";819
case HTTP_STATUS_PERMANENT_REDIRECT:820
return "Permanent Redirect";821
case HTTP_STATUS_BAD_REQUEST:822
return "Bad Request";823
case HTTP_STATUS_UNAUTHORIZED:824
return "Unauthorized";825
case HTTP_STATUS_PAYMENT_REQUIRED:826
return "Payment Required";827
case HTTP_STATUS_FORBIDDEN:828
return "Forbidden";829
case HTTP_STATUS_NOT_FOUND:830
return "Not Found";831
case HTTP_STATUS_METHOD_NOT_ALLOWED:832
return "Method Not Allowed";833
case HTTP_STATUS_NOT_ACCEPTABLE:834
return "Not Acceptable";835
case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:836
return "Proxy Authentication Required";837
case HTTP_STATUS_REQUEST_TIMEOUT:838
return "Request Timeout";839
case HTTP_STATUS_CONFLICT:840
return "Conflict";841
case HTTP_STATUS_GONE:842
return "Gone";843
case HTTP_STATUS_LENGTH_REQUIRED:844
return "Length Required";845
case HTTP_STATUS_PRECONDITION_FAILED:846
return "Precondition Failed";847
case HTTP_STATUS_PAYLOAD_TOO_LARGE:848
return "Payload Too Large";849
case HTTP_STATUS_URI_TOO_LONG:850
return "URI Too Long";851
case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:852
return "Unsupported Media Type";853
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:854
return "Range Not Satisfiable";855
case HTTP_STATUS_EXPECTATION_FAILED:856
return "Expectation Failed";857
case HTTP_STATUS_I_AM_A_TEAPOT:858
return "I'm a teapot";859
case HTTP_STATUS_MISDIRECTED_REQUEST:860
return "Misdirected Request";861
case HTTP_STATUS_UNPROCESSABLE_CONTENT:862
return "Unprocessable Content";863
case HTTP_STATUS_LOCKED:864
return "Locked";865
case HTTP_STATUS_FAILED_DEPENDENCY:866
return "Failed Dependency";867
case HTTP_STATUS_TOO_EARLY:868
return "Too Early";869
case HTTP_STATUS_UPGRADE_REQUIRED:870
return "Upgrade Required";871
case HTTP_STATUS_PRECONDITION_REQUIRED:872
return "Precondition Required";873
case HTTP_STATUS_TOO_MANY_REQUESTS:874
return "Too Many Requests";875
case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:876
return "Request Header Fields Too Large";877
case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:878
return "Unavailable For Legal Reasons";879
case HTTP_STATUS_INTERNAL_SERVER_ERROR:880
return "Internal Server Error";881
case HTTP_STATUS_NOT_IMPLEMENTED:882
return "Not Implemented";883
case HTTP_STATUS_BAD_GATEWAY:884
return "Bad Gateway";885
case HTTP_STATUS_SERVICE_UNAVAILABLE:886
return "Service Unavailable";887
case HTTP_STATUS_GATEWAY_TIMEOUT:888
return "Gateway Timeout";889
case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:890
return "HTTP Version Not Supported";891
case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:892
return "Variant Also Negotitates";893
case HTTP_STATUS_INSUFFICIENT_STORAGE:894
return "Insufficient Storage";895
case HTTP_STATUS_LOOP_DETECTED:896
return "Loop Detected";897
case HTTP_STATUS_NOT_EXTENDED:898
return "Not Extended";899
case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:900
return "Network Authentication Required";901
default:902
return NULL;903
}904
}906
// @func _http_conn_read907
// @group http_conn_t908
// @internal909
ssize_t _http_conn_read(http_conn_t *conn, char *buffer, size_t len) {910
return sock_conn_read(conn, buffer, len);911
}913
// @func _http_conn_write914
// @group http_conn_t915
// @internal916
ssize_t _http_conn_write(http_conn_t *conn, char *buffer, size_t len) {917
return sock_conn_write(conn, buffer, len);918
}920
// @impl http_req_header921
char *http_req_header(http_req_t *req, char *key) {922
if (req->headers_len > 0) {923
for (int i = 0; i < req->headers_len; i++) {924
http_header_t *header = &req->headers[i];925
if (strcasecmp(header->key, key) == 0) {926
return header->value;927
}928
}929
}930
return NULL;931
}933
// @impl http_resp_header934
void http_resp_header(http_resp_t *resp, char *key, char *value) {935
resp->headers = (http_header_t *) realloc(resp->headers, sizeof(http_header_t) * (resp->headers_len + 1));936
http_header_t *new_header = &resp->headers[resp->headers_len];937
resp->headers_len++;938
int key_len = strlen(key);939
new_header->key = (char *) malloc(sizeof(char) * (key_len + 1));940
memcpy(new_header->key, key, key_len);941
new_header->key[key_len] = '\0';942
int value_len = strlen(value);943
new_header->value = (char *) malloc(sizeof(char) * (value_len + 1));944
memcpy(new_header->value, value, value_len);945
new_header->value[value_len] = '\0';946
}948
// @impl http_resp_create949
http_resp_t http_resp_create(http_status_t status) {950
return (http_resp_t) {951
.version = strdup(HTTP_VERSION),952
.status = status,953
.headers = NULL,954
.headers_len = 0,955
.body = NULL,956
.body_len = 0,957
};958
}960
// @impl http_resp_body961
void http_resp_body(http_resp_t *resp, char *body, long len) {962
if (resp != NULL && body != NULL) {963
resp->body = (char *) malloc(sizeof(char) * len);964
memcpy(resp->body, body, len);965
resp->body_len = len;966
}967
}969
// @impl http_req_free970
void http_req_free(http_req_t *req) {971
if (req->method != NULL) {972
free(req->method);973
}974
if (req->url != NULL) {975
free(req->url);976
}977
if (req->version != NULL) {978
free(req->version);979
}980
if (req->headers_len > 0) {981
for (int i = 0; i < req->headers_len; i++) {982
http_header_t *header = &req->headers[i];983
if (header->key != NULL) {984
free(header->key);985
}986
if (header->value != NULL) {987
free(header->value);988
}989
}990
free(req->headers);991
}992
if (req->body != NULL) {993
free(req->body);994
}995
if (req->ext_data != NULL) {996
free(req->ext_data);997
}998
}1000
// @impl http_resp_free1001
void http_resp_free(http_resp_t *resp) {1002
if (resp->version != NULL) {1003
free(resp->version);1004
}1005
if (resp->headers_len > 0) {1006
for (int i = 0; i < resp->headers_len; i++) {1007
http_header_t *header = &resp->headers[i];1008
if (header->key != NULL) {1009
free(header->key);1010
}1011
if (header->value != NULL) {1012
free(header->value);1013
}1014
}1015
if (resp->headers != NULL) {1016
free(resp->headers);1017
}1018
}1019
if (resp->body != NULL) {1020
free(resp->body);1021
}1022
}1024
// @impl _http_req_read1025
http_err_t _http_req_read(http_req_t *req, http_conn_t *conn) {1026
int len = 0;1027
int ln = 0;1028
int start = 0;1029
char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];1030
*req = (http_req_t) {1031
.conn = conn,1032
.method = NULL,1033
.url = NULL,1034
.version = NULL,1035
.headers = NULL,1036
.headers_len = 0,1037
.body = NULL,1038
.body_len = 0,1039
.ext_data = NULL,1040
};1041
while (true) {1042
char c;1043
int read = _http_conn_read(conn, &c, 1);1044
if (read == 0) {1045
break;1046
}1047
// read timeout1048
if (read == -1 || read == SSL_ERROR_SYSCALL) {1049
if (errno == EWOULDBLOCK || errno == EAGAIN) {1050
return SOCK_ERR_READ_TIMEOUT;1051
}1052
}1053
// break if too long1054
if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {1055
return SOCK_ERR_REQUEST_TOO_LONG;1056
}1057
buffer[len] = c;1058
len++;1059
// read head1060
if (len >= 2) {1061
char *slice = buffer + (len - 2);1062
if (strncmp(slice, "\r\n", 2) == 0) {1063
int line_len = (len - 2) - start;1064
if (line_len > 0) {1065
// read line1066
char line[line_len + 1];1067
memcpy(line, buffer + start, line_len);1068
line[line_len] = '\0';1069
// read method, url, and version1070
if (ln == 0) {1071
int arg = 0;1072
int start = 0;1073
for (int i = 0; i <= line_len; i++) {1074
if (line[i] == ' ' || i == line_len) {1075
// read method1076
if (arg == 0) {1077
int method_length = i - start;1078
req->method = (char *) malloc(sizeof(char) * (method_length + 1));1079
memcpy(req->method, line + start, method_length);1080
req->method[method_length] = '\0';1081
}1082
// read url1083
if (arg == 1) {1084
int url_length = i - start;1085
req->url = (char *) malloc(sizeof(char) * (url_length + 1));1086
memcpy(req->url, line + start, url_length);1087
req->url[url_length] = '\0';1088
}1089
// read version1090
if (arg == 2) {1091
int version_length = i - start;1092
req->version = (char *) malloc(sizeof(char) * (version_length + 1));1093
memcpy(req->version, line + start, version_length);1094
req->version[version_length] = '\0';1095
}1096
start = i + 1;1097
arg++;1098
}1099
}1100
}1101
// read headers1102
else {1103
int sep = 0;1104
req->headers = (http_header_t *) realloc(req->headers, sizeof(http_header_t) * (req->headers_len + 1));1105
http_header_t *header = &req->headers[req->headers_len];1106
req->headers_len++;1107
for (int i = 0; i < line_len; i++) {1108
if (line[i] == ':') {1109
int key_len = i;1110
header->key = (char *) malloc(sizeof(char) * (key_len + 1));1111
memcpy(header->key, line, key_len);1112
header->key[key_len] = '\0';1113
sep = i + 2;1114
break;1115
}1116
}1117
int value_len = line_len - sep;1118
header->value = (char *) malloc(sizeof(char) * (value_len + 1));1119
memcpy(header->value, line + sep, value_len);1120
header->value[value_len] = '\0';1121
}1122
}1123
start = len;1124
ln++;1125
}1126
}1127
// read body1128
if (len >= 4) {1129
char *slice = buffer + (len - 4);1130
if (strncmp(slice, "\r\n\r\n", 4) == 0) {1131
char *content_length = http_req_header(req, (char *) "Content-Length");1132
if (content_length != NULL) {1133
req->body_len = strtol(content_length, NULL, 10);1134
if (req->body_len > 0) {1135
req->body = (char *) malloc(sizeof(char) * (req->body_len + 1));1136
_http_conn_read(conn, req->body, req->body_len);1137
req->body[req->body_len] = '\0';1138
}1139
}1140
break;1141
}1142
}1143
}1144
return HTTP_ERR_OK;1145
}1147
// @impl http_resp_write_head1148
void http_resp_write_head(http_resp_t *resp, http_conn_t *conn) {1149
_http_conn_write(conn, resp->version, strlen(resp->version));1150
_http_conn_write(conn, (char *) " ", 1);1151
char status[4];1152
snprintf(status, 4, "%d", resp->status);1153
_http_conn_write(conn, status, strlen(status));1154
_http_conn_write(conn, (char *) " ", 1);1155
const char *status_message = _http_status_str(resp->status);1156
_http_conn_write(conn, (char *) status_message, strlen(status_message));1157
_http_conn_write(conn, (char *) "\r\n", 2);1158
if (resp->headers_len > 0) {1159
for (int i = 0; i < resp->headers_len; i++) {1160
http_header_t *header = &resp->headers[i];1161
_http_conn_write(conn, header->key, strlen(header->key));1162
_http_conn_write(conn, (char *) ": ", 2);1163
_http_conn_write(conn, header->value, strlen(header->value));1164
_http_conn_write(conn, (char *) "\r\n", 2);1165
}1166
}1167
_http_conn_write(conn, (char *) "\r\n", 2);1168
}1170
// @impl http_resp_write_body1171
void http_resp_write_body(http_resp_t *resp, http_conn_t *conn) {1172
if (resp->body != NULL) {1173
_http_conn_write(conn, resp->body, resp->body_len);1174
}1175
}1177
// @impl http_resp_write1178
void http_resp_write(http_resp_t *resp, http_conn_t *conn) {1179
if (resp->status == __HTTP_STATUS_HANDLED) {1180
return;1181
}1182
bool has_content_length = false;1183
if (resp->body != NULL) {1184
if (resp->headers_len > 0) {1185
for (int i = 0; i < resp->headers_len; i++) {1186
http_header_t *header = &resp->headers[i];1187
if (strcasecmp(header->key, "Content-Length") == 0) {1188
has_content_length = true;1189
break;1190
}1191
}1192
}1193
if (!has_content_length) {1194
char content_length[50];1195
snprintf(content_length, 50, "%ld", resp->body_len);1196
http_resp_header(resp, (char *) "Content-Length", content_length);1197
}1198
}1199
http_resp_write_head(resp, conn);1200
http_resp_write_body(resp, conn);1201
}1203
// @impl http_bind1204
http_err_t http_bind(http_t *self, char *hostname, int port, http_host_t *hosts, int hosts_len) {1205
return sock_bind(self->sock, hostname, port, hosts, hosts_len);1206
}1208
// @impl http_listen1209
http_err_t http_listen(http_t *self) {1210
return sock_listen(self->sock);1211
}1213
// @impl http_bind_listen1214
http_err_t http_bind_listen(http_t *self, char *hostname, int port) {1215
return sock_bind_listen(self->sock, hostname, port);1216
}1218
// @impl http_close1219
void http_close(http_t *self) {1220
sock_close(self->sock);1221
}1223
#endif // SO_HTTP_IMPL1224
#endif // _SO_HTTP_H