so://phie

tpee

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

blob: 1dbbad1c3ea0b6c77917ea029d74c14a4344bce0 (36253 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 tpee.h

19#pragma once

20

21#include <stdbool.h>

22#include <sys/socket.h>

23

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

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

26#include <openssl/ssl.h>

27

28#ifdef TPEE_IMPL

29#define SOCK_IMPL

30#endif // TPEE_IMPL

31

32// @include <sock.h>

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

34#include <sock.h>

35

36// @enum tpee_err_t

37// @desc Error code.

38typedef enum {

39 TPEE_ERR_OK = SOCK_ERR_OK,

40 TPEE_ERR__COUNT,

41} tpee_err_t;

42

43// @enum tpee_status_t

44// @desc TPEE status code.

45typedef enum {

46 TPEE_STATUS_CONTINUE = 100,

47 TPEE_STATUS_SWITCHING_PROTOCOLS = 101,

48 TPEE_STATUS_PROCESSING = 102,

49 TPEE_STATUS_EARLY_HINTS = 103,

50 TPEE_STATUS_OK = 200,

51 TPEE_STATUS_CREATED = 201,

52 TPEE_STATUS_ACCEPTED = 202,

53 TPEE_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,

54 TPEE_STATUS_NO_CONTENT = 204,

55 TPEE_STATUS_RESET_CONTENT = 205,

56 TPEE_STATUS_PARTIAL_CONTENT = 206,

57 TPEE_STATUS_MULTI_STATUS = 207,

58 TPEE_STATUS_ALREADY_REPORTED = 208,

59 TPEE_STATUS_IM_USED = 226,

60 TPEE_STATUS_MULTIPLE_CHOICES = 300,

61 TPEE_STATUS_MOVED_PERMANENTLY = 301,

62 TPEE_STATUS_FOUND = 302,

63 TPEE_STATUS_SEE_OTHER = 303,

64 TPEE_STATUS_NOT_MODIFIED = 304,

65 TPEE_STATUS_TEMPORARY_REDIRECT = 307,

66 TPEE_STATUS_PERMANENT_REDIRECT = 308,

67 TPEE_STATUS_BAD_REQUEST = 400,

68 TPEE_STATUS_UNAUTHORIZED = 401,

69 TPEE_STATUS_PAYMENT_REQUIRED = 402,

70 TPEE_STATUS_FORBIDDEN = 403,

71 TPEE_STATUS_NOT_FOUND = 404,

72 TPEE_STATUS_METHOD_NOT_ALLOWED = 405,

73 TPEE_STATUS_NOT_ACCEPTABLE = 406,

74 TPEE_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,

75 TPEE_STATUS_REQUEST_TIMEOUT = 408,

76 TPEE_STATUS_CONFLICT = 409,

77 TPEE_STATUS_GONE = 410,

78 TPEE_STATUS_LENGTH_REQUIRED = 411,

79 TPEE_STATUS_PRECONDITION_FAILED = 412,

80 TPEE_STATUS_PAYLOAD_TOO_LARGE = 413,

81 TPEE_STATUS_URI_TOO_LONG = 414,

82 TPEE_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,

83 TPEE_STATUS_RANGE_NOT_SATISFIABLE = 416,

84 TPEE_STATUS_EXPECTATION_FAILED = 417,

85 TPEE_STATUS_I_AM_A_TEAPOT = 418,

86 TPEE_STATUS_MISDIRECTED_REQUEST = 421,

87 TPEE_STATUS_UNPROCESSABLE_CONTENT = 422,

88 TPEE_STATUS_LOCKED = 423,

89 TPEE_STATUS_FAILED_DEPENDENCY = 424,

90 TPEE_STATUS_TOO_EARLY = 425,

91 TPEE_STATUS_UPGRADE_REQUIRED = 426,

92 TPEE_STATUS_PRECONDITION_REQUIRED = 428,

93 TPEE_STATUS_TOO_MANY_REQUESTS = 429,

94 TPEE_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,

95 TPEE_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,

96 TPEE_STATUS_INTERNAL_SERVER_ERROR = 500,

97 TPEE_STATUS_NOT_IMPLEMENTED = 501,

98 TPEE_STATUS_BAD_GATEWAY = 502,

99 TPEE_STATUS_SERVICE_UNAVAILABLE = 503,

100 TPEE_STATUS_GATEWAY_TIMEOUT = 504,

101 TPEE_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,

102 TPEE_STATUS_VARIANT_ALSO_NEGOTITATES = 506,

103 TPEE_STATUS_INSUFFICIENT_STORAGE = 507,

104 TPEE_STATUS_LOOP_DETECTED = 508,

105 TPEE_STATUS_NOT_EXTENDED = 510,

106 TPEE_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,

107 __TPEE_STATUS_HANDLED = 999,

108} tpee_status_t;

109

110// @type tpee_t

111// @groupdef tpee_t

112// @desc Global context struct. Implemented here {tpee}.

113typedef struct tpee tpee_t;

114

115// @type tpee_host_t

116// @desc Represents the host.

117typedef sock_host_t tpee_host_t;

118

119// @type tpee_bind_t

120// @desc Represents the binding (port).

121typedef sock_bind_t tpee_bind_t;

122

123// @type tpee_conn_t

124// @groupdef tpee_conn_t

125// @desc Represents a client connection.

126typedef sock_conn_t tpee_conn_t;

127

128// @struct tpee_header_t

129// @desc A TPEE header.

130typedef struct {

131 char *key;

132 char *value;

133} tpee_header_t;

134

135// @struct tpee_req_t

136// @groupdef tpee_req_t

137// @desc A TPEE request struct.

138typedef struct {

139 tpee_conn_t *conn;

140 char *method;

141 char *url;

142 char *version;

143 tpee_header_t *headers;

144 int headers_len;

145 char *body;

146 long body_len;

147 void *ext_data;

148} tpee_req_t;

149

150// @struct tpee_resp_t

151// @groupdef tpee_resp_t

152// @desc A TPEE response struct.

153typedef struct {

154 char *version;

155 tpee_status_t status;

156 tpee_header_t *headers;

157 int headers_len;

158 char *body;

159 long body_len;

160} tpee_resp_t;

161

162// @type tpee_global_fn_t

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

164typedef tpee_resp_t (*tpee_global_fn_t)(tpee_t *, tpee_req_t *);

165

166// @type tpee_handle_fn_t

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

168typedef tpee_resp_t (*tpee_handle_fn_t)(tpee_req_t *);

169

170// @type tpee_hook_fn_t

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

172typedef void (*tpee_hook_fn_t)(tpee_req_t *);

173

174// @struct tpee_route_t

175// @desc A route.

176typedef struct {

177 char *method;

178 char *path;

179 tpee_handle_fn_t fn;

180} tpee_route_t;

181

182// @struct tpee_pair_t

183typedef struct {

184 char *key;

185 char *value;

186} tpee_pair_t;

187

188// @struct tpee_pairs_t

189// @groupdef tpee_pairs_t

190typedef struct {

191 tpee_pair_t *pairs;

192 size_t len;

193} tpee_pairs_t;

194

195// @struct tpee

196// @group tpee_t

197// @desc Implementation of the global context struct. Type here {tpee_t}.

198struct tpee {

199 sock_t *sock;

200 tpee_global_fn_t fn;

201};

202

203// @func tpee_init

204// @group tpee_t

205// @desc Initializes global library context {tpee_t}. Free with {tpee_cleanup}.

206// @return {tpee_t} * - Returns the global library context.

207tpee_t *tpee_init(void);

208

209// @func tpee_cleanup

210// @group tpee_t

211// @desc Cleans up {tpee_t}.

212// @param {tpee_t} *self - The global library context.

213void tpee_cleanup(tpee_t *self);

214

215// @func tpee_on_global

216// @group tpee_t

217// @desc Set and override the default global route handler {_tpee_on_global}.

218// @param {tpee_t} *self - The global library context.

219// @param {tpee_global_fn_t} fn - The global route handler.

220void tpee_on_global(tpee_t *self, tpee_global_fn_t fn);

221

222// @func tpee_on_route

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

224// @desc Registers a new route.

225// @param char *method - The TPEE method.

226// @param char *url - The TPEE URL (path).

227// @param {tpee_handle_fn_t} fn - The route handler.

228void tpee_on_route(char *method, char *url, tpee_handle_fn_t fn);

229

230// @func tpee_on_default

231// @note Use macro {TPEE_DEFAULT} instead.

232// @desc Registers a fallback handler.

233// @param {tpee_handle_fn_t} fn - The route handler.

234void tpee_on_default(tpee_handle_fn_t fn);

235

236// @func tpee_on_pre_route

237// @note Use macro {TPEE_PRE_HOOK} instead.

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

239// @param {tpee_hook_fn_t} fn - The hook handler.

240void tpee_on_pre_route(tpee_hook_fn_t fn);

241

242// @func tpee_on_post_route

243// @note Use macro {TPEE_POST_HOOK} instead.

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

245// @param {tpee_hook_fn_t} fn - The hook handler.

246void tpee_on_post_route(tpee_hook_fn_t fn);

247

248// @func tpee_req_path

249// @group tpee_req_t

250// @param {tpee_req_t} *req - The TPEE request.

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

252char *tpee_req_path(tpee_req_t *req);

253

254// @func tpee_req_body

255// @group tpee_req_t

256// @param {tpee_req_t} *req - The TPEE request.

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

258char *tpee_req_body(tpee_req_t *req);

259

260// @func tpee_req_queries

261// @group tpee_req_t

262// @param {tpee_req_t} *req - The TPEE request.

263// @return {tpee_pairs_t} - Returns the request queries.

264tpee_pairs_t tpee_req_queries(tpee_req_t *req);

265

266// @func tpee_req_params

267// @group tpee_req_t

268// @param {tpee_req_t} *req - The TPEE request.

269// @return {tpee_pairs_t} - Returns the request params.

270tpee_pairs_t tpee_req_params(tpee_req_t *req);

271

272// @func tpee_pairs_get

273// @group tpee_pairs_t

274char *tpee_pairs_get(tpee_pairs_t *self, char *key);

275

276// @func tpee_pairs_has

277// @group tpee_pairs_t

278bool tpee_pairs_has(tpee_pairs_t *self, char *key);

279

280// @func tpee_pairs_free

281// @group tpee_pairs_t

282void tpee_pairs_free(tpee_pairs_t *self);

283

284// @func tpee_req_header

285// @group tpee_req_t

286// @param {tpee_req_t} *req - The TPEE request.

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

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

289char *tpee_req_header(tpee_req_t *req, char *key);

290

291// @func tpee_resp_header

292// @group tpee_resp_t

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

294// @param {tpee_resp_t} *resp - The TPEE response.

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

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

297void tpee_resp_header(tpee_resp_t *resp, char *key, char *value);

298

299// @func tpee_resp_create

300// @group tpee_resp_t

301// @desc Creates a new response with a given TPEE status. Freed with {tpee_resp_free}.

302// @param {tpee_status_t} status - The TPEE status code.

303// @return {tpee_resp_t} - Returns a TPEE response.

304tpee_resp_t tpee_resp_create(tpee_status_t status);

305

306// @func tpee_resp_body

307// @group tpee_resp_t

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

309// @param {tpee_resp_t} *resp - The TPEE response.

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

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

312void tpee_resp_body(tpee_resp_t *resp, char *body, long len);

313

314// @func tpee_req_free

315// @group tpee_req_t

316// @desc Frees a request.

317// @param {tpee_req_t} *req - The TPEE request.

318void tpee_req_free(tpee_req_t *req);

319

320// @func tpee_resp_write_head

321// @group tpee_resp_t

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

323// @param {tpee_resp_t} *resp - The TPEE response.

324// @param {tpee_conn_t} *conn - The TPEE connection.

325void tpee_resp_write_head(tpee_resp_t *resp, tpee_conn_t *conn);

326

327// @func tpee_resp_write_body

328// @group tpee_resp_t

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

330// @param {tpee_resp_t} *resp - The TPEE response.

331// @param {tpee_conn_t} *conn - The TPEE connection.

332void tpee_resp_write_body(tpee_resp_t *resp, tpee_conn_t *conn);

333

334// @func tpee_resp_write

335// @group tpee_resp_t

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

337// @param {tpee_resp_t} *resp - The TPEE response.

338// @param {tpee_conn_t} *conn - The TPEE connection.

339void tpee_resp_write(tpee_resp_t *resp, tpee_conn_t *conn);

340

341// @func tpee_resp_free

342// @group tpee_resp_t

343// @desc Frees a response.

344// @param {tpee_resp_t} *resp - The TPEE response.

345void tpee_resp_free(tpee_resp_t *resp);

346

347// @func tpee_bind

348// @group tpee_t

349// @param {tpee_t} *self - The global library context.

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

351// @param int port - The port.

352// @param {tpee_host_t} *hosts - The host to bind to.

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

354tpee_err_t tpee_bind(tpee_t *self, char *hostname, int port, tpee_host_t *hosts, int hosts_len);

355

356// @func tpee_listen

357// @group tpee_t

358// @param {tpee_t} *self - The global library context.

359tpee_err_t tpee_listen(tpee_t *self);

360

361// @func tpee_bind_listen

362// @group tpee_t

363// @param {tpee_t} *self - The global library context.

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

365// @param int port - The port.

366tpee_err_t tpee_bind_listen(tpee_t *self, char *hostname, int port);

367

368// @func tpee_close

369// @group tpee_t

370// @param {tpee_t} *self - The global library context.

371void tpee_close(tpee_t *self);

372

373// @func _tpee_req_read

374// @group tpee_req_t

375// @internal

376// @param {tpee_req_t} *req - The TPEE request.

377// @param {tpee_conn_t} *conn - The TPEE connection.

378// @return {tpee_err_t} - Returns an TPEE error code.

379tpee_err_t _tpee_req_read(tpee_req_t *req, tpee_conn_t *conn);

380

381#ifdef TPEE_IMPL

382

383#include <stdio.h>

384#include <stdlib.h>

385#include <string.h>

386#include <ctype.h>

387#include <time.h>

388#include <unistd.h>

389#include <pthread.h>

390#include <netdb.h>

391#include <poll.h>

392#include <errno.h>

393#include <signal.h>

394

395// @macro TPEE_VERSION

396// @internal

397#define TPEE_VERSION "HTTP/1.1"

398

399// @macro TPEE_MAX_REQUEST_HEAD_SIZE

400// @internal

401#define TPEE_MAX_REQUEST_HEAD_SIZE 1000000

402

403// @macro TPEE_RESP_HANDLED

404// @group tpee_resp_t

405// @desc Handled {tpee_resp_t}.

406#define TPEE_RESP_HANDLED (tpee_resp_t) { .status = __TPEE_STATUS_HANDLED }

407

408// @macro _TPEE_ON

409// @internal

410#define _TPEE_ON(method, path, fn_name) \

411 static tpee_resp_t fn_name(tpee_req_t *req); \

412 __attribute__((constructor)) \

413 static void __macro_tpee_fn_register_##fn_name() { \

414 tpee_on_route(method, path, &fn_name); \

415 } \

