A low-key HTTP micro-framework for people who hate web bloat
git clone git://soophie.de/tpee
1
default: build3
build:4
cc -o libhttp.so -shared -fPIC -lpthread -lssl -Wall -Wextra libhttp.c1
default: install3
install:7
cc -o libhttp.so -shared -fPIC libhttp.c8
sudo cp libhttp.h /usr/local/include/9
sudo cp libhttp.so /usr/local/lib/10
sudo ldconfig11
rm libhttp.so4
sudo cp src/libhttp.h /usr/local/include/6
uninstall:7
sudo rm /usr/local/include/libhttp.h15
sudo rm /usr/local/lib/libhttp.so17
clean:18
rm libhttp.so
7
```8
sudo make install9
```11
## Usage13
```c14
#define LIB_HTTP_IMPL15
#include <libhttp.h>17
http_response_t do_handle(http_request_t *request) {18
http_response_t response = http_response_create(HTTP_STATUS_OK);19
http_header_set(&response, "Content-Type", "text/html");20
http_response_body(&response, "<h1>Hello, World!</h1>", 22);21
return response;22
}24
int main(void) {25
http_t *http = http_init();26
http_on_request(http, do_handle);27
if (http_bind(http, "0.0.0.0", 80, NULL, 0) != HTTP_ERR_OK) {28
printf("failed to bind port :80\n");29
http_cleanup(http);30
return 1;31
}32
if (http_listen(http) == HTTP_ERR_OK) {33
printf("server is running on port :80\n");34
pause();35
}36
http_close(http);37
printf("server stopped\n");38
http_cleanup(http);39
return 0;40
}41
```
1
#include <stdio.h>2
#include <stdlib.h>3
#include <stdbool.h>4
#include <string.h>5
#include <time.h>6
#include <unistd.h>7
#include <pthread.h>8
#include <netdb.h>9
#include <errno.h>10
#include <poll.h>11
#include <signal.h>12
#include <openssl/ssl.h>14
#include "libhttp.h"16
#define HTTP_MAX_REQUEST_HEAD_SIZE 100000018
http_bind_t *http_binds = NULL;19
int http_binds_len = 0;20
pthread_t http_thread;21
bool http_quit = false;22
bool http_error = false;23
SSL_CTX *http_ssl_ctx = NULL;25
http_response_t (*on_request_fn)(http_request_t *) = NULL;27
void http_on_request(http_response_t fn(http_request_t *)) {28
on_request_fn = fn;29
}31
char *http_read_file(char *filename) {32
FILE *fp = fopen(filename, "r");33
fseek(fp, 0, SEEK_END);34
long len = ftell(fp);35
fseek(fp, 0, SEEK_SET);36
char *content = malloc(sizeof(char) * (len + 1));37
fread(content, len, sizeof(char), fp);38
content[len] = '\0';39
fclose(fp);40
return content;41
}43
char *http_status_str(http_status_t status) {44
switch (status) {45
case HTTP_STATUS_CONTINUE:46
return "Continue";47
case HTTP_STATUS_SWITCHING_PROTOCOLS:48
return "Switching Protocols";49
case HTTP_STATUS_PROCESSING:50
return "Processing";51
case HTTP_STATUS_EARLY_HINTS:52
return "Early Hints";53
case HTTP_STATUS_OK:54
return "OK";55
case HTTP_STATUS_CREATED:56
return "Created";57
case HTTP_STATUS_ACCEPTED:58
return "Accepted";59
case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:60
return "Non-Authoritative Information";61
case HTTP_STATUS_NO_CONTENT:62
return "No Content";63
case HTTP_STATUS_RESET_CONTENT:64
return "Reset Content";65
case HTTP_STATUS_PARTIAL_CONTENT:66
return "Partial Content";67
case HTTP_STATUS_MULTI_STATUS:68
return "Multi-Status";69
case HTTP_STATUS_ALREADY_REPORTED:70
return "Already Reported";71
case HTTP_STATUS_IM_USED:72
return "IM Used";73
case HTTP_STATUS_MULTIPLE_CHOICES:74
return "Multiple Choices";75
case HTTP_STATUS_MOVED_PERMANENTLY:76
return "Moved Permanently";77
case HTTP_STATUS_FOUND:78
return "Found";79
case HTTP_STATUS_SEE_OTHER:80
return "See Other";81
case HTTP_STATUS_NOT_MODIFIED:82
return "Not Modified";83
case HTTP_STATUS_TEMPORARY_REDIRECT:84
return "Temporary Redirect";85
case HTTP_STATUS_PERMANENT_REDIRECT:86
return "Permanent Redirect";87
case HTTP_STATUS_BAD_REQUEST:88
return "Bad Request";89
case HTTP_STATUS_UNAUTHORIZED:90
return "Unauthorized";91
case HTTP_STATUS_PAYMENT_REQUIRED:92
return "Payment Required";93
case HTTP_STATUS_FORBIDDEN:94
return "Forbidden";95
case HTTP_STATUS_NOT_FOUND:96
return "Not Found";97
case HTTP_STATUS_METHOD_NOT_ALLOWED:98
return "Method Not Allowed";99
case HTTP_STATUS_NOT_ACCEPTABLE:100
return "Not Acceptable";101
case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:102
return "Proxy Authentication Required";103
case HTTP_STATUS_REQUEST_TIMEOUT:104
return "Request Timeout";105
case HTTP_STATUS_CONFLICT:106
return "Conflict";107
case HTTP_STATUS_GONE:108
return "Gone";109
case HTTP_STATUS_LENGTH_REQUIRED:110
return "Length Required";111
case HTTP_STATUS_PRECONDITION_FAILED:112
return "Precondition Failed";113
case HTTP_STATUS_PAYLOAD_TOO_LARGE:114
return "Payload Too Large";115
case HTTP_STATUS_URI_TOO_LONG:116
return "URI Too Long";117
case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:118
return "Unsupported Media Type";119
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:120
return "Range Not Satisfiable";121
case HTTP_STATUS_EXPECTATION_FAILED:122
return "Expectation Failed";123
case HTTP_STATUS_I_AM_A_TEAPOT:124
return "I'm a teapot";125
case HTTP_STATUS_MISDIRECTED_REQUEST:126
return "Misdirected Request";127
case HTTP_STATUS_UNPROCESSABLE_CONTENT:128
return "Unprocessable Content";129
case HTTP_STATUS_LOCKED:130
return "Locked";131
case HTTP_STATUS_FAILED_DEPENDENCY:132
return "Failed Dependency";133
case HTTP_STATUS_TOO_EARLY:134
return "Too Early";135
case HTTP_STATUS_UPGRADE_REQUIRED:136
return "Upgrade Required";137
case HTTP_STATUS_PRECONDITION_REQUIRED:138
return "Precondition Required";139
case HTTP_STATUS_TOO_MANY_REQUESTS:140
return "Too Many Requests";141
case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:142
return "Request Header Fields Too Large";143
case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:144
return "Unavailable For Legal Reasons";145
case HTTP_STATUS_INTERNAL_SERVER_ERROR:146
return "Internal Server Error";147
case HTTP_STATUS_NOT_IMPLEMENTED:148
return "Not Implemented";149
case HTTP_STATUS_BAD_GATEWAY:150
return "Bad Gateway";151
case HTTP_STATUS_SERVICE_UNAVAILABLE:152
return "Service Unavailable";153
case HTTP_STATUS_GATEWAY_TIMEOUT:154
return "Gateway Timeout";155
case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:156
return "HTTP Version Not Supported";157
case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:158
return "Variant Also Negotitates";159
case HTTP_STATUS_INSUFFICIENT_STORAGE:160
return "Insufficient Storage";161
case HTTP_STATUS_LOOP_DETECTED:162
return "Loop Detected";163
case HTTP_STATUS_NOT_EXTENDED:164
return "Not Extended";165
case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:166
return "Network Authentication Required";167
default:168
return NULL;169
}170
}172
ssize_t http_read(http_conn_t *conn, void *buffer, size_t len) {173
if (conn->ssl != NULL) {174
return SSL_read(conn->ssl, buffer, len);175
}176
return read(conn->sockfd, buffer, len);177
}179
ssize_t http_write(http_conn_t *conn, void *buffer, size_t len) {180
if (conn->ssl != NULL) {181
return SSL_write(conn->ssl, buffer, len);182
}183
return write(conn->sockfd, buffer, len);184
}186
char *http_header_get(http_request_t *request, char *key) {187
if (request->headers_len > 0) {188
for (int i = 0; i < request->headers_len; i++) {189
http_header_t *header = &request->headers[i];190
if (strcmp(header->key, key) == 0) {191
return header->value;192
}193
}194
}195
return NULL;196
}198
void http_header_set(http_response_t *response, char *key, char *value) {199
http_header_t *new_header = NULL;200
if (response->headers_len > 0) {201
for (int i = 0; i < response->headers_len; i++) {202
http_header_t *header = &response->headers[i];203
if (strcmp(header->key, key) == 0) {204
new_header = header;205
break;206
}207
}208
}209
if (new_header == NULL) {210
response->headers = realloc(response->headers, sizeof(http_header_t) * (response->headers_len + 1));211
new_header = &response->headers[response->headers_len];212
response->headers_len++;213
}214
int key_len = strlen(key);215
new_header->key = malloc(sizeof(char) * (key_len + 1));216
memcpy(new_header->key, key, key_len);217
new_header->key[key_len] = '\0';218
int value_len = strlen(value);219
new_header->value = malloc(sizeof(char) * (value_len + 1));220
memcpy(new_header->value, value, value_len);221
new_header->value[value_len] = '\0';222
}224
http_response_t http_response_create(http_status_t status) {225
char *version = "HTTP/1.1";226
int version_len = strlen(version);227
http_response_t response = { NULL, status, NULL, 0, NULL, 0 };228
response.version = malloc(sizeof(char) * (version_len + 1));229
memcpy(response.version, version, version_len);230
response.version[version_len] = '\0';231
return response;232
}234
void http_response_body(http_response_t *response, char *body, long len) {235
if (response != NULL && body != NULL) {236
response->body = malloc(sizeof(char) * len);237
memcpy(response->body, body, len);238
response->body_len = len;239
char content_length[50];240
snprintf(content_length, 50, "%ld", len);241
http_header_set(response, "Content-Length", content_length);242
}243
}245
void http_response_file(http_response_t *response, char *filename) {246
char *content = http_read_file(filename);247
if (content != NULL) {248
http_response_body(response, content, strlen(content));249
free(content);250
}251
}253
void http_request_free(http_request_t *request) {254
if (request->method != NULL) {255
free(request->method);256
}257
if (request->url != NULL) {258
free(request->url);259
}260
if (request->version != NULL) {261
free(request->version);262
}263
if (request->headers_len > 0) {264
for (int i = 0; i < request->headers_len; i++) {265
http_header_t *header = &request->headers[i];266
if (header->key != NULL) {267
free(header->key);268
}269
if (header->value != NULL) {270
free(header->value);271
}272
}273
}274
if (request->body != NULL) {275
free(request->body);276
}277
if (request->ext_data != NULL) {278
free(request->ext_data);279
}280
}282
void http_response_free(http_response_t *response) {283
if (response->version != NULL) {284
free(response->version);285
}286
if (response->headers_len > 0) {287
for (int i = 0; i < response->headers_len; i++) {288
http_header_t *header = &response->headers[i];289
if (header->key != NULL) {290
free(header->key);291
}292
if (header->value != NULL) {293
free(header->value);294
}295
}296
}297
if (response->body != NULL) {298
free(response->body);299
}300
}302
http_request_t http_read_request(http_conn_t *conn) {303
int len = 0;304
int ln = 0;305
int start = 0;306
char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];307
http_request_t request = {308
.conn = conn,309
.method = NULL,310
.url = NULL,311
.version = NULL,312
.headers = NULL,313
.headers_len = 0,314
.body = NULL,315
.body_len = 0,316
.ext_data = NULL,317
};318
while (true) {319
char c;320
int read = http_read(conn, &c, 1);321
if (read == 0) {322
break;323
}324
// break if too long325
if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {326
perror("request is too long");327
break;328
}329
buffer[len] = c;330
len++;331
// read head332
if (len >= 2) {333
char *slice = buffer + (len - 2);334
if (strncmp(slice, "\r\n", 2) == 0) {335
int line_len = (len - 2) - start;336
if (line_len > 0) {337
// read line338
char line[line_len + 1];339
memcpy(line, buffer + start, line_len);340
line[line_len] = '\0';341
// read method, url, and version342
if (ln == 0) {343
int arg = 0;344
int start = 0;345
for (int i = 0; i <= line_len; i++) {346
if (line[i] == ' ' || i == line_len) {347
// read method348
if (arg == 0) {349
int method_length = i - start;350
request.method = malloc(sizeof(char) * (method_length + 1));351
memcpy(request.method, line + start, method_length);352
request.method[method_length] = '\0';353
}354
// read url355
if (arg == 1) {356
int url_length = i - start;357
request.url = malloc(sizeof(char) * (url_length + 1));358
memcpy(request.url, line + start, url_length);359
request.url[url_length] = '\0';360
}361
// read version362
if (arg == 2) {363
int version_length = i - start;364
request.version = malloc(sizeof(char) * (version_length + 1));365
memcpy(request.version, line + start, version_length);366
request.version[version_length] = '\0';367
}368
start = i + 1;369
arg++;370
}371
}372
}373
// read headers374
else {375
int sep = 0;376
request.headers = realloc(request.headers, sizeof(http_header_t) * (request.headers_len + 1));377
http_header_t *header = &request.headers[request.headers_len];378
request.headers_len++;379
for (int i = 0; i < line_len; i++) {380
if (line[i] == ':') {381
int key_len = i;382
header->key = malloc(sizeof(char) * (key_len + 1));383
memcpy(header->key, line, key_len);384
header->key[key_len] = '\0';385
sep = i + 2;386
break;387
}388
}389
int value_len = line_len - sep;390
header->value = malloc(sizeof(char) * (value_len + 1));391
memcpy(header->value, line + sep, value_len);392
header->value[value_len] = '\0';393
}394
}395
start = len;396
ln++;397
}398
}399
// read body400
if (len >= 4) {401
char *slice = buffer + (len - 4);402
if (strncmp(slice, "\r\n\r\n", 4) == 0) {403
char *content_length = http_header_get(&request, "Content-Length");404
if (content_length != NULL) {405
request.body_len = strtol(content_length, NULL, 10);406
if (request.body_len > 0) {407
request.body = malloc(sizeof(char) * (request.body_len + 1));408
http_read(conn, request.body, request.body_len);409
request.body[request.body_len] = '\0';410
}411
}412
break;413
}414
}415
}416
return request;417
}419
void http_write_response(http_conn_t *conn, http_response_t response) {420
http_write(conn, response.version, strlen(response.version));421
http_write(conn, " ", 1);422
char status[4];423
snprintf(status, 4, "%d", response.status);424
http_write(conn, status, strlen(status));425
http_write(conn, " ", 1);426
char *status_message = http_status_str(response.status);427
http_write(conn, status_message, strlen(status_message));428
http_write(conn, "\r\n", 2);429
if (response.headers_len > 0) {430
for (int i = 0; i < response.headers_len; i++) {431
http_header_t *header = &response.headers[i];432
http_write(conn, header->key, strlen(header->key));433
http_write(conn, ": ", 2);434
http_write(conn, header->value, strlen(header->value));435
http_write(conn, "\r\n", 2);436
}437
}438
http_write(conn, "\r\n", 2);439
if (response.body != NULL) {440
http_write(conn, response.body, response.body_len);441
}442
}444
void *http_handle_client(void *ptr) {445
if (!ptr) {446
pthread_exit(0);447
}448
http_conn_t *conn = (http_conn_t *) ptr;449
if (conn->bind->hosts_len > 0) {450
SSL_CTX_set_tlsext_servername_arg(http_ssl_ctx, (void *) conn);451
conn->ssl = SSL_new(http_ssl_ctx);452
SSL_set_fd(conn->ssl, conn->sockfd);453
if (SSL_accept(conn->ssl) <= 0) {454
pthread_exit(0);455
}456
}457
http_request_t request = http_read_request(conn);458
if (request.method != NULL && request.url != NULL) {459
if (on_request_fn != NULL) {460
http_response_t response = on_request_fn(&request);461
http_write_response(conn, response);462
http_response_free(&response);463
}464
}465
http_request_free(&request);466
if (conn->ssl != NULL) {467
SSL_shutdown(conn->ssl);468
SSL_free(conn->ssl);469
}470
close(conn->sockfd);471
free(conn);472
pthread_exit(0);473
}475
void *http_handle_server(void *ptr) {476
(void)(ptr);477
struct pollfd fds[http_binds_len];478
for (int i = 0; i < http_binds_len; i++) {479
fds[i].fd = http_binds[i].sockfd;480
fds[i].events = POLLIN | POLLPRI;481
}482
while (!http_quit) {483
struct timespec sleep_req, sleep_rem;484
sleep_req.tv_sec = 0;485
sleep_req.tv_nsec = 100000000;486
nanosleep(&sleep_req, &sleep_rem);487
if (poll(fds, http_binds_len, 100)) {488
for (int i = 0; i < http_binds_len; i++) {489
if (fds[i].revents & POLLIN) {490
http_conn_t *conn = malloc(sizeof(http_conn_t));491
conn->addr_len = sizeof(conn->addr);492
conn->sockfd = accept(http_binds[i].sockfd, &conn->addr, (socklen_t *) &conn->addr_len);493
conn->bind = &http_binds[i];494
conn->ssl = NULL;495
if (conn->sockfd <= 0) {496
free(conn);497
}498
else {499
pthread_t thread;500
pthread_attr_t thread_attr;501
pthread_attr_init(&thread_attr);502
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);503
pthread_create(&thread, &thread_attr, http_handle_client, (void *) conn);504
pthread_attr_destroy(&thread_attr);505
}506
}507
}508
}509
}510
pthread_exit(0);511
}513
int http_tls_sni_callback(SSL *ssl, int *al, void *arg) {514
(void)(al);515
http_conn_t *conn = (http_conn_t *) arg;516
const char *hostname = SSL_get_servername(ssl, 0);517
if (hostname != NULL) {518
for (int i = 0; i < http_binds_len; i++) {519
for (int j = 0; j < http_binds[i].hosts_len; j++) {520
http_host_t *http_host = &http_binds[i].hosts[j];521
if (strcmp(http_host->hostname, hostname) == 0) {522
conn->curr_host = http_host;523
SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);524
return SSL_TLSEXT_ERR_OK;525
}526
}527
}528
}529
return SSL_TLSEXT_ERR_NOACK;530
}532
void http_bind(char *hostname, int port, http_host_t *hosts, int hosts_len) {533
http_binds = realloc(http_binds, sizeof(http_bind_t) * (http_binds_len + 1));534
http_bind_t *http_bind = &http_binds[http_binds_len];535
http_bind->sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);536
http_bind->port = port;537
if (http_bind->sockfd <= 0) {538
perror("cannot create socket");539
errno = HTTP_ERR_NO_SOCKET;540
http_error = true;541
return;542
}543
struct hostent *host = gethostbyname(hostname);544
if (!host) {545
perror("unknown host");546
errno = HTTP_ERR_UNKNOWN_HOST;547
http_error = true;548
return;549
}550
struct sockaddr_in addr;551
addr.sin_family = AF_INET;552
memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);553
addr.sin_port = htons(port);554
int enable = 1;555
if (setsockopt(http_bind->sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {556
perror("cannot reuse address");557
errno = HTTP_ERR_NO_ADDR_REUSE;558
http_error = true;559
return;560
}561
if (bind(http_bind->sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {562
perror("cannot bind socket to port");563
errno = HTTP_ERR_ADDR_IN_USE;564
http_error = true;565
return;566
}567
if (listen(http_bind->sockfd, 5) < 0) {568
perror("cannot listen on port");569
errno = HTTP_ERR_NO_LISTEN;570
http_error = true;571
return;572
}573
for (int i = 0; i < hosts_len; i++) {574
http_host_t *http_host = &hosts[i];575
if (http_host->certificate != NULL && http_host->private_key != NULL) {576
const SSL_METHOD *method = TLS_server_method();577
http_host->ssl_ctx = SSL_CTX_new(method);578
if (!http_host->ssl_ctx) {579
perror("cannot create SSL context");580
errno = HTTP_ERR_NO_SSL_CONTEXT;581
http_error = true;582
return;583
}584
if (SSL_CTX_use_certificate_chain_file(http_host->ssl_ctx, http_host->certificate) <= 0) {585
perror("cannot use certificate file");586
errno = HTTP_ERR_INVALID_CERTIFICATE;587
http_error = true;588
}589
if (SSL_CTX_use_PrivateKey_file(http_host->ssl_ctx, http_host->private_key, SSL_FILETYPE_PEM) <= 0) {590
perror("cannot use private key file");591
errno = HTTP_ERR_INVALID_PRIVATE_KEY;592
http_error = true;593
}594
}595
else {596
http_host->ssl_ctx = NULL;597
}598
}599
http_bind->hosts = hosts;600
http_bind->hosts_len = hosts_len;601
http_binds_len++;602
}604
void http_listen(void) {605
signal(SIGPIPE, SIG_IGN);606
if (http_error) {607
return;608
}609
errno = 0;610
const SSL_METHOD *method = TLS_server_method();611
http_ssl_ctx = SSL_CTX_new(method);612
if (!http_ssl_ctx) {613
perror("cannot create SSL context");614
errno = HTTP_ERR_NO_SSL_CONTEXT;615
http_error = true;616
return;617
}618
SSL_CTX_set_tlsext_servername_callback(http_ssl_ctx, http_tls_sni_callback);619
pthread_create(&http_thread, 0, http_handle_server, NULL);620
}622
void http_close(void) {623
http_quit = true;624
if (!http_error) {625
pthread_join(http_thread, NULL);626
}627
for (int i = 0; i < http_binds_len; i++) {628
close(http_binds[i].sockfd);629
for (int j = 0; j < http_binds[i].hosts_len; j++) {630
if (http_binds[i].hosts[j].ssl_ctx != NULL) {631
SSL_CTX_free(http_binds[i].hosts[j].ssl_ctx);632
}633
}634
}635
if (http_ssl_ctx != NULL) {636
free(http_ssl_ctx);637
}638
}
1
#pragma once3
#include "sys/socket.h"4
#include "openssl/ssl.h"6
typedef enum {7
HTTP_ERR_NO_SOCKET = 1,8
HTTP_ERR_UNKNOWN_HOST = 2,9
HTTP_ERR_NO_ADDR_REUSE = 3,10
HTTP_ERR_ADDR_IN_USE = 4,11
HTTP_ERR_NO_LISTEN = 5,12
HTTP_ERR_NO_SSL_CONTEXT = 6,13
HTTP_ERR_INVALID_CERTIFICATE = 7,14
HTTP_ERR_INVALID_PRIVATE_KEY = 8,15
} http_error_t;17
typedef enum {18
HTTP_STATUS_CONTINUE = 100,19
HTTP_STATUS_SWITCHING_PROTOCOLS = 101,20
HTTP_STATUS_PROCESSING = 102,21
HTTP_STATUS_EARLY_HINTS = 103,22
HTTP_STATUS_OK = 200,23
HTTP_STATUS_CREATED = 201,24
HTTP_STATUS_ACCEPTED = 202,25
HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,26
HTTP_STATUS_NO_CONTENT = 204,27
HTTP_STATUS_RESET_CONTENT = 205,28
HTTP_STATUS_PARTIAL_CONTENT = 206,29
HTTP_STATUS_MULTI_STATUS = 207,30
HTTP_STATUS_ALREADY_REPORTED = 208,31
HTTP_STATUS_IM_USED = 226,32
HTTP_STATUS_MULTIPLE_CHOICES = 300,33
HTTP_STATUS_MOVED_PERMANENTLY = 301,34
HTTP_STATUS_FOUND = 302,35
HTTP_STATUS_SEE_OTHER = 303,36
HTTP_STATUS_NOT_MODIFIED = 304,37
HTTP_STATUS_TEMPORARY_REDIRECT = 307,38
HTTP_STATUS_PERMANENT_REDIRECT = 308,39
HTTP_STATUS_BAD_REQUEST = 400,40
HTTP_STATUS_UNAUTHORIZED = 401,41
HTTP_STATUS_PAYMENT_REQUIRED = 402,42
HTTP_STATUS_FORBIDDEN = 403,43
HTTP_STATUS_NOT_FOUND = 404,44
HTTP_STATUS_METHOD_NOT_ALLOWED = 405,45
HTTP_STATUS_NOT_ACCEPTABLE = 406,46
HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,47
HTTP_STATUS_REQUEST_TIMEOUT = 408,48
HTTP_STATUS_CONFLICT = 409,49
HTTP_STATUS_GONE = 410,50
HTTP_STATUS_LENGTH_REQUIRED = 411,51
HTTP_STATUS_PRECONDITION_FAILED = 412,52
HTTP_STATUS_PAYLOAD_TOO_LARGE = 413,53
HTTP_STATUS_URI_TOO_LONG = 414,54
HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,55
HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416,56
HTTP_STATUS_EXPECTATION_FAILED = 417,57
HTTP_STATUS_I_AM_A_TEAPOT = 418,58
HTTP_STATUS_MISDIRECTED_REQUEST = 421,59
HTTP_STATUS_UNPROCESSABLE_CONTENT = 422,60
HTTP_STATUS_LOCKED = 423,61
HTTP_STATUS_FAILED_DEPENDENCY = 424,62
HTTP_STATUS_TOO_EARLY = 425,63
HTTP_STATUS_UPGRADE_REQUIRED = 426,64
HTTP_STATUS_PRECONDITION_REQUIRED = 428,65
HTTP_STATUS_TOO_MANY_REQUESTS = 429,66
HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,67
HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,68
HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,69
HTTP_STATUS_NOT_IMPLEMENTED = 501,70
HTTP_STATUS_BAD_GATEWAY = 502,71
HTTP_STATUS_SERVICE_UNAVAILABLE = 503,72
HTTP_STATUS_GATEWAY_TIMEOUT = 504,73
HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,74
HTTP_STATUS_VARIANT_ALSO_NEGOTITATES = 506,75
HTTP_STATUS_INSUFFICIENT_STORAGE = 507,76
HTTP_STATUS_LOOP_DETECTED = 508,77
HTTP_STATUS_NOT_EXTENDED = 510,78
HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,79
} http_status_t;81
typedef struct {82
char *hostname;83
char *certificate;84
char *private_key;85
SSL_CTX *ssl_ctx;86
} http_host_t;88
typedef struct {89
int sockfd;90
http_host_t *hosts;91
int hosts_len;92
int port;93
} http_bind_t;95
typedef struct {96
int sockfd;97
struct sockaddr addr;98
int addr_len;99
SSL *ssl;100
http_bind_t *bind;101
http_host_t *curr_host;102
} http_conn_t;104
typedef struct {105
char *key;106
char *value;107
} http_header_t;109
typedef struct {110
http_conn_t *conn;111
char *method;112
char *url;113
char *version;114
http_header_t *headers;115
int headers_len;116
char *body;117
long body_len;118
void *ext_data;119
} http_request_t;121
typedef struct {122
char *version;123
http_status_t status;124
http_header_t *headers;125
int headers_len;126
char *body;127
long body_len;128
} http_response_t;130
void http_on_request(http_response_t fn(http_request_t *));132
char *http_header_get(http_request_t *request, char *key);133
void http_header_set(http_response_t *response, char *key, char *value);135
http_response_t http_response_create(http_status_t status);136
void http_response_body(http_response_t *response, char *body, long len);137
void http_response_file(http_response_t *response, char *filename);139
void http_bind(char *hostname, int port, http_host_t *hosts, int hosts_len);140
void http_listen(void);141
void http_close(void);
1
#ifndef LIB_HTTP_H2
#define LIB_HTTP_H4
#include <stdbool.h>5
#include <openssl/ssl.h>6
#include <sys/socket.h>8
typedef enum {9
HTTP_ERR_OK = 0,10
HTTP_ERR_NO_SOCKET = 1,11
HTTP_ERR_UNKNOWN_HOST = 2,12
HTTP_ERR_NO_ADDR_REUSE = 3,13
HTTP_ERR_ADDR_IN_USE = 4,14
HTTP_ERR_NO_LISTEN = 5,15
HTTP_ERR_NO_SSL_CONTEXT = 6,16
HTTP_ERR_INVALID_CERTIFICATE = 7,17
HTTP_ERR_INVALID_PRIVATE_KEY = 8,18
} http_error_t;20
typedef enum {21
HTTP_STATUS_CONTINUE = 100,22
HTTP_STATUS_SWITCHING_PROTOCOLS = 101,23
HTTP_STATUS_PROCESSING = 102,24
HTTP_STATUS_EARLY_HINTS = 103,25
HTTP_STATUS_OK = 200,26
HTTP_STATUS_CREATED = 201,27
HTTP_STATUS_ACCEPTED = 202,28
HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,29
HTTP_STATUS_NO_CONTENT = 204,30
HTTP_STATUS_RESET_CONTENT = 205,31
HTTP_STATUS_PARTIAL_CONTENT = 206,32
HTTP_STATUS_MULTI_STATUS = 207,33
HTTP_STATUS_ALREADY_REPORTED = 208,34
HTTP_STATUS_IM_USED = 226,35
HTTP_STATUS_MULTIPLE_CHOICES = 300,36
HTTP_STATUS_MOVED_PERMANENTLY = 301,37
HTTP_STATUS_FOUND = 302,38
HTTP_STATUS_SEE_OTHER = 303,39
HTTP_STATUS_NOT_MODIFIED = 304,40
HTTP_STATUS_TEMPORARY_REDIRECT = 307,41
HTTP_STATUS_PERMANENT_REDIRECT = 308,42
HTTP_STATUS_BAD_REQUEST = 400,43
HTTP_STATUS_UNAUTHORIZED = 401,44
HTTP_STATUS_PAYMENT_REQUIRED = 402,45
HTTP_STATUS_FORBIDDEN = 403,46
HTTP_STATUS_NOT_FOUND = 404,47
HTTP_STATUS_METHOD_NOT_ALLOWED = 405,48
HTTP_STATUS_NOT_ACCEPTABLE = 406,49
HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,50
HTTP_STATUS_REQUEST_TIMEOUT = 408,51
HTTP_STATUS_CONFLICT = 409,52
HTTP_STATUS_GONE = 410,53
HTTP_STATUS_LENGTH_REQUIRED = 411,54
HTTP_STATUS_PRECONDITION_FAILED = 412,55
HTTP_STATUS_PAYLOAD_TOO_LARGE = 413,56
HTTP_STATUS_URI_TOO_LONG = 414,57
HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,58
HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416,59
HTTP_STATUS_EXPECTATION_FAILED = 417,60
HTTP_STATUS_I_AM_A_TEAPOT = 418,61
HTTP_STATUS_MISDIRECTED_REQUEST = 421,62
HTTP_STATUS_UNPROCESSABLE_CONTENT = 422,63
HTTP_STATUS_LOCKED = 423,64
HTTP_STATUS_FAILED_DEPENDENCY = 424,65
HTTP_STATUS_TOO_EARLY = 425,66
HTTP_STATUS_UPGRADE_REQUIRED = 426,67
HTTP_STATUS_PRECONDITION_REQUIRED = 428,68
HTTP_STATUS_TOO_MANY_REQUESTS = 429,69
HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,70
HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,71
HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,72
HTTP_STATUS_NOT_IMPLEMENTED = 501,73
HTTP_STATUS_BAD_GATEWAY = 502,74
HTTP_STATUS_SERVICE_UNAVAILABLE = 503,75
HTTP_STATUS_GATEWAY_TIMEOUT = 504,76
HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,77
HTTP_STATUS_VARIANT_ALSO_NEGOTITATES = 506,78
HTTP_STATUS_INSUFFICIENT_STORAGE = 507,79
HTTP_STATUS_LOOP_DETECTED = 508,80
HTTP_STATUS_NOT_EXTENDED = 510,81
HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,82
} http_status_t;84
typedef struct Http http_t;86
typedef struct {87
char *hostname;88
char *certificate;89
char *private_key;90
SSL_CTX *ssl_ctx;91
} http_host_t;93
typedef struct {94
int sockfd;95
http_host_t *hosts;96
int hosts_len;97
int port;98
} http_bind_t;100
typedef struct {101
int sockfd;102
struct sockaddr addr;103
int addr_len;104
SSL *ssl;105
http_bind_t *curr_bind;106
http_host_t *curr_host;107
http_t *http;108
} http_conn_t;110
typedef struct {111
char *key;112
char *value;113
} http_header_t;115
typedef struct {116
http_conn_t *conn;117
char *method;118
char *url;119
char *version;120
http_header_t *headers;121
int headers_len;122
char *body;123
long body_len;124
void *ext_data;125
} http_request_t;127
typedef struct {128
char *version;129
http_status_t status;130
http_header_t *headers;131
int headers_len;132
char *body;133
long body_len;134
} http_response_t;136
struct Http {137
http_bind_t *binds;138
int binds_len;139
pthread_t thread;140
bool quit;141
SSL_CTX *ssl_ctx;142
http_response_t (*on_request_fn)(http_request_t *);143
};145
http_t *http_init(void);146
void http_cleanup(http_t *http);147
void http_on_request(http_t *http, http_response_t fn(http_request_t *));148
char *http_header_get(http_request_t *request, char *key);149
void http_header_set(http_response_t *response, char *key, char *value);150
http_response_t http_response_create(http_status_t status);151
void http_response_body(http_response_t *response, char *body, long len);152
void http_response_file(http_response_t *response, char *filename);153
http_error_t http_bind(http_t *http, char *hostname, int port, http_host_t *hosts, int hosts_len);154
http_error_t http_listen(http_t *http);155
void http_close(http_t *http);157
#ifdef LIB_HTTP_IMPL159
#include <stdio.h>160
#include <stdlib.h>161
#include <string.h>162
#include <time.h>163
#include <unistd.h>164
#include <pthread.h>165
#include <netdb.h>166
#include <poll.h>167
#include <signal.h>168
#include <openssl/ssl.h>169
#include <sys/socket.h>171
#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000173
http_t *http_init(void) {174
http_t *http = (http_t *) malloc(sizeof(http_t));175
*http = (http_t) {176
.binds = NULL,177
.binds_len = 0,178
.quit = false,179
.ssl_ctx = NULL,180
.on_request_fn = NULL,181
};182
return http;183
}185
void http_cleanup(http_t *http) {186
free(http);187
}189
void http_on_request(http_t *http, http_response_t fn(http_request_t *)) {190
http->on_request_fn = fn;191
}193
char *http_read_file(char *filename) {194
FILE *fp = fopen(filename, "r");195
fseek(fp, 0, SEEK_END);196
long len = ftell(fp);197
fseek(fp, 0, SEEK_SET);198
char *content = (char *) malloc(sizeof(char) * (len + 1));199
fread(content, len, sizeof(char), fp);200
content[len] = '\0';201
fclose(fp);202
return content;203
}205
const char *http_status_str(http_status_t status) {206
switch (status) {207
case HTTP_STATUS_CONTINUE:208
return "Continue";209
case HTTP_STATUS_SWITCHING_PROTOCOLS:210
return "Switching Protocols";211
case HTTP_STATUS_PROCESSING:212
return "Processing";213
case HTTP_STATUS_EARLY_HINTS:214
return "Early Hints";215
case HTTP_STATUS_OK:216
return "OK";217
case HTTP_STATUS_CREATED:218
return "Created";219
case HTTP_STATUS_ACCEPTED:220
return "Accepted";221
case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:222
return "Non-Authoritative Information";223
case HTTP_STATUS_NO_CONTENT:224
return "No Content";225
case HTTP_STATUS_RESET_CONTENT:226
return "Reset Content";227
case HTTP_STATUS_PARTIAL_CONTENT:228
return "Partial Content";229
case HTTP_STATUS_MULTI_STATUS:230
return "Multi-Status";231
case HTTP_STATUS_ALREADY_REPORTED:232
return "Already Reported";233
case HTTP_STATUS_IM_USED:234
return "IM Used";235
case HTTP_STATUS_MULTIPLE_CHOICES:236
return "Multiple Choices";237
case HTTP_STATUS_MOVED_PERMANENTLY:238
return "Moved Permanently";239
case HTTP_STATUS_FOUND:240
return "Found";241
case HTTP_STATUS_SEE_OTHER:242
return "See Other";243
case HTTP_STATUS_NOT_MODIFIED:244
return "Not Modified";245
case HTTP_STATUS_TEMPORARY_REDIRECT:246
return "Temporary Redirect";247
case HTTP_STATUS_PERMANENT_REDIRECT:248
return "Permanent Redirect";249
case HTTP_STATUS_BAD_REQUEST:250
return "Bad Request";251
case HTTP_STATUS_UNAUTHORIZED:252
return "Unauthorized";253
case HTTP_STATUS_PAYMENT_REQUIRED:254
return "Payment Required";255
case HTTP_STATUS_FORBIDDEN:256
return "Forbidden";257
case HTTP_STATUS_NOT_FOUND:258
return "Not Found";259
case HTTP_STATUS_METHOD_NOT_ALLOWED:260
return "Method Not Allowed";261
case HTTP_STATUS_NOT_ACCEPTABLE:262
return "Not Acceptable";263
case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:264
return "Proxy Authentication Required";265
case HTTP_STATUS_REQUEST_TIMEOUT:266
return "Request Timeout";267
case HTTP_STATUS_CONFLICT:268
return "Conflict";269
case HTTP_STATUS_GONE:270
return "Gone";271
case HTTP_STATUS_LENGTH_REQUIRED:272
return "Length Required";273
case HTTP_STATUS_PRECONDITION_FAILED:274
return "Precondition Failed";275
case HTTP_STATUS_PAYLOAD_TOO_LARGE:276
return "Payload Too Large";277
case HTTP_STATUS_URI_TOO_LONG:278
return "URI Too Long";279
case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:280
return "Unsupported Media Type";281
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:282
return "Range Not Satisfiable";283
case HTTP_STATUS_EXPECTATION_FAILED:284
return "Expectation Failed";285
case HTTP_STATUS_I_AM_A_TEAPOT:286
return "I'm a teapot";287
case HTTP_STATUS_MISDIRECTED_REQUEST:288
return "Misdirected Request";289
case HTTP_STATUS_UNPROCESSABLE_CONTENT:290
return "Unprocessable Content";291
case HTTP_STATUS_LOCKED:292
return "Locked";293
case HTTP_STATUS_FAILED_DEPENDENCY:294
return "Failed Dependency";295
case HTTP_STATUS_TOO_EARLY:296
return "Too Early";297
case HTTP_STATUS_UPGRADE_REQUIRED:298
return "Upgrade Required";299
case HTTP_STATUS_PRECONDITION_REQUIRED:300
return "Precondition Required";301
case HTTP_STATUS_TOO_MANY_REQUESTS:302
return "Too Many Requests";303
case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:304
return "Request Header Fields Too Large";305
case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:306
return "Unavailable For Legal Reasons";307
case HTTP_STATUS_INTERNAL_SERVER_ERROR:308
return "Internal Server Error";309
case HTTP_STATUS_NOT_IMPLEMENTED:310
return "Not Implemented";311
case HTTP_STATUS_BAD_GATEWAY:312
return "Bad Gateway";313
case HTTP_STATUS_SERVICE_UNAVAILABLE:314
return "Service Unavailable";315
case HTTP_STATUS_GATEWAY_TIMEOUT:316
return "Gateway Timeout";317
case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:318
return "HTTP Version Not Supported";319
case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:320
return "Variant Also Negotitates";321
case HTTP_STATUS_INSUFFICIENT_STORAGE:322
return "Insufficient Storage";323
case HTTP_STATUS_LOOP_DETECTED:324
return "Loop Detected";325
case HTTP_STATUS_NOT_EXTENDED:326
return "Not Extended";327
case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:328
return "Network Authentication Required";329
default:330
return NULL;331
}332
}334
ssize_t http_read(http_conn_t *conn, char *buffer, size_t len) {335
if (conn->ssl != NULL) {336
return SSL_read(conn->ssl, buffer, len);337
}338
return read(conn->sockfd, buffer, len);339
}341
ssize_t http_write(http_conn_t *conn, char *buffer, size_t len) {342
if (conn->ssl != NULL) {343
return SSL_write(conn->ssl, buffer, len);344
}345
return write(conn->sockfd, buffer, len);346
}348
char *http_header_get(http_request_t *request, char *key) {349
if (request->headers_len > 0) {350
for (int i = 0; i < request->headers_len; i++) {351
http_header_t *header = &request->headers[i];352
if (strcmp(header->key, key) == 0) {353
return header->value;354
}355
}356
}357
return NULL;358
}360
void http_header_set(http_response_t *response, char *key, char *value) {361
response->headers = (http_header_t *) realloc(response->headers, sizeof(http_header_t) * (response->headers_len + 1));362
http_header_t *new_header = &response->headers[response->headers_len];363
response->headers_len++;364
int key_len = strlen(key);365
new_header->key = (char *) malloc(sizeof(char) * (key_len + 1));366
memcpy(new_header->key, key, key_len);367
new_header->key[key_len] = '\0';368
int value_len = strlen(value);369
new_header->value = (char *) malloc(sizeof(char) * (value_len + 1));370
memcpy(new_header->value, value, value_len);371
new_header->value[value_len] = '\0';372
}374
http_response_t http_response_create(http_status_t status) {375
const char *version = "HTTP/1.1";376
int version_len = strlen(version);377
http_response_t response = { NULL, status, NULL, 0, NULL, 0 };378
response.version = (char *) malloc(sizeof(char) * (version_len + 1));379
memcpy(response.version, version, version_len);380
response.version[version_len] = '\0';381
return response;382
}384
void http_response_body(http_response_t *response, char *body, long len) {385
if (response != NULL && body != NULL) {386
response->body = (char *) malloc(sizeof(char) * len);387
memcpy(response->body, body, len);388
response->body_len = len;389
char content_length[50];390
snprintf(content_length, 50, "%ld", len);391
http_header_set(response, (char *) "Content-Length", content_length);392
}393
}395
void http_response_file(http_response_t *response, char *filename) {396
char *content = http_read_file(filename);397
if (content != NULL) {398
http_response_body(response, content, strlen(content));399
free(content);400
}401
}403
void http_request_free(http_request_t *request) {404
if (request->method != NULL) {405
free(request->method);406
}407
if (request->url != NULL) {408
free(request->url);409
}410
if (request->version != NULL) {411
free(request->version);412
}413
if (request->headers_len > 0) {414
for (int i = 0; i < request->headers_len; i++) {415
http_header_t *header = &request->headers[i];416
if (header->key != NULL) {417
free(header->key);418
}419
if (header->value != NULL) {420
free(header->value);421
}422
}423
}424
if (request->body != NULL) {425
free(request->body);426
}427
if (request->ext_data != NULL) {428
free(request->ext_data);429
}430
}432
void http_response_free(http_response_t *response) {433
if (response->version != NULL) {434
free(response->version);435
}436
if (response->headers_len > 0) {437
for (int i = 0; i < response->headers_len; i++) {438
http_header_t *header = &response->headers[i];439
if (header->key != NULL) {440
free(header->key);441
}442
if (header->value != NULL) {443
free(header->value);444
}445
}446
}447
if (response->body != NULL) {448
free(response->body);449
}450
}452
http_request_t http_read_request(http_conn_t *conn) {453
int len = 0;454
int ln = 0;455
int start = 0;456
char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];457
http_request_t request = {458
.conn = conn,459
.method = NULL,460
.url = NULL,461
.version = NULL,462
.headers = NULL,463
.headers_len = 0,464
.body = NULL,465
.body_len = 0,466
.ext_data = NULL,467
};468
while (true) {469
char c;470
int read = http_read(conn, &c, 1);471
if (read == 0) {472
break;473
}474
// break if too long475
if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {476
perror("request is too long");477
break;478
}479
buffer[len] = c;480
len++;481
// read head482
if (len >= 2) {483
char *slice = buffer + (len - 2);484
if (strncmp(slice, "\r\n", 2) == 0) {485
int line_len = (len - 2) - start;486
if (line_len > 0) {487
// read line488
char line[line_len + 1];489
memcpy(line, buffer + start, line_len);490
line[line_len] = '\0';491
// read method, url, and version492
if (ln == 0) {493
int arg = 0;494
int start = 0;495
for (int i = 0; i <= line_len; i++) {496
if (line[i] == ' ' || i == line_len) {497
// read method498
if (arg == 0) {499
int method_length = i - start;500
request.method = (char *) malloc(sizeof(char) * (method_length + 1));501
memcpy(request.method, line + start, method_length);502
request.method[method_length] = '\0';503
}504
// read url505
if (arg == 1) {506
int url_length = i - start;507
request.url = (char *) malloc(sizeof(char) * (url_length + 1));508
memcpy(request.url, line + start, url_length);509
request.url[url_length] = '\0';510
}511
// read version512
if (arg == 2) {513
int version_length = i - start;514
request.version = (char *) malloc(sizeof(char) * (version_length + 1));515
memcpy(request.version, line + start, version_length);516
request.version[version_length] = '\0';517
}518
start = i + 1;519
arg++;520
}521
}522
}523
// read headers524
else {525
int sep = 0;526
request.headers = (http_header_t *) realloc(request.headers, sizeof(http_header_t) * (request.headers_len + 1));527
http_header_t *header = &request.headers[request.headers_len];528
request.headers_len++;529
for (int i = 0; i < line_len; i++) {530
if (line[i] == ':') {531
int key_len = i;532
header->key = (char *) malloc(sizeof(char) * (key_len + 1));533
memcpy(header->key, line, key_len);534
header->key[key_len] = '\0';535
sep = i + 2;536
break;537
}538
}539
int value_len = line_len - sep;540
header->value = (char *) malloc(sizeof(char) * (value_len + 1));541
memcpy(header->value, line + sep, value_len);542
header->value[value_len] = '\0';543
}544
}545
start = len;546
ln++;547
}548
}549
// read body550
if (len >= 4) {551
char *slice = buffer + (len - 4);552
if (strncmp(slice, "\r\n\r\n", 4) == 0) {553
char *content_length = http_header_get(&request, (char *) "Content-Length");554
if (content_length != NULL) {555
request.body_len = strtol(content_length, NULL, 10);556
if (request.body_len > 0) {557
request.body = (char *) malloc(sizeof(char) * (request.body_len + 1));558
http_read(conn, request.body, request.body_len);559
request.body[request.body_len] = '\0';560
}561
}562
break;563
}564
}565
}566
return request;567
}569
void http_write_response(http_conn_t *conn, http_response_t response) {570
http_write(conn, response.version, strlen(response.version));571
http_write(conn, (char *) " ", 1);572
char status[4];573
snprintf(status, 4, "%d", response.status);574
http_write(conn, status, strlen(status));575
http_write(conn, (char *) " ", 1);576
const char *status_message = http_status_str(response.status);577
http_write(conn, (char *) status_message, strlen(status_message));578
http_write(conn, (char *) "\r\n", 2);579
if (response.headers_len > 0) {580
for (int i = 0; i < response.headers_len; i++) {581
http_header_t *header = &response.headers[i];582
http_write(conn, header->key, strlen(header->key));583
http_write(conn, (char *) ": ", 2);584
http_write(conn, header->value, strlen(header->value));585
http_write(conn, (char *) "\r\n", 2);586
}587
}588
http_write(conn, (char *) "\r\n", 2);589
if (response.body != NULL) {590
http_write(conn, response.body, response.body_len);591
}592
}594
void *http_handle_client(void *ptr) {595
if (!ptr) {596
pthread_exit(0);597
}598
http_conn_t *conn = (http_conn_t *) ptr;599
if (conn->curr_bind->hosts_len > 0) {600
SSL_CTX_set_tlsext_servername_arg(conn->http->ssl_ctx, (void *) conn);601
conn->ssl = SSL_new(conn->http->ssl_ctx);602
SSL_set_fd(conn->ssl, conn->sockfd);603
if (SSL_accept(conn->ssl) <= 0) {604
pthread_exit(0);605
}606
}607
http_request_t request = http_read_request(conn);608
if (request.method != NULL && request.url != NULL) {609
if (conn->http->on_request_fn != NULL) {610
http_response_t response = conn->http->on_request_fn(&request);611
http_write_response(conn, response);612
http_response_free(&response);613
}614
}615
http_request_free(&request);616
if (conn->ssl != NULL) {617
SSL_shutdown(conn->ssl);618
SSL_free(conn->ssl);619
}620
close(conn->sockfd);621
free(conn);622
pthread_exit(0);623
}625
void *http_handle_server(void *ptr) {626
http_t *http = (http_t *) ptr;627
struct pollfd fds[http->binds_len];628
for (int i = 0; i < http->binds_len; i++) {629
fds[i].fd = http->binds[i].sockfd;630
fds[i].events = POLLIN | POLLPRI;631
}632
while (!http->quit) {633
struct timespec sleep_req, sleep_rem;634
sleep_req.tv_sec = 0;635
sleep_req.tv_nsec = 100000000;636
nanosleep(&sleep_req, &sleep_rem);637
if (poll(fds, http->binds_len, 100)) {638
for (int i = 0; i < http->binds_len; i++) {639
if (fds[i].revents & POLLIN) {640
http_conn_t *conn = (http_conn_t *) malloc(sizeof(http_conn_t));641
conn->addr_len = sizeof(conn->addr);642
conn->sockfd = accept(http->binds[i].sockfd, &conn->addr, (socklen_t *) &conn->addr_len);643
conn->curr_bind = &http->binds[i];644
conn->ssl = NULL;645
conn->http = http;646
if (conn->sockfd <= 0) {647
free(conn);648
}649
else {650
pthread_t thread;651
pthread_attr_t thread_attr;652
pthread_attr_init(&thread_attr);653
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);654
pthread_create(&thread, &thread_attr, http_handle_client, (void *) conn);655
pthread_attr_destroy(&thread_attr);656
}657
}658
}659
}660
}661
pthread_exit(0);662
}664
int http_tls_sni_callback(SSL *ssl, int *al, void *arg) {665
(void)(al);666
http_conn_t *conn = (http_conn_t *) arg;667
const char *hostname = SSL_get_servername(ssl, 0);668
if (hostname != NULL) {669
for (int i = 0; i < conn->http->binds_len; i++) {670
for (int j = 0; j < conn->http->binds[i].hosts_len; j++) {671
http_host_t *http_host = &conn->http->binds[i].hosts[j];672
if (strcmp(http_host->hostname, hostname) == 0) {673
conn->curr_host = http_host;674
SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);675
return SSL_TLSEXT_ERR_OK;676
}677
}678
}679
}680
return SSL_TLSEXT_ERR_NOACK;681
}683
http_error_t http_bind(http_t *http, char *hostname, int port, http_host_t *hosts, int hosts_len) {684
http->binds = (http_bind_t *) realloc(http->binds, sizeof(http_bind_t) * (http->binds_len + 1));685
http_bind_t *http_bind = &http->binds[http->binds_len];686
http_bind->sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);687
http_bind->port = port;688
if (http_bind->sockfd <= 0) {689
return HTTP_ERR_NO_SOCKET;690
}691
struct hostent *host = gethostbyname(hostname);692
if (!host) {693
return HTTP_ERR_UNKNOWN_HOST;694
}695
struct sockaddr_in addr;696
addr.sin_family = AF_INET;697
memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);698
addr.sin_port = htons(port);699
int enable = 1;700
if (setsockopt(http_bind->sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {701
return HTTP_ERR_NO_ADDR_REUSE;702
}703
if (bind(http_bind->sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {704
return HTTP_ERR_ADDR_IN_USE;705
}706
if (listen(http_bind->sockfd, 5) < 0) {707
return HTTP_ERR_NO_LISTEN;708
}709
for (int i = 0; i < hosts_len; i++) {710
http_host_t *http_host = &hosts[i];711
http_host->ssl_ctx = NULL;712
if (http_host->certificate != NULL && http_host->private_key != NULL) {713
const SSL_METHOD *method = TLS_server_method();714
http_host->ssl_ctx = SSL_CTX_new(method);715
if (!http_host->ssl_ctx) {716
return HTTP_ERR_NO_SSL_CONTEXT;717
}718
if (SSL_CTX_use_certificate_chain_file(http_host->ssl_ctx, http_host->certificate) <= 0) {719
return HTTP_ERR_INVALID_CERTIFICATE;720
}721
if (SSL_CTX_use_PrivateKey_file(http_host->ssl_ctx, http_host->private_key, SSL_FILETYPE_PEM) <= 0) {722
return HTTP_ERR_INVALID_PRIVATE_KEY;723
}724
}725
}726
http_bind->hosts = hosts;727
http_bind->hosts_len = hosts_len;728
http->binds_len++;729
return HTTP_ERR_OK;730
}732
http_error_t http_listen(http_t *http) {733
signal(SIGPIPE, SIG_IGN);734
const SSL_METHOD *method = TLS_server_method();735
http->ssl_ctx = SSL_CTX_new(method);736
if (!http->ssl_ctx) {737
return HTTP_ERR_NO_SSL_CONTEXT;738
}739
SSL_CTX_set_tlsext_servername_callback(http->ssl_ctx, http_tls_sni_callback);740
pthread_create(&http->thread, 0, http_handle_server, (void *) http);741
return HTTP_ERR_OK;742
}744
void http_close(http_t *http) {745
http->quit = true;746
pthread_join(http->thread, NULL);747
for (int i = 0; i < http->binds_len; i++) {748
close(http->binds[i].sockfd);749
for (int j = 0; j < http->binds[i].hosts_len; j++) {750
if (http->binds[i].hosts[j].ssl_ctx != NULL) {751
SSL_CTX_free(http->binds[i].hosts[j].ssl_ctx);752
}753
}754
}755
if (http->ssl_ctx != NULL) {756
free(http->ssl_ctx);757
}758
}760
#endif /* LIB_HTTP_IMPL */761
#endif /* LIB_HTTP_H */