so://phie

tpee

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

blob: 231d173b2ac64209b9021f8deabcd7a0f7a06474 (35560 bytes)[doc][blame][raw]

1/*

2 * Copyright (C) 2026 Sophie Sitzler

3 *

4 * This program is free software: you can redistribute it and/or modify

5 * it under the terms of the GNU General Public License as published by

6 * the Free Software Foundation, either version 3 of the License, or

7 * (at your option) any later version.

8 *

9 * This program is distributed in the hope that it will be useful,

10 * but WITHOUT ANY WARRANTY; without even the implied warranty of

11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

12 * GNU General Public License for more details.

13 *

14 * You should have received a copy of the GNU General Public License

15 * along with this program. If not, see <https://www.gnu.org/licenses/>.

16 */

17

18// @file http.h

19

20#ifndef _SO_HTTP_H

21#define _SO_HTTP_H

22

23#include <stdbool.h>

24#include <sys/socket.h>

25

26// @include <openssl/ssl.h>

27// @desc OpenSSL library handling TLS/SSL.

28#include <openssl/ssl.h>

29

30#ifdef SO_HTTP_IMPL

31#define SO_SOCK_IMPL

32#endif // SO_HTTP_IMPL

33

34// @include <so/sock.h>

35// @desc so/sock library handling server/client communication and multi-threading.

36#include <so/sock.h>

37

38// @enum http_err_t

39// @desc Error code.

40typedef enum {

41 HTTP_ERR_OK = SOCK_ERR_OK,

42 HTTP_ERR__COUNT,

43} http_err_t;

44

45// @enum http_status_t

46// @desc HTTP status code.

47typedef enum {

48 HTTP_STATUS_CONTINUE = 100,

49 HTTP_STATUS_SWITCHING_PROTOCOLS = 101,

50 HTTP_STATUS_PROCESSING = 102,

51 HTTP_STATUS_EARLY_HINTS = 103,

52 HTTP_STATUS_OK = 200,

53 HTTP_STATUS_CREATED = 201,

54 HTTP_STATUS_ACCEPTED = 202,

55 HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,

56 HTTP_STATUS_NO_CONTENT = 204,

57 HTTP_STATUS_RESET_CONTENT = 205,

58 HTTP_STATUS_PARTIAL_CONTENT = 206,

59 HTTP_STATUS_MULTI_STATUS = 207,

60 HTTP_STATUS_ALREADY_REPORTED = 208,

61 HTTP_STATUS_IM_USED = 226,

62 HTTP_STATUS_MULTIPLE_CHOICES = 300,

63 HTTP_STATUS_MOVED_PERMANENTLY = 301,

64 HTTP_STATUS_FOUND = 302,

65 HTTP_STATUS_SEE_OTHER = 303,

66 HTTP_STATUS_NOT_MODIFIED = 304,

67 HTTP_STATUS_TEMPORARY_REDIRECT = 307,

68 HTTP_STATUS_PERMANENT_REDIRECT = 308,

69 HTTP_STATUS_BAD_REQUEST = 400,

70 HTTP_STATUS_UNAUTHORIZED = 401,

71 HTTP_STATUS_PAYMENT_REQUIRED = 402,

72 HTTP_STATUS_FORBIDDEN = 403,

73 HTTP_STATUS_NOT_FOUND = 404,

74 HTTP_STATUS_METHOD_NOT_ALLOWED = 405,

75 HTTP_STATUS_NOT_ACCEPTABLE = 406,

76 HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,

77 HTTP_STATUS_REQUEST_TIMEOUT = 408,

78 HTTP_STATUS_CONFLICT = 409,

79 HTTP_STATUS_GONE = 410,

80 HTTP_STATUS_LENGTH_REQUIRED = 411,

81 HTTP_STATUS_PRECONDITION_FAILED = 412,

82 HTTP_STATUS_PAYLOAD_TOO_LARGE = 413,

83 HTTP_STATUS_URI_TOO_LONG = 414,

84 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,

85 HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416,

86 HTTP_STATUS_EXPECTATION_FAILED = 417,

87 HTTP_STATUS_I_AM_A_TEAPOT = 418,

88 HTTP_STATUS_MISDIRECTED_REQUEST = 421,

89 HTTP_STATUS_UNPROCESSABLE_CONTENT = 422,

90 HTTP_STATUS_LOCKED = 423,

91 HTTP_STATUS_FAILED_DEPENDENCY = 424,

92 HTTP_STATUS_TOO_EARLY = 425,

93 HTTP_STATUS_UPGRADE_REQUIRED = 426,

94 HTTP_STATUS_PRECONDITION_REQUIRED = 428,

95 HTTP_STATUS_TOO_MANY_REQUESTS = 429,

96 HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,

97 HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,

98 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,

99 HTTP_STATUS_NOT_IMPLEMENTED = 501,

100 HTTP_STATUS_BAD_GATEWAY = 502,

101 HTTP_STATUS_SERVICE_UNAVAILABLE = 503,

102 HTTP_STATUS_GATEWAY_TIMEOUT = 504,

103 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,

104 HTTP_STATUS_VARIANT_ALSO_NEGOTITATES = 506,

105 HTTP_STATUS_INSUFFICIENT_STORAGE = 507,

106 HTTP_STATUS_LOOP_DETECTED = 508,

107 HTTP_STATUS_NOT_EXTENDED = 510,

108 HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,

109 __HTTP_STATUS_HANDLED = 999,

110} http_status_t;