416 static tpee_resp_t fn_name(tpee_req_t *req)

417

418// @macro TPEE_GET

419#define TPEE_GET(path, fn_name) _TPEE_ON("GET", path, fn_name)

420

421// @macro TPEE_GET

422#define TPEE_HEAD(path, fn_name) _TPEE_ON("HEAD", path, fn_name)

423

424// @macro TPEE_POST

425#define TPEE_POST(path, fn_name) _TPEE_ON("POST", path, fn_name)

426

427// @macro TPEE_PUT

428#define TPEE_PUT(path, fn_name) _TPEE_ON("PUT", path, fn_name)

429

430// @macro TPEE_DELETE

431#define TPEE_DELETE(path, fn_name) _TPEE_ON("DELETE", path, fn_name)

432

433// @macro TPEE_CONNECT

434#define TPEE_CONNECT(path, fn_name) _TPEE_ON("CONNECT", path, fn_name)

435

436// @macro TPEE_OPTIONS

437#define TPEE_OPTIONS(path, fn_name) _TPEE_ON("OPTIONS", path, fn_name)

438

439// @macro TPEE_TRACE

440#define TPEE_TRACE(path, fn_name) _TPEE_ON("TRACE", path, fn_name)

441

442// @macro TPEE_PATCH

443#define TPEE_PATCH(path, fn_name) _TPEE_ON("PATCH", path, fn_name)

