so://phie

tpee

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

blob: 903e4fb1bbd22b5ac013226e6995972fa0d5a891 (31669 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

138typedef struct {

139 char *method;

140 char *path;

141 http_resp_t (*fn)(http_req_t *);

142} http_route_t;

143

144typedef struct {

145 char *key;

146 char *value;

147} http_query_t;

148

149typedef struct {

150 char *path;

151 http_query_t *queries;

152 size_t queries_len;

153} http_url_t;

154

155struct http {

156 http_bind_t *binds;

157 size_t binds_len;

158 pthread_t thread;

159 bool quit;

160 SSL_CTX *ssl_ctx;

161 http_resp_t (*on_req_fn)(http_t *, http_req_t *);

162};

163

164http_t *http_init(void);

165void http_cleanup(http_t *http);

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

167void http_on_route(char *method, char *url, http_resp_t (*fn)(http_req_t *));

168void http_on_default(http_resp_t (*fn)(http_req_t *));

169void http_on_pre_route(void (*fn)(http_req_t *));

170void http_on_post_route(void (*fn)(http_req_t *));

171http_url_t http_url_init(http_req_t *req);

172void http_url_free(http_url_t *self);

173char *http_url_get(http_url_t *self, char *key);

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

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

176http_resp_t http_resp_create(http_status_t status);

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

178void http_req_free(http_req_t *req);

179void http_resp_free(http_resp_t *resp);

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

181http_err_t http_listen(http_t *http);

182void http_close(http_t *http);

183

184#ifdef LIB_HTTP_IMPL

185

186#include <stdio.h>

187#include <stdlib.h>

188#include <string.h>

189#include <time.h>

190#include <unistd.h>

191#include <pthread.h>

192#include <netdb.h>

193#include <poll.h>

194#include <errno.h>

195#include <signal.h>

196#include <openssl/ssl.h>

197#include <sys/socket.h>

198

199#define HTTP_VERSION "HTTP/1.1"

200#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

201#define HTTP_SERVER_BACKLOG 5

202#define HTTP_SERVER_SLEEP_TIME 100000000

203#define HTTP_SERVER_POLL_TIME 100

204

205#define _HTTP_ON(method, path, fn_name) \

206 static http_resp_t fn_name(http_req_t *req); \

207 __attribute__((constructor)) \

208 static void __macro_http_fn_register_##fn_name() { \

209 http_on_route(method, path, &fn_name); \

210 } \

211 static http_resp_t fn_name(http_req_t *req)

212

213#define HTTP_GET(path, fn_name) _HTTP_ON("GET", path, fn_name)

214#define HTTP_HEAD(path, fn_name) _HTTP_ON("HEAD", path, fn_name)

215#define HTTP_POST(path, fn_name) _HTTP_ON("POST", path, fn_name)

216#define HTTP_PUT(path, fn_name) _HTTP_ON("PUT", path, fn_name)

217#define HTTP_DELETE(path, fn_name) _HTTP_ON("DELETE", path, fn_name)

218#define HTTP_CONNECT(path, fn_name) _HTTP_ON("CONNECT", path, fn_name)

219#define HTTP_OPTIONS(path, fn_name) _HTTP_ON("OPTIONS", path, fn_name)

220#define HTTP_TRACE(path, fn_name) _HTTP_ON("TRACE", path, fn_name)

221#define HTTP_PATCH(path, fn_name) _HTTP_ON("PATCH", path, fn_name)

222

223#define HTTP_DEFAULT(fn_name) \

224 static http_resp_t fn_name(http_req_t *req); \

225 __attribute__((constructor)) \

226 static void __macro_http_fn_register_##fn_name() { \

227 http_on_default(&fn_name); \

228 } \

229 static http_resp_t fn_name(http_req_t *req)

230

231#define HTTP_MIDDLEWARE_PRE(fn_name) \

232 static void fn_name(http_req_t *req); \

233 __attribute__((constructor)) \

234 static void __macro_http_fn_register_##fn_name() { \

235 http_on_pre_route(&fn_name); \

236 } \

237 static void fn_name(http_req_t *req)

238

