so://phie

tpee

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

blob: 29a0caf5a0af661b508e415042d1323574ea74f2 (24810 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_error_t;

19

20typedef enum {

21 HTTP_STATUS_CONTINUE = 100,

22 HTTP_STATUS_SWITCHING_PROTOCOLS = 101,

23 HTTP_STATUS_PROCESSING = 102,

24 HTTP_STATUS_EARLY_HINTS = 103,

25 HTTP_STATUS_OK = 200,

26 HTTP_STATUS_CREATED = 201,

27 HTTP_STATUS_ACCEPTED = 202,

28 HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,

29 HTTP_STATUS_NO_CONTENT = 204,

30 HTTP_STATUS_RESET_CONTENT = 205,

31 HTTP_STATUS_PARTIAL_CONTENT = 206,

32 HTTP_STATUS_MULTI_STATUS = 207,

33 HTTP_STATUS_ALREADY_REPORTED = 208,

34 HTTP_STATUS_IM_USED = 226,

35 HTTP_STATUS_MULTIPLE_CHOICES = 300,

36 HTTP_STATUS_MOVED_PERMANENTLY = 301,

37 HTTP_STATUS_FOUND = 302,

38 HTTP_STATUS_SEE_OTHER = 303,

39 HTTP_STATUS_NOT_MODIFIED = 304,

40 HTTP_STATUS_TEMPORARY_REDIRECT = 307,

41 HTTP_STATUS_PERMANENT_REDIRECT = 308,

42 HTTP_STATUS_BAD_REQUEST = 400,

43 HTTP_STATUS_UNAUTHORIZED = 401,

44 HTTP_STATUS_PAYMENT_REQUIRED = 402,

45 HTTP_STATUS_FORBIDDEN = 403,

46 HTTP_STATUS_NOT_FOUND = 404,

47 HTTP_STATUS_METHOD_NOT_ALLOWED = 405,

48 HTTP_STATUS_NOT_ACCEPTABLE = 406,

49 HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,

50 HTTP_STATUS_REQUEST_TIMEOUT = 408,

51 HTTP_STATUS_CONFLICT = 409,

52 HTTP_STATUS_GONE = 410,

53 HTTP_STATUS_LENGTH_REQUIRED = 411,

54 HTTP_STATUS_PRECONDITION_FAILED = 412,

55 HTTP_STATUS_PAYLOAD_TOO_LARGE = 413,

56 HTTP_STATUS_URI_TOO_LONG = 414,

57 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,

58 HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416,

59 HTTP_STATUS_EXPECTATION_FAILED = 417,

60 HTTP_STATUS_I_AM_A_TEAPOT = 418,

61 HTTP_STATUS_MISDIRECTED_REQUEST = 421,

62 HTTP_STATUS_UNPROCESSABLE_CONTENT = 422,

63 HTTP_STATUS_LOCKED = 423,

64 HTTP_STATUS_FAILED_DEPENDENCY = 424,

65 HTTP_STATUS_TOO_EARLY = 425,

66 HTTP_STATUS_UPGRADE_REQUIRED = 426,

67 HTTP_STATUS_PRECONDITION_REQUIRED = 428,

68 HTTP_STATUS_TOO_MANY_REQUESTS = 429,

69 HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,

70 HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,

71 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,

72 HTTP_STATUS_NOT_IMPLEMENTED = 501,

73 HTTP_STATUS_BAD_GATEWAY = 502,

74 HTTP_STATUS_SERVICE_UNAVAILABLE = 503,

75 HTTP_STATUS_GATEWAY_TIMEOUT = 504,

76 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,

77 HTTP_STATUS_VARIANT_ALSO_NEGOTITATES = 506,

78 HTTP_STATUS_INSUFFICIENT_STORAGE = 507,

79 HTTP_STATUS_LOOP_DETECTED = 508,

80 HTTP_STATUS_NOT_EXTENDED = 510,

81 HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,

82} http_status_t;

83

84typedef struct Http http_t;

85

86typedef struct {

87 char *hostname;

88 char *certificate;

89 char *private_key;

90 SSL_CTX *ssl_ctx;

91} http_host_t;

92

93typedef struct {

94 int sockfd;

95 http_host_t *hosts;

96 int hosts_len;

97 int port;

98} http_bind_t;

99

100typedef struct {

101 int sockfd;

102 struct sockaddr addr;

103 int addr_len;

104 SSL *ssl;

105 http_bind_t *curr_bind;

106 http_host_t *curr_host;

107 http_t *http;

108} http_conn_t;

109

110typedef struct {

111 char *key;

112 char *value;

113} http_header_t;

114

115typedef struct {

116 http_conn_t *conn;

117 char *method;

118 char *url;

119 char *version;

120 http_header_t *headers;

121 int headers_len;

122 char *body;

123 long body_len;

124 void *ext_data;

125} http_request_t;

126

127typedef struct {

128 char *version;

129 http_status_t status;

130 http_header_t *headers;

131 int headers_len;

132 char *body;

133 long body_len;

134} http_response_t;

135

136struct Http {

137 http_bind_t *binds;

138 int binds_len;

139 pthread_t thread;

140 bool quit;

141 SSL_CTX *ssl_ctx;

142 http_response_t (*on_request_fn)(http_request_t *);

143};

144

145http_t *http_init(void);

146void http_cleanup(http_t *http);

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

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

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

150http_response_t http_response_create(http_status_t status);

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

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

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

154http_error_t http_listen(http_t *http);

155void http_close(http_t *http);

156

157#ifdef LIB_HTTP_IMPL

158

159#include <stdio.h>

160#include <stdlib.h>

161#include <string.h>

162#include <time.h>

163#include <unistd.h>

164#include <pthread.h>

165#include <netdb.h>

166#include <poll.h>

167#include <signal.h>

168#include <openssl/ssl.h>

169#include <sys/socket.h>

170

171#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

172

173http_t *http_init(void) {

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

175 *http = (http_t) {

176 .binds = NULL,

177 .binds_len = 0,

178 .quit = false,

179 .ssl_ctx = NULL,

180 .on_request_fn = NULL,

181 };

182 return http;

183}

184

185void http_cleanup(http_t *http) {

186 free(http);

187}

188

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

190 http->on_request_fn = fn;

191}

