so://phie

tpee

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

blob: 10449dc387731c05c1252556ddb2e51261909546 (33275 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_write_head(http_conn_t *conn, http_resp_t *resp);

187void http_resp_write_body(http_conn_t *conn, http_resp_t *resp);

188void http_resp_write(http_conn_t *conn, http_resp_t *resp);

189void http_resp_free(http_resp_t *resp);

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

191http_err_t http_listen(http_t *http);

192void http_close(http_t *http);

193

194#ifdef LIB_HTTP_IMPL

195

196#include <stdio.h>

197#include <stdlib.h>

198#include <string.h>

199#include <ctype.h>

200#include <time.h>

201#include <unistd.h>

202#include <pthread.h>

203#include <netdb.h>

204#include <poll.h>

205#include <errno.h>

206#include <signal.h>

207#include <openssl/ssl.h>

208#include <sys/socket.h>

209

210#define HTTP_VERSION "HTTP/1.1"

211#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

212#define HTTP_SERVER_BACKLOG 5

213#define HTTP_SERVER_SLEEP_TIME 100000000

214#define HTTP_SERVER_POLL_TIME 100

215

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

217 static http_resp_t fn_name(http_req_t *req); \

218 __attribute__((constructor)) \

219 static void __macro_http_fn_register_##fn_name() { \

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

221 } \

222 static http_resp_t fn_name(http_req_t *req)

223

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

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

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

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

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

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

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

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

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

233

234#define HTTP_DEFAULT(fn_name) \

235 static http_resp_t fn_name(http_req_t *req); \

236 __attribute__((constructor)) \

237 static void __macro_http_fn_register_##fn_name() { \

238 http_on_default(&fn_name); \

239 } \

240 static http_resp_t fn_name(http_req_t *req)

241

242#define HTTP_MIDDLEWARE_PRE(fn_name) \

243 static void fn_name(http_req_t *req); \

244 __attribute__((constructor)) \

245 static void __macro_http_fn_register_##fn_name() { \

246 http_on_pre_route(&fn_name); \

247 } \

248 static void fn_name(http_req_t *req)

249

250#define HTTP_MIDDLEWARE_POST(fn_name) \

251 static void fn_name(http_req_t *req); \

252 __attribute__((constructor)) \

253 static void __macro_http_fn_register_##fn_name() { \

254 http_on_post_route(&fn_name); \

255 } \

256 static void fn_name(http_req_t *req)

257

258http_route_t *_http_routes = NULL;

259size_t _http_routes_len = 0;

260http_handle_fn_t _http_default_route;

261http_hook_fn_t _http_pre_route;

262http_hook_fn_t _http_post_route;

263

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

265 http_resp_t resp = http_resp_create(HTTP_STATUS_NOT_FOUND);

266 if (_http_pre_route != NULL) {

267 _http_pre_route(req);

268 }

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

270 http_route_t *route = &_http_routes[i];

271 char *path = http_req_path(req);

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

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

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

275 if (c == '*') {

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

277 http_resp_free(&resp);

278 resp = route->fn(req);

279 }

280 }

281 else {

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

283 http_resp_free(&resp);

284 resp = route->fn(req);

285 }

286 }

287 }

288 free(path);

289 if (resp.status != HTTP_STATUS_NOT_FOUND) {

290 if (_http_post_route != NULL) {

291 _http_post_route(req);

292 }

293 return resp;

294 }

295 }

296 if (_http_default_route != NULL) {

297 http_resp_free(&resp);

298 resp = _http_default_route(req);

299 }

300 if (_http_post_route != NULL) {

301 _http_post_route(req);

302 }

303 return resp;

304}

305

306http_t *http_init(void) {

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

308 *http = (http_t) {

309 .binds = NULL,

310 .binds_len = 0,

311 .quit = false,

312 .ssl_ctx = NULL,

313 .fn = &_http_on_global,

314 };

315 return http;

316}

317

318void http_cleanup(http_t *http) {

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

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

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

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

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

324 }

325 }

326 }

327 free(http->binds);

328 }

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

330 SSL_CTX_free(http->ssl_ctx);

331 }

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

333 free(_http_routes);

334 }

335 free(http);

336}

337

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

339 http->fn = fn;

340}

341

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

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

344 _http_routes[_http_routes_len] = (http_route_t) {

345 .method = method,

346 .path = path,

347 .fn = fn,

348 };

349 _http_routes_len++;

350}

351

352void http_on_default(http_handle_fn_t fn) {

353 _http_default_route = fn;

354}

355

356void http_on_pre_route(http_hook_fn_t fn) {

357 _http_pre_route = fn;

358}

359

360void http_on_post_route(http_hook_fn_t fn) {

361 _http_post_route = fn;

362}