239#define HTTP_MIDDLEWARE_POST(fn_name) \

240 static void fn_name(http_req_t *req); \

241 __attribute__((constructor)) \

242 static void __macro_http_fn_register_##fn_name() { \

243 http_on_post_route(&fn_name); \

244 } \

245 static void fn_name(http_req_t *req)

246

247http_route_t *_http_routes = NULL;

248size_t _http_routes_len = 0;

249http_resp_t (*_http_default_route)(http_req_t *);

250void (*_http_pre_route)(http_req_t *);

251void (*_http_post_route)(http_req_t *);

252

253http_resp_t _http_on_req(http_t *http, http_req_t *req) {

254 http_resp_t resp = http_resp_create(HTTP_STATUS_NOT_FOUND);

255 if (_http_pre_route != NULL) {

256 _http_pre_route(req);

257 }

258 for (size_t i = 0; i < _http_routes_len; i++) {

259 http_route_t *route = &_http_routes[i];

260 http_url_t url = http_url_init(req);

261 if (strcmp(route->method, req->method) == 0) {

262 size_t len = strlen(route->path);

263 char c = route->path[len - 1];

264 if (c == '*') {

265 if (strncmp(route->path, url.path, len - 1) == 0) {

266 http_resp_free(&resp);

267 resp = route->fn(req);

268 }

269 }

270 else {

271 if (strcmp(route->path, url.path) == 0) {

272 http_resp_free(&resp);

273 resp = route->fn(req);

274 }

275 }

276 }

277 http_url_free(&url);

278 if (resp.status != HTTP_STATUS_NOT_FOUND) {

279 if (_http_post_route != NULL) {

280 _http_post_route(req);

281 }

282 return resp;

283 }

284 }

285 if (_http_default_route != NULL) {

286 http_resp_free(&resp);

287 resp = _http_default_route(req);

288 }

289 if (_http_post_route != NULL) {

290 _http_post_route(req);

291 }

292 return resp;

293}

294

295http_t *http_init(void) {

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

297 *http = (http_t) {

298 .binds = NULL,

299 .binds_len = 0,

300 .quit = false,

301 .ssl_ctx = NULL,

302 .on_req_fn = &_http_on_req,

303 };

304 return http;

305}

306

307void http_cleanup(http_t *http) {

308 if (http->binds != NULL) {

309 for (size_t i = 0; i < http->binds_len; i++) {

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

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

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

313 }

314 }

315 }

316 free(http->binds);

317 }

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

319 SSL_CTX_free(http->ssl_ctx);

320 }

321 if (_http_routes != NULL && _http_routes_len > 0) {

322 free(_http_routes);

323 }

324 free(http);

325}

326

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

328 http->on_req_fn = fn;

329}

330

331void http_on_route(char *method, char *path, http_resp_t (*fn)(http_req_t *)) {

332 _http_routes = realloc(_http_routes, sizeof(http_route_t) * (_http_routes_len + 1));

333 _http_routes[_http_routes_len] = (http_route_t) {

334 .method = method,

335 .path = path,

336 .fn = fn,

337 };

338 _http_routes_len++;

339}

340

341void http_on_default(http_resp_t (*fn)(http_req_t *)) {

342 _http_default_route = fn;

343}

344

345void http_on_pre_route(void (*fn)(http_req_t *)) {

346 _http_pre_route = fn;

347}

348

349void http_on_post_route(void (*fn)(http_req_t *)) {

350 _http_post_route = fn;

351}

352