192

193char *http_read_file(char *filename) {

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

195 fseek(fp, 0, SEEK_END);

196 long len = ftell(fp);

197 fseek(fp, 0, SEEK_SET);

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

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

200 content[len] = '\0';

201 fclose(fp);

202 return content;

203}

204

205const char *http_status_str(http_status_t status) {

206 switch (status) {

207 case HTTP_STATUS_CONTINUE:

208 return "Continue";

209 case HTTP_STATUS_SWITCHING_PROTOCOLS:

210 return "Switching Protocols";

211 case HTTP_STATUS_PROCESSING:

212 return "Processing";

213 case HTTP_STATUS_EARLY_HINTS:

214 return "Early Hints";

215 case HTTP_STATUS_OK:

216 return "OK";

217 case HTTP_STATUS_CREATED:

218 return "Created";

219 case HTTP_STATUS_ACCEPTED:

220 return "Accepted";

221 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

222 return "Non-Authoritative Information";

223 case HTTP_STATUS_NO_CONTENT:

224 return "No Content";

225 case HTTP_STATUS_RESET_CONTENT:

226 return "Reset Content";

227 case HTTP_STATUS_PARTIAL_CONTENT:

228 return "Partial Content";

229 case HTTP_STATUS_MULTI_STATUS:

230 return "Multi-Status";

231 case HTTP_STATUS_ALREADY_REPORTED:

232 return "Already Reported";

233 case HTTP_STATUS_IM_USED:

234 return "IM Used";

235 case HTTP_STATUS_MULTIPLE_CHOICES:

236 return "Multiple Choices";

237 case HTTP_STATUS_MOVED_PERMANENTLY:

238 return "Moved Permanently";

239 case HTTP_STATUS_FOUND:

240 return "Found";

241 case HTTP_STATUS_SEE_OTHER:

242 return "See Other";

243 case HTTP_STATUS_NOT_MODIFIED:

244 return "Not Modified";

245 case HTTP_STATUS_TEMPORARY_REDIRECT:

246 return "Temporary Redirect";

247 case HTTP_STATUS_PERMANENT_REDIRECT:

248 return "Permanent Redirect";

249 case HTTP_STATUS_BAD_REQUEST:

250 return "Bad Request";

251 case HTTP_STATUS_UNAUTHORIZED:

252 return "Unauthorized";

253 case HTTP_STATUS_PAYMENT_REQUIRED:

254 return "Payment Required";

255 case HTTP_STATUS_FORBIDDEN:

256 return "Forbidden";

257 case HTTP_STATUS_NOT_FOUND:

258 return "Not Found";

259 case HTTP_STATUS_METHOD_NOT_ALLOWED:

260 return "Method Not Allowed";

261 case HTTP_STATUS_NOT_ACCEPTABLE:

262 return "Not Acceptable";

263 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

264 return "Proxy Authentication Required";

265 case HTTP_STATUS_REQUEST_TIMEOUT:

266 return "Request Timeout";

267 case HTTP_STATUS_CONFLICT:

268 return "Conflict";

269 case HTTP_STATUS_GONE:

270 return "Gone";

271 case HTTP_STATUS_LENGTH_REQUIRED:

272 return "Length Required";

273 case HTTP_STATUS_PRECONDITION_FAILED:

274 return "Precondition Failed";

275 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

276 return "Payload Too Large";

277 case HTTP_STATUS_URI_TOO_LONG:

278 return "URI Too Long";

279 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

280 return "Unsupported Media Type";

281 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

282 return "Range Not Satisfiable";

283 case HTTP_STATUS_EXPECTATION_FAILED:

284 return "Expectation Failed";

285 case HTTP_STATUS_I_AM_A_TEAPOT:

286 return "I'm a teapot";

287 case HTTP_STATUS_MISDIRECTED_REQUEST:

288 return "Misdirected Request";

289 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

290 return "Unprocessable Content";

291 case HTTP_STATUS_LOCKED:

292 return "Locked";

293 case HTTP_STATUS_FAILED_DEPENDENCY:

294 return "Failed Dependency";

295 case HTTP_STATUS_TOO_EARLY:

296 return "Too Early";

297 case HTTP_STATUS_UPGRADE_REQUIRED:

298 return "Upgrade Required";

299 case HTTP_STATUS_PRECONDITION_REQUIRED:

300 return "Precondition Required";

301 case HTTP_STATUS_TOO_MANY_REQUESTS:

302 return "Too Many Requests";

303 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

304 return "Request Header Fields Too Large";

305 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

306 return "Unavailable For Legal Reasons";

307 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

308 return "Internal Server Error";

309 case HTTP_STATUS_NOT_IMPLEMENTED:

310 return "Not Implemented";

311 case HTTP_STATUS_BAD_GATEWAY:

312 return "Bad Gateway";

313 case HTTP_STATUS_SERVICE_UNAVAILABLE:

314 return "Service Unavailable";

315 case HTTP_STATUS_GATEWAY_TIMEOUT:

316 return "Gateway Timeout";

317 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

318 return "HTTP Version Not Supported";

319 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

320 return "Variant Also Negotitates";

321 case HTTP_STATUS_INSUFFICIENT_STORAGE:

322 return "Insufficient Storage";

323 case HTTP_STATUS_LOOP_DETECTED:

324 return "Loop Detected";

325 case HTTP_STATUS_NOT_EXTENDED:

326 return "Not Extended";

327 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

328 return "Network Authentication Required";

329 default:

330 return NULL;

331 }

332}