363

364char *http_req_path(http_req_t *req) {

365 char *uri = req->url;

366 size_t url_len = strlen(uri);

367 size_t i = 0;

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

369 size_t c = uri[i];

370 if (c == '?') {

371 break;

372 }

373 }

374 size_t len = i;

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

376 memcpy(path, uri, len);

377 path[len] = '\0';

378 return path;

379}

380

381char *http_req_body(http_req_t *req) {

382 return req->body;

383}

384

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

386 size_t j = 0;

387 size_t k = 0;

388 char decoded[len + 1];

389 while (j < len) {

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

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

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

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

394 j += 3;

395 continue;

396 }

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

398 j++;

399 continue;

400 }

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

402 decoded[k++] = ' ';

403 j++;

404 continue;

405 }

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

407 }

408 decoded[k] = '\0';

409 size_t ret_len = strlen(decoded);

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

411 memcpy(ret, decoded, ret_len);

412 ret[ret_len] = '\0';

413 return ret;

414}

415

416http_pairs_t _http_pairs_init(char *uri) {

417 http_pairs_t self = (http_pairs_t) {

418 .pairs = NULL,

419 .len = 0,

420 };

421 int url_len = strlen(uri);

422 size_t set = 0;

423 size_t lim = 0;

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

425 char c = uri[i];

426 // find 'key=value' pair

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

428 size_t key_len = i - set;

429 if (key_len > 0) {

430 if (lim > set) {

431 key_len = lim - set;

432 }

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

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

435 // read key

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

437 pair->value = NULL;

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

439 // read value

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

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

442 }

443 self.len++;

444 }

445 set = i + 1;

446 }

447 // find '=' delimiter

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

449 lim = i;

450 }

451 }

452 return self;

453}

454

455http_pairs_t http_req_queries(http_req_t *req) {

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

457 // skip path

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

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

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

461 }

462 }

463 return (http_pairs_t) {

464 .pairs = NULL,

465 .len = 0,

466 };

467}

468

469http_pairs_t http_req_params(http_req_t *req) {

470 return _http_pairs_init(req->body);

471}

472

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

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

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

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

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

478 return pair->value;

479 }

480 }

481 }

482 return NULL;

483}

484

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

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

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

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

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

490 return true;

491 }

492 }

493 }

494 return false;

495}

496

497void http_pairs_free(http_pairs_t *self) {

498 if (self == NULL) {

499 return;

500 }

501 if (self->len > 0) {

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

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

504 free(pair->key);

505 if (pair->value) {

506 free(pair->value);

507 }

508 }

509 free(self->pairs);

510 }

511}

512

