so://phie

tpee

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

blob: d9f9bf429de5158e3ccefdd6661b26e69bb7578a (36227 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

20#ifndef _SO_TPEE_H

21#define _SO_TPEE_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_TPEE_IMPL

31#define SO_SOCK_IMPL

32#endif // SO_TPEE_IMPL

33

34// @include <sock.h>

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

36#include <sock.h>

37

38// @enum tpee_err_t

39// @desc Error code.

40typedef enum {

41 TPEE_ERR_OK = SOCK_ERR_OK,

42 TPEE_ERR__COUNT,

43} tpee_err_t;

44

45// @enum tpee_status_t

46// @desc TPEE status code.

47typedef enum {

48 TPEE_STATUS_CONTINUE = 100,

49 TPEE_STATUS_SWITCHING_PROTOCOLS = 101,

50 TPEE_STATUS_PROCESSING = 102,

51 TPEE_STATUS_EARLY_HINTS = 103,

52 TPEE_STATUS_OK = 200,

53 TPEE_STATUS_CREATED = 201,

54 TPEE_STATUS_ACCEPTED = 202,

55 TPEE_STATUS_NON_AUTHORITATIVE_INFORMATION = 203,

56 TPEE_STATUS_NO_CONTENT = 204,

57 TPEE_STATUS_RESET_CONTENT = 205,

58 TPEE_STATUS_PARTIAL_CONTENT = 206,

59 TPEE_STATUS_MULTI_STATUS = 207,

60 TPEE_STATUS_ALREADY_REPORTED = 208,

61 TPEE_STATUS_IM_USED = 226,

62 TPEE_STATUS_MULTIPLE_CHOICES = 300,

63 TPEE_STATUS_MOVED_PERMANENTLY = 301,

64 TPEE_STATUS_FOUND = 302,

65 TPEE_STATUS_SEE_OTHER = 303,

66 TPEE_STATUS_NOT_MODIFIED = 304,

67 TPEE_STATUS_TEMPORARY_REDIRECT = 307,

68 TPEE_STATUS_PERMANENT_REDIRECT = 308,

69 TPEE_STATUS_BAD_REQUEST = 400,

70 TPEE_STATUS_UNAUTHORIZED = 401,

71 TPEE_STATUS_PAYMENT_REQUIRED = 402,

72 TPEE_STATUS_FORBIDDEN = 403,

73 TPEE_STATUS_NOT_FOUND = 404,

74 TPEE_STATUS_METHOD_NOT_ALLOWED = 405,

75 TPEE_STATUS_NOT_ACCEPTABLE = 406,

76 TPEE_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407,

77 TPEE_STATUS_REQUEST_TIMEOUT = 408,

78 TPEE_STATUS_CONFLICT = 409,

79 TPEE_STATUS_GONE = 410,

80 TPEE_STATUS_LENGTH_REQUIRED = 411,

81 TPEE_STATUS_PRECONDITION_FAILED = 412,

82 TPEE_STATUS_PAYLOAD_TOO_LARGE = 413,

83 TPEE_STATUS_URI_TOO_LONG = 414,

84 TPEE_STATUS_UNSUPPORTED_MEDIA_TYPE = 415,

85 TPEE_STATUS_RANGE_NOT_SATISFIABLE = 416,

86 TPEE_STATUS_EXPECTATION_FAILED = 417,

87 TPEE_STATUS_I_AM_A_TEAPOT = 418,

88 TPEE_STATUS_MISDIRECTED_REQUEST = 421,

89 TPEE_STATUS_UNPROCESSABLE_CONTENT = 422,

90 TPEE_STATUS_LOCKED = 423,

91 TPEE_STATUS_FAILED_DEPENDENCY = 424,

92 TPEE_STATUS_TOO_EARLY = 425,

93 TPEE_STATUS_UPGRADE_REQUIRED = 426,

94 TPEE_STATUS_PRECONDITION_REQUIRED = 428,

95 TPEE_STATUS_TOO_MANY_REQUESTS = 429,

96 TPEE_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,

97 TPEE_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451,

98 TPEE_STATUS_INTERNAL_SERVER_ERROR = 500,

99 TPEE_STATUS_NOT_IMPLEMENTED = 501,

100 TPEE_STATUS_BAD_GATEWAY = 502,

101 TPEE_STATUS_SERVICE_UNAVAILABLE = 503,

102 TPEE_STATUS_GATEWAY_TIMEOUT = 504,

103 TPEE_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505,

104 TPEE_STATUS_VARIANT_ALSO_NEGOTITATES = 506,

105 TPEE_STATUS_INSUFFICIENT_STORAGE = 507,

106 TPEE_STATUS_LOOP_DETECTED = 508,

107 TPEE_STATUS_NOT_EXTENDED = 510,

108 TPEE_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511,

109 __TPEE_STATUS_HANDLED = 999,

110} tpee_status_t;

111

112// @type tpee_t

113// @groupdef tpee_t

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

115typedef struct tpee tpee_t;

116

117// @type tpee_host_t

118// @desc Represents the host.

119typedef sock_host_t tpee_host_t;

120

121// @type tpee_bind_t

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

123typedef sock_bind_t tpee_bind_t;

124

125// @type tpee_conn_t

126// @groupdef tpee_conn_t

127// @desc Represents a client connection.

128typedef sock_conn_t tpee_conn_t;

129

130// @struct tpee_header_t

131// @desc A TPEE header.

132typedef struct {

133 char *key;

134 char *value;

135} tpee_header_t;

136

137// @struct tpee_req_t

138// @groupdef tpee_req_t

139// @desc A TPEE request struct.

140typedef struct {

141 tpee_conn_t *conn;

142 char *method;

143 char *url;

144 char *version;

145 tpee_header_t *headers;

146 int headers_len;

147 char *body;

148 long body_len;

149 void *ext_data;

150} tpee_req_t;

151

152// @struct tpee_resp_t

153// @groupdef tpee_resp_t

154// @desc A TPEE response struct.

155typedef struct {

156 char *version;

157 tpee_status_t status;

158 tpee_header_t *headers;

159 int headers_len;

160 char *body;

161 long body_len;

162} tpee_resp_t;

163

164// @type tpee_global_fn_t

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

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

167

168// @type tpee_handle_fn_t

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

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

171

172// @type tpee_hook_fn_t

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

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

175

176// @struct tpee_route_t

177// @desc A route.

178typedef struct {

179 char *method;

180 char *path;

181 tpee_handle_fn_t fn;

182} tpee_route_t;

183

184// @struct tpee_pair_t

185typedef struct {

186 char *key;

187 char *value;

188} tpee_pair_t;

189

190// @struct tpee_pairs_t

191// @groupdef tpee_pairs_t

192typedef struct {

193 tpee_pair_t *pairs;

194 size_t len;

195} tpee_pairs_t;

196

197// @struct tpee

198// @group tpee_t

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

200struct tpee {

201 sock_t *sock;

202 tpee_global_fn_t fn;

203};

204

205// @func tpee_init

206// @group tpee_t

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

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

209tpee_t *tpee_init(void);

210

211// @func tpee_cleanup

212// @group tpee_t

213// @desc Cleans up {tpee_t}.

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

215void tpee_cleanup(tpee_t *self);

216

217// @func tpee_on_global

218// @group tpee_t

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

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

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

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

223

224// @func tpee_on_route

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

226// @desc Registers a new route.

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

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

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

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

231

232// @func tpee_on_default

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

234// @desc Registers a fallback handler.

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

236void tpee_on_default(tpee_handle_fn_t fn);

237

238// @func tpee_on_pre_route

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

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

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

242void tpee_on_pre_route(tpee_hook_fn_t fn);

243

244// @func tpee_on_post_route

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

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

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

248void tpee_on_post_route(tpee_hook_fn_t fn);

249

250// @func tpee_req_path

251// @group tpee_req_t

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

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

254char *tpee_req_path(tpee_req_t *req);

255

256// @func tpee_req_body

257// @group tpee_req_t

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

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

260char *tpee_req_body(tpee_req_t *req);

261

262// @func tpee_req_queries

263// @group tpee_req_t

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

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

266tpee_pairs_t tpee_req_queries(tpee_req_t *req);

267

268// @func tpee_req_params

269// @group tpee_req_t

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

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

272tpee_pairs_t tpee_req_params(tpee_req_t *req);

273

274// @func tpee_pairs_get

275// @group tpee_pairs_t

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

277

278// @func tpee_pairs_has

279// @group tpee_pairs_t

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

281

282// @func tpee_pairs_free

283// @group tpee_pairs_t

284void tpee_pairs_free(tpee_pairs_t *self);

285

286// @func tpee_req_header

287// @group tpee_req_t

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

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

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

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

292

293// @func tpee_resp_header

294// @group tpee_resp_t

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

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

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

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

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

300

301// @func tpee_resp_create

302// @group tpee_resp_t

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

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

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

306tpee_resp_t tpee_resp_create(tpee_status_t status);

307

308// @func tpee_resp_body

309// @group tpee_resp_t

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

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

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

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

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

315

316// @func tpee_req_free

317// @group tpee_req_t

318// @desc Frees a request.

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

320void tpee_req_free(tpee_req_t *req);

321

322// @func tpee_resp_write_head

323// @group tpee_resp_t

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

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

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

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

328

329// @func tpee_resp_write_body

330// @group tpee_resp_t

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

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

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

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

335

336// @func tpee_resp_write

337// @group tpee_resp_t

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

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

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

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

342

343// @func tpee_resp_free

344// @group tpee_resp_t

345// @desc Frees a response.

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

347void tpee_resp_free(tpee_resp_t *resp);

348

349// @func tpee_bind

350// @group tpee_t

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

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

353// @param int port - The port.

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

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

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

357

358// @func tpee_listen

359// @group tpee_t

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

361tpee_err_t tpee_listen(tpee_t *self);

362

363// @func tpee_bind_listen

364// @group tpee_t

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

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

367// @param int port - The port.

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

369

370// @func tpee_close

371// @group tpee_t

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

373void tpee_close(tpee_t *self);

374

375// @func _tpee_req_read

376// @group tpee_req_t

377// @internal

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

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

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

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

382

383#ifdef SO_TPEE_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 TPEE_VERSION

398// @internal

399#define TPEE_VERSION "HTTP/1.1"

400

401// @macro TPEE_MAX_REQUEST_HEAD_SIZE

402// @internal

403#define TPEE_MAX_REQUEST_HEAD_SIZE 1000000

404

405// @macro TPEE_RESP_HANDLED

406// @group tpee_resp_t

407// @desc Handled {tpee_resp_t}.

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

409

410// @macro _TPEE_ON

411// @internal

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

413 static tpee_resp_t fn_name(tpee_req_t *req); \

414 __attribute__((constructor)) \

415 static void __macro_tpee_fn_register_##fn_name() { \

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

417 } \