353http_url_t http_url_init(http_req_t *req) {

354 http_url_t self = (http_url_t) {

355 .path = NULL,

356 .queries = NULL,

357 .queries_len = 0,

358 };

359 char *uri = req->url;

360 int url_len = strlen(uri);

361 size_t i = 0;

362 // read path

363 for (; i < url_len; i++) {

364 size_t c = uri[i];

365 if (c == '?') {

366 break;

367 }

368 }

369 size_t len = i;

370 self.path = malloc(sizeof(char) * (len + 1));

371 memcpy(self.path, uri, len);

372 self.path[len] = '\0';

373 i++;

374 uri += i;

375 if (i < url_len) {

376 int j = 0;

377 url_len = strlen(uri);

378 int start = j;

379 int sep = -1;

380 for (; j <= url_len; j++) {

381 int c = uri[j];

382 if (c == '&' || j == url_len) {

383 int query_len = j - start;

384 if (query_len > 0) {

385 self.queries = realloc(self.queries, sizeof(http_query_t) * (self.queries_len + 1));

386 http_query_t *query = &self.queries[self.queries_len];

387 query->key = NULL;

388 query->value = NULL;

389 // read query key

390 int key_len = j - start;

391 if (sep != -1) {

392 key_len = sep - start;

393 }

394 query->key = malloc(sizeof(char) * (key_len + 1));

395 memcpy(query->key, uri + start, key_len);

396 query->key[key_len] = '\0';

397 // read query value

398 if (sep != -1) {

399 int value_len = i - (sep + 1);

400 if (value_len > 0) {

401 query->value = malloc(sizeof(char) * (value_len + 1));

402 memcpy(query->value, uri + sep + 1, value_len);

403 query->value[value_len] = '\0';

404 // decode url

405 // TODO impl full decoding

406 size_t len = strlen(query->value);

407 for (size_t k = 0; k < len; k++) {

408 char c = query->value[k];

409 if (c == '+') {

410 query->value[k] = ' ';

411 }

412 }

413 }

414 }

415 self.queries_len++;

416 }

417 start = j + 1;

418 sep = -1; // unset separator

419 }

420 if (c == '=') {

421 sep = j;

422 }

423 }

424 }

425 return self;

426}

427

428void http_url_free(http_url_t *self) {

429 if (self) {

430 free(self->path);

431 if (self->queries_len > 0) {

432 for (size_t i = 0; i < self->queries_len; i++) {

433 http_query_t *query = &self->queries[i];

434 free(query->key);

435 if (query->value) {

436 free(query->value);

437 }

438 }

439 free(self->queries);

440 }

441 }

442}

443

444char *http_url_get(http_url_t *self, char *key) {

445 if (self && self->queries_len > 0) {

446 for (size_t i = 0; i < self->queries_len; i++) {

447 http_query_t *query = &self->queries[i];

448 if (strcmp(query->key, key) == 0) {

449 return query->value;

450 }

451 }

452 }

453 return NULL;

454}

455

