so://phie

tpee

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

blob: 257b2e35d962a8601dd83450581cb454844201b9 (32462 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 http_resp_t (*http_global_fn_t)(http_t *, http_req_t *);

139typedef http_resp_t (*http_handle_fn_t)(http_req_t *);

140typedef void (*http_hook_fn_t)(http_req_t *);

141

142typedef struct {

143 char *method;

144 char *path;

145 http_handle_fn_t fn;

146} http_route_t;

147

148typedef struct {

149 char *key;

150 char *value;

151} http_pair_t;

152

153typedef struct {

154 http_pair_t *pairs;

155 size_t len;

156} http_pairs_t;

157

158struct http {

159 http_bind_t *binds;

160 size_t binds_len;

161 pthread_t thread;

162 bool quit;

163 SSL_CTX *ssl_ctx;

164 http_global_fn_t fn;

165};

166

167http_t *http_init(void);

168void http_cleanup(http_t *http);

169void http_on_global(http_t *http, http_global_fn_t fn);

170void http_on_route(char *method, char *url, http_handle_fn_t fn);

171void http_on_default(http_handle_fn_t fn);

172void http_on_pre_route(http_hook_fn_t fn);

173void http_on_post_route(http_hook_fn_t fn);

174char *http_req_path(http_req_t *req);

175char *http_req_body(http_req_t *req);

176http_pairs_t http_req_queries(http_req_t *req);

177http_pairs_t http_req_params(http_req_t *req);

178char *http_pairs_get(http_pairs_t *self, char *key);

179bool http_pairs_has(http_pairs_t *self, char *key);

180void http_pairs_free(http_pairs_t *self);

181char *http_req_header(http_req_t *req, char *key);

182void http_resp_header(http_resp_t *resp, char *key, char *value);

183http_resp_t http_resp_create(http_status_t status);

184void http_resp_body(http_resp_t *resp, char *body, long len);

185void http_req_free(http_req_t *req);

186void http_resp_free(http_resp_t *resp);

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

188http_err_t http_listen(http_t *http);

189void http_close(http_t *http);

190

191#ifdef LIB_HTTP_IMPL

192

193#include <stdio.h>

194#include <stdlib.h>

195#include <string.h>

196#include <ctype.h>

197#include <time.h>

198#include <unistd.h>

199#include <pthread.h>

200#include <netdb.h>

201#include <poll.h>

202#include <errno.h>

203#include <signal.h>

204#include <openssl/ssl.h>

205#include <sys/socket.h>

206

207#define HTTP_VERSION "HTTP/1.1"

208#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

209#define HTTP_SERVER_BACKLOG 5

210#define HTTP_SERVER_SLEEP_TIME 100000000

211#define HTTP_SERVER_POLL_TIME 100

212

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

214 static http_resp_t fn_name(http_req_t *req); \

215 __attribute__((constructor)) \

216 static void __macro_http_fn_register_##fn_name() { \

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

218 } \

219 static http_resp_t fn_name(http_req_t *req)

220

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

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

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

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

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

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

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

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

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

230

231#define HTTP_DEFAULT(fn_name) \

232 static http_resp_t fn_name(http_req_t *req); \

233 __attribute__((constructor)) \

234 static void __macro_http_fn_register_##fn_name() { \

235 http_on_default(&fn_name); \

236 } \

237 static http_resp_t fn_name(http_req_t *req)

238

239#define HTTP_MIDDLEWARE_PRE(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_pre_route(&fn_name); \

244 } \

245 static void fn_name(http_req_t *req)

246

247#define HTTP_MIDDLEWARE_POST(fn_name) \

248 static void fn_name(http_req_t *req); \

249 __attribute__((constructor)) \

250 static void __macro_http_fn_register_##fn_name() { \

251 http_on_post_route(&fn_name); \

252 } \

253 static void fn_name(http_req_t *req)

254

255http_route_t *_http_routes = NULL;

256size_t _http_routes_len = 0;

257http_handle_fn_t _http_default_route;

258http_hook_fn_t _http_pre_route;

259http_hook_fn_t _http_post_route;

260