418 static tpee_resp_t fn_name(tpee_req_t *req)

419

420// @macro TPEE_GET

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

422

423// @macro TPEE_GET

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

425

426// @macro TPEE_POST

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

428

429// @macro TPEE_PUT

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

431

432// @macro TPEE_DELETE

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

434

435// @macro TPEE_CONNECT

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

437

438// @macro TPEE_OPTIONS

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

440

441// @macro TPEE_TRACE

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

443

444// @macro TPEE_PATCH

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

446

447// @macro TPEE_DEFAULT

448#define TPEE_DEFAULT(fn_name) \

449 static tpee_resp_t fn_name(tpee_req_t *req); \

450 __attribute__((constructor)) \

451 static void __macro_tpee_fn_register_##fn_name() { \

452 tpee_on_default(&fn_name); \

453 } \

454 static tpee_resp_t fn_name(tpee_req_t *req)

455

456// @macro TPEE_PRE_HOOK

457#define TPEE_PRE_HOOK(fn_name) \

458 static void fn_name(tpee_req_t *req); \

459 __attribute__((constructor)) \

460 static void __macro_tpee_fn_register_##fn_name() { \

461 tpee_on_pre_route(&fn_name); \

462 } \

463 static void fn_name(tpee_req_t *req)

464

465// @macro TPEE_POST_HOOK