111

112// @type http_t

113// @groupdef http_t

114// @desc Global context struct. Implemented here {http}.

115typedef struct http http_t;

116

117// @type http_host_t

118// @desc Represents a the host.

119typedef sock_host_t http_host_t;

120

121// @type http_bind_t

122// @desc Represents a the binding (port).

123typedef sock_bind_t http_bind_t;

124

125// @type http_conn_t

126// @groupdef http_conn_t

127// @desc Represents a client connection.

128typedef sock_conn_t http_conn_t;

129

130// @struct http_header_t

131// @desc A HTTP header.

132typedef struct {

133 char *key;

134 char *value;

135} http_header_t;

136

137// @struct http_req_t

138// @groupdef http_req_t

139// @desc A HTTP request struct.

140typedef struct {

141 http_conn_t *conn;

142 char *method;

143 char *url;

144 char *version;

145 http_header_t *headers;

146 int headers_len;

147 char *body;

148 long body_len;

149 void *ext_data;

150} http_req_t;

151

152// @struct http_resp_t

153// @groupdef http_resp_t

154// @desc A HTTP response struct.

155typedef struct {

156 char *version;

157 http_status_t status;

158 http_header_t *headers;

159 int headers_len;

160 char *body;

161 long body_len;

162} http_resp_t;

163

164// @type http_global_fn_t

165// @desc A function type for a global route handler.

166typedef http_resp_t (*http_global_fn_t)(http_t *, http_req_t *);

167

168// @type http_handle_fn_t

169// @desc A function type for a route handler.

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

171

172// @type http_hook_fn_t

173// @desc A function type for a hook handler.

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

175

176// @struct http_route_t

177// @desc A route.

178typedef struct {

179 char *method;

180 char *path;

181 http_handle_fn_t fn;

182} http_route_t;

183

184// @struct http_pair_t

185typedef struct {

186 char *key;

187 char *value;

188} http_pair_t;

189

190// @struct http_pairs_t

191// @groupdef http_pairs_t

192typedef struct {

193 http_pair_t *pairs;

194 size_t len;

195} http_pairs_t;

196

197// @struct http

198// @group http_t

199// @desc Implementation of the global context struct. Type here {http_t}.

200struct http {

201 sock_t *sock;

202 http_global_fn_t fn;

203};

204

205// @func http_init

206// @group http_t

207// @desc Initializes global library context {http_t}. Free with {http_cleanup}.

208// @return {http_t} * - Returns the global library context.

209http_t *http_init(void);

210

211// @func http_cleanup

212// @group http_t

213// @desc Cleans up {http_t}.

214// @param {http_t} *self - The global library context.

215void http_cleanup(http_t *self);

216

217// @func http_on_global

218// @group http_t

219// @desc Set and override the default global route handler {_http_on_global}.

220// @param {http_t} *self - The global library context.

221// @param {http_global_fn_t} fn - The global route handler.

222void http_on_global(http_t *self, http_global_fn_t fn);

223

224// @func http_on_route

225// @note Use macros like {HTTP_GET} and others to register routes more easily.

226// @desc Registers a new route.

227// @param char *method - The HTTP method.

228// @param char *url - The HTTP URL (path).

229// @param {http_handle_fn_t} fn - The route handler.

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

231

232// @func http_on_default

233// @note Use macro {HTTP_DEFAULT} instead.

