so://phie

tpee

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

blob: 468f1119e16ccd209548f45f6711683033fdbc8d (25462 bytes)[doc][blame][raw]

1#ifndef LIB_HTTP_H

2#define LIB_HTTP_H

3

4#include <stdbool.h>

5#include <openssl/ssl.h>

6#include <sys/socket.h>

7

8typedef 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_ERR_READ_TIMEOUT = 9,

19 HTTP_ERR_REQUEST_TOO_LONG = 10,

20} http_error_t;

21

22typedef enum {

23 HTTP_STATUS_CONTINUE = 100,

24 HTTP_STATUS_SWITCHING_PROTOCOLS = 101,

25 HTTP_STATUS_PROCESSING = 102,

26 HTTP_STATUS_EARLY_HINTS = 103,

27 HTTP_STATUS_OK = 200,

28 HTTP_STATUS_CREATED = 201,

29 HTTP_STATUS_ACCEPTED = 202,

30 HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,

31 HTTP_STATUS_NO_CONTENT = 204,

32 HTTP_STATUS_RESET_CONTENT = 205,

33 HTTP_STATUS_PARTIAL_CONTENT = 206,

34 HTTP_STATUS_MULTI_STATUS = 207,

35 HTTP_STATUS_ALREADY_REPORTED = 208,

36 HTTP_STATUS_IM_USED = 226,

37 HTTP_STATUS_MULTIPLE_CHOICES = 300,

38 HTTP_STATUS_MOVED_PERMANENTLY = 301,

39 HTTP_STATUS_FOUND = 302,

40 HTTP_STATUS_SEE_OTHER = 303,

41 HTTP_STATUS_NOT_MODIFIED = 304,

42 HTTP_STATUS_TEMPORARY_REDIRECT = 307,

43 HTTP_STATUS_PERMANENT_REDIRECT = 308,

44 HTTP_STATUS_BAD_REQUEST = 400,

45 HTTP_STATUS_UNAUTHORIZED = 401,

46 HTTP_STATUS_PAYMENT_REQUIRED = 402,

47 HTTP_STATUS_FORBIDDEN = 403,

48 HTTP_STATUS_NOT_FOUND = 404,

49 HTTP_STATUS_METHOD_NOT_ALLOWED = 405,

50 HTTP_STATUS_NOT_ACCEPTABLE = 406,

51 HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,

52 HTTP_STATUS_REQUEST_TIMEOUT = 408,

53 HTTP_STATUS_CONFLICT = 409,

54 HTTP_STATUS_GONE = 410,

55 HTTP_STATUS_LENGTH_REQUIRED = 411,

56 HTTP_STATUS_PRECONDITION_FAILED = 412,

57 HTTP_STATUS_PAYLOAD_TOO_LARGE = 413,

58 HTTP_STATUS_URI_TOO_LONG = 414,

59 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,

60 HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416,

61 HTTP_STATUS_EXPECTATION_FAILED = 417,

62 HTTP_STATUS_I_AM_A_TEAPOT = 418,

63 HTTP_STATUS_MISDIRECTED_REQUEST = 421,

64 HTTP_STATUS_UNPROCESSABLE_CONTENT = 422,

65 HTTP_STATUS_LOCKED = 423,

66 HTTP_STATUS_FAILED_DEPENDENCY = 424,

67 HTTP_STATUS_TOO_EARLY = 425,

68 HTTP_STATUS_UPGRADE_REQUIRED = 426,

69 HTTP_STATUS_PRECONDITION_REQUIRED = 428,

70 HTTP_STATUS_TOO_MANY_REQUESTS = 429,

71 HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,

72 HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,

73 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,

74 HTTP_STATUS_NOT_IMPLEMENTED = 501,

75 HTTP_STATUS_BAD_GATEWAY = 502,

76 HTTP_STATUS_SERVICE_UNAVAILABLE = 503,

77 HTTP_STATUS_GATEWAY_TIMEOUT = 504,

78 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,

79 HTTP_STATUS_VARIANT_ALSO_NEGOTITATES = 506,

80 HTTP_STATUS_INSUFFICIENT_STORAGE = 507,

81 HTTP_STATUS_LOOP_DETECTED = 508,

82 HTTP_STATUS_NOT_EXTENDED = 510,

83 HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,

84} http_status_t;