456const char *http_status_str(http_status_t status) {

457 switch (status) {

458 case HTTP_STATUS_CONTINUE:

459 return "Continue";

460 case HTTP_STATUS_SWITCHING_PROTOCOLS:

461 return "Switching Protocols";

462 case HTTP_STATUS_PROCESSING:

463 return "Processing";

464 case HTTP_STATUS_EARLY_HINTS:

465 return "Early Hints";

466 case HTTP_STATUS_OK:

467 return "OK";

468 case HTTP_STATUS_CREATED:

469 return "Created";

470 case HTTP_STATUS_ACCEPTED:

471 return "Accepted";

472 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

473 return "Non-Authoritative Information";

474 case HTTP_STATUS_NO_CONTENT:

475 return "No Content";

476 case HTTP_STATUS_RESET_CONTENT:

477 return "Reset Content";

478 case HTTP_STATUS_PARTIAL_CONTENT:

479 return "Partial Content";

480 case HTTP_STATUS_MULTI_STATUS:

481 return "Multi-Status";

482 case HTTP_STATUS_ALREADY_REPORTED:

483 return "Already Reported";

484 case HTTP_STATUS_IM_USED:

485 return "IM Used";

486 case HTTP_STATUS_MULTIPLE_CHOICES:

487 return "Multiple Choices";

488 case HTTP_STATUS_MOVED_PERMANENTLY:

489 return "Moved Permanently";

490 case HTTP_STATUS_FOUND:

491 return "Found";

492 case HTTP_STATUS_SEE_OTHER:

493 return "See Other";

494 case HTTP_STATUS_NOT_MODIFIED:

495 return "Not Modified";

496 case HTTP_STATUS_TEMPORARY_REDIRECT:

497 return "Temporary Redirect";

498 case HTTP_STATUS_PERMANENT_REDIRECT:

499 return "Permanent Redirect";

500 case HTTP_STATUS_BAD_REQUEST:

501 return "Bad Request";

502 case HTTP_STATUS_UNAUTHORIZED:

503 return "Unauthorized";

504 case HTTP_STATUS_PAYMENT_REQUIRED:

505 return "Payment Required";

506 case HTTP_STATUS_FORBIDDEN:

507 return "Forbidden";

508 case HTTP_STATUS_NOT_FOUND:

509 return "Not Found";

510 case HTTP_STATUS_METHOD_NOT_ALLOWED:

511 return "Method Not Allowed";

512 case HTTP_STATUS_NOT_ACCEPTABLE:

513 return "Not Acceptable";

514 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

515 return "Proxy Authentication Required";

516 case HTTP_STATUS_REQUEST_TIMEOUT:

517 return "Request Timeout";

518 case HTTP_STATUS_CONFLICT:

519 return "Conflict";

520 case HTTP_STATUS_GONE:

521 return "Gone";

522 case HTTP_STATUS_LENGTH_REQUIRED:

523 return "Length Required";

524 case HTTP_STATUS_PRECONDITION_FAILED:

525 return "Precondition Failed";

526 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

527 return "Payload Too Large";

528 case HTTP_STATUS_URI_TOO_LONG:

529 return "URI Too Long";

530 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

531 return "Unsupported Media Type";

532 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

533 return "Range Not Satisfiable";

534 case HTTP_STATUS_EXPECTATION_FAILED:

535 return "Expectation Failed";

536 case HTTP_STATUS_I_AM_A_TEAPOT:

537 return "I'm a teapot";

538 case HTTP_STATUS_MISDIRECTED_REQUEST:

539 return "Misdirected Request";

540 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

541 return "Unprocessable Content";

542 case HTTP_STATUS_LOCKED:

543 return "Locked";

544 case HTTP_STATUS_FAILED_DEPENDENCY:

545 return "Failed Dependency";

546 case HTTP_STATUS_TOO_EARLY:

547 return "Too Early";

548 case HTTP_STATUS_UPGRADE_REQUIRED:

549 return "Upgrade Required";

550 case HTTP_STATUS_PRECONDITION_REQUIRED:

551 return "Precondition Required";

552 case HTTP_STATUS_TOO_MANY_REQUESTS:

553 return "Too Many Requests";

554 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

555 return "Request Header Fields Too Large";

556 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

557 return "Unavailable For Legal Reasons";

558 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

559 return "Internal Server Error";

560 case HTTP_STATUS_NOT_IMPLEMENTED:

561 return "Not Implemented";

562 case HTTP_STATUS_BAD_GATEWAY:

563 return "Bad Gateway";

564 case HTTP_STATUS_SERVICE_UNAVAILABLE:

565 return "Service Unavailable";

566 case HTTP_STATUS_GATEWAY_TIMEOUT:

567 return "Gateway Timeout";

568 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

569 return "HTTP Version Not Supported";

570 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

571 return "Variant Also Negotitates";

572 case HTTP_STATUS_INSUFFICIENT_STORAGE:

573 return "Insufficient Storage";

574 case HTTP_STATUS_LOOP_DETECTED:

575 return "Loop Detected";

576 case HTTP_STATUS_NOT_EXTENDED:

577 return "Not Extended";

578 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

579 return "Network Authentication Required";

580 default:

581 return NULL;

582 }

583}

584

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

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

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

588 }

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

590}

591

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

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

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

595 }

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

597}

598

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

600 if (req->headers_len > 0) {

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

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

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

604 return header->value;

605 }

606 }

607 }

608 return NULL;

609}

610

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

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

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

614 resp->headers_len++;

615 int key_len = strlen(key);

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

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

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

619 int value_len = strlen(value);

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

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

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

623}

624

625http_resp_t http_resp_create(http_status_t status) {

626 return (http_resp_t) {

627 .version = strdup(HTTP_VERSION),

628 .status = status,

629 .headers = NULL,

630 .headers_len = 0,

631 .body = NULL,

632 .body_len = 0,

633 };

634}

