so://phie

tpee

A low-key HTTP micro-framework for people who hate web bloat
git clone git://soophie.de/tpee

blob: e889a719fb23ab1dc6788c718ca15aec8c178a63 (19672 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>

13

14#include "libhttp.h"

15

16#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

17

18http_bind_t *http_binds = NULL;

19int http_binds_len = 0;

20pthread_t http_thread;

21bool http_quit = false;

22bool http_error = false;

23SSL_CTX *http_ssl_ctx = NULL;

24

25http_response_t (*on_request_fn)(http_request_t *) = NULL;

26

27void http_on_request(http_response_t fn(http_request_t *)) {

28 on_request_fn = fn;

29}

30

31char *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}

42

43char *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}

171

172ssize_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}

178

179ssize_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}

185

186char *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}

197

198void 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}

223

224http_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}

233

234void 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}

244

245void 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}

252

253void 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}

281

282void 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}

301

302http_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 long

325 if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {

326 perror("request is too long");

327 break;

328 }

329 buffer[len] = c;

330 len++;

331 // read head

332 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 line

338 char line[line_len + 1];

339 memcpy(line, buffer + start, line_len);

340 line[line_len] = '\0';

341 // read method, url, and version

342 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 method

348 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 url

355 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 version

362 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 headers

374 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 body

400 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 request.body = malloc(sizeof(char) * (request.body_len + 1));

407 http_read(conn, request.body, request.body_len);

408 request.body[request.body_len] = '\0';

409 }

410 break;

411 }

412 }

413 }

414 return request;

415}

416

417void http_write_response(http_conn_t *conn, http_response_t response) {

418 http_write(conn, response.version, strlen(response.version));

419 http_write(conn, " ", 1);

420 char status[4];

421 snprintf(status, 4, "%d", response.status);

422 http_write(conn, status, strlen(status));

423 http_write(conn, " ", 1);

424 char *status_message = http_status_str(response.status);

425 http_write(conn, status_message, strlen(status_message));

426 http_write(conn, "\r\n", 2);

427 if (response.headers_len > 0) {

428 for (int i = 0; i < response.headers_len; i++) {

429 http_header_t *header = &response.headers[i];

430 http_write(conn, header->key, strlen(header->key));

431 http_write(conn, ": ", 2);

432 http_write(conn, header->value, strlen(header->value));

433 http_write(conn, "\r\n", 2);

434 }

435 }

436 http_write(conn, "\r\n", 2);

437 if (response.body != NULL) {

438 http_write(conn, response.body, response.body_len);

439 }

440}

441

442void *http_handle_client(void *ptr) {

443 if (!ptr) {

444 pthread_exit(0);

445 }

446 http_conn_t *conn = (http_conn_t *) ptr;

447 if (conn->bind->hosts_len > 0) {

448 SSL_CTX_set_tlsext_servername_arg(http_ssl_ctx, (void *) conn);

449 conn->ssl = SSL_new(http_ssl_ctx);

450 SSL_set_fd(conn->ssl, conn->sockfd);

451 if (SSL_accept(conn->ssl) <= 0) {

452 pthread_exit(0);

453 }

454 }

455 http_request_t request = http_read_request(conn);

456 if (request.method != NULL && request.url != NULL) {

457 if (on_request_fn != NULL) {

458 http_response_t response = on_request_fn(&request);

459 http_write_response(conn, response);

460 http_response_free(&response);

461 }

462 }

463 http_request_free(&request);

464 if (conn->ssl != NULL) {

465 SSL_shutdown(conn->ssl);

466 SSL_free(conn->ssl);

467 }

468 close(conn->sockfd);

469 free(conn);

470 pthread_exit(0);

471}

472

473void *http_handle_server(void *ptr) {

474 (void)(ptr);

475 struct pollfd fds[http_binds_len];

476 for (int i = 0; i < http_binds_len; i++) {

477 fds[i].fd = http_binds[i].sockfd;

478 fds[i].events = POLLIN | POLLPRI;

479 }

480 while (!http_quit) {

481 struct timespec sleep_req, sleep_rem;

482 sleep_req.tv_sec = 0;

483 sleep_req.tv_nsec = 100000000;

484 nanosleep(&sleep_req, &sleep_rem);

485 if (poll(fds, http_binds_len, 100)) {

486 for (int i = 0; i < http_binds_len; i++) {

487 if (fds[i].revents & POLLIN) {

488 http_conn_t *conn = malloc(sizeof(http_conn_t));

489 conn->addr_len = sizeof(conn->addr);

490 conn->sockfd = accept(http_binds[i].sockfd, &conn->addr, (socklen_t *) &conn->addr_len);

491 conn->bind = &http_binds[i];

492 conn->ssl = NULL;

493 if (conn->sockfd <= 0) {

494 free(conn);

495 }

496 else {

497 pthread_t thread;

498 pthread_attr_t thread_attr;

499 pthread_attr_init(&thread_attr);

500 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

501 pthread_create(&thread, &thread_attr, http_handle_client, (void *) conn);

502 pthread_attr_destroy(&thread_attr);

503 }

504 }

505 }

506 }

507 }

508 pthread_exit(0);

509}