85

86typedef struct Http http_t;

87

88typedef struct {

89 char *hostname;

90 char *certificate;

91 char *private_key;

92 SSL_CTX *ssl_ctx;

93} http_host_t;

94

95typedef struct {

96 int sockfd;

97 http_host_t *hosts;

98 int hosts_len;

99 int port;

100} http_bind_t;

101

102typedef struct {

103 int sockfd;

104 struct sockaddr addr;

105 int addr_len;

106 SSL *ssl;

107 http_bind_t *curr_bind;

108 http_host_t *curr_host;

109 http_t *http;

110} http_conn_t;

111

112typedef struct {

113 char *key;

114 char *value;

115} http_header_t;

116

117typedef struct {

118 http_conn_t *conn;

119 char *method;

120 char *url;

121 char *version;

122 http_header_t *headers;

123 int headers_len;

124 char *body;

125 long body_len;

126 void *ext_data;

127} http_request_t;

128

129typedef struct {

130 char *version;

131 http_status_t status;

132 http_header_t *headers;

133 int headers_len;

134 char *body;

135 long body_len;

136} http_response_t;

137

138struct Http {

139 http_bind_t *binds;

140 int binds_len;

141 pthread_t thread;

142 bool quit;

143 SSL_CTX *ssl_ctx;

144 http_response_t (*on_request_fn)(http_request_t *);

145};

146

147http_t *http_init(void);

148void http_cleanup(http_t *http);

149void http_on_request(http_t *http, http_response_t fn(http_request_t *));

150char *http_header_get(http_request_t *request, char *key);

151void http_header_set(http_response_t *response, char *key, char *value);

152http_response_t http_response_create(http_status_t status);

153void http_response_body(http_response_t *response, char *body, long len);

154void http_response_file(http_response_t *response, char *filename);

155http_error_t http_bind(http_t *http, char *hostname, int port, http_host_t *hosts, int hosts_len);

156http_error_t http_listen(http_t *http);

157void http_close(http_t *http);

158

159#ifdef LIB_HTTP_IMPL

160

161#include <stdio.h>

162#include <stdlib.h>

163#include <string.h>

164#include <time.h>

165#include <unistd.h>

166#include <pthread.h>

167#include <netdb.h>

168#include <poll.h>

169#include <errno.h>

170#include <signal.h>

171#include <openssl/ssl.h>

172#include <sys/socket.h>

173

174#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

175

176http_t *http_init(void) {

177 http_t *http = (http_t *) malloc(sizeof(http_t));

178 *http = (http_t) {

179 .binds = NULL,

180 .binds_len = 0,

181 .quit = false,

182 .ssl_ctx = NULL,

183 .on_request_fn = NULL,

184 };

185 return http;

186}

187

188void http_cleanup(http_t *http) {

189 free(http);

190}

191

192void http_on_request(http_t *http, http_response_t fn(http_request_t *)) {

193 http->on_request_fn = fn;

194}

195

196char *http_read_file(char *filename) {

197 FILE *fp = fopen(filename, "r");

198 fseek(fp, 0, SEEK_END);

199 long len = ftell(fp);

200 fseek(fp, 0, SEEK_SET);

201 char *content = (char *) malloc(sizeof(char) * (len + 1));

202 fread(content, len, sizeof(char), fp);

203 content[len] = '\0';

204 fclose(fp);

205 return content;

206}

207

