so://phie

tpee

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

blob: ed46da4e5f814e0eb1e6214bbd4ae18d3b0bb244 (24435 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_err_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_req_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_resp_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_resp_t (*on_req_fn)(http_req_t *);

145};

146

147http_t *http_init(void);

148void http_cleanup(http_t *http);

149void http_on_req(http_t *http, http_resp_t fn(http_req_t *));

150char *http_header_get(http_req_t *req, char *key);

151void http_header_set(http_resp_t *resp, char *key, char *value);

152http_resp_t http_resp_create(http_status_t status);

153void http_resp_body_set(http_resp_t *resp, char *body, long len);

154http_err_t http_bind(http_t *http, char *hostname, int port, http_host_t *hosts, int hosts_len);

155http_err_t http_listen(http_t *http);

156void http_close(http_t *http);

157

158#ifdef LIB_HTTP_IMPL

159

160#include <stdio.h>

161#include <stdlib.h>

162#include <string.h>

163#include <time.h>

164#include <unistd.h>

165#include <pthread.h>

166#include <netdb.h>

167#include <poll.h>

168#include <errno.h>

169#include <signal.h>

170#include <openssl/ssl.h>

171#include <sys/socket.h>

172

173#define HTTP_VERSION "HTTP/1.1"

174#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

175#define HTTP_SERVER_BACKLOG 5

176#define HTTP_SERVER_SLEEP_TIME 100000000

177#define HTTP_SERVER_POLL_TIME 100

178

179http_t *http_init(void) {

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

181 *http = (http_t) {

182 .binds = NULL,

183 .binds_len = 0,

184 .quit = false,

185 .ssl_ctx = NULL,

186 .on_req_fn = NULL,

187 };

188 return http;

189}

190

191void http_cleanup(http_t *http) {

192 free(http);

193}

194

195void http_on_req(http_t *http, http_resp_t fn(http_req_t *)) {

196 http->on_req_fn = fn;

197}

198

199const char *http_status_str(http_status_t status) {

200 switch (status) {

201 case HTTP_STATUS_CONTINUE:

202 return "Continue";

203 case HTTP_STATUS_SWITCHING_PROTOCOLS:

204 return "Switching Protocols";

205 case HTTP_STATUS_PROCESSING:

206 return "Processing";

207 case HTTP_STATUS_EARLY_HINTS:

208 return "Early Hints";

209 case HTTP_STATUS_OK:

210 return "OK";

211 case HTTP_STATUS_CREATED:

212 return "Created";

213 case HTTP_STATUS_ACCEPTED:

214 return "Accepted";

215 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

216 return "Non-Authoritative Information";

217 case HTTP_STATUS_NO_CONTENT:

218 return "No Content";

219 case HTTP_STATUS_RESET_CONTENT:

220 return "Reset Content";

221 case HTTP_STATUS_PARTIAL_CONTENT:

222 return "Partial Content";

223 case HTTP_STATUS_MULTI_STATUS:

224 return "Multi-Status";

225 case HTTP_STATUS_ALREADY_REPORTED:

226 return "Already Reported";

227 case HTTP_STATUS_IM_USED:

228 return "IM Used";

229 case HTTP_STATUS_MULTIPLE_CHOICES:

230 return "Multiple Choices";

231 case HTTP_STATUS_MOVED_PERMANENTLY:

232 return "Moved Permanently";

233 case HTTP_STATUS_FOUND:

234 return "Found";

235 case HTTP_STATUS_SEE_OTHER:

236 return "See Other";

237 case HTTP_STATUS_NOT_MODIFIED:

238 return "Not Modified";

239 case HTTP_STATUS_TEMPORARY_REDIRECT:

240 return "Temporary Redirect";

241 case HTTP_STATUS_PERMANENT_REDIRECT:

242 return "Permanent Redirect";

243 case HTTP_STATUS_BAD_REQUEST:

244 return "Bad Request";

245 case HTTP_STATUS_UNAUTHORIZED:

246 return "Unauthorized";

247 case HTTP_STATUS_PAYMENT_REQUIRED:

248 return "Payment Required";

249 case HTTP_STATUS_FORBIDDEN:

250 return "Forbidden";

251 case HTTP_STATUS_NOT_FOUND:

252 return "Not Found";

253 case HTTP_STATUS_METHOD_NOT_ALLOWED:

254 return "Method Not Allowed";

255 case HTTP_STATUS_NOT_ACCEPTABLE:

256 return "Not Acceptable";

257 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

258 return "Proxy Authentication Required";

259 case HTTP_STATUS_REQUEST_TIMEOUT:

260 return "Request Timeout";

261 case HTTP_STATUS_CONFLICT:

262 return "Conflict";

263 case HTTP_STATUS_GONE:

264 return "Gone";

265 case HTTP_STATUS_LENGTH_REQUIRED:

266 return "Length Required";

267 case HTTP_STATUS_PRECONDITION_FAILED:

268 return "Precondition Failed";

269 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

270 return "Payload Too Large";

271 case HTTP_STATUS_URI_TOO_LONG:

272 return "URI Too Long";

273 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

274 return "Unsupported Media Type";

275 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

276 return "Range Not Satisfiable";

277 case HTTP_STATUS_EXPECTATION_FAILED:

278 return "Expectation Failed";

279 case HTTP_STATUS_I_AM_A_TEAPOT:

280 return "I'm a teapot";

281 case HTTP_STATUS_MISDIRECTED_REQUEST:

282 return "Misdirected Request";

283 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

284 return "Unprocessable Content";

285 case HTTP_STATUS_LOCKED:

286 return "Locked";

287 case HTTP_STATUS_FAILED_DEPENDENCY:

288 return "Failed Dependency";

289 case HTTP_STATUS_TOO_EARLY:

290 return "Too Early";

291 case HTTP_STATUS_UPGRADE_REQUIRED:

292 return "Upgrade Required";

293 case HTTP_STATUS_PRECONDITION_REQUIRED:

294 return "Precondition Required";

295 case HTTP_STATUS_TOO_MANY_REQUESTS:

296 return "Too Many Requests";

297 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

298 return "Request Header Fields Too Large";

299 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

300 return "Unavailable For Legal Reasons";

301 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

302 return "Internal Server Error";

303 case HTTP_STATUS_NOT_IMPLEMENTED:

304 return "Not Implemented";

305 case HTTP_STATUS_BAD_GATEWAY:

306 return "Bad Gateway";

307 case HTTP_STATUS_SERVICE_UNAVAILABLE:

308 return "Service Unavailable";

309 case HTTP_STATUS_GATEWAY_TIMEOUT:

310 return "Gateway Timeout";

311 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

312 return "HTTP Version Not Supported";

313 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

314 return "Variant Also Negotitates";

315 case HTTP_STATUS_INSUFFICIENT_STORAGE:

316 return "Insufficient Storage";

317 case HTTP_STATUS_LOOP_DETECTED:

318 return "Loop Detected";

319 case HTTP_STATUS_NOT_EXTENDED:

320 return "Not Extended";

321 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

322 return "Network Authentication Required";

323 default:

324 return NULL;

325 }

326}