510

511int http_tls_sni_callback(SSL *ssl, int *al, void *arg) {

512 (void)(al);

513 http_conn_t *conn = (http_conn_t *) arg;

514 const char *hostname = SSL_get_servername(ssl, 0);

515 if (hostname != NULL) {

516 for (int i = 0; i < http_binds_len; i++) {

517 for (int j = 0; j < http_binds[i].hosts_len; j++) {

518 http_host_t *http_host = &http_binds[i].hosts[j];

519 if (strcmp(http_host->hostname, hostname) == 0) {

520 conn->curr_host = http_host;

521 SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);

522 return SSL_TLSEXT_ERR_OK;

523 }

524 }

525 }

526 }

527 return SSL_TLSEXT_ERR_NOACK;

528}

529

530void http_bind(char *hostname, int port, http_host_t *hosts, int hosts_len) {

531 http_binds = realloc(http_binds, sizeof(http_bind_t) * (http_binds_len + 1));

532 http_bind_t *http_bind = &http_binds[http_binds_len];

533 http_bind->sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

534 if (http_bind->sockfd <= 0) {

535 perror("cannot create socket");

536 errno = HTTP_ERR_NO_SOCKET;

537 http_error = true;

538 return;

539 }

540 struct hostent *host = gethostbyname(hostname);

541 if (!host) {

542 perror("unknown host");

543 errno = HTTP_ERR_UNKNOWN_HOST;

544 http_error = true;

545 return;

546 }

547 struct sockaddr_in addr;

548 addr.sin_family = AF_INET;

549 memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);

550 addr.sin_port = htons(port);

551 int enable = 1;

552 if (setsockopt(http_bind->sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {

553 perror("cannot reuse address");

554 errno = HTTP_ERR_NO_ADDR_REUSE;

555 http_error = true;

556 return;

557 }

558 if (bind(http_bind->sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {

559 perror("cannot bind socket to port");

560 errno = HTTP_ERR_ADDR_IN_USE;

561 http_error = true;

562 return;

563 }

564 if (listen(http_bind->sockfd, 5) < 0) {

565 perror("cannot listen on port");

566 errno = HTTP_ERR_NO_LISTEN;

567 http_error = true;

568 return;

569 }

570 for (int i = 0; i < hosts_len; i++) {

571 http_host_t *http_host = &hosts[i];

572 if (http_host->certificate != NULL && http_host->private_key != NULL) {

573 const SSL_METHOD *method = TLS_server_method();

574 http_host->ssl_ctx = SSL_CTX_new(method);

575 if (!http_host->ssl_ctx) {

576 perror("cannot create SSL context");

577 errno = HTTP_ERR_NO_SSL_CONTEXT;

578 http_error = true;

579 return;

580 }

581 if (SSL_CTX_use_certificate_file(http_host->ssl_ctx, http_host->certificate, SSL_FILETYPE_PEM) <= 0) {

582 perror("cannot use certificate file");

583 errno = HTTP_ERR_INVALID_CERTIFICATE;

584 http_error = true;

585 }

586 if (SSL_CTX_use_PrivateKey_file(http_host->ssl_ctx, http_host->private_key, SSL_FILETYPE_PEM) <= 0) {

587 perror("cannot use private key file");

588 errno = HTTP_ERR_INVALID_PRIVATE_KEY;

589 http_error = true;

590 }

591 }

592 else {

593 http_host->ssl_ctx = NULL;

594 }

595 }

596 http_bind->hosts = hosts;

597 http_bind->hosts_len = hosts_len;

598 http_binds_len++;

599}

600

601void http_listen(void) {

602 signal(SIGPIPE, SIG_IGN);

603 if (http_error) {

604 return;

605 }

606 errno = 0;

607 const SSL_METHOD *method = TLS_server_method();

608 http_ssl_ctx = SSL_CTX_new(method);

609 if (!http_ssl_ctx) {

610 perror("cannot create SSL context");

611 errno = HTTP_ERR_NO_SSL_CONTEXT;

612 http_error = true;

613 return;

614 }

615 SSL_CTX_set_tlsext_servername_callback(http_ssl_ctx, http_tls_sni_callback);

616 pthread_create(&http_thread, 0, http_handle_server, NULL);

617}

618

619void http_close(void) {

620 http_quit = true;

621 if (!http_error) {

622 pthread_join(http_thread, NULL);

623 }

624 for (int i = 0; i < http_binds_len; i++) {

625 close(http_binds[i].sockfd);

626 for (int j = 0; j < http_binds[i].hosts_len; j++) {

627 if (http_binds[i].hosts[j].ssl_ctx != NULL) {

628 SSL_CTX_free(http_binds[i].hosts[j].ssl_ctx);

629 }

630 }

631 }

632 if (http_ssl_ctx != NULL) {

633 free(http_ssl_ctx);

634 }

635}