635

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

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

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

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

640 resp->body_len = len;

641 char content_length[50];

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

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

644 }

645}

646

647void http_req_free(http_req_t *req) {

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

649 free(req->method);

650 }

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

652 free(req->url);

653 }

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

655 free(req->version);

656 }

657 if (req->headers_len > 0) {

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

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

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

661 free(header->key);

662 }

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

664 free(header->value);

665 }

666 }

667 free(req->headers);

668 }

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

670 free(req->body);

671 }

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

673 free(req->ext_data);

674 }

675}

676

677void http_resp_free(http_resp_t *resp) {

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

679 free(resp->version);

680 }

681 if (resp->headers_len > 0) {

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

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

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

685 free(header->key);

686 }

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

688 free(header->value);

689 }

690 }

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

692 free(resp->headers);

693 }

694 }

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

696 free(resp->body);

697 }

698}

699

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

701 int len = 0;

702 int ln = 0;

703 int start = 0;

704 char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];

705 *req = (http_req_t) {

706 .conn = conn,

707 .method = NULL,

708 .url = NULL,

709 .version = NULL,

710 .headers = NULL,

711 .headers_len = 0,

712 .body = NULL,

713 .body_len = 0,

714 .ext_data = NULL,

715 };

716 while (true) {

717 char c;

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

719 if (read == 0) {

720 break;

721 }

722 // read timeout

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

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

725 return HTTP_ERR_READ_TIMEOUT;

726 }

727 }

728 // break if too long

729 if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {

730 return HTTP_ERR_REQUEST_TOO_LONG;

731 }

732 buffer[len] = c;

733 len++;

734 // read head

735 if (len >= 2) {

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

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

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

739 if (line_len > 0) {

740 // read line

741 char line[line_len + 1];

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

743 line[line_len] = '\0';

744 // read method, url, and version

745 if (ln == 0) {

746 int arg = 0;

747 int start = 0;

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

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

750 // read method

751 if (arg == 0) {

752 int method_length = i - start;

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

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

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

756 }

757 // read url

758 if (arg == 1) {

759 int url_length = i - start;

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

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

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

763 }

764 // read version

765 if (arg == 2) {

766 int version_length = i - start;

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

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

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

770 }

771 start = i + 1;

772 arg++;

773 }

774 }

775 }

776 // read headers

777 else {

778 int sep = 0;

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

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

781 req->headers_len++;

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

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

784 int key_len = i;

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

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

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

788 sep = i + 2;

789 break;

790 }

791 }

792 int value_len = line_len - sep;

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

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

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

796 }

797 }

798 start = len;

799 ln++;

800 }

801 }

802 // read body

803 if (len >= 4) {

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

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

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

807 if (content_length != NULL) {

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

809 if (req->body_len > 0) {

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

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

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

813 }

814 }

815 break;

816 }

817 }

818 }

819 return HTTP_ERR_OK;

820}

821

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

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

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

825 char status[4];

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

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

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

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

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

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

832 if (resp.headers_len > 0) {

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

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

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

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

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

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

839 }

840 }

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

842 if (resp.body != NULL) {

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

844 }

845}

846

847void *_http_client_handle(void *ptr) {

848 if (!ptr) {

849 pthread_exit(0);

850 }

851 http_conn_t *conn = (http_conn_t *) ptr;

852 struct timeval timeout;

853 timeout.tv_sec = 5;

854 timeout.tv_usec = 0;

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

856 close(conn->sockfd);

857 free(conn);

858 pthread_exit(0);

859 }

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

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

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

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

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

865 close(conn->sockfd);

866 free(conn);

867 pthread_exit(0);

868 }

869 }

870 http_req_t req;

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

872 if (err != HTTP_ERR_OK) {

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

874 SSL_shutdown(conn->ssl);

875 SSL_free(conn->ssl);

876 }

877 close(conn->sockfd);

878 free(conn);

879 pthread_exit(0);

880 }

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

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

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

884 http_resp_write(conn, resp);

885 http_resp_free(&resp);

886 }

887 }

888 http_req_free(&req);

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