333

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

335 struct pollfd fds[1];

336 fds[0].fd = conn->sockfd;

337 fds[0].events = POLLIN | POLLPRI;

338 if (poll(fds, 1, 100) && fds[0].revents & POLLIN) {

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

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

341 }

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

343 }

344 return 0;

345}

346

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

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

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

350 }

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

352}

353

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

355 if (request->headers_len > 0) {

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

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

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

359 return header->value;

360 }

361 }

362 }

363 return NULL;

364}

365

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

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

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

369 response->headers_len++;

370 int key_len = strlen(key);

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

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

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

374 int value_len = strlen(value);

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

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

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

378}

379

380http_response_t http_response_create(http_status_t status) {

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

382 int version_len = strlen(version);

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

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

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

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

387 return response;

388}

389

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

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

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

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

394 response->body_len = len;

395 char content_length[50];

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

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

398 }

399}

400

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

402 char *content = http_read_file(filename);

403 if (content != NULL) {

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

405 free(content);

406 }

407}

408

409void http_request_free(http_request_t *request) {

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

411 free(request->method);

412 }

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

414 free(request->url);

415 }

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

417 free(request->version);

418 }

419 if (request->headers_len > 0) {

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

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

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

423 free(header->key);

424 }

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

426 free(header->value);

427 }