234// @desc Registers a fallback handler.

235// @param {http_handle_fn_t} fn - The route handler.

236void http_on_default(http_handle_fn_t fn);

237

238// @func http_on_pre_route

239// @note Use macro {HTTP_PRE_HOOK} instead.

240// @desc Registers a hook handler which is performed before the route handler is executed.

241// @param {http_hook_fn_t} fn - The hook handler.

242void http_on_pre_route(http_hook_fn_t fn);

243

244// @func http_on_post_route

245// @note Use macro {HTTP_POST_HOOK} instead.

246// @desc Registers a hook handler which is performed after the route handler is executed.

247// @param {http_hook_fn_t} fn - The hook handler.

248void http_on_post_route(http_hook_fn_t fn);

249

250// @func http_req_path

251// @group http_req_t

252// @param {http_req_t} *req - The HTTP request.

253// @return char * - Returns the request path.

254char *http_req_path(http_req_t *req);

255

256// @func http_req_body

257// @group http_req_t

258// @param {http_req_t} *req - The HTTP request.

259// @return char * - Returns the request body.

260char *http_req_body(http_req_t *req);

261

262// @func http_req_queries

263// @group http_req_t

264// @param {http_req_t} *req - The HTTP request.

265// @return {http_pairs_t} - Returns the request queries.

266http_pairs_t http_req_queries(http_req_t *req);

267

268// @func http_req_params

269// @group http_req_t

270// @param {http_req_t} *req - The HTTP request.

271// @return {http_pairs_t} - Returns the request params.

272http_pairs_t http_req_params(http_req_t *req);

273

274// @func http_pairs_get

275// @group http_pairs_t

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

277

278// @func http_pairs_has

279// @group http_pairs_t

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

281

282// @func http_pairs_free

283// @group http_pairs_t

284void http_pairs_free(http_pairs_t *self);

285

286// @func http_req_header

287// @group http_req_t

288// @param {http_req_t} *req - The HTTP request.

289// @param char *key - The header key.

290// @return char * - Returns a header value.

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

292

293// @func http_resp_header

294// @group http_resp_t

295// @desc Writes a header to the response. The header content is consumed and can be freed afterward.

296// @param {http_resp_t} *resp - The HTTP response.

297// @param char *key - The header key.

298// @param char *value - The header value.

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

300

301// @func http_resp_create

302// @group http_resp_t

303// @desc Creates a new response with a given HTTP status. Freed with {http_resp_free}.

304// @param {http_status_t} status - The HTTP status code.

305// @return {http_resp_t} - Returns a HTTP response.

306http_resp_t http_resp_create(http_status_t status);

307

308// @func http_resp_body

309// @group http_resp_t

310// @desc Writes body content to the response. The body content is consumed and can be freed afterward.

311// @param {http_resp_t} *resp - The HTTP response.

312// @param char *body - The body content.

313// @param long len - The body length.

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

315

316// @func http_req_free

317// @group http_req_t

318// @desc Frees a request.

319// @param {http_req_t} *req - The HTTP request.

320void http_req_free(http_req_t *req);

321

322// @func http_resp_write_head

323// @group http_resp_t

324// @desc Writes a response header to the socket stream.

325// @param {http_resp_t} *resp - The HTTP response.

326// @param {http_conn_t} *conn - The HTTP connection.

327void http_resp_write_head(http_resp_t *resp, http_conn_t *conn);

328

329// @func http_resp_write_body

330// @group http_resp_t

331// @desc Writes a response body to the socket stream.

332// @param {http_resp_t} *resp - The HTTP response.

333// @param {http_conn_t} *conn - The HTTP connection.

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

335

336// @func http_resp_write

337// @group http_resp_t

338// @desc Writes a response to the socket stream.

339// @param {http_resp_t} *resp - The HTTP response.

340// @param {http_conn_t} *conn - The HTTP connection.

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

342

343// @func http_resp_free

344// @group http_resp_t

345// @desc Frees a response.

346// @param {http_resp_t} *resp - The HTTP response.

347void http_resp_free(http_resp_t *resp);

348

349// @func http_bind

350// @group http_t

351// @param {http_t} *self - The global library context.

352// @param char *hostname - The hostname.

353// @param int port - The port.

354// @param {http_host_t} *hosts - The host to bind to.

355// @param int hosts_len - The host length of to be bound host.