261http_resp_t _http_on_global(http_t *http, http_req_t *req) {

262 http_resp_t resp = http_resp_create(HTTP_STATUS_NOT_FOUND);

263 if (_http_pre_route != NULL) {

264 _http_pre_route(req);

265 }

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

267 http_route_t *route = &_http_routes[i];

268 char *path = http_req_path(req);

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

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

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

272 if (c == '*') {

273 if (strncmp(route->path, path, len - 1) == 0) {

274 http_resp_free(&resp);

275 resp = route->fn(req);

276 }

277 }

278 else {

279 if (strcmp(route->path, path) == 0) {

280 http_resp_free(&resp);

281 resp = route->fn(req);

282 }

283 }

284 }

285 free(path);

286 if (resp.status != HTTP_STATUS_NOT_FOUND) {

287 if (_http_post_route != NULL) {

288 _http_post_route(req);

289 }

290 return resp;

291 }

292 }

293 if (_http_default_route != NULL) {

294 http_resp_free(&resp);

295 resp = _http_default_route(req);

296 }

297 if (_http_post_route != NULL) {

298 _http_post_route(req);

299 }

300 return resp;

301}

302

303http_t *http_init(void) {

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

305 *http = (http_t) {

306 .binds = NULL,

307 .binds_len = 0,

308 .quit = false,

309 .ssl_ctx = NULL,

310 .fn = &_http_on_global,

311 };

312 return http;

313}

314

315void http_cleanup(http_t *http) {

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

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

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

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

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

321 }

322 }

323 }

324 free(http->binds);

325 }

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

327 SSL_CTX_free(http->ssl_ctx);

328 }

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

330 free(_http_routes);

331 }

332 free(http);

333}

334

335void http_on_global(http_t *http, http_global_fn_t fn) {

336 http->fn = fn;

337}

338

339void http_on_route(char *method, char *path, http_handle_fn_t fn) {

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

341 _http_routes[_http_routes_len] = (http_route_t) {

342 .method = method,

343 .path = path,

344 .fn = fn,

345 };

346 _http_routes_len++;

347}

348

349void http_on_default(http_handle_fn_t fn) {

350 _http_default_route = fn;

351}

352

353void http_on_pre_route(http_hook_fn_t fn) {

354 _http_pre_route = fn;

355}

356

357void http_on_post_route(http_hook_fn_t fn) {

358 _http_post_route = fn;

359}

360

361char *http_req_path(http_req_t *req) {

362 char *uri = req->url;

363 size_t url_len = strlen(uri);

364 size_t i = 0;

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

366 size_t c = uri[i];

367 if (c == '?') {

368 break;

369 }

370 }

371 size_t len = i;

372 char *path = malloc(len + 1);

373 memcpy(path, uri, len);

374 path[len] = '\0';

375 return path;

376}

377

378char *http_req_body(http_req_t *req) {

379 return req->body;

380}

381

382char *_http_pair_decode(char *str, size_t len) {

383 size_t j = 0;

384 size_t k = 0;

385 char decoded[len + 1];

386 while (j < len) {

387 if (str[j] == '%') {

388 if (j + 2 < len && isxdigit(str[j + 1]) && isxdigit(str[j + 2])) {

389 char hex[3] = { str[j + 1], str[j + 2], '\0' };

390 decoded[k++] = (char) strtol(hex, NULL, 16);

391 j += 3;

392 continue;

393 }

394 decoded[k++] = '%';

395 j++;

396 continue;

397 }

398 if (str[j] == '+') {

399 decoded[k++] = ' ';

400 j++;

401 continue;

402 }

403 decoded[k++] = str[j++];

404 }

405 decoded[k] = '\0';

406 size_t ret_len = strlen(decoded);

407 char *ret = malloc(ret_len + 1);

408 memcpy(ret, decoded, ret_len);

409 ret[ret_len] = '\0';

410 return ret;

411}

412