513const char *_http_status_str(http_status_t status) {

514 switch (status) {

515 case HTTP_STATUS_CONTINUE:

516 return "Continue";

517 case HTTP_STATUS_SWITCHING_PROTOCOLS:

518 return "Switching Protocols";

519 case HTTP_STATUS_PROCESSING:

520 return "Processing";

521 case HTTP_STATUS_EARLY_HINTS:

522 return "Early Hints";

523 case HTTP_STATUS_OK:

524 return "OK";

525 case HTTP_STATUS_CREATED:

526 return "Created";

527 case HTTP_STATUS_ACCEPTED:

528 return "Accepted";

529 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

530 return "Non-Authoritative Information";

531 case HTTP_STATUS_NO_CONTENT:

532 return "No Content";

533 case HTTP_STATUS_RESET_CONTENT:

534 return "Reset Content";

535 case HTTP_STATUS_PARTIAL_CONTENT:

536 return "Partial Content";

537 case HTTP_STATUS_MULTI_STATUS:

538 return "Multi-Status";

539 case HTTP_STATUS_ALREADY_REPORTED:

540 return "Already Reported";

541 case HTTP_STATUS_IM_USED:

542 return "IM Used";

543 case HTTP_STATUS_MULTIPLE_CHOICES:

544 return "Multiple Choices";

545 case HTTP_STATUS_MOVED_PERMANENTLY:

546 return "Moved Permanently";

547 case HTTP_STATUS_FOUND:

548 return "Found";

549 case HTTP_STATUS_SEE_OTHER:

550 return "See Other";

551 case HTTP_STATUS_NOT_MODIFIED:

552 return "Not Modified";

553 case HTTP_STATUS_TEMPORARY_REDIRECT:

554 return "Temporary Redirect";

555 case HTTP_STATUS_PERMANENT_REDIRECT:

556 return "Permanent Redirect";

557 case HTTP_STATUS_BAD_REQUEST:

558 return "Bad Request";

559 case HTTP_STATUS_UNAUTHORIZED:

560 return "Unauthorized";

561 case HTTP_STATUS_PAYMENT_REQUIRED:

562 return "Payment Required";

563 case HTTP_STATUS_FORBIDDEN:

564 return "Forbidden";

565 case HTTP_STATUS_NOT_FOUND:

566 return "Not Found";

567 case HTTP_STATUS_METHOD_NOT_ALLOWED:

568 return "Method Not Allowed";

569 case HTTP_STATUS_NOT_ACCEPTABLE:

570 return "Not Acceptable";

571 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

572 return "Proxy Authentication Required";

573 case HTTP_STATUS_REQUEST_TIMEOUT:

574 return "Request Timeout";

575 case HTTP_STATUS_CONFLICT:

576 return "Conflict";

577 case HTTP_STATUS_GONE:

578 return "Gone";

579 case HTTP_STATUS_LENGTH_REQUIRED:

580 return "Length Required";

581 case HTTP_STATUS_PRECONDITION_FAILED:

582 return "Precondition Failed";

583 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

584 return "Payload Too Large";

585 case HTTP_STATUS_URI_TOO_LONG:

586 return "URI Too Long";

587 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

588 return "Unsupported Media Type";

589 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

590 return "Range Not Satisfiable";

591 case HTTP_STATUS_EXPECTATION_FAILED:

592 return "Expectation Failed";

593 case HTTP_STATUS_I_AM_A_TEAPOT:

594 return "I'm a teapot";

595 case HTTP_STATUS_MISDIRECTED_REQUEST:

596 return "Misdirected Request";

597 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

598 return "Unprocessable Content";

599 case HTTP_STATUS_LOCKED:

600 return "Locked";

601 case HTTP_STATUS_FAILED_DEPENDENCY:

602 return "Failed Dependency";

603 case HTTP_STATUS_TOO_EARLY:

604 return "Too Early";

605 case HTTP_STATUS_UPGRADE_REQUIRED:

606 return "Upgrade Required";

607 case HTTP_STATUS_PRECONDITION_REQUIRED:

608 return "Precondition Required";

609 case HTTP_STATUS_TOO_MANY_REQUESTS:

610 return "Too Many Requests";

611 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

612 return "Request Header Fields Too Large";

613 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

614 return "Unavailable For Legal Reasons";

615 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

616 return "Internal Server Error";

617 case HTTP_STATUS_NOT_IMPLEMENTED:

618 return "Not Implemented";

619 case HTTP_STATUS_BAD_GATEWAY:

620 return "Bad Gateway";

621 case HTTP_STATUS_SERVICE_UNAVAILABLE:

622 return "Service Unavailable";

623 case HTTP_STATUS_GATEWAY_TIMEOUT:

624 return "Gateway Timeout";

625 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

626 return "HTTP Version Not Supported";

627 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

628 return "Variant Also Negotitates";

629 case HTTP_STATUS_INSUFFICIENT_STORAGE:

630 return "Insufficient Storage";

631 case HTTP_STATUS_LOOP_DETECTED:

632 return "Loop Detected";

633 case HTTP_STATUS_NOT_EXTENDED:

634 return "Not Extended";

635 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

636 return "Network Authentication Required";

637 default:

638 return NULL;

639 }

640}

641

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

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

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

645 }

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

647}

648

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

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

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

652 }

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

654}

655

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

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 (strcasecmp(header->key, key) == 0) {

661 return header->value;

662 }

663 }

664 }

665 return NULL;

666}

667

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

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

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

671 resp->headers_len++;

672 int key_len = strlen(key);

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

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

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

676 int value_len = strlen(value);

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

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

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

680}

681

682http_resp_t http_resp_create(http_status_t status) {

683 return (http_resp_t) {

684 .version = strdup(HTTP_VERSION),

685 .status = status,

686 .headers = NULL,

687 .headers_len = 0,

688 .body = NULL,

689 .body_len = 0,

690 };

691}

692

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

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

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

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

697 resp->body_len = len;

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_head(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}

897

898void http_resp_write_body(http_conn_t *conn, http_resp_t *resp) {

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

900 http_write(conn, resp->body, resp->body_len);

901 }

902}

903

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

905 bool has_content_length = false;

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

907 if (resp->headers_len > 0) {

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

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

910 if (strcasecmp(header->key, "Content-Length") == 0) {

911 has_content_length = true;

912 break;

913 }

914 }

915 }

916 if (!has_content_length) {

917 char content_length[50];

918 snprintf(content_length, 50, "%ld", resp->body_len);

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

920 }

921 }

922 http_resp_write_head(conn, resp);

923 http_resp_write_body(conn, resp);

924}

925