444

445// @macro TPEE_DEFAULT

446#define TPEE_DEFAULT(fn_name) \

447 static tpee_resp_t fn_name(tpee_req_t *req); \

448 __attribute__((constructor)) \

449 static void __macro_tpee_fn_register_##fn_name() { \

450 tpee_on_default(&fn_name); \

451 } \

452 static tpee_resp_t fn_name(tpee_req_t *req)

453

454// @macro TPEE_PRE_HOOK

455#define TPEE_PRE_HOOK(fn_name) \

456 static void fn_name(tpee_req_t *req); \

457 __attribute__((constructor)) \

458 static void __macro_tpee_fn_register_##fn_name() { \

459 tpee_on_pre_route(&fn_name); \

460 } \

461 static void fn_name(tpee_req_t *req)

462

463// @macro TPEE_POST_HOOK

464#define TPEE_POST_HOOK(fn_name) \

465 static void fn_name(tpee_req_t *req); \

466 __attribute__((constructor)) \

467 static void __macro_tpee_fn_register_##fn_name() { \

468 tpee_on_post_route(&fn_name); \

469 } \

470 static void fn_name(tpee_req_t *req)

471

472// @global _tpee_routes

473// @internal

474tpee_route_t *_tpee_routes = NULL;

475

476// @global _tpee_routes_len