208const char *http_status_str(http_status_t status) {

209 switch (status) {

210 case HTTP_STATUS_CONTINUE:

211 return "Continue";

212 case HTTP_STATUS_SWITCHING_PROTOCOLS:

213 return "Switching Protocols";

214 case HTTP_STATUS_PROCESSING:

215 return "Processing";

216 case HTTP_STATUS_EARLY_HINTS:

217 return "Early Hints";

218 case HTTP_STATUS_OK:

219 return "OK";

220 case HTTP_STATUS_CREATED:

221 return "Created";

222 case HTTP_STATUS_ACCEPTED:

223 return "Accepted";

224 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

225 return "Non-Authoritative Information";

226 case HTTP_STATUS_NO_CONTENT:

227 return "No Content";

228 case HTTP_STATUS_RESET_CONTENT:

229 return "Reset Content";

230 case HTTP_STATUS_PARTIAL_CONTENT:

231 return "Partial Content";

232 case HTTP_STATUS_MULTI_STATUS:

233 return "Multi-Status";

234 case HTTP_STATUS_ALREADY_REPORTED:

235 return "Already Reported";

236 case HTTP_STATUS_IM_USED:

237 return "IM Used";

238 case HTTP_STATUS_MULTIPLE_CHOICES:

239 return "Multiple Choices";

240 case HTTP_STATUS_MOVED_PERMANENTLY:

241 return "Moved Permanently";

242 case HTTP_STATUS_FOUND:

243 return "Found";

244 case HTTP_STATUS_SEE_OTHER:

245 return "See Other";

246 case HTTP_STATUS_NOT_MODIFIED:

247 return "Not Modified";

248 case HTTP_STATUS_TEMPORARY_REDIRECT:

249 return "Temporary Redirect";

250 case HTTP_STATUS_PERMANENT_REDIRECT:

251 return "Permanent Redirect";

252 case HTTP_STATUS_BAD_REQUEST:

253 return "Bad Request";

254 case HTTP_STATUS_UNAUTHORIZED:

255 return "Unauthorized";

256 case HTTP_STATUS_PAYMENT_REQUIRED:

257 return "Payment Required";

258 case HTTP_STATUS_FORBIDDEN:

259 return "Forbidden";

260 case HTTP_STATUS_NOT_FOUND:

261 return "Not Found";

262 case HTTP_STATUS_METHOD_NOT_ALLOWED:

263 return "Method Not Allowed";

264 case HTTP_STATUS_NOT_ACCEPTABLE:

265 return "Not Acceptable";

266 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

267 return "Proxy Authentication Required";

268 case HTTP_STATUS_REQUEST_TIMEOUT:

269 return "Request Timeout";

270 case HTTP_STATUS_CONFLICT:

271 return "Conflict";

272 case HTTP_STATUS_GONE:

273 return "Gone";

274 case HTTP_STATUS_LENGTH_REQUIRED:

275 return "Length Required";

276 case HTTP_STATUS_PRECONDITION_FAILED:

277 return "Precondition Failed";

278 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

279 return "Payload Too Large";

280 case HTTP_STATUS_URI_TOO_LONG:

281 return "URI Too Long";

282 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

283 return "Unsupported Media Type";

284 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

285 return "Range Not Satisfiable";

286 case HTTP_STATUS_EXPECTATION_FAILED:

287 return "Expectation Failed";

288 case HTTP_STATUS_I_AM_A_TEAPOT:

289 return "I'm a teapot";

290 case HTTP_STATUS_MISDIRECTED_REQUEST:

291 return "Misdirected Request";

292 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

293 return "Unprocessable Content";

294 case HTTP_STATUS_LOCKED:

295 return "Locked";

296 case HTTP_STATUS_FAILED_DEPENDENCY:

297 return "Failed Dependency";

298 case HTTP_STATUS_TOO_EARLY:

299 return "Too Early";

300 case HTTP_STATUS_UPGRADE_REQUIRED:

301 return "Upgrade Required";

302 case HTTP_STATUS_PRECONDITION_REQUIRED:

303 return "Precondition Required";

304 case HTTP_STATUS_TOO_MANY_REQUESTS:

305 return "Too Many Requests";

306 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

307 return "Request Header Fields Too Large";

308 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

309 return "Unavailable For Legal Reasons";

310 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

311 return "Internal Server Error";

312 case HTTP_STATUS_NOT_IMPLEMENTED:

313 return "Not Implemented";

314 case HTTP_STATUS_BAD_GATEWAY:

315 return "Bad Gateway";

316 case HTTP_STATUS_SERVICE_UNAVAILABLE:

317 return "Service Unavailable";

318 case HTTP_STATUS_GATEWAY_TIMEOUT:

319 return "Gateway Timeout";

320 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

321 return "HTTP Version Not Supported";

322 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

323 return "Variant Also Negotitates";

324 case HTTP_STATUS_INSUFFICIENT_STORAGE:

325 return "Insufficient Storage";

326 case HTTP_STATUS_LOOP_DETECTED:

327 return "Loop Detected";

328 case HTTP_STATUS_NOT_EXTENDED:

329 return "Not Extended";

330 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

331 return "Network Authentication Required";

332 default:

333 return NULL;

334 }

335}

