so://phie

tpee

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

blob: 5095a59e521c3304577c20c0000a34b3d4a209d8 (36819 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_conn_read

285// @group tpee_conn_t

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

287// @param char * - The buffer to read into.

288// @param size_t - The size of the buffer.

289ssize_t tpee_conn_read(tpee_conn_t *conn, char *buffer, size_t len);

290

291// @func tpee_conn_write

292// @group tpee_conn_t

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

294// @param char * - The buffer to be written.

295// @param size_t - The size of the buffer.

296ssize_t tpee_conn_write(tpee_conn_t *conn, char *buffer, size_t len);

297

298// @func tpee_req_header

299// @group tpee_req_t

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

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

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

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

304

305// @func tpee_resp_header

306// @group tpee_resp_t

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

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

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

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

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

312

313// @func tpee_resp_create

314// @group tpee_resp_t

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

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

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

318tpee_resp_t tpee_resp_create(tpee_status_t status);

319

320// @func tpee_resp_body

321// @group tpee_resp_t

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

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

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

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

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

327

328// @func tpee_req_free

329// @group tpee_req_t

330// @desc Frees a request.

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

332void tpee_req_free(tpee_req_t *req);

333

334// @func tpee_resp_write_head

335// @group tpee_resp_t

336// @desc Writes a response header 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_head(tpee_resp_t *resp, tpee_conn_t *conn);

340

341// @func tpee_resp_write_body

342// @group tpee_resp_t

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

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

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

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

347

348// @func tpee_resp_write

349// @group tpee_resp_t

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

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

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

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

354

355// @func tpee_resp_free

356// @group tpee_resp_t

357// @desc Frees a response.

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

359void tpee_resp_free(tpee_resp_t *resp);

360

361// @func tpee_bind

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.

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

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

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

369

370// @func tpee_listen

371// @group tpee_t

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

373tpee_err_t tpee_listen(tpee_t *self);

374

375// @func tpee_bind_listen

376// @group tpee_t

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

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

379// @param int port - The port.

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

381

382// @func tpee_close

383// @group tpee_t

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

385void tpee_close(tpee_t *self);

386

387// @func _tpee_req_read

388// @group tpee_req_t

389// @internal

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

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

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

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

394

395#ifdef TPEE_IMPL

396

397#include <stdio.h>

398#include <stdlib.h>

399#include <string.h>

400#include <ctype.h>

401#include <time.h>

402#include <unistd.h>

403#include <pthread.h>

404#include <netdb.h>

405#include <poll.h>

406#include <errno.h>

407#include <signal.h>

408

409// @macro TPEE_VERSION

410// @internal

411#define TPEE_VERSION "HTTP/1.1"

412

413// @macro TPEE_MAX_REQUEST_HEAD_SIZE

414// @internal

415#define TPEE_MAX_REQUEST_HEAD_SIZE 1000000

416

417// @macro TPEE_RESP_HANDLED

418// @group tpee_resp_t

419// @desc Handled {tpee_resp_t}.

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

421

422// @macro _TPEE_ON

423// @internal

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

425 static tpee_resp_t fn_name(tpee_req_t *req); \

426 __attribute__((constructor)) \

427 static void __macro_tpee_fn_register_##fn_name(void) { \

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

429 } \

430 static tpee_resp_t fn_name(tpee_req_t *req)

431

432// @macro TPEE_GET

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

434

435// @macro TPEE_GET

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

437

438// @macro TPEE_POST

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

440

441// @macro TPEE_PUT

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

443

444// @macro TPEE_DELETE

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

446

447// @macro TPEE_CONNECT

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

449

450// @macro TPEE_OPTIONS

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

452

453// @macro TPEE_TRACE

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

455

456// @macro TPEE_PATCH

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

458

459// @macro TPEE_DEFAULT

460#define TPEE_DEFAULT(fn_name) \

461 static tpee_resp_t fn_name(tpee_req_t *req); \

462 __attribute__((constructor)) \

463 static void __macro_tpee_fn_register_##fn_name(void) { \

464 tpee_on_default(&fn_name); \