356http_err_t http_bind(http_t *self, char *hostname, int port, http_host_t *hosts, int hosts_len);

357

358// @func http_listen

359// @group http_t

360// @param {http_t} *self - The global library context.

361http_err_t http_listen(http_t *self);

362

363// @func http_bind_listen

364// @group http_t

365// @param {http_t} *self - The global library context.

366// @param char *hostname - The hostname.

367// @param int port - The port.

368http_err_t http_bind_listen(http_t *self, char *hostname, int port);

369

370// @func http_close

371// @group http_t

372// @param {http_t} *self - The global library context.

373void http_close(http_t *self);

374

375// @func _http_req_read

376// @group http_req_t

377// @internal

378// @param {http_req_t} *req - The HTTP request.

379// @param {http_conn_t} *conn - The HTTP connection.

380// @return {http_err_t} - Returns an HTTP error code.

381http_err_t _http_req_read(http_req_t *req, http_conn_t *conn);

382

383#ifdef SO_HTTP_IMPL

384

385#include <stdio.h>

386#include <stdlib.h>

387#include <string.h>

388#include <ctype.h>

389#include <time.h>

390#include <unistd.h>

391#include <pthread.h>

392#include <netdb.h>

393#include <poll.h>

394#include <errno.h>

395#include <signal.h>

396

397// @macro HTTP_VERSION

398// @internal

399#define HTTP_VERSION "HTTP/1.1"

400

401// @macro HTTP_MAX_REQUEST_HEAD_SIZE

402// @internal

403#define HTTP_MAX_REQUEST_HEAD_SIZE 1000000

404

405// @macro HTTP_RESP_HANDLED

406// @group http_resp_t

407// @desc Handled {http_resp_t}.

408#define HTTP_RESP_HANDLED (http_resp_t) { .status = __HTTP_STATUS_HANDLED }

409

410// @macro _HTTP_ON

411// @internal

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

413 static http_resp_t fn_name(http_req_t *req); \

414 __attribute__((constructor)) \

415 static void __macro_http_fn_register_##fn_name() { \

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

417 } \

418 static http_resp_t fn_name(http_req_t *req)

419

420// @macro HTTP_GET

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

422

423// @macro HTTP_GET

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

425

426// @macro HTTP_POST

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

428

429// @macro HTTP_PUT

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

431

432// @macro HTTP_DELETE

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

434

435// @macro HTTP_CONNECT

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

437

438// @macro HTTP_OPTIONS

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

440

441// @macro HTTP_TRACE

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

443

444// @macro HTTP_PATCH

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

446

447// @macro HTTP_DEFAULT

448#define HTTP_DEFAULT(fn_name) \

449 static http_resp_t fn_name(http_req_t *req); \

450 __attribute__((constructor)) \

451 static void __macro_http_fn_register_##fn_name() { \

452 http_on_default(&fn_name); \

453 } \

454 static http_resp_t fn_name(http_req_t *req)

455

456// @macro HTTP_PRE_HOOK

457#define HTTP_PRE_HOOK(fn_name) \

458 static void fn_name(http_req_t *req); \

459 __attribute__((constructor)) \

460 static void __macro_http_fn_register_##fn_name() { \

461 http_on_pre_route(&fn_name); \

462 } \

463 static void fn_name(http_req_t *req)

464

465// @macro HTTP_POST_HOOK

466#define HTTP_POST_HOOK(fn_name) \

467 static void fn_name(http_req_t *req); \

468 __attribute__((constructor)) \

469 static void __macro_http_fn_register_##fn_name() { \

470 http_on_post_route(&fn_name); \

471 } \

472 static void fn_name(http_req_t *req)

473

474// @global _http_routes

475// @internal

476http_route_t *_http_routes = NULL;

477

478// @global _http_routes_len

479// @internal

480size_t _http_routes_len = 0;

481

482// @global _http_default_route

483// @internal

484http_handle_fn_t _http_default_route;

485

486// @global _http_pre_route

487// @internal

488http_hook_fn_t _http_pre_route;

489

490// @global _http_post_route

491// @internal

492http_hook_fn_t _http_post_route;

493

494// @func _http_on_global

495// @group http_t

496// @internal

497// @desc The default route handler. Can be overwritten with {http_on_global}.

498// @param {http_t} *self - The global library context.

499// @param {http_req_t} *req - The HTTP request.

500// @return {http_resp_t} - Returns a HTTP response.