336

337ssize_t http_read(http_conn_t *conn, char *buffer, size_t len) {

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

339 return SSL_read(conn->ssl, buffer, len);

340 }

341 return read(conn->sockfd, buffer, len);

342}

343

344ssize_t http_write(http_conn_t *conn, char *buffer, size_t len) {

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

346 return SSL_write(conn->ssl, buffer, len);

347 }

348 return write(conn->sockfd, buffer, len);

349}

350

351char *http_header_get(http_request_t *request, char *key) {

352 if (request->headers_len > 0) {

353 for (int i = 0; i < request->headers_len; i++) {

354 http_header_t *header = &request->headers[i];

355 if (strcmp(header->key, key) == 0) {

356 return header->value;

357 }

358 }

359 }

360 return NULL;

361}

362

363void http_header_set(http_response_t *response, char *key, char *value) {

364 response->headers = (http_header_t *) realloc(response->headers, sizeof(http_header_t) * (response->headers_len + 1));

365 http_header_t *new_header = &response->headers[response->headers_len];

366 response->headers_len++;

367 int key_len = strlen(key);

368 new_header->key = (char *) malloc(sizeof(char) * (key_len + 1));

369 memcpy(new_header->key, key, key_len);

370 new_header->key[key_len] = '\0';

371 int value_len = strlen(value);

372 new_header->value = (char *) malloc(sizeof(char) * (value_len + 1));

373 memcpy(new_header->value, value, value_len);

374 new_header->value[value_len] = '\0';

375}

376

377http_response_t http_response_create(http_status_t status) {

378 const char *version = "HTTP/1.1";

379 int version_len = strlen(version);

380 http_response_t response = { NULL, status, NULL, 0, NULL, 0 };

381 response.version = (char *) malloc(sizeof(char) * (version_len + 1));

382 memcpy(response.version, version, version_len);

383 response.version[version_len] = '\0';

384 return response;

385}

386

387void http_response_body(http_response_t *response, char *body, long len) {

388 if (response != NULL && body != NULL) {

389 response->body = (char *) malloc(sizeof(char) * len);

390 memcpy(response->body, body, len);

391 response->body_len = len;

392 char content_length[50];

393 snprintf(content_length, 50, "%ld", len);

394 http_header_set(response, (char *) "Content-Length", content_length);

395 }

396}

397

398void http_response_file(http_response_t *response, char *filename) {

399 char *content = http_read_file(filename);

400 if (content != NULL) {

401 http_response_body(response, content, strlen(content));

402 free(content);

403 }

404}

405