466#define TPEE_POST_HOOK(fn_name) \

467 static void fn_name(tpee_req_t *req); \

468 __attribute__((constructor)) \

469 static void __macro_tpee_fn_register_##fn_name() { \

470 tpee_on_post_route(&fn_name); \

471 } \

472 static void fn_name(tpee_req_t *req)

473

474// @global _tpee_routes

475// @internal

476tpee_route_t *_tpee_routes = NULL;

477

478// @global _tpee_routes_len

479// @internal

480size_t _tpee_routes_len = 0;

481

482// @global _tpee_default_route

483// @internal

484tpee_handle_fn_t _tpee_default_route;

485

486// @global _tpee_pre_route

487// @internal

488tpee_hook_fn_t _tpee_pre_route;

489

490// @global _tpee_post_route

491// @internal

492tpee_hook_fn_t _tpee_post_route;

493

494// @func _tpee_on_global

495// @group tpee_t

496// @internal

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

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

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

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

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

502 tpee_resp_t resp = tpee_resp_create(TPEE_STATUS_NOT_FOUND);

503 if (_tpee_pre_route != NULL) {

504 _tpee_pre_route(req);

505 }

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

507 tpee_route_t *route = &_tpee_routes[i];

508 char *path = tpee_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 tpee_resp_free(&resp);