465 } \

466 static tpee_resp_t fn_name(tpee_req_t *req)

467

468// @macro TPEE_PRE_HOOK

469#define TPEE_PRE_HOOK(fn_name) \

470 static void fn_name(tpee_req_t *req); \

471 __attribute__((constructor)) \

472 static void __macro_tpee_fn_register_##fn_name(void) { \

473 tpee_on_pre_route(&fn_name); \

474 } \

475 static void fn_name(tpee_req_t *req)

476

477// @macro TPEE_POST_HOOK

478#define TPEE_POST_HOOK(fn_name) \

479 static void fn_name(tpee_req_t *req); \

480 __attribute__((constructor)) \

481 static void __macro_tpee_fn_register_##fn_name(void) { \

482 tpee_on_post_route(&fn_name); \

483 } \

484 static void fn_name(tpee_req_t *req)

485

486// @global _tpee_routes

487// @internal

488tpee_route_t *_tpee_routes = NULL;

489

490// @global _tpee_routes_len

491// @internal

492size_t _tpee_routes_len = 0;

493

494// @global _tpee_default_route

495// @internal

496tpee_handle_fn_t _tpee_default_route;

497

498// @global _tpee_pre_route

499// @internal

500tpee_hook_fn_t _tpee_pre_route;

501

502// @global _tpee_post_route

503// @internal

504tpee_hook_fn_t _tpee_post_route;

505

506// @func _tpee_on_global

507// @group tpee_t

508// @internal

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

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

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

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

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

514 (void) self;

515 tpee_resp_t resp = tpee_resp_create(TPEE_STATUS_NOT_FOUND);

516 if (_tpee_pre_route != NULL) {

517 _tpee_pre_route(req);

518 }

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

520 tpee_route_t *route = &_tpee_routes[i];

521 char *path = tpee_req_path(req);

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

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

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

525 if (c == '*') {

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

527 tpee_resp_free(&resp);

528 resp = route->fn(req);

529 }

530 }

531 else {

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

533 tpee_resp_free(&resp);

534 resp = route->fn(req);

535 }

536 }

537 }

538 free(path);

539 if (resp.status != TPEE_STATUS_NOT_FOUND) {

540 if (_tpee_post_route != NULL) {

541 _tpee_post_route(req);

542 }

543 return resp;

544 }

545 }

546 if (_tpee_default_route != NULL) {

547 tpee_resp_free(&resp);

548 resp = _tpee_default_route(req);

549 }

550 if (_tpee_post_route != NULL) {

551 _tpee_post_route(req);

552 }

553 return resp;

554}

555

556// @func _tpee_on_handle

557// @internal

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

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

560 tpee_req_t req;

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

562 if (err != TPEE_ERR_OK) {

563 return (sock_err_t) err;

564 }

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

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

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

568 tpee_resp_write(&resp, conn);

569 tpee_resp_free(&resp);

570 }

571 }

572 tpee_req_free(&req);

573 return (sock_err_t) TPEE_ERR_OK;

574}

575

576// @impl tpee_init

577tpee_t *tpee_init(void) {

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

579 *self = (tpee_t) {

580 .sock = sock_init(),

581 .fn = &_tpee_on_global,

582 };

583 sock_set_ext(self->sock, self);

584 sock_on_global(self->sock, _tpee_on_handle);

585 return self;

586}

587

588// @impl tpee_cleanup

589void tpee_cleanup(tpee_t *self) {

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

591 sock_cleanup(self->sock);

592 }

593 if (_tpee_routes != NULL && _tpee_routes_len > 0) {

594 free(_tpee_routes);

595 _tpee_routes = NULL;

596 _tpee_routes_len = 0;

597 }

598 free(self);

599}

600

601// @impl tpee_on_global

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

603 self->fn = fn;

604}

605

606// @impl tpee_on_route

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

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

609 _tpee_routes[_tpee_routes_len] = (tpee_route_t) {

610 .method = method,

611 .path = path,

612 .fn = fn,

613 };

614 _tpee_routes_len++;

615}

616

617// @impl tpee_on_default