406void http_request_free(http_request_t *request) {

407 if (request->method != NULL) {

408 free(request->method);

409 }

410 if (request->url != NULL) {

411 free(request->url);

412 }

413 if (request->version != NULL) {

414 free(request->version);

415 }

416 if (request->headers_len > 0) {

417 for (int i = 0; i < request->headers_len; i++) {

418 http_header_t *header = &request->headers[i];

419 if (header->key != NULL) {

420 free(header->key);

421 }

422 if (header->value != NULL) {

423 free(header->value);

424 }

425 }

426 }

427 if (request->body != NULL) {

428 free(request->body);

429 }

430 if (request->ext_data != NULL) {

431 free(request->ext_data);

432 }

433}

434

435void http_response_free(http_response_t *response) {

436 if (response->version != NULL) {

437 free(response->version);

438 }

439 if (response->headers_len > 0) {

440 for (int i = 0; i < response->headers_len; i++) {

441 http_header_t *header = &response->headers[i];

442 if (header->key != NULL) {

443 free(header->key);

444 }

445 if (header->value != NULL) {

446 free(header->value);

447 }

448 }

449 }

450 if (response->body != NULL) {

451 free(response->body);

452 }

453}

454

455http_error_t http_read_request(http_conn_t *conn, http_request_t *request) {

456 int len = 0;

457 int ln = 0;

458 int start = 0;

459 char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];

460 *request = (http_request_t) {

461 .conn = conn,

462 .method = NULL,

463 .url = NULL,

464 .version = NULL,

465 .headers = NULL,

466 .headers_len = 0,

467 .body = NULL,

468 .body_len = 0,

469 .ext_data = NULL,

470 };

471 while (true) {

472 char c;

473 int read = http_read(conn, &c, 1);

474 if (read == 0) {

475 break;

476 }

477 // read timeout

478 if (read == -1 || read == SSL_ERROR_SYSCALL) {

479 if (errno == EWOULDBLOCK || errno == EAGAIN) {

480 return HTTP_ERR_READ_TIMEOUT;

481 }

482 }

483 // break if too long

484 if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {

485 return HTTP_ERR_REQUEST_TOO_LONG;

486 }

487 buffer[len] = c;

488 len++;

489 // read head

490 if (len >= 2) {

491 char *slice = buffer + (len - 2);

492 if (strncmp(slice, "\r\n", 2) == 0) {

493 int line_len = (len - 2) - start;

494 if (line_len > 0) {

495 // read line

496 char line[line_len + 1];

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

498 line[line_len] = '\0';

499 // read method, url, and version

500 if (ln == 0) {

501 int arg = 0;

502 int start = 0;

503 for (int i = 0; i <= line_len; i++) {

504 if (line[i] == ' ' || i == line_len) {

505 // read method

506 if (arg == 0) {

507 int method_length = i - start;

508 request->method = (char *) malloc(sizeof(char) * (method_length + 1));

509 memcpy(request->method, line + start, method_length);

510 request->method[method_length] = '\0';

511 }

512 // read url

513 if (arg == 1) {

514 int url_length = i - start;

515 request->url = (char *) malloc(sizeof(char) * (url_length + 1));

516 memcpy(request->url, line + start, url_length);

517 request->url[url_length] = '\0';

518 }

519 // read version

520 if (arg == 2) {

521 int version_length = i - start;

522 request->version = (char *) malloc(sizeof(char) * (version_length + 1));

523 memcpy(request->version, line + start, version_length);

524 request->version[version_length] = '\0';

525 }

526 start = i + 1;

527 arg++;

528 }

529 }

530 }

531 // read headers

532 else {

533 int sep = 0;

534 request->headers = (http_header_t *) realloc(request->headers, sizeof(http_header_t) * (request->headers_len + 1));

535 http_header_t *header = &request->headers[request->headers_len];

536 request->headers_len++;

537 for (int i = 0; i < line_len; i++) {

538 if (line[i] == ':') {

539 int key_len = i;

540 header->key = (char *) malloc(sizeof(char) * (key_len + 1));

541 memcpy(header->key, line, key_len);

542 header->key[key_len] = '\0';

543 sep = i + 2;

544 break;

545 }

546 }

547 int value_len = line_len - sep;

548 header->value = (char *) malloc(sizeof(char) * (value_len + 1));

549 memcpy(header->value, line + sep, value_len);

550 header->value[value_len] = '\0';

551 }

552 }

553 start = len;

554 ln++;

555 }

556 }

557 // read body

558 if (len >= 4) {

559 char *slice = buffer + (len - 4);

560 if (strncmp(slice, "\r\n\r\n", 4) == 0) {

561 char *content_length = http_header_get(request, (char *) "Content-Length");

562 if (content_length != NULL) {

563 request->body_len = strtol(content_length, NULL, 10);

564 if (request->body_len > 0) {

565 request->body = (char *) malloc(sizeof(char) * (request->body_len + 1));

566 http_read(conn, request->body, request->body_len);

567 request->body[request->body_len] = '\0';

568 }

569 }

570 break;

571 }

572 }

573 }