515 resp = route->fn(req);

516 }

517 }

518 else {

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

520 tpee_resp_free(&resp);

521 resp = route->fn(req);

522 }

523 }

524 }

525 free(path);

526 if (resp.status != TPEE_STATUS_NOT_FOUND) {

527 if (_tpee_post_route != NULL) {

528 _tpee_post_route(req);

529 }

530 return resp;

531 }

532 }

533 if (_tpee_default_route != NULL) {

534 tpee_resp_free(&resp);

535 resp = _tpee_default_route(req);

536 }

537 if (_tpee_post_route != NULL) {

538 _tpee_post_route(req);

539 }

540 return resp;

541}

542

543// @func _tpee_on_handle

544// @internal

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

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

547 tpee_req_t req;

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

549 if (err != TPEE_ERR_OK) {

550 return err;

551 }

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

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

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

555 tpee_resp_write(&resp, conn);

556 tpee_resp_free(&resp);

557 }

558 }

559 tpee_req_free(&req);

560 return TPEE_ERR_OK;

561}

562

563// @impl tpee_init

564tpee_t *tpee_init(void) {

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

566 *self = (tpee_t) {

567 .sock = sock_init(),

568 .fn = &_tpee_on_global,

569 };

570 sock_set_ext(self->sock, self);

571 sock_on_global(self->sock, _tpee_on_handle);

572 return self;

573}

574

575// @impl tpee_cleanup

576void tpee_cleanup(tpee_t *self) {

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

578 sock_cleanup(self->sock);

579 }

580 free(self);

581}

582

583// @impl tpee_on_global

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

585 self->fn = fn;

586}

587

588// @impl tpee_on_route

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

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

591 _tpee_routes[_tpee_routes_len] = (tpee_route_t) {

592 .method = method,

593 .path = path,

594 .fn = fn,

595 };

596 _tpee_routes_len++;

597}

598

599// @impl tpee_on_default

600void tpee_on_default(tpee_handle_fn_t fn) {

601 _tpee_default_route = fn;

602}

603

604// @impl tpee_on_pre_route

605void tpee_on_pre_route(tpee_hook_fn_t fn) {

606 _tpee_pre_route = fn;

607}

608

609// @impl tpee_on_post_route

610void tpee_on_post_route(tpee_hook_fn_t fn) {

611 _tpee_post_route = fn;

612}

613

614// @impl tpee_req_path

615char *tpee_req_path(tpee_req_t *req) {

616 char *uri = req->url;

617 size_t url_len = strlen(uri);

618 size_t i = 0;

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

620 size_t c = uri[i];

621 if (c == '?') {

622 break;

623 }

624 }

625 size_t len = i;

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

627 memcpy(path, uri, len);

628 path[len] = '\0';

629 return path;

630}

631

632// @impl tpee_req_body

633char *tpee_req_body(tpee_req_t *req) {

634 return req->body;

635}

636

637// @func _tpee_pair_decode

638// @internal

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

640 size_t j = 0;

641 size_t k = 0;

642 char decoded[len + 1];

643 while (j < len) {

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

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

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

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

648 j += 3;

649 continue;

650 }

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

652 j++;

653 continue;

654 }

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

656 decoded[k++] = ' ';

657 j++;

658 continue;

659 }

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

661 }

662 decoded[k] = '\0';

663 size_t ret_len = strlen(decoded);

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

665 memcpy(ret, decoded, ret_len);

666 ret[ret_len] = '\0';

667 return ret;

668}

669

670// @func _tpee_pairs_init

671// @group tpee_pairs_t

672// @internal

673tpee_pairs_t _tpee_pairs_init(char *uri) {

674 tpee_pairs_t self = (tpee_pairs_t) {

675 .pairs = NULL,

676 .len = 0,

677 };

678 int url_len = strlen(uri);

679 size_t set = 0;

680 size_t lim = 0;

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

682 char c = uri[i];

683 // find 'key=value' pair

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

685 size_t key_len = i - set;

686 if (key_len > 0) {

687 if (lim > set) {

688 key_len = lim - set;

689 }

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

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

692 // read key

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

694 pair->value = NULL;

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

696 // read value

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

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

699 }

700 self.len++;

701 }