618void tpee_on_default(tpee_handle_fn_t fn) {

619 _tpee_default_route = fn;

620}

621

622// @impl tpee_on_pre_route

623void tpee_on_pre_route(tpee_hook_fn_t fn) {

624 _tpee_pre_route = fn;

625}

626

627// @impl tpee_on_post_route

628void tpee_on_post_route(tpee_hook_fn_t fn) {

629 _tpee_post_route = fn;

630}

631

632// @impl tpee_req_path

633char *tpee_req_path(tpee_req_t *req) {

634 char *uri = req->url;

635 size_t url_len = strlen(uri);

636 size_t i = 0;

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

638 size_t c = uri[i];

639 if (c == '?') {

640 break;

641 }

642 }

643 size_t len = i;

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

645 memcpy(path, uri, len);

646 path[len] = '\0';

647 return path;

648}

649

650// @impl tpee_req_body

651char *tpee_req_body(tpee_req_t *req) {

652 return req->body;

653}

654

655// @func _tpee_pair_decode

656// @internal

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

658 size_t j = 0;

659 size_t k = 0;

660 char decoded[len + 1];

661 while (j < len) {

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

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

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

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

666 j += 3;

667 continue;

668 }

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

670 j++;

671 continue;

672 }

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

674 decoded[k++] = ' ';

675 j++;

676 continue;

677 }

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

679 }

680 decoded[k] = '\0';

681 size_t ret_len = strlen(decoded);

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

683 memcpy(ret, decoded, ret_len);

684 ret[ret_len] = '\0';

685 return ret;

686}

687

688// @func _tpee_pairs_init

689// @group tpee_pairs_t

690// @internal

691tpee_pairs_t _tpee_pairs_init(char *uri) {

692 tpee_pairs_t self = (tpee_pairs_t) {

693 .pairs = NULL,

694 .len = 0,

695 };

696 size_t url_len = strlen(uri);

697 size_t set = 0;

698 size_t lim = 0;

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

700 // find 'key=value' pair

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

702 size_t key_len = i - set;

703 if (key_len > 0) {

704 if (lim > set) {

705 key_len = lim - set;

706 }

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

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

709 // read key

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

711 pair->value = NULL;

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

713 // read value

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

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

716 }

717 self.len++;

718 }

719 set = i + 1;

720 }

721 // find '=' delimiter

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

723 lim = i;

724 }

725 }

726 return self;

727}

728

729// @impl tpee_req_queries

730tpee_pairs_t tpee_req_queries(tpee_req_t *req) {

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

732 // skip path

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

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

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

736 }

737 }

738 return (tpee_pairs_t) {

739 .pairs = NULL,

740 .len = 0,

741 };

742}

743

744// @impl tpee_req_params

745tpee_pairs_t tpee_req_params(tpee_req_t *req) {

746 return _tpee_pairs_init(req->body);

747}

748

749// @impl tpee_pairs_get

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

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

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

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

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

755 return pair->value;

756 }

757 }

758 }

759 return NULL;

760}

761

762// @impl tpee_pairs_has

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

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

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

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

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

768 return true;

769 }

770 }

771 }

772 return false;

773}

774

775// @impl tpee_pairs_free

776void tpee_pairs_free(tpee_pairs_t *self) {

777 if (self == NULL) {

778 return;

779 }

780 if (self->len > 0) {

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

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

783 free(pair->key);

784 if (pair->value) {

785 free(pair->value);

786 }

787 }

788 free(self->pairs);

789 }

790}

791

792// @func _tpee_status_str

793// @internal