574 return HTTP_ERR_OK;

575}

576

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

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

579 http_write(conn, (char *) " ", 1);

580 char status[4];

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

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

583 http_write(conn, (char *) " ", 1);

584 const char *status_message = http_status_str(response.status);

585 http_write(conn, (char *) status_message, strlen(status_message));

586 http_write(conn, (char *) "\r\n", 2);

587 if (response.headers_len > 0) {

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

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

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

591 http_write(conn, (char *) ": ", 2);

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

593 http_write(conn, (char *) "\r\n", 2);

594 }

595 }

596 http_write(conn, (char *) "\r\n", 2);

597 if (response.body != NULL) {

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

599 }

600}

601

602void *http_handle_client(void *ptr) {

603 if (!ptr) {

604 pthread_exit(0);

605 }

606 http_conn_t *conn = (http_conn_t *) ptr;

607 struct timeval timeout;

608 timeout.tv_sec = 5;

609 timeout.tv_usec = 0;

610 if (setsockopt(conn->sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout)) < 0) {

611 close(conn->sockfd);

612 free(conn);

613 pthread_exit(0);

614 }

615 if (conn->curr_bind->hosts_len > 0) {

616 SSL_CTX_set_tlsext_servername_arg(conn->http->ssl_ctx, (void *) conn);

617 conn->ssl = SSL_new(conn->http->ssl_ctx);

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

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

620 close(conn->sockfd);

621 free(conn);

622 pthread_exit(0);

623 }

624 }

625 http_request_t request;

626 http_error_t err = http_read_request(conn, &request);

627 if (err != HTTP_ERR_OK) {

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

629 SSL_shutdown(conn->ssl);

630 SSL_free(conn->ssl);

631 }

632 close(conn->sockfd);

633 free(conn);

634 pthread_exit(0);

635 }

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

637 if (conn->http->on_request_fn != NULL) {

638 http_response_t response = conn->http->on_request_fn(&request);

639 http_write_response(conn, response);

640 http_response_free(&response);

641 }

642 }

643 http_request_free(&request);

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

645 SSL_shutdown(conn->ssl);

646 SSL_free(conn->ssl);

647 }

648 close(conn->sockfd);

649 free(conn);

650 pthread_exit(0);

651}

652

653void *http_handle_server(void *ptr) {

654 http_t *http = (http_t *) ptr;

655 struct pollfd fds[http->binds_len];

656 for (int i = 0; i < http->binds_len; i++) {

657 fds[i].fd = http->binds[i].sockfd;

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

659 }

660 while (!http->quit) {

661 struct timespec sleep_req, sleep_rem;

662 sleep_req.tv_sec = 0;

663 sleep_req.tv_nsec = 100000000;

664 nanosleep(&sleep_req, &sleep_rem);

665 if (poll(fds, http->binds_len, 100)) {

666 for (int i = 0; i < http->binds_len; i++) {

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

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

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

670 conn->sockfd = accept(http->binds[i].sockfd, &conn->addr, (socklen_t *) &conn->addr_len);

671 conn->curr_bind = &http->binds[i];

672 conn->ssl = NULL;

673 conn->http = http;

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

675 free(conn);

676 }

677 else {

678 pthread_t thread;

679 pthread_attr_t thread_attr;

680 pthread_attr_init(&thread_attr);

681 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

683 pthread_attr_destroy(&thread_attr);

684 }

685 }

686 }

687 }