413http_pairs_t _http_pairs_init(char *uri) {

414 http_pairs_t self = (http_pairs_t) {

415 .pairs = NULL,

416 .len = 0,

417 };

418 int url_len = strlen(uri);

419 size_t set = 0;

420 size_t lim = 0;

421 for (size_t i = 0; i < url_len + 1; i++) {

422 char c = uri[i];

423 // find 'key=value' pair

424 if (i == url_len || uri[i] == '&') {

425 size_t key_len = i - set;

426 if (key_len > 0) {

427 if (lim > set) {

428 key_len = lim - set;

429 }

430 self.pairs = realloc(self.pairs, sizeof(http_pair_t) * (self.len + 1));

431 http_pair_t *pair = &self.pairs[self.len];

432 // read key

433 pair->key = _http_pair_decode(uri + set, key_len);

434 pair->value = NULL;

435 if (i > set + key_len + 1) {

436 // read value

437 size_t value_len = i - (set + key_len + 1);

438 pair->value = _http_pair_decode(uri + set + key_len + 1, value_len);

439 }

440 self.len++;

441 }

442 set = i + 1;

443 }

444 // find '=' delimiter

445 if (uri[i] == '=') {

446 lim = i;

447 }

448 }

449 return self;

450}

451

452http_pairs_t http_req_queries(http_req_t *req) {

453 size_t url_len = strlen(req->url);

454 // skip path

455 for (size_t i = 0; i < url_len; i++) {

456 if (req->url[i] == '?') {

457 return _http_pairs_init(req->url + i + 1);

458 }

459 }

460 return (http_pairs_t) {

461 .pairs = NULL,

462 .len = 0,

463 };

464}

465

466http_pairs_t http_req_params(http_req_t *req) {

467 return _http_pairs_init(req->body);

468}

469

470char *http_pairs_get(http_pairs_t *self, char *key) {

471 if (self && self->len > 0) {

472 for (size_t i = 0; i < self->len; i++) {

473 http_pair_t *pair = &self->pairs[i];

474 if (strcmp(pair->key, key) == 0) {

475 return pair->value;

476 }

477 }

478 }

479 return NULL;

480}

481

482bool http_pairs_has(http_pairs_t *self, char *key) {

483 if (self && self->len > 0) {

484 for (size_t i = 0; i < self->len; i++) {

485 http_pair_t *pair = &self->pairs[i];

486 if (strcmp(pair->key, key) == 0) {

487 return true;

488 }

489 }

490 }

491 return false;

492}

493

494void http_pairs_free(http_pairs_t *self) {

495 if (self == NULL) {

496 return;

497 }

498 if (self->len > 0) {

499 for (size_t i = 0; i < self->len; i++) {

500 http_pair_t *pair = &self->pairs[i];

501 free(pair->key);

502 if (pair->value) {

503 free(pair->value);

504 }

505 }

506 free(self->pairs);

507 }

508}

509