794const char *_tpee_status_str(tpee_status_t status) {

795 switch (status) {

796 case TPEE_STATUS_CONTINUE:

797 return "Continue";

798 case TPEE_STATUS_SWITCHING_PROTOCOLS:

799 return "Switching Protocols";

800 case TPEE_STATUS_PROCESSING:

801 return "Processing";

802 case TPEE_STATUS_EARLY_HINTS:

803 return "Early Hints";

804 case TPEE_STATUS_OK:

805 return "OK";

806 case TPEE_STATUS_CREATED:

807 return "Created";

808 case TPEE_STATUS_ACCEPTED:

809 return "Accepted";

810 case TPEE_STATUS_NON_AUTHORITATIVE_INFORMATION:

811 return "Non-Authoritative Information";

812 case TPEE_STATUS_NO_CONTENT:

813 return "No Content";

814 case TPEE_STATUS_RESET_CONTENT:

815 return "Reset Content";

816 case TPEE_STATUS_PARTIAL_CONTENT:

817 return "Partial Content";

818 case TPEE_STATUS_MULTI_STATUS:

819 return "Multi-Status";

820 case TPEE_STATUS_ALREADY_REPORTED:

821 return "Already Reported";

822 case TPEE_STATUS_IM_USED:

823 return "IM Used";

824 case TPEE_STATUS_MULTIPLE_CHOICES:

825 return "Multiple Choices";

826 case TPEE_STATUS_MOVED_PERMANENTLY:

827 return "Moved Permanently";

828 case TPEE_STATUS_FOUND:

829 return "Found";

830 case TPEE_STATUS_SEE_OTHER:

831 return "See Other";

832 case TPEE_STATUS_NOT_MODIFIED:

833 return "Not Modified";

834 case TPEE_STATUS_TEMPORARY_REDIRECT:

835 return "Temporary Redirect";

836 case TPEE_STATUS_PERMANENT_REDIRECT:

837 return "Permanent Redirect";

838 case TPEE_STATUS_BAD_REQUEST:

839 return "Bad Request";

840 case TPEE_STATUS_UNAUTHORIZED:

841 return "Unauthorized";

842 case TPEE_STATUS_PAYMENT_REQUIRED:

843 return "Payment Required";

844 case TPEE_STATUS_FORBIDDEN:

845 return "Forbidden";

846 case TPEE_STATUS_NOT_FOUND:

847 return "Not Found";

848 case TPEE_STATUS_METHOD_NOT_ALLOWED:

849 return "Method Not Allowed";

850 case TPEE_STATUS_NOT_ACCEPTABLE:

851 return "Not Acceptable";

852 case TPEE_STATUS_PROXY_AUTHENTICATION_REQUIRED:

853 return "Proxy Authentication Required";

854 case TPEE_STATUS_REQUEST_TIMEOUT:

855 return "Request Timeout";

856 case TPEE_STATUS_CONFLICT:

857 return "Conflict";

858 case TPEE_STATUS_GONE:

859 return "Gone";

860 case TPEE_STATUS_LENGTH_REQUIRED:

861 return "Length Required";

862 case TPEE_STATUS_PRECONDITION_FAILED:

863 return "Precondition Failed";

864 case TPEE_STATUS_PAYLOAD_TOO_LARGE:

865 return "Payload Too Large";

866 case TPEE_STATUS_URI_TOO_LONG:

867 return "URI Too Long";

868 case TPEE_STATUS_UNSUPPORTED_MEDIA_TYPE:

869 return "Unsupported Media Type";

870 case TPEE_STATUS_RANGE_NOT_SATISFIABLE:

871 return "Range Not Satisfiable";

872 case TPEE_STATUS_EXPECTATION_FAILED:

873 return "Expectation Failed";

874 case TPEE_STATUS_I_AM_A_TEAPOT:

875 return "I'm a teapot";

876 case TPEE_STATUS_MISDIRECTED_REQUEST:

877 return "Misdirected Request";

878 case TPEE_STATUS_UNPROCESSABLE_CONTENT:

879 return "Unprocessable Content";

880 case TPEE_STATUS_LOCKED:

881 return "Locked";

882 case TPEE_STATUS_FAILED_DEPENDENCY:

883 return "Failed Dependency";

884 case TPEE_STATUS_TOO_EARLY:

885 return "Too Early";

886 case TPEE_STATUS_UPGRADE_REQUIRED:

887 return "Upgrade Required";

888 case TPEE_STATUS_PRECONDITION_REQUIRED:

889 return "Precondition Required";

890 case TPEE_STATUS_TOO_MANY_REQUESTS:

891 return "Too Many Requests";

892 case TPEE_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

893 return "Request Header Fields Too Large";

894 case TPEE_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

895 return "Unavailable For Legal Reasons";

896 case TPEE_STATUS_INTERNAL_SERVER_ERROR:

897 return "Internal Server Error";

898 case TPEE_STATUS_NOT_IMPLEMENTED:

899 return "Not Implemented";

900 case TPEE_STATUS_BAD_GATEWAY:

901 return "Bad Gateway";

902 case TPEE_STATUS_SERVICE_UNAVAILABLE:

903 return "Service Unavailable";

904 case TPEE_STATUS_GATEWAY_TIMEOUT:

905 return "Gateway Timeout";

906 case TPEE_STATUS_HTTP_VERSION_NOT_SUPPORTED:

907 return "HTTP Version Not Supported";

908 case TPEE_STATUS_VARIANT_ALSO_NEGOTITATES:

909 return "Variant Also Negotiates";

910 case TPEE_STATUS_INSUFFICIENT_STORAGE:

911 return "Insufficient Storage";

912 case TPEE_STATUS_LOOP_DETECTED:

913 return "Loop Detected";

914 case TPEE_STATUS_NOT_EXTENDED:

915 return "Not Extended";

916 case TPEE_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

917 return "Network Authentication Required";

918 default:

919 return NULL;

920 }

921}