327

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

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

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

331 }

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

333}

334

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

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

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

338 }

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

340}

341

342char *http_header_get(http_req_t *req, char *key) {

343 if (req->headers_len > 0) {

344 for (int i = 0; i < req->headers_len; i++) {

345 http_header_t *header = &req->headers[i];

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

347 return header->value;

348 }

349 }

350 }

351 return NULL;

352}

353

354void http_header_set(http_resp_t *resp, char *key, char *value) {

355 resp->headers = (http_header_t *) realloc(resp->headers, sizeof(http_header_t) * (resp->headers_len + 1));

356 http_header_t *new_header = &resp->headers[resp->headers_len];

357 resp->headers_len++;

358 int key_len = strlen(key);

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

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

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

362 int value_len = strlen(value);

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

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

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

366}

367

368http_resp_t http_resp_create(http_status_t status) {

369 return (http_resp_t) {

370 .version = strdup(HTTP_VERSION),

371 .status = status,

372 .headers = NULL,

373 .headers_len = 0,

374 .body = NULL,

375 .body_len = 0,

376 };

377}

378

379void http_resp_body_set(http_resp_t *resp, char *body, long len) {

380 if (resp != NULL && body != NULL) {

381 resp->body = (char *) malloc(sizeof(char) * len);

382 memcpy(resp->body, body, len);

383 resp->body_len = len;

384 char content_length[50];

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

386 http_header_set(resp, (char *) "Content-Length", content_length);

387 }

388}

389

390void http_req_free(http_req_t *req) {

391 if (req->method != NULL) {

392 free(req->method);

393 }

394 if (req->url != NULL) {

395 free(req->url);

396 }

397 if (req->version != NULL) {

398 free(req->version);

399 }

400 if (req->headers_len > 0) {

401 for (int i = 0; i < req->headers_len; i++) {

402 http_header_t *header = &req->headers[i];

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

404 free(header->key);

405 }

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

407 free(header->value);

408 }

409 }

410 }

411 if (req->body != NULL) {

412 free(req->body);

413 }

414 if (req->ext_data != NULL) {

415 free(req->ext_data);

416 }

417}

418