510const char *_http_status_str(http_status_t status) {

511 switch (status) {

512 case HTTP_STATUS_CONTINUE:

513 return "Continue";

514 case HTTP_STATUS_SWITCHING_PROTOCOLS:

515 return "Switching Protocols";

516 case HTTP_STATUS_PROCESSING:

517 return "Processing";

518 case HTTP_STATUS_EARLY_HINTS:

519 return "Early Hints";

520 case HTTP_STATUS_OK:

521 return "OK";

522 case HTTP_STATUS_CREATED:

523 return "Created";

524 case HTTP_STATUS_ACCEPTED:

525 return "Accepted";

526 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

527 return "Non-Authoritative Information";

528 case HTTP_STATUS_NO_CONTENT:

529 return "No Content";

530 case HTTP_STATUS_RESET_CONTENT:

531 return "Reset Content";

532 case HTTP_STATUS_PARTIAL_CONTENT:

533 return "Partial Content";

534 case HTTP_STATUS_MULTI_STATUS:

535 return "Multi-Status";

536 case HTTP_STATUS_ALREADY_REPORTED:

537 return "Already Reported";

538 case HTTP_STATUS_IM_USED:

539 return "IM Used";

540 case HTTP_STATUS_MULTIPLE_CHOICES:

541 return "Multiple Choices";

542 case HTTP_STATUS_MOVED_PERMANENTLY:

543 return "Moved Permanently";

544 case HTTP_STATUS_FOUND:

545 return "Found";

546 case HTTP_STATUS_SEE_OTHER:

547 return "See Other";

548 case HTTP_STATUS_NOT_MODIFIED:

549 return "Not Modified";

550 case HTTP_STATUS_TEMPORARY_REDIRECT:

551 return "Temporary Redirect";

552 case HTTP_STATUS_PERMANENT_REDIRECT:

553 return "Permanent Redirect";

554 case HTTP_STATUS_BAD_REQUEST:

555 return "Bad Request";

556 case HTTP_STATUS_UNAUTHORIZED:

557 return "Unauthorized";

558 case HTTP_STATUS_PAYMENT_REQUIRED:

559 return "Payment Required";

560 case HTTP_STATUS_FORBIDDEN:

561 return "Forbidden";

562 case HTTP_STATUS_NOT_FOUND:

563 return "Not Found";

564 case HTTP_STATUS_METHOD_NOT_ALLOWED:

565 return "Method Not Allowed";

566 case HTTP_STATUS_NOT_ACCEPTABLE:

567 return "Not Acceptable";

568 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

569 return "Proxy Authentication Required";

570 case HTTP_STATUS_REQUEST_TIMEOUT:

571 return "Request Timeout";

572 case HTTP_STATUS_CONFLICT:

573 return "Conflict";

574 case HTTP_STATUS_GONE:

575 return "Gone";

576 case HTTP_STATUS_LENGTH_REQUIRED:

577 return "Length Required";

578 case HTTP_STATUS_PRECONDITION_FAILED:

579 return "Precondition Failed";

580 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

581 return "Payload Too Large";

582 case HTTP_STATUS_URI_TOO_LONG:

583 return "URI Too Long";

584 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

585 return "Unsupported Media Type";

586 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

587 return "Range Not Satisfiable";

588 case HTTP_STATUS_EXPECTATION_FAILED:

589 return "Expectation Failed";

590 case HTTP_STATUS_I_AM_A_TEAPOT:

591 return "I'm a teapot";

592 case HTTP_STATUS_MISDIRECTED_REQUEST:

593 return "Misdirected Request";

594 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

595 return "Unprocessable Content";

596 case HTTP_STATUS_LOCKED:

597 return "Locked";

598 case HTTP_STATUS_FAILED_DEPENDENCY:

599 return "Failed Dependency";

600 case HTTP_STATUS_TOO_EARLY:

601 return "Too Early";

602 case HTTP_STATUS_UPGRADE_REQUIRED:

603 return "Upgrade Required";

604 case HTTP_STATUS_PRECONDITION_REQUIRED:

605 return "Precondition Required";

606 case HTTP_STATUS_TOO_MANY_REQUESTS:

607 return "Too Many Requests";

608 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

609 return "Request Header Fields Too Large";

610 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

611 return "Unavailable For Legal Reasons";

612 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

613 return "Internal Server Error";

614 case HTTP_STATUS_NOT_IMPLEMENTED:

615 return "Not Implemented";

616 case HTTP_STATUS_BAD_GATEWAY:

617 return "Bad Gateway";

618 case HTTP_STATUS_SERVICE_UNAVAILABLE:

619 return "Service Unavailable";

620 case HTTP_STATUS_GATEWAY_TIMEOUT:

621 return "Gateway Timeout";

622 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

623 return "HTTP Version Not Supported";

624 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

625 return "Variant Also Negotitates";

626 case HTTP_STATUS_INSUFFICIENT_STORAGE:

627 return "Insufficient Storage";

628 case HTTP_STATUS_LOOP_DETECTED:

629 return "Loop Detected";

630 case HTTP_STATUS_NOT_EXTENDED:

631 return "Not Extended";

632 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

633 return "Network Authentication Required";

634 default:

635 return NULL;

636 }

637}

638

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

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

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

642 }

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

644}

645

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

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

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

649 }

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

651}

652

653char *http_req_header(http_req_t *req, char *key) {

654 if (req->headers_len > 0) {

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

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

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

658 return header->value;

659 }

660 }

661 }

662 return NULL;

663}

664

665void http_resp_header(http_resp_t *resp, char *key, char *value) {

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

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

668 resp->headers_len++;

669 int key_len = strlen(key);

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

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

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

673 int value_len = strlen(value);

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

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

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

677}

678

