A low-key HTTP micro-framework for people who hate web bloat
git clone git://soophie.de/tpee
blob: c5744a2cdea74f2b6689733f440ef5e2f794d973 (17111 bytes)[doc][blame][raw]
1
#include <stdio.h>2
#include <stdlib.h>3
#include <stdbool.h>4
#include <string.h>5
#include <unistd.h>6
#include <pthread.h>7
#include <netdb.h>8
#include <errno.h>9
#include <poll.h>10
#include <signal.h>11
#include <openssl/ssl.h>13
#include "libhttp.h"15
#define MAX_REQUEST_HEAD_SIZE 4096017
int http_sockfd;18
pthread_t http_thread;19
bool http_quit = false;20
bool http_error = false;21
SSL_CTX *http_ctx = NULL;23
http_response_t (*on_request_fn)(http_request_t *) = NULL;25
void http_on_request(http_response_t fn(http_request_t *)) {26
on_request_fn = fn;27
}29
char *http_read_file(char *filename) {30
FILE *fp = fopen(filename, "r");31
fseek(fp, 0, SEEK_END);32
long len = ftell(fp);33
fseek(fp, 0, SEEK_SET);34
char *content = malloc(sizeof(char) * (len + 1));35
fread(content, len, sizeof(char), fp);36
content[len] = '\0';37
fclose(fp);38
return content;39
}41
char *http_status_str(http_status_t status) {42
switch (status) {43
case HTTP_STATUS_CONTINUE:44
return "Continue";45
case HTTP_STATUS_SWITCHING_PROTOCOLS:46
return "Switching Protocols";47
case HTTP_STATUS_PROCESSING:48
return "Processing";49
case HTTP_STATUS_EARLY_HINTS:50
return "Early Hints";51
case HTTP_STATUS_OK:52
return "OK";53
case HTTP_STATUS_CREATED:54
return "Created";55
case HTTP_STATUS_ACCEPTED:56
return "Accepted";57
case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:58
return "Non-Authoritative Information";59
case HTTP_STATUS_NO_CONTENT:60
return "No Content";61
case HTTP_STATUS_RESET_CONTENT:62
return "Reset Content";63
case HTTP_STATUS_PARTIAL_CONTENT:64
return "Partial Content";65
case HTTP_STATUS_MULTI_STATUS:66
return "Multi-Status";67
case HTTP_STATUS_ALREADY_REPORTED:68
return "Already Reported";69
case HTTP_STATUS_IM_USED:70
return "IM Used";71
case HTTP_STATUS_MULTIPLE_CHOICES:72
return "Multiple Choices";73
case HTTP_STATUS_MOVED_PERMANENTLY:74
return "Moved Permanently";75
case HTTP_STATUS_FOUND:76
return "Found";77
case HTTP_STATUS_SEE_OTHER:78
return "See Other";79
case HTTP_STATUS_NOT_MODIFIED:80
return "Not Modified";81
case HTTP_STATUS_TEMPORARY_REDIRECT:82
return "Temporary Redirect";83
case HTTP_STATUS_PERMANENT_REDIRECT:84
return "Permanent Redirect";85
case HTTP_STATUS_BAD_REQUEST:86
return "Bad Request";87
case HTTP_STATUS_UNAUTHORIZED:88
return "Unauthorized";89
case HTTP_STATUS_PAYMENT_REQUIRED:90
return "Payment Required";91
case HTTP_STATUS_FORBIDDEN:92
return "Forbidden";93
case HTTP_STATUS_NOT_FOUND:94
return "Not Found";95
case HTTP_STATUS_METHOD_NOT_ALLOWED:96
return "Method Not Allowed";97
case HTTP_STATUS_NOT_ACCEPTABLE:98
return "Not Acceptable";99
case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:100
return "Proxy Authentication Required";101
case HTTP_STATUS_REQUEST_TIMEOUT:102
return "Request Timeout";103
case HTTP_STATUS_CONFLICT:104
return "Conflict";105
case HTTP_STATUS_GONE:106
return "Gone";107
case HTTP_STATUS_LENGTH_REQUIRED:108
return "Length Required";109
case HTTP_STATUS_PRECONDITION_FAILED:110
return "Precondition Failed";111
case HTTP_STATUS_PAYLOAD_TOO_LARGE:112
return "Payload Too Large";113
case HTTP_STATUS_URI_TOO_LONG:114
return "URI Too Long";115
case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:116
return "Unsupported Media Type";117
case HTTP_STATUS_RANGE_NOT_SATISFIABLE:118
return "Range Not Satisfiable";119
case HTTP_STATUS_EXPECTATION_FAILED:120
return "Expectation Failed";121
case HTTP_STATUS_I_AM_A_TEAPOT:122
return "I'm a teapot";123
case HTTP_STATUS_MISDIRECTED_REQUEST:124
return "Misdirected Request";125
case HTTP_STATUS_UNPROCESSABLE_CONTENT:126
return "Unprocessable Content";127
case HTTP_STATUS_LOCKED:128
return "Locked";129
case HTTP_STATUS_FAILED_DEPENDENCY:130
return "Failed Dependency";131
case HTTP_STATUS_TOO_EARLY:132
return "Too Early";133
case HTTP_STATUS_UPGRADE_REQUIRED:134
return "Upgrade Required";135
case HTTP_STATUS_PRECONDITION_REQUIRED:136
return "Precondition Required";137
case HTTP_STATUS_TOO_MANY_REQUESTS:138
return "Too Many Requests";139
case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:140
return "Request Header Fields Too Large";141
case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:142
return "Unavailable For Legal Reasons";143
case HTTP_STATUS_INTERNAL_SERVER_ERROR:144
return "Internal Server Error";145
case HTTP_STATUS_NOT_IMPLEMENTED:146
return "Not Implemented";147
case HTTP_STATUS_BAD_GATEWAY:148
return "Bad Gateway";149
case HTTP_STATUS_SERVICE_UNAVAILABLE:150
return "Service Unavailable";151
case HTTP_STATUS_GATEWAY_TIMEOUT:152
return "Gateway Timeout";153
case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:154
return "HTTP Version Not Supported";155
case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:156
return "Variant Also Negotitates";157
case HTTP_STATUS_INSUFFICIENT_STORAGE:158
return "Insufficient Storage";159
case HTTP_STATUS_LOOP_DETECTED:160
return "Loop Detected";161
case HTTP_STATUS_NOT_EXTENDED:162
return "Not Extended";163
case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:164
return "Network Authentication Required";165
default:166
return NULL;167
}168
}170
ssize_t http_read(conn_t *conn, void *buffer, size_t len) {171
if (conn->ssl != NULL) {172
return SSL_read(conn->ssl, buffer, len);173
}174
return read(conn->sockfd, buffer, len);175
}177
ssize_t http_write(conn_t *conn, void *buffer, size_t len) {178
if (conn->ssl != NULL) {179
return SSL_write(conn->ssl, buffer, len);180
}181
return write(conn->sockfd, buffer, len);182
}184
char *http_header_get(http_request_t *request, char *key) {185
if (request->headers_len > 0) {186
for (int i = 0; i < request->headers_len; i++) {187
http_header_t *header = &request->headers[i];188
if (strcmp(header->key, key) == 0) {189
return header->value;190
}191
}192
}193
return NULL;194
}196
void http_header_set(http_response_t *response, char *key, char *value) {197
http_header_t *new_header = NULL;198
if (response->headers_len > 0) {199
for (int i = 0; i < response->headers_len; i++) {200
http_header_t *header = &response->headers[i];201
if (strcmp(header->key, key) == 0) {202
new_header = header;203
break;204
}205
}206
}207
if (new_header == NULL) {208
response->headers = realloc(response->headers, sizeof(http_header_t) * (response->headers_len + 1));209
new_header = &response->headers[response->headers_len];210
response->headers_len++;211
}212
int key_len = strlen(key);213
new_header->key = malloc(sizeof(char) * (key_len + 1));214
memcpy(new_header->key, key, key_len);215
new_header->key[key_len] = '\0';216
int value_len = strlen(value);217
new_header->value = malloc(sizeof(char) * (value_len + 1));218
memcpy(new_header->value, value, value_len);219
new_header->value[value_len] = '\0';220
}222
http_response_t http_response_create(http_status_t status) {223
char *version = "HTTP/1.1";224
int version_len = strlen(version);225
http_response_t response = { NULL, status, NULL, 0, NULL, 0 };226
response.version = malloc(sizeof(char) * (version_len + 1));227
memcpy(response.version, version, version_len);228
response.version[version_len] = '\0';229
return response;230
}232
void http_response_body(http_response_t *response, char *body, long len) {233
if (response != NULL && body != NULL) {234
response->body = malloc(sizeof(char) * len);235
memcpy(response->body, body, len);236
response->body_len = len;237
char content_length[50];238
snprintf(content_length, 50, "%ld", len);239
http_header_set(response, "Content-Length", content_length);240
}241
}243
void http_response_file(http_response_t *response, char *filename) {244
char *content = http_read_file(filename);245
if (content != NULL) {246
http_response_body(response, content, strlen(content));247
free(content);248
}249
}251
void http_request_free(http_request_t *request) {252
if (request->method != NULL) {253
free(request->method);254
}255
if (request->url != NULL) {256
free(request->url);257
}258
if (request->version != NULL) {259
free(request->version);260
}261
if (request->headers_len > 0) {262
for (int i = 0; i < request->headers_len; i++) {263
http_header_t *header = &request->headers[i];264
if (header->key != NULL) {265
free(header->key);266
}267
if (header->value != NULL) {268
free(header->value);269
}270
}271
}272
if (request->body != NULL) {273
free(request->body);274
}275
}277
void http_response_free(http_response_t *response) {278
if (response->version != NULL) {279
free(response->version);280
}281
if (response->headers_len > 0) {282
for (int i = 0; i < response->headers_len; i++) {283
http_header_t *header = &response->headers[i];284
if (header->key != NULL) {285
free(header->key);286
}287
if (header->value != NULL) {288
free(header->value);289
}290
}291
}292
if (response->body != NULL) {293
free(response->body);294
}295
}297
http_request_t http_read_request(conn_t *conn) {298
int len = 0;299
int ln = 0;300
int start = 0;301
char buffer[10240];302
http_request_t request = { conn, NULL, NULL, NULL, NULL, 0, NULL, 0 };303
while (true) {304
char c;305
http_read(conn, &c, 1);306
// break if too long307
if (len == MAX_REQUEST_HEAD_SIZE) {308
perror("request is too long");309
break;310
}311
buffer[len] = c;312
len++;313
// read head314
if (len >= 2) {315
char *slice = buffer + (len - 2);316
if (strncmp(slice, "\r\n", 2) == 0) {317
int line_len = (len - 2) - start;318
if (line_len > 0) {319
// read line320
char line[line_len + 1];321
memcpy(line, buffer + start, line_len);322
line[line_len] = '\0';323
// read method, url, and version324
if (ln == 0) {325
int arg = 0;326
int start = 0;327
for (int i = 0; i <= line_len; i++) {328
if (line[i] == ' ' || i == line_len) {329
// read method330
if (arg == 0) {331
int method_length = i - start;332
request.method = malloc(sizeof(char) * (method_length + 1));333
memcpy(request.method, line + start, method_length);334
request.method[method_length] = '\0';335
}336
// read url337
if (arg == 1) {338
int url_length = i - start;339
request.url = malloc(sizeof(char) * (url_length + 1));340
memcpy(request.url, line + start, url_length);341
request.url[url_length] = '\0';342
}343
// read version344
if (arg == 2) {345
int version_length = i - start;346
request.version = malloc(sizeof(char) * (version_length + 1));347
memcpy(request.version, line + start, version_length);348
request.version[version_length] = '\0';349
}350
start = i + 1;351
arg++;352
}353
}354
}355
// read headers356
else {357
int sep = 0;358
request.headers = realloc(request.headers, sizeof(http_header_t) * (request.headers_len + 1));359
http_header_t *header = &request.headers[request.headers_len];360
request.headers_len++;361
for (int i = 0; i < line_len; i++) {362
if (line[i] == ':') {363
int key_len = i;364
header->key = malloc(sizeof(char) * (key_len + 1));365
memcpy(header->key, line, key_len);366
header->key[key_len] = '\0';367
sep = i + 2;368
break;369
}370
}371
int value_len = line_len - sep;372
header->value = malloc(sizeof(char) * (value_len + 1));373
memcpy(header->value, line + sep, value_len);374
header->value[value_len] = '\0';375
}376
}377
start = len;378
ln++;379
}380
}381
// read body382
if (len >= 4) {383
char *slice = buffer + (len - 4);384
if (strncmp(slice, "\r\n\r\n", 4) == 0) {385
char *content_length = http_header_get(&request, "Content-Length");386
if (content_length != NULL) {387
request.body_len = strtol(content_length, NULL, 10);388
http_read(conn, request.body, request.body_len);389
}390
break;391
}392
}393
}394
return request;395
}397
void http_write_response(conn_t *conn, http_response_t response) {398
http_write(conn, response.version, strlen(response.version));399
http_write(conn, " ", 1);400
char status[4];401
snprintf(status, 4, "%d", response.status);402
http_write(conn, status, strlen(status));403
http_write(conn, " ", 1);404
char *status_message = http_status_str(response.status);405
http_write(conn, status_message, strlen(status_message));406
http_write(conn, "\r\n", 2);407
if (response.headers_len > 0) {408
for (int i = 0; i < response.headers_len; i++) {409
http_header_t *header = &response.headers[i];410
http_write(conn, header->key, strlen(header->key));411
http_write(conn, ": ", 2);412
http_write(conn, header->value, strlen(header->value));413
http_write(conn, "\r\n", 2);414
}415
}416
http_write(conn, "\r\n", 2);417
if (response.body != NULL) {418
http_write(conn, response.body, response.body_len);419
}420
}422
void *http_handle_client(void *ptr) {423
if (!ptr) {424
pthread_exit(0);425
}426
conn_t *conn = (conn_t *) ptr;427
if (http_ctx != NULL) {428
conn->ssl = SSL_new(http_ctx);429
SSL_set_fd(conn->ssl, conn->sockfd);430
if (SSL_accept(conn->ssl) <= 0) {431
perror("cannot SSL handshake");432
pthread_exit(0);433
}434
}435
http_request_t request = http_read_request(conn);436
if (request.method != NULL && request.url != NULL) {437
long addr = ((struct sockaddr_in *) &request.conn->addr)->sin_addr.s_addr;438
printf(439
"%ld.%ld.%ld.%ld -> %s %s\n",440
(addr ) & 0xff,441
(addr >> 8) & 0xff,442
(addr >> 16) & 0xff,443
(addr >> 24) & 0xff,444
request.method,445
request.url446
);447
if (on_request_fn != NULL) {448
http_response_t response = on_request_fn(&request);449
http_write_response(conn, response);450
http_response_free(&response);451
}452
}453
http_request_free(&request);454
if (http_ctx != NULL) {455
SSL_shutdown(conn->ssl);456
SSL_free(conn->ssl);457
}458
close(conn->sockfd);459
free(conn);460
pthread_exit(0);461
}463
void *http_handle_server(void *ptr) {464
if (!ptr) {465
pthread_exit(0);466
}467
int sockfd = *((int *) ptr);468
struct pollfd fds[1];469
fds[0].fd = sockfd;470
fds[0].events = POLLIN | POLLPRI;471
while (!http_quit) {472
usleep(100000);473
if (poll(fds, 1, 100)) {474
conn_t *conn = malloc(sizeof(conn_t));475
conn->addr_len = sizeof(conn->addr);476
conn->sockfd = accept(sockfd, &conn->addr, (socklen_t *) &conn->addr_len);477
conn->ssl = NULL;478
if (conn->sockfd <= 0) {479
free(conn);480
}481
else {482
pthread_t thread;483
pthread_create(&thread, 0, http_handle_client, (void *) conn);484
pthread_detach(thread);485
}486
}487
}488
pthread_exit(0);489
}491
void http_tls_enable(char *certificate, char *private_key) {492
const SSL_METHOD *method = TLS_server_method();493
http_ctx = SSL_CTX_new(method);494
if (!http_ctx) {495
perror("cannot create SSL context");496
errno = HTTP_ERR_NO_SSL_CONTEXT;497
http_error = true;498
return;499
}500
if (SSL_CTX_use_certificate_file(http_ctx, certificate, SSL_FILETYPE_PEM) <= 0) {501
perror("cannot use certificate file");502
errno = HTTP_ERR_INVALID_CERTIFICATE;503
http_error = true;504
}505
if (SSL_CTX_use_PrivateKey_file(http_ctx, private_key, SSL_FILETYPE_PEM) <= 0) {506
perror("cannot use private key file");507
errno = HTTP_ERR_INVALID_PRIVATE_KEY;508
http_error = true;509
}510
}512
void http_listen(char *hostname, int port) {513
signal(SIGPIPE, SIG_IGN);514
if (http_error) {515
return;516
}517
errno = 0;518
http_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);519
if (http_sockfd <= 0) {520
perror("cannot create socket");521
errno = HTTP_ERR_NO_SOCKET;522
http_error = true;523
return;524
}525
struct hostent *host = gethostbyname(hostname);526
if (!host) {527
perror("unknown host");528
errno = HTTP_ERR_UNKNOWN_HOST;529
http_error = true;530
return;531
}532
struct sockaddr_in addr;533
addr.sin_family = AF_INET;534
memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);535
addr.sin_port = htons(port);536
int enable = 1;537
if (setsockopt(http_sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {538
perror("cannot reuse address");539
errno = HTTP_ERR_NO_ADDR_REUSE;540
http_error = true;541
return;542
}543
if (bind(http_sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {544
perror("cannot bind socket to port");545
errno = HTTP_ERR_ADDR_IN_USE;546
http_error = true;547
return;548
}549
if (listen(http_sockfd, 5) < 0) {550
perror("cannot listen on port");551
errno = HTTP_ERR_NO_LISTEN;552
http_error = true;553
return;554
}555
pthread_create(&http_thread, 0, http_handle_server, (void *) &http_sockfd);556
}558
void http_close() {559
http_quit = true;560
if (!http_error) {561
pthread_join(http_thread, NULL);562
}563
close(http_sockfd);564
if (http_ctx != NULL) {565
SSL_CTX_free(http_ctx);566
}567
}