477// @internal

478size_t _tpee_routes_len = 0;

479

480// @global _tpee_default_route

481// @internal

482tpee_handle_fn_t _tpee_default_route;

483

484// @global _tpee_pre_route

485// @internal

486tpee_hook_fn_t _tpee_pre_route;

487

488// @global _tpee_post_route

489// @internal

490tpee_hook_fn_t _tpee_post_route;

491

492// @func _tpee_on_global

493// @group tpee_t

494// @internal

495// @desc The default route handler. Can be overwritten with {tpee_on_global}.

496// @param {tpee_t} *self - The global library context.

497// @param {tpee_req_t} *req - The TPEE request.

498// @return {tpee_resp_t} - Returns a TPEE response.

499tpee_resp_t _tpee_on_global(tpee_t *self, tpee_req_t *req) {

500 (void) self;

501 tpee_resp_t resp = tpee_resp_create(TPEE_STATUS_NOT_FOUND);

502 if (_tpee_pre_route != NULL) {

503 _tpee_pre_route(req);

504 }

505 for (size_t i = 0; i < _tpee_routes_len; i++) {

506 tpee_route_t *route = &_tpee_routes[i];

507 char *path = tpee_req_path(req);

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

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

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

511 if (c == '*') {

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

513 tpee_resp_free(&resp);

514 resp = route->fn(req);

515 }

516 }

517 else {

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

519 tpee_resp_free(&resp);

520 resp = route->fn(req);

521 }

522 }

523 }

524 free(path);

525 if (resp.status != TPEE_STATUS_NOT_FOUND) {

526 if (_tpee_post_route != NULL) {

527 _tpee_post_route(req);

528 }

529 return resp;

530 }

531 }

532 if (_tpee_default_route != NULL) {

533 tpee_resp_free(&resp);

534 resp = _tpee_default_route(req);

535 }

536 if (_tpee_post_route != NULL) {

537 _tpee_post_route(req);

538 }

539 return resp;

540}

541

542// @func _tpee_on_handle

543// @internal