501http_resp_t _http_on_global(http_t *self, http_req_t *req) {

502 http_resp_t resp = http_resp_create(HTTP_STATUS_NOT_FOUND);

503 if (_http_pre_route != NULL) {

504 _http_pre_route(req);

505 }

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

507 http_route_t *route = &_http_routes[i];

508 char *path = http_req_path(req);

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

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

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

512 if (c == '*') {

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

514 http_resp_free(&resp);

515 resp = route->fn(req);

516 }

517 }

518 else {

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

520 http_resp_free(&resp);

521 resp = route->fn(req);

522 }

523 }

524 }

525 free(path);

526 if (resp.status != HTTP_STATUS_NOT_FOUND) {

527 if (_http_post_route != NULL) {

528 _http_post_route(req);

529 }

530 return resp;

531 }

532 }

533 if (_http_default_route != NULL) {

534 http_resp_free(&resp);

535 resp = _http_default_route(req);

536 }

537 if (_http_post_route != NULL) {

538 _http_post_route(req);

539 }

540 return resp;

541}

542

543// @func _http_on_handle

544// @internal

545sock_err_t _http_on_handle(sock_t *sock, http_conn_t *conn) {

546 http_t *self= (http_t *) sock->ext;

547 http_req_t req;

548 http_err_t err = _http_req_read(&req, conn);

549 if (err != HTTP_ERR_OK) {

550 return err;

551 }

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

553 if (self->fn != NULL) {

554 http_resp_t resp = self->fn(self, &req);

555 http_resp_write(&resp, conn);

556 http_resp_free(&resp);

557 }

558 }

559 http_req_free(&req);

560 return HTTP_ERR_OK;

561}

562

563http_t *http_init(void) {

564 http_t *self = (http_t *) malloc(sizeof(http_t));

565 *self = (http_t) {

566 .sock = sock_init(),

567 .fn = &_http_on_global,

568 };

569 sock_set_ext(self->sock, self);

570 sock_on_global(self->sock, _http_on_handle);

571 return self;

572}

573

574void http_cleanup(http_t *self) {

575 if (self->sock != NULL) {

576 sock_cleanup(self->sock);

577 }

578 free(self);

579}

580

581void http_on_global(http_t *self, http_global_fn_t fn) {

582 self->fn = fn;

583}

584

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

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

587 _http_routes[_http_routes_len] = (http_route_t) {

588 .method = method,

589 .path = path,

590 .fn = fn,

591 };

592 _http_routes_len++;

593}

594

595void http_on_default(http_handle_fn_t fn) {

596 _http_default_route = fn;

597}

598

599void http_on_pre_route(http_hook_fn_t fn) {

600 _http_pre_route = fn;

601}

602

603void http_on_post_route(http_hook_fn_t fn) {

604 _http_post_route = fn;

605}

606

607char *http_req_path(http_req_t *req) {

608 char *uri = req->url;

609 size_t url_len = strlen(uri);

610 size_t i = 0;

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

612 size_t c = uri[i];

613 if (c == '?') {

614 break;

615 }

616 }

617 size_t len = i;

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

619 memcpy(path, uri, len);

620 path[len] = '\0';

621 return path;

622}

623

624char *http_req_body(http_req_t *req) {

625 return req->body;

626}

627

628// @func _http_pair_decode

629// @internal

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

631 size_t j = 0;

632 size_t k = 0;

633 char decoded[len + 1];

634 while (j < len) {

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

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

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

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

639 j += 3;

640 continue;

641 }

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

643 j++;

644 continue;

645 }

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

647 decoded[k++] = ' ';

648 j++;

649 continue;

650 }

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

652 }

653 decoded[k] = '\0';

654 size_t ret_len = strlen(decoded);

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

656 memcpy(ret, decoded, ret_len);

657 ret[ret_len] = '\0';

658 return ret;

659}

660

661// @func _http_pairs_init

662// @group http_pairs_t

663// @internal

664http_pairs_t _http_pairs_init(char *uri) {

665 http_pairs_t self = (http_pairs_t) {

666 .pairs = NULL,

667 .len = 0,

668 };

669 int url_len = strlen(uri);

670 size_t set = 0;

671 size_t lim = 0;

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

673 char c = uri[i];

674 // find 'key=value' pair

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

676 size_t key_len = i - set;

677 if (key_len > 0) {

678 if (lim > set) {

679 key_len = lim - set;

680 }

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

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

683 // read key

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

685 pair->value = NULL;

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

687 // read value

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

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

690 }

691 self.len++;

692 }