679http_resp_t http_resp_create(http_status_t status) {

680 return (http_resp_t) {

681 .version = strdup(HTTP_VERSION),

682 .status = status,

683 .headers = NULL,

684 .headers_len = 0,

685 .body = NULL,

686 .body_len = 0,

687 };

688}

689

690void http_resp_body(http_resp_t *resp, char *body, long len) {

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

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

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

694 resp->body_len = len;

695 char content_length[50];

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

697 http_resp_header(resp, (char *) "Content-Length", content_length);

698 }

699}

700

701void http_req_free(http_req_t *req) {

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

703 free(req->method);

704 }

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

706 free(req->url);

707 }

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

709 free(req->version);

710 }

711 if (req->headers_len > 0) {

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

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

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

715 free(header->key);

716 }

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

718 free(header->value);

719 }

720 }

721 free(req->headers);

722 }

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

724 free(req->body);

725 }

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

727 free(req->ext_data);

728 }

729}

730

731void http_resp_free(http_resp_t *resp) {

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

733 free(resp->version);

734 }

735 if (resp->headers_len > 0) {

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

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

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

739 free(header->key);

740 }

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

742 free(header->value);

743 }

744 }

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

746 free(resp->headers);

747 }

748 }

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

750 free(resp->body);

751 }

752}

753

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

755 int len = 0;

756 int ln = 0;

757 int start = 0;

758 char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];

759 *req = (http_req_t) {

760 .conn = conn,

761 .method = NULL,

762 .url = NULL,

763 .version = NULL,

764 .headers = NULL,

765 .headers_len = 0,

766 .body = NULL,

767 .body_len = 0,

768 .ext_data = NULL,

769 };

770 while (true) {

771 char c;

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

773 if (read == 0) {

774 break;

775 }

776 // read timeout

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

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

779 return HTTP_ERR_READ_TIMEOUT;

780 }

781 }

782 // break if too long

783 if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {

784 return HTTP_ERR_REQUEST_TOO_LONG;

785 }

786 buffer[len] = c;

787 len++;

788 // read head

789 if (len >= 2) {

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

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

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

793 if (line_len > 0) {

794 // read line

795 char line[line_len + 1];

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

797 line[line_len] = '\0';

798 // read method, url, and version

799 if (ln == 0) {

800 int arg = 0;

801 int start = 0;

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

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

804 // read method

805 if (arg == 0) {

806 int method_length = i - start;

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

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

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

810 }

811 // read url

812 if (arg == 1) {

813 int url_length = i - start;

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

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

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

817 }

818 // read version

819 if (arg == 2) {

820 int version_length = i - start;

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

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

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

824 }

825 start = i + 1;

826 arg++;

827 }

828 }

829 }

830 // read headers

831 else {

832 int sep = 0;

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

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

835 req->headers_len++;

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

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

838 int key_len = i;

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

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

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

842 sep = i + 2;

843 break;

844 }

845 }

846 int value_len = line_len - sep;

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

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

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

850 }

851 }

852 start = len;

853 ln++;

854 }

855 }

856 // read body

857 if (len >= 4) {

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

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

860 char *content_length = http_req_header(req, (char *) "Content-Length");

861 if (content_length != NULL) {

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

863 if (req->body_len > 0) {

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

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

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

867 }

868 }

869 break;

870 }

871 }

872 }

873 return HTTP_ERR_OK;

874}

875

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

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

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

879 char status[4];

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

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

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

883 const char *status_message = _http_status_str(resp.status);

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

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

886 if (resp.headers_len > 0) {

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

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

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

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

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

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

893 }

894 }

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

896 if (resp.body != NULL) {

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

898 }

899}

900

901void *_http_client_handle(void *ptr) {

902 if (!ptr) {

903 pthread_exit(0);

904 }

905 http_conn_t *conn = (http_conn_t *) ptr;

906 struct timeval timeout;

907 timeout.tv_sec = 5;

908 timeout.tv_usec = 0;

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

910 close(conn->sockfd);

911 free(conn);

912 pthread_exit(0);

913 }

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

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

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

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

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

919 close(conn->sockfd);

920 free(conn);

921 pthread_exit(0);

922 }

923 }

924 http_req_t req;

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

