A low-key HTTP micro-framework for people who hate web bloat
git clone git://soophie.de/tpee
blob: 2bed89c20522b718077c527dbe34e4ad20dd829a (19742 bytes)[doc][blame][raw]
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
}