702 set = i + 1;

703 }

704 // find '=' delimiter

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

706 lim = i;

707 }

708 }

709 return self;

710}

711

712// @impl tpee_req_queries

713tpee_pairs_t tpee_req_queries(tpee_req_t *req) {

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

715 // skip path

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

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

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

719 }

720 }

721 return (tpee_pairs_t) {

722 .pairs = NULL,

723 .len = 0,

724 };

725}

726

727// @impl tpee_req_params

728tpee_pairs_t tpee_req_params(tpee_req_t *req) {

729 return _tpee_pairs_init(req->body);

730}

731

732// @impl tpee_pairs_get

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

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

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

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

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

738 return pair->value;

739 }

740 }

741 }

742 return NULL;

743}

744

745// @impl tpee_pairs_has

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

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

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

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

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

751 return true;

752 }

753 }

754 }

755 return false;

756}

757

758// @impl tpee_pairs_free

759void tpee_pairs_free(tpee_pairs_t *self) {

760 if (self == NULL) {

761 return;

762 }

763 if (self->len > 0) {

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

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

766 free(pair->key);

767 if (pair->value) {

768 free(pair->value);

769 }

770 }

771 free(self->pairs);

772 }

773}

774

775// @func _tpee_status_str

776// @internal

777const char *_tpee_status_str(tpee_status_t status) {

778 switch (status) {

779 case TPEE_STATUS_CONTINUE:

780 return "Continue";

781 case TPEE_STATUS_SWITCHING_PROTOCOLS:

782 return "Switching Protocols";

783 case TPEE_STATUS_PROCESSING:

784 return "Processing";

785 case TPEE_STATUS_EARLY_HINTS:

786 return "Early Hints";

787 case TPEE_STATUS_OK:

788 return "OK";

789 case TPEE_STATUS_CREATED:

790 return "Created";

791 case TPEE_STATUS_ACCEPTED:

792 return "Accepted";

793 case TPEE_STATUS_NON_AUTHORITATIVE_INFORMATION:

794 return "Non-Authoritative Information";

795 case TPEE_STATUS_NO_CONTENT:

796 return "No Content";

797 case TPEE_STATUS_RESET_CONTENT:

798 return "Reset Content";

799 case TPEE_STATUS_PARTIAL_CONTENT:

800 return "Partial Content";

801 case TPEE_STATUS_MULTI_STATUS:

802 return "Multi-Status";

803 case TPEE_STATUS_ALREADY_REPORTED:

804 return "Already Reported";

805 case TPEE_STATUS_IM_USED:

806 return "IM Used";

807 case TPEE_STATUS_MULTIPLE_CHOICES:

808 return "Multiple Choices";

809 case TPEE_STATUS_MOVED_PERMANENTLY:

810 return "Moved Permanently";

811 case TPEE_STATUS_FOUND:

812 return "Found";

813 case TPEE_STATUS_SEE_OTHER:

814 return "See Other";

815 case TPEE_STATUS_NOT_MODIFIED:

816 return "Not Modified";

817 case TPEE_STATUS_TEMPORARY_REDIRECT:

818 return "Temporary Redirect";

819 case TPEE_STATUS_PERMANENT_REDIRECT:

820 return "Permanent Redirect";

821 case TPEE_STATUS_BAD_REQUEST:

822 return "Bad Request";

823 case TPEE_STATUS_UNAUTHORIZED:

824 return "Unauthorized";

825 case TPEE_STATUS_PAYMENT_REQUIRED:

826 return "Payment Required";

827 case TPEE_STATUS_FORBIDDEN:

828 return "Forbidden";

829 case TPEE_STATUS_NOT_FOUND:

830 return "Not Found";

831 case TPEE_STATUS_METHOD_NOT_ALLOWED:

832 return "Method Not Allowed";

833 case TPEE_STATUS_NOT_ACCEPTABLE:

834 return "Not Acceptable";

835 case TPEE_STATUS_PROXY_AUTHENTICATION_REQUIRED:

836 return "Proxy Authentication Required";

837 case TPEE_STATUS_REQUEST_TIMEOUT:

838 return "Request Timeout";

839 case TPEE_STATUS_CONFLICT:

840 return "Conflict";

841 case TPEE_STATUS_GONE:

842 return "Gone";

843 case TPEE_STATUS_LENGTH_REQUIRED:

844 return "Length Required";

845 case TPEE_STATUS_PRECONDITION_FAILED:

846 return "Precondition Failed";

847 case TPEE_STATUS_PAYLOAD_TOO_LARGE:

848 return "Payload Too Large";

849 case TPEE_STATUS_URI_TOO_LONG:

850 return "URI Too Long";

851 case TPEE_STATUS_UNSUPPORTED_MEDIA_TYPE:

852 return "Unsupported Media Type";

853 case TPEE_STATUS_RANGE_NOT_SATISFIABLE:

854 return "Range Not Satisfiable";

855 case TPEE_STATUS_EXPECTATION_FAILED:

856 return "Expectation Failed";

857 case TPEE_STATUS_I_AM_A_TEAPOT:

858 return "I'm a teapot";

859 case TPEE_STATUS_MISDIRECTED_REQUEST:

860 return "Misdirected Request";

861 case TPEE_STATUS_UNPROCESSABLE_CONTENT:

862 return "Unprocessable Content";

863 case TPEE_STATUS_LOCKED:

864 return "Locked";

865 case TPEE_STATUS_FAILED_DEPENDENCY:

866 return "Failed Dependency";

867 case TPEE_STATUS_TOO_EARLY:

868 return "Too Early";

869 case TPEE_STATUS_UPGRADE_REQUIRED:

870 return "Upgrade Required";

871 case TPEE_STATUS_PRECONDITION_REQUIRED:

872 return "Precondition Required";

873 case TPEE_STATUS_TOO_MANY_REQUESTS:

874 return "Too Many Requests";

875 case TPEE_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

876 return "Request Header Fields Too Large";

877 case TPEE_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

878 return "Unavailable For Legal Reasons";

879 case TPEE_STATUS_INTERNAL_SERVER_ERROR:

880 return "Internal Server Error";

881 case TPEE_STATUS_NOT_IMPLEMENTED:

882 return "Not Implemented";

883 case TPEE_STATUS_BAD_GATEWAY:

884 return "Bad Gateway";

885 case TPEE_STATUS_SERVICE_UNAVAILABLE:

886 return "Service Unavailable";

887 case TPEE_STATUS_GATEWAY_TIMEOUT:

888 return "Gateway Timeout";

889 case TPEE_STATUS_HTTP_VERSION_NOT_SUPPORTED:

890 return "HTTP Version Not Supported";

891 case TPEE_STATUS_VARIANT_ALSO_NEGOTITATES:

892 return "Variant Also Negotiates";

893 case TPEE_STATUS_INSUFFICIENT_STORAGE:

894 return "Insufficient Storage";

895 case TPEE_STATUS_LOOP_DETECTED:

896 return "Loop Detected";

897 case TPEE_STATUS_NOT_EXTENDED:

898 return "Not Extended";

899 case TPEE_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

900 return "Network Authentication Required";

901 default:

902 return NULL;

903 }

904}