890 SSL_shutdown(conn->ssl);

891 SSL_free(conn->ssl);

892 }

893 close(conn->sockfd);

894 free(conn);

895 pthread_exit(0);

896}

897

898void *_http_server_handle(void *ptr) {

899 http_t *http = (http_t *) ptr;

900 struct pollfd fds[http->binds_len];

901 for (size_t i = 0; i < http->binds_len; i++) {

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

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

904 }

905 while (!http->quit) {

906 struct timespec sleep_req, sleep_rem;

907 sleep_req.tv_sec = 0;

908 sleep_req.tv_nsec = HTTP_SERVER_SLEEP_TIME;

909 nanosleep(&sleep_req, &sleep_rem);

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

911 for (size_t i = 0; i < http->binds_len; i++) {

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

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

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

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

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

917 conn->ssl = NULL;

918 conn->http = http;

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

920 free(conn);

921 }

922 else {

923 pthread_t thread;

924 pthread_attr_t thread_attr;

925 pthread_attr_init(&thread_attr);

926 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

927 pthread_create(&thread, &thread_attr, _http_client_handle, (void *) conn);

928 pthread_attr_destroy(&thread_attr);

929 }

930 }

931 }

932 }

933 }

934 pthread_exit(0);

935}

936

937int _http_tls_sni_callback(SSL *ssl, int *al, void *arg) {

938 (void) al;

939 http_conn_t *conn = (http_conn_t *) arg;

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

941 if (hostname != NULL) {

942 for (size_t i = 0; i < conn->http->binds_len; i++) {

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

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

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

946 conn->curr_host = http_host;

947 SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);

948 return SSL_TLSEXT_ERR_OK;

949 }

950 }

951 }

952 }

953 return SSL_TLSEXT_ERR_NOACK;

954}

955

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

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

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

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

960 http_bind->port = port;

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

962 return HTTP_ERR_NO_SOCKET;

963 }

964 struct hostent *host = gethostbyname(hostname);

965 if (!host) {

966 return HTTP_ERR_UNKNOWN_HOST;

967 }

968 struct sockaddr_in addr;

969 addr.sin_family = AF_INET;

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

971 addr.sin_port = htons(port);

972 int enable = 1;

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

974 return HTTP_ERR_NO_ADDR_REUSE;

975 }

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

977 return HTTP_ERR_ADDR_IN_USE;

978 }

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

980 return HTTP_ERR_NO_LISTEN;

981 }

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

983 http_host_t *http_host = &hosts[i];

984 http_host->ssl_ctx = NULL;

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

986 const SSL_METHOD *method = TLS_server_method();

987 http_host->ssl_ctx = SSL_CTX_new(method);

988 if (!http_host->ssl_ctx) {

989 return HTTP_ERR_NO_SSL_CONTEXT;

990 }

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

992 return HTTP_ERR_INVALID_CERTIFICATE;

993 }

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

995 return HTTP_ERR_INVALID_PRIVATE_KEY;

996 }

997 }

998 }

999 http_bind->hosts = hosts;

1000 http_bind->hosts_len = hosts_len;

1001 http->binds_len++;

1002 return HTTP_ERR_OK;

1003}

1004

1005http_err_t http_listen(http_t *http) {

1006 signal(SIGPIPE, SIG_IGN);

1007 const SSL_METHOD *method = TLS_server_method();

1008 http->ssl_ctx = SSL_CTX_new(method);

1009 if (!http->ssl_ctx) {

1010 return HTTP_ERR_NO_SSL_CONTEXT;

1011 }

1012 SSL_CTX_set_tlsext_servername_callback(http->ssl_ctx, _http_tls_sni_callback);

1013 pthread_create(&http->thread, 0, _http_server_handle, (void *) http);

1014 return HTTP_ERR_OK;

1015}

1016

1017void http_close(http_t *http) {

1018 http->quit = true;

1019 pthread_join(http->thread, NULL);

1020 for (size_t i = 0; i < http->binds_len; i++) {

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

1022 }

1023}

1024

1025#endif /* LIB_HTTP_IMPL */

1026#endif /* LIB_HTTP_H */