922

923// @impl tpee_conn_read

924ssize_t tpee_conn_read(tpee_conn_t *conn, char *buffer, size_t len) {

925 return sock_conn_read(conn, buffer, len);

926}

927

928// @impl tpee_conn_write

929ssize_t tpee_conn_write(tpee_conn_t *conn, char *buffer, size_t len) {

930 return sock_conn_write(conn, buffer, len);

931}

932

933// @impl tpee_req_header

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

935 if (req->headers_len > 0) {

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

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

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

939 return header->value;

940 }

941 }

942 }

943 return NULL;

944}

945

946// @impl tpee_resp_header

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

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

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

950 resp->headers_len++;

951 int key_len = strlen(key);

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

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

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

955 int value_len = strlen(value);

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

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

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

959}

960

961// @impl tpee_resp_create

962tpee_resp_t tpee_resp_create(tpee_status_t status) {

963 return (tpee_resp_t) {

964 .version = strdup(TPEE_VERSION),

965 .status = status,

966 .headers = NULL,

967 .headers_len = 0,

968 .body = NULL,

969 .body_len = 0,

970 };

971}

972

973// @impl tpee_resp_body

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

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

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

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

978 resp->body_len = len;

979 }

980}

981

982// @impl tpee_req_free

983void tpee_req_free(tpee_req_t *req) {

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

985 free(req->method);

986 }

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

988 free(req->url);

989 }

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

991 free(req->version);

992 }

993 if (req->headers_len > 0) {

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

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

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

997 free(header->key);

998 }

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

1000 free(header->value);

1001 }

1002 }

1003 free(req->headers);

1004 }

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

1006 free(req->body);

1007 }

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

1009 free(req->ext_data);

1010 }

1011}

1012

1013// @impl tpee_resp_free

1014void tpee_resp_free(tpee_resp_t *resp) {

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

1016 free(resp->version);

1017 }

1018 if (resp->headers_len > 0) {

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

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

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

1022 free(header->key);

1023 }

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

1025 free(header->value);

1026 }

1027 }

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

1029 free(resp->headers);

1030 }

1031 }

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

1033 free(resp->body);

1034 }

1035}

1036

1037// @impl _tpee_req_read

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

1039 int len = 0;

1040 int ln = 0;

1041 int start = 0;

1042 char buffer[TPEE_MAX_REQUEST_HEAD_SIZE];

1043 *req = (tpee_req_t) {

1044 .conn = conn,

1045 .method = NULL,

1046 .url = NULL,

1047 .version = NULL,

1048 .headers = NULL,

1049 .headers_len = 0,

1050 .body = NULL,

1051 .body_len = 0,

1052 .ext_data = NULL,

1053 };