905

906// @func _tpee_conn_read

907// @group tpee_conn_t

908// @internal

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

910 return sock_conn_read(conn, buffer, len);

911}

912

913// @func _tpee_conn_write

914// @group tpee_conn_t

915// @internal

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

917 return sock_conn_write(conn, buffer, len);

918}

919

920// @impl tpee_req_header

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

922 if (req->headers_len > 0) {

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

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

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

926 return header->value;

927 }

928 }

929 }

930 return NULL;

931}

932

933// @impl tpee_resp_header

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

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

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

937 resp->headers_len++;

938 int key_len = strlen(key);

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

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

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

942 int value_len = strlen(value);

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

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

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

946}

947

948// @impl tpee_resp_create

949tpee_resp_t tpee_resp_create(tpee_status_t status) {

950 return (tpee_resp_t) {

951 .version = strdup(TPEE_VERSION),

952 .status = status,

953 .headers = NULL,

954 .headers_len = 0,

955 .body = NULL,

956 .body_len = 0,

957 };

958}

959

960// @impl tpee_resp_body

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

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

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

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

965 resp->body_len = len;

966 }

967}

968

969// @impl tpee_req_free

970void tpee_req_free(tpee_req_t *req) {

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

972 free(req->method);

973 }

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

975 free(req->url);

976 }

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

978 free(req->version);

979 }