544sock_err_t _tpee_on_handle(sock_t *sock, tpee_conn_t *conn) {

545 tpee_t *self= (tpee_t *) sock->ext;

546 tpee_req_t req;

547 tpee_err_t err = _tpee_req_read(&req, conn);

548 if (err != TPEE_ERR_OK) {

549 return (sock_err_t) err;

550 }

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

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

553 tpee_resp_t resp = self->fn(self, &req);

554 tpee_resp_write(&resp, conn);

555 tpee_resp_free(&resp);

556 }

557 }

558 tpee_req_free(&req);

559 return (sock_err_t) TPEE_ERR_OK;

560}

561

562// @impl tpee_init

563tpee_t *tpee_init(void) {

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

565 *self = (tpee_t) {

566 .sock = sock_init(),

567 .fn = &_tpee_on_global,

568 };

569 sock_set_ext(self->sock, self);

570 sock_on_global(self->sock, _tpee_on_handle);

571 return self;

572}

573

574// @impl tpee_cleanup

575void tpee_cleanup(tpee_t *self) {

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

577 sock_cleanup(self->sock);

578 }

579 free(self);

580}

581

582// @impl tpee_on_global

583void tpee_on_global(tpee_t *self, tpee_global_fn_t fn) {

584 self->fn = fn;

585}

586

587// @impl tpee_on_route

588void tpee_on_route(char *method, char *path, tpee_handle_fn_t fn) {

589 _tpee_routes = realloc(_tpee_routes, sizeof(tpee_route_t) * (_tpee_routes_len + 1));

590 _tpee_routes[_tpee_routes_len] = (tpee_route_t) {

591 .method = method,

592 .path = path,

593 .fn = fn,

594 };

595 _tpee_routes_len++;

596}

597

598// @impl tpee_on_default

599void tpee_on_default(tpee_handle_fn_t fn) {

600 _tpee_default_route = fn;

601}

602

603// @impl tpee_on_pre_route

604void tpee_on_pre_route(tpee_hook_fn_t fn) {

605 _tpee_pre_route = fn;

606}

607

608// @impl tpee_on_post_route

609void tpee_on_post_route(tpee_hook_fn_t fn) {

610 _tpee_post_route = fn;

611}

612

613// @impl tpee_req_path

614char *tpee_req_path(tpee_req_t *req) {

615 char *uri = req->url;

616 size_t url_len = strlen(uri);

617 size_t i = 0;

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

619 size_t c = uri[i];

620 if (c == '?') {

621 break;

622 }

623 }

624 size_t len = i;

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

626 memcpy(path, uri, len);

627 path[len] = '\0';

628 return path;

629}

630

631// @impl tpee_req_body

632char *tpee_req_body(tpee_req_t *req) {

633 return req->body;

634}

635

636// @func _tpee_pair_decode

637// @internal

638char *_tpee_pair_decode(char *str, size_t len) {

639 size_t j = 0;

640 size_t k = 0;

641 char decoded[len + 1];

642 while (j < len) {

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

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

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

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

647 j += 3;

648 continue;

649 }

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

651 j++;

652 continue;

653 }

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

655 decoded[k++] = ' ';

656 j++;

657 continue;

658 }

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

660 }

661 decoded[k] = '\0';

662 size_t ret_len = strlen(decoded);

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

664 memcpy(ret, decoded, ret_len);

665 ret[ret_len] = '\0';

666 return ret;

667}

668

669// @func _tpee_pairs_init

670// @group tpee_pairs_t

671// @internal

672tpee_pairs_t _tpee_pairs_init(char *uri) {

673 tpee_pairs_t self = (tpee_pairs_t) {

674 .pairs = NULL,

675 .len = 0,

676 };

677 size_t url_len = strlen(uri);

678 size_t set = 0;

679 size_t lim = 0;

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

681 // find 'key=value' pair

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

683 size_t key_len = i - set;

684 if (key_len > 0) {

685 if (lim > set) {

686 key_len = lim - set;

687 }

688 self.pairs = realloc(self.pairs, sizeof(tpee_pair_t) * (self.len + 1));

689 tpee_pair_t *pair = &self.pairs[self.len];

690 // read key

691 pair->key = _tpee_pair_decode(uri + set, key_len);

692 pair->value = NULL;

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

694 // read value

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

696 pair->value = _tpee_pair_decode(uri + set + key_len + 1, value_len);

697 }

698 self.len++;

699 }

700 set = i + 1;

701 }

702 // find '=' delimiter

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

704 lim = i;

705 }

706 }

707 return self;

708}

709

710// @impl tpee_req_queries

711tpee_pairs_t tpee_req_queries(tpee_req_t *req) {

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

713 // skip path

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

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

716 return _tpee_pairs_init(req->url + i + 1);

717 }

718 }

719 return (tpee_pairs_t) {

720 .pairs = NULL,

721 .len = 0,

722 };

723}

724

725// @impl tpee_req_params

726tpee_pairs_t tpee_req_params(tpee_req_t *req) {

727 return _tpee_pairs_init(req->body);

728}

729

730// @impl tpee_pairs_get

731char *tpee_pairs_get(tpee_pairs_t *self, char *key) {

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

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

734 tpee_pair_t *pair = &self->pairs[i];

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

736 return pair->value;

737 }

738 }

739 }

740 return NULL;

741}