926void *_http_client_handle(void *ptr) {

927 if (!ptr) {

928 pthread_exit(0);

929 }

930 http_conn_t *conn = (http_conn_t *) ptr;

931 struct timeval timeout;

932 timeout.tv_sec = 5;

933 timeout.tv_usec = 0;

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

935 close(conn->sockfd);

936 free(conn);

937 pthread_exit(0);

938 }

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

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

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

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

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

944 close(conn->sockfd);

945 free(conn);

946 pthread_exit(0);

947 }

948 }

949 http_req_t req;

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

951 if (err != HTTP_ERR_OK) {

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

953 SSL_shutdown(conn->ssl);

954 SSL_free(conn->ssl);

955 }

956 close(conn->sockfd);

957 free(conn);

958 pthread_exit(0);

959 }

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

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

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

963 http_resp_write(conn, &resp);

964 http_resp_free(&resp);

965 }

966 }

967 http_req_free(&req);

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

969 SSL_shutdown(conn->ssl);

970 SSL_free(conn->ssl);

971 }

972 close(conn->sockfd);

973 free(conn);

974 pthread_exit(0);

975}

976

977void *_http_server_handle(void *ptr) {

978 http_t *http = (http_t *) ptr;

979 struct pollfd fds[http->binds_len];

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

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

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

983 }

984 while (!http->quit) {

985 struct timespec sleep_req, sleep_rem;

986 sleep_req.tv_sec = 0;

987 sleep_req.tv_nsec = HTTP_SERVER_SLEEP_TIME;

988 nanosleep(&sleep_req, &sleep_rem);

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

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

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

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

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

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

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

996 conn->ssl = NULL;

997 conn->http = http;

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

999 free(conn);

1000 }

1001 else {

1002 pthread_t thread;

1003 pthread_attr_t thread_attr;

1004 pthread_attr_init(&thread_attr);

1005 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

1007 pthread_attr_destroy(&thread_attr);

1008 }

1009 }

1010 }

1011 }

1012 }

1013 pthread_exit(0);

1014}

1015

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

1017 (void) al;

1018 http_conn_t *conn = (http_conn_t *) arg;

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

1020 if (hostname != NULL) {

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

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

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

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

1025 conn->curr_host = http_host;

1026 SSL_set_SSL_CTX(ssl, http_host->ssl_ctx);

1027 return SSL_TLSEXT_ERR_OK;

1028 }

1029 }

1030 }

1031 }

1032 return SSL_TLSEXT_ERR_NOACK;

1033}

1034

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

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

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

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

1039 http_bind->port = port;

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

1041 return HTTP_ERR_NO_SOCKET;

1042 }

1043 struct hostent *host = gethostbyname(hostname);

1044 if (!host) {

1045 return HTTP_ERR_UNKNOWN_HOST;

1046 }

1047 struct sockaddr_in addr;

1048 addr.sin_family = AF_INET;

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

1050 addr.sin_port = htons(port);

1051 int enable = 1;

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

1053 return HTTP_ERR_NO_ADDR_REUSE;

1054 }

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

1056 return HTTP_ERR_ADDR_IN_USE;

1057 }

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

1059 return HTTP_ERR_NO_LISTEN;

1060 }

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

1062 http_host_t *http_host = &hosts[i];

1063 http_host->ssl_ctx = NULL;

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

1065 const SSL_METHOD *method = TLS_server_method();

1066 http_host->ssl_ctx = SSL_CTX_new(method);

1067 if (!http_host->ssl_ctx) {

1068 return HTTP_ERR_NO_SSL_CONTEXT;

1069 }

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

1071 return HTTP_ERR_INVALID_CERTIFICATE;

1072 }

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

1074 return HTTP_ERR_INVALID_PRIVATE_KEY;

1075 }

1076 }

1077 }

1078 http_bind->hosts = hosts;

1079 http_bind->hosts_len = hosts_len;

1080 http->binds_len++;

1081 return HTTP_ERR_OK;

1082}

1083

1084http_err_t http_listen(http_t *http) {

1085 signal(SIGPIPE, SIG_IGN);

1086 const SSL_METHOD *method = TLS_server_method();

1087 http->ssl_ctx = SSL_CTX_new(method);

1088 if (!http->ssl_ctx) {

1089 return HTTP_ERR_NO_SSL_CONTEXT;

1090 }

1091 SSL_CTX_set_tlsext_servername_callback(http->ssl_ctx, _http_tls_sni_callback);

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

1093 return HTTP_ERR_OK;

1094}

1095

1096void http_close(http_t *http) {

1097 http->quit = true;

1098 pthread_join(http->thread, NULL);

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

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

1101 }

1102}

1103

1104#endif /* LIB_HTTP_IMPL */

1105#endif /* LIB_HTTP_H */