1054 while (true) {

1055 char c;

1056 int read = tpee_conn_read(conn, &c, 1);

1057 if (read == 0) {

1058 break;

1059 }

1060 // read timeout

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

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

1063 return (tpee_err_t) SOCK_ERR_READ_TIMEOUT;

1064 }

1065 }

1066 // break if too long

1067 if (len == TPEE_MAX_REQUEST_HEAD_SIZE) {

1068 return (tpee_err_t) SOCK_ERR_REQUEST_TOO_LONG;

1069 }

1070 buffer[len] = c;

1071 len++;

1072 // read head

1073 if (len >= 2) {

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

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

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

1077 if (line_len > 0) {

1078 // read line

1079 char line[line_len + 1];

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

1081 line[line_len] = '\0';

1082 // read method, url, and version

1083 if (ln == 0) {

1084 int arg = 0;

1085 int start = 0;

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

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

1088 // read method

1089 if (arg == 0) {

1090 int method_length = i - start;

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

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

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

1094 }

1095 // read url

1096 if (arg == 1) {

1097 int url_length = i - start;

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

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

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

1101 }

1102 // read version

1103 if (arg == 2) {

1104 int version_length = i - start;

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

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

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

1108 }

1109 start = i + 1;

1110 arg++;

1111 }

1112 }

1113 }

1114 // read headers

1115 else {

1116 int sep = 0;

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

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

1119 req->headers_len++;

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

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

1122 int key_len = i;

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

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

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

1126 sep = i + 2;

1127 break;

1128 }

1129 }

1130 int value_len = line_len - sep;

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

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

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

1134 }

1135 }

1136 start = len;

1137 ln++;

1138 }

1139 }

1140 // read body

1141 if (len >= 4) {

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

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

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

1145 if (content_length != NULL) {

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

1147 if (req->body_len > 0) {

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

1149 tpee_conn_read(conn, req->body, req->body_len);

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

1151 }

1152 }

1153 break;

1154 }

1155 }

1156 }

1157 return TPEE_ERR_OK;

1158}

1159

1160// @impl tpee_resp_write_head

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

1162 tpee_conn_write(conn, resp->version, strlen(resp->version));

1163 tpee_conn_write(conn, (char *) " ", 1);

1164 char status[4];

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

1166 tpee_conn_write(conn, status, strlen(status));

1167 tpee_conn_write(conn, (char *) " ", 1);

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

1169 tpee_conn_write(conn, (char *) status_message, strlen(status_message));

1170 tpee_conn_write(conn, (char *) "\r\n", 2);

1171 if (resp->headers_len > 0) {

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

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

1174 tpee_conn_write(conn, header->key, strlen(header->key));

1175 tpee_conn_write(conn, (char *) ": ", 2);

1176 tpee_conn_write(conn, header->value, strlen(header->value));

1177 tpee_conn_write(conn, (char *) "\r\n", 2);

1178 }

1179 }

1180 tpee_conn_write(conn, (char *) "\r\n", 2);

1181}

1182

1183// @impl tpee_resp_write_body

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

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

1186 tpee_conn_write(conn, resp->body, resp->body_len);

1187 }

1188}

1189

1190// @impl tpee_resp_write

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

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

1193 return;

1194 }

1195 bool has_content_length = false;

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

1197 if (resp->headers_len > 0) {

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

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

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

1201 has_content_length = true;

1202 break;

1203 }

1204 }

1205 }

1206 if (!has_content_length) {

1207 char content_length[50];

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

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

1210 }

1211 }

1212 tpee_resp_write_head(resp, conn);

1213 tpee_resp_write_body(resp, conn);

1214}

1215

1216// @impl tpee_bind

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

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

1219}

1220

1221// @impl tpee_listen

1222tpee_err_t tpee_listen(tpee_t *self) {

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

1224}

1225

1226// @impl tpee_bind_listen

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

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

1229}

1230

1231// @impl tpee_close

1232void tpee_close(tpee_t *self) {

1233 sock_close(self->sock);

1234}

1235

1236#endif // TPEE_IMPL