428 }

429 }

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

431 free(request->body);

432 }

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

434 free(request->ext_data);

435 }

436}

437

438void http_response_free(http_response_t *response) {

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

440 free(response->version);

441 }

442 if (response->headers_len > 0) {

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

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

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

446 free(header->key);

447 }

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

449 free(header->value);

450 }

451 }

452 }

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

454 free(response->body);

455 }

456}

457

458http_request_t http_read_request(http_conn_t *conn) {

459 int len = 0;

460 int ln = 0;

461 int start = 0;

462 char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];

463 http_request_t request = {

464 .conn = conn,

465 .method = NULL,

466 .url = NULL,

467 .version = NULL,

468 .headers = NULL,

469 .headers_len = 0,

470 .body = NULL,

471 .body_len = 0,

472 .ext_data = NULL,

473 };

474 while (true) {

475 char c;

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

477 if (read == 0) {

478 break;

479 }

480 // break if too long

481 if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {

482 perror("request is too long");

483 break;

484 }

485 buffer[len] = c;

486 len++;

487 // read head

488 if (len >= 2) {

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

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

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

492 if (line_len > 0) {

493 // read line

494 char line[line_len + 1];

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

496 line[line_len] = '\0';

497 // read method, url, and version

498 if (ln == 0) {

499 int arg = 0;

500 int start = 0;

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

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

503 // read method

504 if (arg == 0) {

505 int method_length = i - start;

506 request.method = (char *) malloc(sizeof(char) * (method_length + 1));

507 memcpy(request.method, line + start, method_length);

508 request.method[method_length] = '\0';

509 }

510 // read url

511 if (arg == 1) {

512 int url_length = i - start;

513 request.url = (char *) malloc(sizeof(char) * (url_length + 1));

514 memcpy(request.url, line + start, url_length);

515 request.url[url_length] = '\0';

516 }

517 // read version

518 if (arg == 2) {

519 int version_length = i - start;

520 request.version = (char *) malloc(sizeof(char) * (version_length + 1));

521 memcpy(request.version, line + start, version_length);

522 request.version[version_length] = '\0';

523 }

524 start = i + 1;

525 arg++;

526 }

527 }

528 }

529 // read headers

530 else {

531 int sep = 0;

532 request.headers = (http_header_t *) realloc(request.headers, sizeof(http_header_t) * (request.headers_len + 1));

533 http_header_t *header = &request.headers[request.headers_len];

534 request.headers_len++;

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

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

537 int key_len = i;

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

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

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

541 sep = i + 2;

542 break;

543 }

544 }

545 int value_len = line_len - sep;

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

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

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

549 }

550 }

551 start = len;

552 ln++;

553 }

554 }

555 // read body

556 if (len >= 4) {

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

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

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

560 if (content_length != NULL) {

561 request.body_len = strtol(content_length, NULL, 10);

562 if (request.body_len > 0) {

563 request.body = (char *) malloc(sizeof(char) * (request.body_len + 1));

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

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

566 }

567 }

568 break;

569 }

570 }

571 }

572 return request;

573}

574

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

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

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

578 char status[4];

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

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

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

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

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

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

585 if (response.headers_len > 0) {

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

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

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

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

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

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

592 }

593 }

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