693 set = i + 1;

694 }

695 // find '=' delimiter

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

697 lim = i;

698 }

699 }

700 return self;

701}

702

703http_pairs_t http_req_queries(http_req_t *req) {

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

705 // skip path

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

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

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

709 }

710 }

711 return (http_pairs_t) {

712 .pairs = NULL,

713 .len = 0,

714 };

715}

716

717http_pairs_t http_req_params(http_req_t *req) {

718 return _http_pairs_init(req->body);

719}

720

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

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

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

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

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

726 return pair->value;

727 }

728 }

729 }

730 return NULL;

731}

732

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

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

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

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

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

738 return true;

739 }

740 }

741 }

742 return false;

743}

744

745void http_pairs_free(http_pairs_t *self) {

746 if (self == NULL) {

747 return;

748 }

749 if (self->len > 0) {

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

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

752 free(pair->key);

753 if (pair->value) {

754 free(pair->value);

755 }

756 }

757 free(self->pairs);

758 }

759}

760

761// @func _http_status_str

762// @internal

763const char *_http_status_str(http_status_t status) {

764 switch (status) {

765 case HTTP_STATUS_CONTINUE:

766 return "Continue";

767 case HTTP_STATUS_SWITCHING_PROTOCOLS:

768 return "Switching Protocols";

769 case HTTP_STATUS_PROCESSING:

770 return "Processing";

771 case HTTP_STATUS_EARLY_HINTS:

772 return "Early Hints";

773 case HTTP_STATUS_OK:

774 return "OK";

775 case HTTP_STATUS_CREATED:

776 return "Created";

777 case HTTP_STATUS_ACCEPTED:

778 return "Accepted";

779 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

780 return "Non-Authoritative Information";

781 case HTTP_STATUS_NO_CONTENT:

782 return "No Content";

783 case HTTP_STATUS_RESET_CONTENT:

784 return "Reset Content";

785 case HTTP_STATUS_PARTIAL_CONTENT:

786 return "Partial Content";

787 case HTTP_STATUS_MULTI_STATUS:

788 return "Multi-Status";

789 case HTTP_STATUS_ALREADY_REPORTED:

790 return "Already Reported";

791 case HTTP_STATUS_IM_USED:

792 return "IM Used";

793 case HTTP_STATUS_MULTIPLE_CHOICES:

794 return "Multiple Choices";

795 case HTTP_STATUS_MOVED_PERMANENTLY:

796 return "Moved Permanently";

797 case HTTP_STATUS_FOUND:

798 return "Found";

799 case HTTP_STATUS_SEE_OTHER:

800 return "See Other";

801 case HTTP_STATUS_NOT_MODIFIED:

802 return "Not Modified";

803 case HTTP_STATUS_TEMPORARY_REDIRECT:

804 return "Temporary Redirect";

805 case HTTP_STATUS_PERMANENT_REDIRECT:

806 return "Permanent Redirect";

807 case HTTP_STATUS_BAD_REQUEST:

808 return "Bad Request";

809 case HTTP_STATUS_UNAUTHORIZED:

810 return "Unauthorized";

811 case HTTP_STATUS_PAYMENT_REQUIRED:

812 return "Payment Required";

813 case HTTP_STATUS_FORBIDDEN:

814 return "Forbidden";

815 case HTTP_STATUS_NOT_FOUND:

816 return "Not Found";

817 case HTTP_STATUS_METHOD_NOT_ALLOWED:

818 return "Method Not Allowed";

819 case HTTP_STATUS_NOT_ACCEPTABLE:

820 return "Not Acceptable";

821 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

822 return "Proxy Authentication Required";

823 case HTTP_STATUS_REQUEST_TIMEOUT:

824 return "Request Timeout";

825 case HTTP_STATUS_CONFLICT:

826 return "Conflict";

827 case HTTP_STATUS_GONE:

828 return "Gone";

829 case HTTP_STATUS_LENGTH_REQUIRED:

830 return "Length Required";

831 case HTTP_STATUS_PRECONDITION_FAILED:

832 return "Precondition Failed";

833 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

834 return "Payload Too Large";

835 case HTTP_STATUS_URI_TOO_LONG:

836 return "URI Too Long";

837 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

838 return "Unsupported Media Type";

839 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

840 return "Range Not Satisfiable";

841 case HTTP_STATUS_EXPECTATION_FAILED:

842 return "Expectation Failed";

843 case HTTP_STATUS_I_AM_A_TEAPOT:

844 return "I'm a teapot";

845 case HTTP_STATUS_MISDIRECTED_REQUEST:

846 return "Misdirected Request";

847 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

848 return "Unprocessable Content";

849 case HTTP_STATUS_LOCKED:

850 return "Locked";

851 case HTTP_STATUS_FAILED_DEPENDENCY:

852 return "Failed Dependency";

853 case HTTP_STATUS_TOO_EARLY:

854 return "Too Early";

855 case HTTP_STATUS_UPGRADE_REQUIRED:

856 return "Upgrade Required";

857 case HTTP_STATUS_PRECONDITION_REQUIRED:

858 return "Precondition Required";

859 case HTTP_STATUS_TOO_MANY_REQUESTS:

860 return "Too Many Requests";

861 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

862 return "Request Header Fields Too Large";

863 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

864 return "Unavailable For Legal Reasons";

865 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

866 return "Internal Server Error";

867 case HTTP_STATUS_NOT_IMPLEMENTED:

868 return "Not Implemented";

869 case HTTP_STATUS_BAD_GATEWAY:

870 return "Bad Gateway";

871 case HTTP_STATUS_SERVICE_UNAVAILABLE:

872 return "Service Unavailable";

873 case HTTP_STATUS_GATEWAY_TIMEOUT:

874 return "Gateway Timeout";

875 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

876 return "HTTP Version Not Supported";

877 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

878 return "Variant Also Negotitates";

879 case HTTP_STATUS_INSUFFICIENT_STORAGE:

880 return "Insufficient Storage";

881 case HTTP_STATUS_LOOP_DETECTED:

882 return "Loop Detected";

883 case HTTP_STATUS_NOT_EXTENDED:

884 return "Not Extended";

885 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

886 return "Network Authentication Required";

887 default:

888 return NULL;

889 }

890}