419void http_resp_free(http_resp_t *resp) {

420 if (resp->version != NULL) {

421 free(resp->version);

422 }

423 if (resp->headers_len > 0) {

424 for (int i = 0; i < resp->headers_len; i++) {

425 http_header_t *header = &resp->headers[i];

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

427 free(header->key);

428 }

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

430 free(header->value);

431 }

432 }

433 if (resp->headers != NULL) {

434 free(resp->headers);

435 }

436 }

437 if (resp->body != NULL) {

438 free(resp->body);

439 }

440}

441

442http_err_t http_read_req(http_conn_t *conn, http_req_t *req) {

443 int len = 0;

444 int ln = 0;

445 int start = 0;

446 char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];

447 *req = (http_req_t) {

448 .conn = conn,

449 .method = NULL,

450 .url = NULL,

451 .version = NULL,

452 .headers = NULL,

453 .headers_len = 0,

454 .body = NULL,

455 .body_len = 0,

456 .ext_data = NULL,

457 };

458 while (true) {

459 char c;

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

461 if (read == 0) {

462 break;

463 }

464 // read timeout

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

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

467 return HTTP_ERR_READ_TIMEOUT;

468 }

469 }

470 // break if too long

471 if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {

472 return HTTP_ERR_REQUEST_TOO_LONG;

473 }

474 buffer[len] = c;

475 len++;

476 // read head

477 if (len >= 2) {

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

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

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

481 if (line_len > 0) {

482 // read line

483 char line[line_len + 1];

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

485 line[line_len] = '\0';

486 // read method, url, and version

487 if (ln == 0) {

488 int arg = 0;

489 int start = 0;

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

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

492 // read method

493 if (arg == 0) {

494 int method_length = i - start;

495 req->method = (char *) malloc(sizeof(char) * (method_length + 1));

496 memcpy(req->method, line + start, method_length);

497 req->method[method_length] = '\0';

498 }

499 // read url

500 if (arg == 1) {

501 int url_length = i - start;

502 req->url = (char *) malloc(sizeof(char) * (url_length + 1));

503 memcpy(req->url, line + start, url_length);

504 req->url[url_length] = '\0';

505 }

506 // read version

507 if (arg == 2) {

508 int version_length = i - start;

509 req->version = (char *) malloc(sizeof(char) * (version_length + 1));

510 memcpy(req->version, line + start, version_length);

511 req->version[version_length] = '\0';

512 }

513 start = i + 1;

514 arg++;

515 }

516 }

517 }

518 // read headers

519 else {

520 int sep = 0;

521 req->headers = (http_header_t *) realloc(req->headers, sizeof(http_header_t) * (req->headers_len + 1));

522 http_header_t *header = &req->headers[req->headers_len];

523 req->headers_len++;

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

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

526 int key_len = i;

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

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

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

530 sep = i + 2;

531 break;

532 }

533 }

534 int value_len = line_len - sep;

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

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

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

538 }

539 }

540 start = len;

541 ln++;

542 }

543 }

544 // read body

545 if (len >= 4) {

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

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

548 char *content_length = http_header_get(req, (char *) "Content-Length");

549 if (content_length != NULL) {

550 req->body_len = strtol(content_length, NULL, 10);

551 if (req->body_len > 0) {

552 req->body = (char *) malloc(sizeof(char) * (req->body_len + 1));

553 http_read(conn, req->body, req->body_len);

554 req->body[req->body_len] = '\0';

555 }

556 }

557 break;

558 }

559 }

560 }

561 return HTTP_ERR_OK;

562}

563

564void http_resp_write(http_conn_t *conn, http_resp_t resp) {

565 http_write(conn, resp.version, strlen(resp.version));

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

567 char status[4];

568 snprintf(status, 4, "%d", resp.status);

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

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

571 const char *status_message = http_status_str(resp.status);

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

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

574 if (resp.headers_len > 0) {

575 for (int i = 0; i < resp.headers_len; i++) {

576 http_header_t *header = &resp.headers[i];

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

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

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

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

581 }

582 }

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

584 if (resp.body != NULL) {

585 http_write(conn, resp.body, resp.body_len);

586 }

587}

588

589void *http_client_handle(void *ptr) {

590 if (!ptr) {

591 pthread_exit(0);

592 }

593 http_conn_t *conn = (http_conn_t *) ptr;

594 struct timeval timeout;

595 timeout.tv_sec = 5;

596 timeout.tv_usec = 0;

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

598 close(conn->sockfd);

599 free(conn);

600 pthread_exit(0);

601 }

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

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

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

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

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

607 close(conn->sockfd);

608 free(conn);

609 pthread_exit(0);

610 }

611 }

612 http_req_t req;