980 if (req->headers_len > 0) {

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

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

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

984 free(header->key);

985 }

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

987 free(header->value);

988 }

989 }

990 free(req->headers);

991 }

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

993 free(req->body);

994 }

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

996 free(req->ext_data);

997 }

998}

999

1000// @impl tpee_resp_free

1001void tpee_resp_free(tpee_resp_t *resp) {

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

1003 free(resp->version);

1004 }

1005 if (resp->headers_len > 0) {

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

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

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

1009 free(header->key);

1010 }

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

1012 free(header->value);

1013 }

1014 }

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

1016 free(resp->headers);

1017 }

1018 }

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

1020 free(resp->body);

1021 }

1022}

1023

1024// @impl _tpee_req_read

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

1026 int len = 0;

1027 int ln = 0;

1028 int start = 0;

1029 char buffer[TPEE_MAX_REQUEST_HEAD_SIZE];

1030 *req = (tpee_req_t) {

1031 .conn = conn,

1032 .method = NULL,

1033 .url = NULL,

1034 .version = NULL,

1035 .headers = NULL,

1036 .headers_len = 0,

1037 .body = NULL,

1038 .body_len = 0,

1039 .ext_data = NULL,

1040 };

1041 while (true) {

1042 char c;

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

1044 if (read == 0) {

1045 break;

1046 }

1047 // read timeout

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

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

1050 return SOCK_ERR_READ_TIMEOUT;

1051 }

1052 }

1053 // break if too long

1054 if (len == TPEE_MAX_REQUEST_HEAD_SIZE) {

1055 return SOCK_ERR_REQUEST_TOO_LONG;

1056 }

1057 buffer[len] = c;

1058 len++;

1059 // read head

1060 if (len >= 2) {

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

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

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

1064 if (line_len > 0) {

1065 // read line

1066 char line[line_len + 1];

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

1068 line[line_len] = '\0';

1069 // read method, url, and version

1070 if (ln == 0) {

1071 int arg = 0;

1072 int start = 0;

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

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

1075 // read method

1076 if (arg == 0) {

1077 int method_length = i - start;

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

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

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

1081 }

1082 // read url

1083 if (arg == 1) {

1084 int url_length = i - start;

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

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

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

1088 }

1089 // read version

1090 if (arg == 2) {

1091 int version_length = i - start;

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

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

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

1095 }

1096 start = i + 1;

1097 arg++;

1098 }

1099 }

1100 }

1101 // read headers

1102 else {

1103 int sep = 0;

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

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

1106 req->headers_len++;

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

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

1109 int key_len = i;

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

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

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

1113 sep = i + 2;

1114 break;

1115 }

1116 }

1117 int value_len = line_len - sep;

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

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

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

1121 }

1122 }

1123 start = len;

1124 ln++;

1125 }

1126 }

1127 // read body

1128 if (len >= 4) {

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

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

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

1132 if (content_length != NULL) {

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

1134 if (req->body_len > 0) {

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

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

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

1138 }

1139 }

1140 break;

1141 }

1142 }

1143 }

1144 return TPEE_ERR_OK;

1145}

1146

1147// @impl tpee_resp_write_head

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

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

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

1151 char status[4];

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

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

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

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

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

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

1158 if (resp->headers_len > 0) {

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

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

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

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

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

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

1165 }

1166 }

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

1168}

1169

1170// @impl tpee_resp_write_body

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

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

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

1174 }

1175}

1176

1177// @impl tpee_resp_write

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

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

1180 return;

1181 }

1182 bool has_content_length = false;

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

1184 if (resp->headers_len > 0) {

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

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

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

1188 has_content_length = true;

1189 break;

1190 }

1191 }

1192 }

1193 if (!has_content_length) {

1194 char content_length[50];

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

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

1197 }

1198 }

1199 tpee_resp_write_head(resp, conn);

1200 tpee_resp_write_body(resp, conn);

1201}

1202

1203// @impl tpee_bind

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

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

1206}

1207

1208// @impl tpee_listen

1209tpee_err_t tpee_listen(tpee_t *self) {

1210 return sock_listen(self->sock);

1211}

1212

1213// @impl tpee_bind_listen

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

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

1216}

1217

1218// @impl tpee_close

1219void tpee_close(tpee_t *self) {

1220 sock_close(self->sock);

1221}

1222

1223#endif // SO_TPEE_IMPL

1224#endif // _SO_TPEE_H