891

892// @func _http_conn_read

893// @group http_conn_t

894// @internal

895ssize_t _http_conn_read(http_conn_t *conn, char *buffer, size_t len) {

896 return sock_conn_read(conn, buffer, len);

897}

898

899// @func _http_conn_write

900// @group http_conn_t

901// @internal

902ssize_t _http_conn_write(http_conn_t *conn, char *buffer, size_t len) {

903 return sock_conn_write(conn, buffer, len);

904}

905

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

907 if (req->headers_len > 0) {

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

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

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

911 return header->value;

912 }

913 }

914 }

915 return NULL;

916}

917

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

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

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

921 resp->headers_len++;

922 int key_len = strlen(key);

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

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

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

926 int value_len = strlen(value);

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

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

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

930}

931

932http_resp_t http_resp_create(http_status_t status) {

933 return (http_resp_t) {

934 .version = strdup(HTTP_VERSION),

935 .status = status,

936 .headers = NULL,

937 .headers_len = 0,

938 .body = NULL,

939 .body_len = 0,

940 };

941}

942

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

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

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

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

947 resp->body_len = len;

948 }

949}

950

951void http_req_free(http_req_t *req) {

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

953 free(req->method);

954 }

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

956 free(req->url);

957 }

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

959 free(req->version);

960 }

961 if (req->headers_len > 0) {

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

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

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

965 free(header->key);

966 }

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

968 free(header->value);

969 }

970 }

971 free(req->headers);

972 }

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

974 free(req->body);

975 }

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

977 free(req->ext_data);

978 }

979}

980

981void http_resp_free(http_resp_t *resp) {

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

983 free(resp->version);

984 }

985 if (resp->headers_len > 0) {

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

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

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

989 free(header->key);

990 }

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

992 free(header->value);

993 }

994 }

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

996 free(resp->headers);

997 }

998 }

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

1000 free(resp->body);

1001 }

1002}

1003

1004http_err_t _http_req_read(http_req_t *req, http_conn_t *conn) {

1005 int len = 0;

1006 int ln = 0;

1007 int start = 0;

1008 char buffer[HTTP_MAX_REQUEST_HEAD_SIZE];

1009 *req = (http_req_t) {

1010 .conn = conn,

1011 .method = NULL,

1012 .url = NULL,

1013 .version = NULL,

1014 .headers = NULL,

1015 .headers_len = 0,

1016 .body = NULL,

1017 .body_len = 0,

1018 .ext_data = NULL,

1019 };

1020 while (true) {

1021 char c;

1022 int read = _http_conn_read(conn, &c, 1);

1023 if (read == 0) {

1024 break;

1025 }

1026 // read timeout

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

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

1029 return SOCK_ERR_READ_TIMEOUT;

1030 }

1031 }