613 http_err_t err = http_read_req(conn, &req);

614 if (err != HTTP_ERR_OK) {

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

616 SSL_shutdown(conn->ssl);

617 SSL_free(conn->ssl);

618 }

619 close(conn->sockfd);

620 free(conn);

621 pthread_exit(0);

622 }

623 if (req.method != NULL && req.url != NULL) {

624 if (conn->http->on_req_fn != NULL) {

625 http_resp_t resp = conn->http->on_req_fn(&req);

626 http_resp_write(conn, resp);

627 http_resp_free(&resp);

628 }

629 }

630 http_req_free(&req);

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

632 SSL_shutdown(conn->ssl);

633 SSL_free(conn->ssl);

634 }

635 close(conn->sockfd);

636 free(conn);

637 pthread_exit(0);

638}

639

640void *http_server_handle(void *ptr) {

641 http_t *http = (http_t *) ptr;

642 struct pollfd fds[http->binds_len];

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

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

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

646 }

647 while (!http->quit) {

648 struct timespec sleep_req, sleep_rem;

649 sleep_req.tv_sec = 0;

650 sleep_req.tv_nsec = HTTP_SERVER_SLEEP_TIME;

651 nanosleep(&sleep_req, &sleep_rem);

652 if (poll(fds, http->binds_len, HTTP_SERVER_POLL_TIME)) {

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

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

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

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

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

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

659 conn->ssl = NULL;

660 conn->http = http;

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

662 free(conn);

663 }

664 else {

665 pthread_t thread;

666 pthread_attr_t thread_attr;

667 pthread_attr_init(&thread_attr);

668 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

669 pthread_create(&thread, &thread_attr, http_client_handle, (void *) conn);

670 pthread_attr_destroy(&thread_attr);

671 }

672 }

673 }

674 }

675 }

676 pthread_exit(0);

677}

678

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

680 (void) al;

681 http_conn_t *conn = (http_conn_t *) arg;

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

683 if (hostname != NULL) {

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

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

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

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

688 conn->curr_host = http_host;

689 SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);

690 return SSL_TLSEXT_ERR_OK;

691 }

692 }

693 }

694 }

695 return SSL_TLSEXT_ERR_NOACK;

696}

697

698http_err_t http_bind(http_t *http, char *hostname, int port, http_host_t *hosts, int hosts_len) {

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

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

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

702 http_bind->port = port;

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

704 return HTTP_ERR_NO_SOCKET;

705 }

706 struct hostent *host = gethostbyname(hostname);

707 if (!host) {

708 return HTTP_ERR_UNKNOWN_HOST;

709 }

710 struct sockaddr_in addr;

711 addr.sin_family = AF_INET;

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

713 addr.sin_port = htons(port);

714 int enable = 1;

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

716 return HTTP_ERR_NO_ADDR_REUSE;

717 }

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

719 return HTTP_ERR_ADDR_IN_USE;

720 }

721 if (listen(http_bind->sockfd, HTTP_SERVER_BACKLOG) < 0) {

722 return HTTP_ERR_NO_LISTEN;

723 }

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

725 http_host_t *http_host = &hosts[i];

726 http_host->ssl_ctx = NULL;

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

728 const SSL_METHOD *method = TLS_server_method();

729 http_host->ssl_ctx = SSL_CTX_new(method);

730 if (!http_host->ssl_ctx) {

731 return HTTP_ERR_NO_SSL_CONTEXT;

732 }

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

734 return HTTP_ERR_INVALID_CERTIFICATE;

735 }

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

737 return HTTP_ERR_INVALID_PRIVATE_KEY;

738 }

739 }

740 }

741 http_bind->hosts = hosts;

742 http_bind->hosts_len = hosts_len;

743 http->binds_len++;

744 return HTTP_ERR_OK;

745}

746

747http_err_t http_listen(http_t *http) {

748 signal(SIGPIPE, SIG_IGN);

749 const SSL_METHOD *method = TLS_server_method();

750 http->ssl_ctx = SSL_CTX_new(method);

751 if (!http->ssl_ctx) {

752 return HTTP_ERR_NO_SSL_CONTEXT;

753 }

754 SSL_CTX_set_tlsext_servername_callback(http->ssl_ctx, http_tls_sni_callback);

755 pthread_create(&http->thread, 0, http_server_handle, (void *) http);

756 return HTTP_ERR_OK;

757}

758

759void http_close(http_t *http) {

760 http->quit = true;

761 pthread_join(http->thread, NULL);

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

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

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

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

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

767 }

768 }

769 }

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

771 free(http->ssl_ctx);

772 }

773}

774

775#endif /* LIB_HTTP_IMPL */

776#endif /* LIB_HTTP_H */