742

743// @impl tpee_pairs_has

744bool tpee_pairs_has(tpee_pairs_t *self, char *key) {

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

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

747 tpee_pair_t *pair = &self->pairs[i];

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

749 return true;

750 }

751 }

752 }

753 return false;

754}

755

756// @impl tpee_pairs_free

757void tpee_pairs_free(tpee_pairs_t *self) {

758 if (self == NULL) {

759 return;

760 }

761 if (self->len > 0) {

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

763 tpee_pair_t *pair = &self->pairs[i];

764 free(pair->key);

765 if (pair->value) {

766 free(pair->value);

767 }

768 }

769 free(self->pairs);

770 }

771}

772

773// @func _tpee_status_str

774// @internal

775const char *_tpee_status_str(tpee_status_t status) {

776 switch (status) {

777 case TPEE_STATUS_CONTINUE:

778 return "Continue";

779 case TPEE_STATUS_SWITCHING_PROTOCOLS:

780 return "Switching Protocols";

781 case TPEE_STATUS_PROCESSING:

782 return "Processing";

783 case TPEE_STATUS_EARLY_HINTS:

784 return "Early Hints";

785 case TPEE_STATUS_OK:

786 return "OK";

787 case TPEE_STATUS_CREATED:

788 return "Created";

789 case TPEE_STATUS_ACCEPTED:

790 return "Accepted";

791 case TPEE_STATUS_NON_AUTHORITATIVE_INFORMATION:

792 return "Non-Authoritative Information";

793 case TPEE_STATUS_NO_CONTENT:

794 return "No Content";

795 case TPEE_STATUS_RESET_CONTENT:

796 return "Reset Content";

797 case TPEE_STATUS_PARTIAL_CONTENT:

798 return "Partial Content";

799 case TPEE_STATUS_MULTI_STATUS:

800 return "Multi-Status";

801 case TPEE_STATUS_ALREADY_REPORTED:

802 return "Already Reported";

803 case TPEE_STATUS_IM_USED:

804 return "IM Used";

805 case TPEE_STATUS_MULTIPLE_CHOICES:

806 return "Multiple Choices";

807 case TPEE_STATUS_MOVED_PERMANENTLY:

808 return "Moved Permanently";

809 case TPEE_STATUS_FOUND:

810 return "Found";

811 case TPEE_STATUS_SEE_OTHER:

812 return "See Other";

813 case TPEE_STATUS_NOT_MODIFIED:

814 return "Not Modified";

815 case TPEE_STATUS_TEMPORARY_REDIRECT:

816 return "Temporary Redirect";

817 case TPEE_STATUS_PERMANENT_REDIRECT:

818 return "Permanent Redirect";

819 case TPEE_STATUS_BAD_REQUEST:

820 return "Bad Request";

821 case TPEE_STATUS_UNAUTHORIZED:

822 return "Unauthorized";

823 case TPEE_STATUS_PAYMENT_REQUIRED:

824 return "Payment Required";

825 case TPEE_STATUS_FORBIDDEN:

826 return "Forbidden";

827 case TPEE_STATUS_NOT_FOUND:

828 return "Not Found";

829 case TPEE_STATUS_METHOD_NOT_ALLOWED:

830 return "Method Not Allowed";

831 case TPEE_STATUS_NOT_ACCEPTABLE:

832 return "Not Acceptable";

833 case TPEE_STATUS_PROXY_AUTHENTICATION_REQUIRED:

834 return "Proxy Authentication Required";

835 case TPEE_STATUS_REQUEST_TIMEOUT:

836 return "Request Timeout";

837 case TPEE_STATUS_CONFLICT:

838 return "Conflict";

839 case TPEE_STATUS_GONE:

840 return "Gone";

841 case TPEE_STATUS_LENGTH_REQUIRED:

842 return "Length Required";

843 case TPEE_STATUS_PRECONDITION_FAILED:

844 return "Precondition Failed";

845 case TPEE_STATUS_PAYLOAD_TOO_LARGE:

846 return "Payload Too Large";

847 case TPEE_STATUS_URI_TOO_LONG:

848 return "URI Too Long";

849 case TPEE_STATUS_UNSUPPORTED_MEDIA_TYPE:

850 return "Unsupported Media Type";

851 case TPEE_STATUS_RANGE_NOT_SATISFIABLE:

852 return "Range Not Satisfiable";

853 case TPEE_STATUS_EXPECTATION_FAILED:

854 return "Expectation Failed";

855 case TPEE_STATUS_I_AM_A_TEAPOT:

856 return "I'm a teapot";

857 case TPEE_STATUS_MISDIRECTED_REQUEST:

858 return "Misdirected Request";

859 case TPEE_STATUS_UNPROCESSABLE_CONTENT:

860 return "Unprocessable Content";

861 case TPEE_STATUS_LOCKED:

862 return "Locked";

863 case TPEE_STATUS_FAILED_DEPENDENCY:

864 return "Failed Dependency";

865 case TPEE_STATUS_TOO_EARLY:

866 return "Too Early";

867 case TPEE_STATUS_UPGRADE_REQUIRED:

868 return "Upgrade Required";

869 case TPEE_STATUS_PRECONDITION_REQUIRED:

870 return "Precondition Required";

871 case TPEE_STATUS_TOO_MANY_REQUESTS:

872 return "Too Many Requests";

873 case TPEE_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

874 return "Request Header Fields Too Large";

875 case TPEE_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

876 return "Unavailable For Legal Reasons";

877 case TPEE_STATUS_INTERNAL_SERVER_ERROR:

878 return "Internal Server Error";

879 case TPEE_STATUS_NOT_IMPLEMENTED:

880 return "Not Implemented";

881 case TPEE_STATUS_BAD_GATEWAY:

882 return "Bad Gateway";

883 case TPEE_STATUS_SERVICE_UNAVAILABLE:

884 return "Service Unavailable";

885 case TPEE_STATUS_GATEWAY_TIMEOUT:

886 return "Gateway Timeout";

887 case TPEE_STATUS_HTTP_VERSION_NOT_SUPPORTED:

888 return "HTTP Version Not Supported";

889 case TPEE_STATUS_VARIANT_ALSO_NEGOTITATES:

890 return "Variant Also Negotiates";

891 case TPEE_STATUS_INSUFFICIENT_STORAGE:

892 return "Insufficient Storage";

893 case TPEE_STATUS_LOOP_DETECTED:

894 return "Loop Detected";

895 case TPEE_STATUS_NOT_EXTENDED:

896 return "Not Extended";

897 case TPEE_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

898 return "Network Authentication Required";

899 default:

900 return NULL;

901 }

902}