1032 // break if too long

1033 if (len == HTTP_MAX_REQUEST_HEAD_SIZE) {

1034 return SOCK_ERR_REQUEST_TOO_LONG;

1035 }

1036 buffer[len] = c;

1037 len++;

1038 // read head

1039 if (len >= 2) {

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

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

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

1043 if (line_len > 0) {

1044 // read line

1045 char line[line_len + 1];

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

1047 line[line_len] = '\0';

1048 // read method, url, and version

1049 if (ln == 0) {

1050 int arg = 0;

1051 int start = 0;

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

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

1054 // read method

1055 if (arg == 0) {

1056 int method_length = i - start;

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

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

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

1060 }

1061 // read url

1062 if (arg == 1) {

1063 int url_length = i - start;

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

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

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

1067 }

1068 // read version

1069 if (arg == 2) {

1070 int version_length = i - start;

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

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

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

1074 }

1075 start = i + 1;

1076 arg++;

1077 }

1078 }

1079 }

1080 // read headers

1081 else {

1082 int sep = 0;

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

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

1085 req->headers_len++;

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

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

1088 int key_len = i;

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

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

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

1092 sep = i + 2;

1093 break;

1094 }

1095 }

1096 int value_len = line_len - sep;

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

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

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

1100 }

1101 }

1102 start = len;

1103 ln++;

1104 }

1105 }

1106 // read body

1107 if (len >= 4) {

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

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

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

1111 if (content_length != NULL) {

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

1113 if (req->body_len > 0) {

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

1115 _http_conn_read(conn, req->body, req->body_len);

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

1117 }

1118 }

1119 break;

1120 }

1121 }

1122 }

1123 return HTTP_ERR_OK;

1124}

1125

1126void http_resp_write_head(http_resp_t *resp, http_conn_t *conn) {

1127 _http_conn_write(conn, resp->version, strlen(resp->version));

1128 _http_conn_write(conn, (char *) " ", 1);

1129 char status[4];

1130 snprintf(status, 4, "%d", resp->status);

1131 _http_conn_write(conn, status, strlen(status));

1132 _http_conn_write(conn, (char *) " ", 1);

1133 const char *status_message = _http_status_str(resp->status);

1134 _http_conn_write(conn, (char *) status_message, strlen(status_message));

1135 _http_conn_write(conn, (char *) "\r\n", 2);

1136 if (resp->headers_len > 0) {

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

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

1139 _http_conn_write(conn, header->key, strlen(header->key));

1140 _http_conn_write(conn, (char *) ": ", 2);

1141 _http_conn_write(conn, header->value, strlen(header->value));

1142 _http_conn_write(conn, (char *) "\r\n", 2);

1143 }

1144 }

1145 _http_conn_write(conn, (char *) "\r\n", 2);

1146}

1147

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

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

1150 _http_conn_write(conn, resp->body, resp->body_len);

1151 }

1152}

1153

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

1155 if (resp->status == __HTTP_STATUS_HANDLED) {

1156 return;

1157 }

1158 bool has_content_length = false;

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

1160 if (resp->headers_len > 0) {

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

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

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

1164 has_content_length = true;

1165 break;

1166 }

1167 }

1168 }

1169 if (!has_content_length) {

1170 char content_length[50];

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

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

1173 }

1174 }

1175 http_resp_write_head(resp, conn);

1176 http_resp_write_body(resp, conn);

1177}

1178

1179http_err_t http_bind(http_t *self, char *hostname, int port, http_host_t *hosts, int hosts_len) {

1180 return sock_bind(self->sock, hostname, port, hosts, hosts_len);

1181}

1182

1183http_err_t http_listen(http_t *self) {

1184 return sock_listen(self->sock);

1185}

1186

1187http_err_t http_bind_listen(http_t *self, char *hostname, int port) {

1188 return sock_bind_listen(self->sock, hostname, port);

1189}

1190

1191void http_close(http_t *self) {

1192 sock_close(self->sock);

1193}

1194

1195#endif // SO_HTTP_IMPL

1196#endif // _SO_HTTP_H