688 }

689 pthread_exit(0);

690}

691

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

693 (void)(al);

694 http_conn_t *conn = (http_conn_t *) arg;

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

696 if (hostname != NULL) {

697 for (int i = 0; i < conn->http->binds_len; i++) {

698 for (int j = 0; j < conn->http->binds[i].hosts_len; j++) {

699 http_host_t *http_host = &conn->http->binds[i].hosts[j];

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

701 conn->curr_host = http_host;

702 SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);

703 return SSL_TLSEXT_ERR_OK;

704 }

705 }

706 }

707 }

708 return SSL_TLSEXT_ERR_NOACK;

709}

710

711http_error_t http_bind(http_t *http, char *hostname, int port, http_host_t *hosts, int hosts_len) {

712 http->binds = (http_bind_t *) realloc(http->binds, sizeof(http_bind_t) * (http->binds_len + 1));

713 http_bind_t *http_bind = &http->binds[http->binds_len];

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

715 http_bind->port = port;

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

717 return HTTP_ERR_NO_SOCKET;

718 }

719 struct hostent *host = gethostbyname(hostname);

720 if (!host) {

721 return HTTP_ERR_UNKNOWN_HOST;

722 }

723 struct sockaddr_in addr;

724 addr.sin_family = AF_INET;

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

726 addr.sin_port = htons(port);

727 int enable = 1;

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

729 return HTTP_ERR_NO_ADDR_REUSE;

730 }

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

732 return HTTP_ERR_ADDR_IN_USE;

733 }

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

735 return HTTP_ERR_NO_LISTEN;

736 }

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

738 http_host_t *http_host = &hosts[i];

739 http_host->ssl_ctx = NULL;

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

741 const SSL_METHOD *method = TLS_server_method();

742 http_host->ssl_ctx = SSL_CTX_new(method);

743 if (!http_host->ssl_ctx) {

744 return HTTP_ERR_NO_SSL_CONTEXT;

745 }

746 if (SSL_CTX_use_certificate_chain_file(http_host->ssl_ctx, http_host->certificate) <= 0) {

747 return HTTP_ERR_INVALID_CERTIFICATE;

748 }

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

750 return HTTP_ERR_INVALID_PRIVATE_KEY;

751 }

752 }

753 }

754 http_bind->hosts = hosts;

755 http_bind->hosts_len = hosts_len;

756 http->binds_len++;

757 return HTTP_ERR_OK;

758}

759

760http_error_t http_listen(http_t *http) {

761 signal(SIGPIPE, SIG_IGN);

762 const SSL_METHOD *method = TLS_server_method();

763 http->ssl_ctx = SSL_CTX_new(method);

764 if (!http->ssl_ctx) {

765 return HTTP_ERR_NO_SSL_CONTEXT;

766 }

767 SSL_CTX_set_tlsext_servername_callback(http->ssl_ctx, http_tls_sni_callback);

768 pthread_create(&http->thread, 0, http_handle_server, (void *) http);

769 return HTTP_ERR_OK;

770}

771

772void http_close(http_t *http) {

773 http->quit = true;

774 pthread_join(http->thread, NULL);

775 for (int i = 0; i < http->binds_len; i++) {

776 close(http->binds[i].sockfd);

777 for (int j = 0; j < http->binds[i].hosts_len; j++) {

778 if (http->binds[i].hosts[j].ssl_ctx != NULL) {

779 SSL_CTX_free(http->binds[i].hosts[j].ssl_ctx);

780 }

781 }

782 }

783 if (http->ssl_ctx != NULL) {

784 free(http->ssl_ctx);

785 }

786}

787

788#endif /* LIB_HTTP_IMPL */

789#endif /* LIB_HTTP_H */