903

904// @func _tpee_conn_read

905// @group tpee_conn_t

906// @internal

907ssize_t _tpee_conn_read(tpee_conn_t *conn, char *buffer, size_t len) {

908 return sock_conn_read(conn, buffer, len);

909}

910

911// @func _tpee_conn_write

912// @group tpee_conn_t

913// @internal

914ssize_t _tpee_conn_write(tpee_conn_t *conn, char *buffer, size_t len) {

915 return sock_conn_write(conn, buffer, len);

916}

917

918// @impl tpee_req_header

919char *tpee_req_header(tpee_req_t *req, char *key) {

920 if (req->headers_len > 0) {

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

922 tpee_header_t *header = &req->headers[i];

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

924 return header->value;

925 }

926 }

927 }

928 return NULL;

929}

930

931// @impl tpee_resp_header

932void tpee_resp_header(tpee_resp_t *resp, char *key, char *value) {

933 resp->headers = (tpee_header_t *) realloc(resp->headers, sizeof(tpee_header_t) * (resp->headers_len + 1));

934 tpee_header_t *new_header = &resp->headers[resp->headers_len];

935 resp->headers_len++;

936 int key_len = strlen(key);

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

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

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

940 int value_len = strlen(value);

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

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

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

944}

945

946// @impl tpee_resp_create

947tpee_resp_t tpee_resp_create(tpee_status_t status) {

948 return (tpee_resp_t) {

949 .version = strdup(TPEE_VERSION),

950 .status = status,

951 .headers = NULL,

952 .headers_len = 0,

953 .body = NULL,

954 .body_len = 0,

955 };

956}

957

958// @impl tpee_resp_body

959void tpee_resp_body(tpee_resp_t *resp, char *body, long len) {

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

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

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

963 resp->body_len = len;

964 }

965}

966

967// @impl tpee_req_free

968void tpee_req_free(tpee_req_t *req) {

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

970 free(req->method);

971 }

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

973 free(req->url);

974 }

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

976 free(req->version);

977 }

978 if (req->headers_len > 0) {

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

980 tpee_header_t *header = &req->headers[i];

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

982 free(header->key);

983 }

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

985 free(header->value);

986 }

987 }

988 free(req->headers);

989 }

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

991 free(req->body);

992 }

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

994 free(req->ext_data);

995 }

996}

997

998// @impl tpee_resp_free

999void tpee_resp_free(tpee_resp_t *resp) {

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

1001 free(resp->version);

1002 }

1003 if (resp->headers_len > 0) {

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

1005 tpee_header_t *header = &resp->headers[i];

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

1007 free(header->key);

1008 }

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

1010 free(header->value);

1011 }

1012 }

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

1014 free(resp->headers);

1015 }

1016 }

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

1018 free(resp->body);

1019 }

1020}

1021

1022// @impl _tpee_req_read

1023tpee_err_t _tpee_req_read(tpee_req_t *req, tpee_conn_t *conn) {

1024 int len = 0;

1025 int ln = 0;

1026 int start = 0;

1027 char buffer[TPEE_MAX_REQUEST_HEAD_SIZE];

1028 *req = (tpee_req_t) {

1029 .conn = conn,

1030 .method = NULL,

1031 .url = NULL,

1032 .version = NULL,

1033 .headers = NULL,

1034 .headers_len = 0,

1035 .body = NULL,

1036 .body_len = 0,

1037 .ext_data = NULL,

1038 };

1039 while (true) {

1040 char c;

1041 int read = _tpee_conn_read(conn, &c, 1);

1042 if (read == 0) {

1043 break;

1044 }

1045 // read timeout

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

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

1048 return (tpee_err_t) SOCK_ERR_READ_TIMEOUT;

1049 }

1050 }