595 if (response.body != NULL) {

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

597 }

598}

599

600void *http_handle_client(void *ptr) {

601 if (!ptr) {

602 pthread_exit(0);

603 }

604 http_conn_t *conn = (http_conn_t *) ptr;

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

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

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

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

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

610 pthread_exit(0);

611 }

612 }

613 http_request_t request = http_read_request(conn);

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

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

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

617 http_write_response(conn, response);

618 http_response_free(&response);

619 }

620 }

621 http_request_free(&request);

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

623 SSL_shutdown(conn->ssl);

624 SSL_free(conn->ssl);

625 }

626 close(conn->sockfd);

627 free(conn);

628 pthread_exit(0);

629}

630

631void *http_handle_server(void *ptr) {

632 http_t *http = (http_t *) ptr;

633 struct pollfd fds[http->binds_len];

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

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

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

637 }

638 while (!http->quit) {

639 struct timespec sleep_req, sleep_rem;

640 sleep_req.tv_sec = 0;

641 sleep_req.tv_nsec = 100000000;

642 nanosleep(&sleep_req, &sleep_rem);

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

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

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

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

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

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

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

650 conn->ssl = NULL;

651 conn->http = http;

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

653 free(conn);

654 }

655 else {

656 pthread_t thread;

657 pthread_attr_t thread_attr;

658 pthread_attr_init(&thread_attr);

659 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

661 pthread_attr_destroy(&thread_attr);

662 }

663 }

664 }

665 }

666 }

667 pthread_exit(0);

668}

669

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

671 (void)(al);

672 http_conn_t *conn = (http_conn_t *) arg;

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

674 if (hostname != NULL) {

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

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

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

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

679 conn->curr_host = http_host;

680 SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);

681 return SSL_TLSEXT_ERR_OK;

682 }

683 }

684 }

685 }

686 return SSL_TLSEXT_ERR_NOACK;

687}

688

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

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

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

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

693 http_bind->port = port;

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

695 return HTTP_ERR_NO_SOCKET;

696 }

697 struct hostent *host = gethostbyname(hostname);

698 if (!host) {

699 return HTTP_ERR_UNKNOWN_HOST;

700 }

701 struct sockaddr_in addr;

702 addr.sin_family = AF_INET;

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

704 addr.sin_port = htons(port);

705 int enable = 1;

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

707 return HTTP_ERR_NO_ADDR_REUSE;

708 }

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

710 return HTTP_ERR_ADDR_IN_USE;

711 }

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

713 return HTTP_ERR_NO_LISTEN;

714 }

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

716 http_host_t *http_host = &hosts[i];

717 http_host->ssl_ctx = NULL;

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

719 const SSL_METHOD *method = TLS_server_method();

720 http_host->ssl_ctx = SSL_CTX_new(method);

721 if (!http_host->ssl_ctx) {

722 return HTTP_ERR_NO_SSL_CONTEXT;

723 }

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

725 return HTTP_ERR_INVALID_CERTIFICATE;

726 }

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

728 return HTTP_ERR_INVALID_PRIVATE_KEY;

729 }

730 }

731 }

732 http_bind->hosts = hosts;

733 http_bind->hosts_len = hosts_len;

734 http->binds_len++;

735 return HTTP_ERR_OK;

736}

737

738http_error_t http_listen(http_t *http) {

739 signal(SIGPIPE, SIG_IGN);

740 const SSL_METHOD *method = TLS_server_method();

741 http->ssl_ctx = SSL_CTX_new(method);

742 if (!http->ssl_ctx) {

743 return HTTP_ERR_NO_SSL_CONTEXT;

744 }

745 SSL_CTX_set_tlsext_servername_callback(http->ssl_ctx, http_tls_sni_callback);

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

747 return HTTP_ERR_OK;

748}

749

750void http_close(http_t *http) {

751 http->quit = true;

752 pthread_join(http->thread, NULL);

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

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

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

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

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

758 }

759 }

760 }

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

762 free(http->ssl_ctx);

763 }

764}

765

766#endif /* LIB_HTTP_IMPL */

767#endif /* LIB_HTTP_H */