926 if (err != HTTP_ERR_OK) {

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

928 SSL_shutdown(conn->ssl);

929 SSL_free(conn->ssl);

930 }

931 close(conn->sockfd);

932 free(conn);

933 pthread_exit(0);

934 }

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

936 if (conn->http->fn != NULL) {

937 http_resp_t resp = conn->http->fn(conn->http, &req);

938 http_resp_write(conn, resp);

939 http_resp_free(&resp);

940 }

941 }

942 http_req_free(&req);

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

944 SSL_shutdown(conn->ssl);

945 SSL_free(conn->ssl);

946 }

947 close(conn->sockfd);

948 free(conn);

949 pthread_exit(0);

950}

951

952void *_http_server_handle(void *ptr) {

953 http_t *http = (http_t *) ptr;

954 struct pollfd fds[http->binds_len];

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

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

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

958 }

959 while (!http->quit) {

960 struct timespec sleep_req, sleep_rem;

961 sleep_req.tv_sec = 0;

962 sleep_req.tv_nsec = HTTP_SERVER_SLEEP_TIME;

963 nanosleep(&sleep_req, &sleep_rem);

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

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

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

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

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

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

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

971 conn->ssl = NULL;

972 conn->http = http;

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

974 free(conn);

975 }

976 else {

977 pthread_t thread;

978 pthread_attr_t thread_attr;

979 pthread_attr_init(&thread_attr);

980 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

982 pthread_attr_destroy(&thread_attr);

983 }

984 }

985 }

986 }

987 }

988 pthread_exit(0);

989}

990

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

992 (void) al;

993 http_conn_t *conn = (http_conn_t *) arg;

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

995 if (hostname != NULL) {

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

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

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

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

1000 conn->curr_host = http_host;

1001 SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);

1002 return SSL_TLSEXT_ERR_OK;

1003 }

1004 }

1005 }

1006 }

1007 return SSL_TLSEXT_ERR_NOACK;

1008}

1009

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

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

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

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

1014 http_bind->port = port;

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

1016 return HTTP_ERR_NO_SOCKET;

1017 }

1018 struct hostent *host = gethostbyname(hostname);

1019 if (!host) {

1020 return HTTP_ERR_UNKNOWN_HOST;

1021 }

1022 struct sockaddr_in addr;

1023 addr.sin_family = AF_INET;

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

1025 addr.sin_port = htons(port);

1026 int enable = 1;

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

1028 return HTTP_ERR_NO_ADDR_REUSE;

1029 }

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

1031 return HTTP_ERR_ADDR_IN_USE;

1032 }

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

1034 return HTTP_ERR_NO_LISTEN;

1035 }

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

1037 http_host_t *http_host = &hosts[i];

1038 http_host->ssl_ctx = NULL;

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

1040 const SSL_METHOD *method = TLS_server_method();

1041 http_host->ssl_ctx = SSL_CTX_new(method);

1042 if (!http_host->ssl_ctx) {

1043 return HTTP_ERR_NO_SSL_CONTEXT;

1044 }

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

1046 return HTTP_ERR_INVALID_CERTIFICATE;

1047 }

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

1049 return HTTP_ERR_INVALID_PRIVATE_KEY;

1050 }

1051 }

1052 }

1053 http_bind->hosts = hosts;

1054 http_bind->hosts_len = hosts_len;

1055 http->binds_len++;

1056 return HTTP_ERR_OK;

1057}

1058

1059http_err_t http_listen(http_t *http) {

1060 signal(SIGPIPE, SIG_IGN);

1061 const SSL_METHOD *method = TLS_server_method();

1062 http->ssl_ctx = SSL_CTX_new(method);

1063 if (!http->ssl_ctx) {

1064 return HTTP_ERR_NO_SSL_CONTEXT;

1065 }

1066 SSL_CTX_set_tlsext_servername_callback(http->ssl_ctx, _http_tls_sni_callback);

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

1068 return HTTP_ERR_OK;

1069}

1070

1071void http_close(http_t *http) {

1072 http->quit = true;

1073 pthread_join(http->thread, NULL);

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

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

1076 }

1077}

1078

1079#endif /* LIB_HTTP_IMPL */

1080#endif /* LIB_HTTP_H */