1051 // break if too long

1052 if (len == TPEE_MAX_REQUEST_HEAD_SIZE) {

1053 return (tpee_err_t) SOCK_ERR_REQUEST_TOO_LONG;

1054 }

1055 buffer[len] = c;

1056 len++;

1057 // read head

1058 if (len >= 2) {

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

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

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

1062 if (line_len > 0) {

1063 // read line

1064 char line[line_len + 1];

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

1066 line[line_len] = '\0';

1067 // read method, url, and version

1068 if (ln == 0) {

1069 int arg = 0;

1070 int start = 0;

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

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

1073 // read method

1074 if (arg == 0) {

1075 int method_length = i - start;

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

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

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

1079 }

1080 // read url

1081 if (arg == 1) {

1082 int url_length = i - start;

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

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

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

1086 }

1087 // read version

1088 if (arg == 2) {

1089 int version_length = i - start;

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

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

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

1093 }

1094 start = i + 1;

1095 arg++;

1096 }

1097 }

1098 }

1099 // read headers

1100 else {

1101 int sep = 0;

1102 req->headers = (tpee_header_t *) realloc(req->headers, sizeof(tpee_header_t) * (req->headers_len + 1));

1103 tpee_header_t *header = &req->headers[req->headers_len];

1104 req->headers_len++;

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

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

1107 int key_len = i;

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

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

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

1111 sep = i + 2;

1112 break;

1113 }

1114 }

1115 int value_len = line_len - sep;

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

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

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

1119 }

1120 }

1121 start = len;

1122 ln++;

1123 }

1124 }

1125 // read body

1126 if (len >= 4) {

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

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

1129 char *content_length = tpee_req_header(req, (char *) "Content-Length");

1130 if (content_length != NULL) {

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

1132 if (req->body_len > 0) {

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

1134 _tpee_conn_read(conn, req->body, req->body_len);

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

1136 }

1137 }

1138 break;

1139 }

1140 }

1141 }

1142 return TPEE_ERR_OK;

1143}

1144

1145// @impl tpee_resp_write_head

1146void tpee_resp_write_head(tpee_resp_t *resp, tpee_conn_t *conn) {

1147 _tpee_conn_write(conn, resp->version, strlen(resp->version));

1148 _tpee_conn_write(conn, (char *) " ", 1);

1149 char status[4];

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

1151 _tpee_conn_write(conn, status, strlen(status));

1152 _tpee_conn_write(conn, (char *) " ", 1);

1153 const char *status_message = _tpee_status_str(resp->status);

1154 _tpee_conn_write(conn, (char *) status_message, strlen(status_message));

1155 _tpee_conn_write(conn, (char *) "\r\n", 2);

1156 if (resp->headers_len > 0) {

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

1158 tpee_header_t *header = &resp->headers[i];

1159 _tpee_conn_write(conn, header->key, strlen(header->key));

1160 _tpee_conn_write(conn, (char *) ": ", 2);

1161 _tpee_conn_write(conn, header->value, strlen(header->value));

1162 _tpee_conn_write(conn, (char *) "\r\n", 2);

1163 }

1164 }

1165 _tpee_conn_write(conn, (char *) "\r\n", 2);

1166}

1167

1168// @impl tpee_resp_write_body

1169void tpee_resp_write_body(tpee_resp_t *resp, tpee_conn_t *conn) {

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

1171 _tpee_conn_write(conn, resp->body, resp->body_len);

1172 }

1173}

1174

1175// @impl tpee_resp_write

1176void tpee_resp_write(tpee_resp_t *resp, tpee_conn_t *conn) {

1177 if (resp->status == __TPEE_STATUS_HANDLED) {

1178 return;

1179 }

1180 bool has_content_length = false;

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

1182 if (resp->headers_len > 0) {

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

1184 tpee_header_t *header = &resp->headers[i];

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

1186 has_content_length = true;

1187 break;

1188 }

1189 }

1190 }

1191 if (!has_content_length) {

1192 char content_length[50];

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

1194 tpee_resp_header(resp, (char *) "Content-Length", content_length);

1195 }

1196 }

1197 tpee_resp_write_head(resp, conn);

1198 tpee_resp_write_body(resp, conn);

1199}

1200

1201// @impl tpee_bind

1202tpee_err_t tpee_bind(tpee_t *self, char *hostname, int port, tpee_host_t *hosts, int hosts_len) {

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

1204}

1205

1206// @impl tpee_listen

1207tpee_err_t tpee_listen(tpee_t *self) {

1208 return (tpee_err_t) sock_listen(self->sock);

1209}

1210

1211// @impl tpee_bind_listen

1212tpee_err_t tpee_bind_listen(tpee_t *self, char *hostname, int port) {

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

1214}

1215

1216// @impl tpee_close

1217void tpee_close(tpee_t *self) {

1218 sock_close(self->sock);

1219}

1220

1221#endif // TPEE_IMPL