so://phie

tpee

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

blob: c278e46824c0ab5eefa0e278c1947d5cbbd0a1f1 (17852 bytes)[doc][blame][raw]

1#include <stdio.h>

2#include <stdlib.h>

3#include <stdbool.h>

4#include <string.h>

5#include <time.h>

6#include <unistd.h>

7#include <pthread.h>

8#include <netdb.h>

9#include <errno.h>

10#include <poll.h>

11#include <signal.h>

12#include <openssl/ssl.h>

13

14#include "libhttp.h"

15

16#define MAX_REQUEST_HEAD_SIZE 40960

17

18int http_sockfd;

19pthread_t http_thread;

20bool http_quit = false;

21bool http_error = false;

22SSL_CTX *http_ctx = NULL;

23

24http_response_t (*on_request_fn)(http_request_t *) = NULL;

25

26void http_on_request(http_response_t fn(http_request_t *)) {

27 on_request_fn = fn;

28}

29

30char *http_read_file(char *filename) {

31 FILE *fp = fopen(filename, "r");

32 fseek(fp, 0, SEEK_END);

33 long len = ftell(fp);

34 fseek(fp, 0, SEEK_SET);

35 char *content = malloc(sizeof(char) * (len + 1));

36 fread(content, len, sizeof(char), fp);

37 content[len] = '\0';

38 fclose(fp);

39 return content;

40}

41

42char *http_status_str(http_status_t status) {

43 switch (status) {

44 case HTTP_STATUS_CONTINUE:

45 return "Continue";

46 case HTTP_STATUS_SWITCHING_PROTOCOLS:

47 return "Switching Protocols";

48 case HTTP_STATUS_PROCESSING:

49 return "Processing";

50 case HTTP_STATUS_EARLY_HINTS:

51 return "Early Hints";

52 case HTTP_STATUS_OK:

53 return "OK";

54 case HTTP_STATUS_CREATED:

55 return "Created";

56 case HTTP_STATUS_ACCEPTED:

57 return "Accepted";

58 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

59 return "Non-Authoritative Information";

60 case HTTP_STATUS_NO_CONTENT:

61 return "No Content";

62 case HTTP_STATUS_RESET_CONTENT:

63 return "Reset Content";

64 case HTTP_STATUS_PARTIAL_CONTENT:

65 return "Partial Content";

66 case HTTP_STATUS_MULTI_STATUS:

67 return "Multi-Status";

68 case HTTP_STATUS_ALREADY_REPORTED:

69 return "Already Reported";

70 case HTTP_STATUS_IM_USED:

71 return "IM Used";

72 case HTTP_STATUS_MULTIPLE_CHOICES:

73 return "Multiple Choices";

74 case HTTP_STATUS_MOVED_PERMANENTLY:

75 return "Moved Permanently";

76 case HTTP_STATUS_FOUND:

77 return "Found";

78 case HTTP_STATUS_SEE_OTHER:

79 return "See Other";

80 case HTTP_STATUS_NOT_MODIFIED:

81 return "Not Modified";

82 case HTTP_STATUS_TEMPORARY_REDIRECT:

83 return "Temporary Redirect";

84 case HTTP_STATUS_PERMANENT_REDIRECT:

85 return "Permanent Redirect";

86 case HTTP_STATUS_BAD_REQUEST:

87 return "Bad Request";

88 case HTTP_STATUS_UNAUTHORIZED:

89 return "Unauthorized";

90 case HTTP_STATUS_PAYMENT_REQUIRED:

91 return "Payment Required";

92 case HTTP_STATUS_FORBIDDEN:

93 return "Forbidden";

94 case HTTP_STATUS_NOT_FOUND:

95 return "Not Found";

96 case HTTP_STATUS_METHOD_NOT_ALLOWED:

97 return "Method Not Allowed";

98 case HTTP_STATUS_NOT_ACCEPTABLE:

99 return "Not Acceptable";

100 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

101 return "Proxy Authentication Required";

102 case HTTP_STATUS_REQUEST_TIMEOUT:

103 return "Request Timeout";

104 case HTTP_STATUS_CONFLICT:

105 return "Conflict";

106 case HTTP_STATUS_GONE:

107 return "Gone";

108 case HTTP_STATUS_LENGTH_REQUIRED:

109 return "Length Required";

110 case HTTP_STATUS_PRECONDITION_FAILED:

111 return "Precondition Failed";

112 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

113 return "Payload Too Large";

114 case HTTP_STATUS_URI_TOO_LONG:

115 return "URI Too Long";

116 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

117 return "Unsupported Media Type";

118 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

119 return "Range Not Satisfiable";

120 case HTTP_STATUS_EXPECTATION_FAILED:

121 return "Expectation Failed";

122 case HTTP_STATUS_I_AM_A_TEAPOT:

123 return "I'm a teapot";

124 case HTTP_STATUS_MISDIRECTED_REQUEST:

125 return "Misdirected Request";

126 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

127 return "Unprocessable Content";

128 case HTTP_STATUS_LOCKED:

129 return "Locked";

130 case HTTP_STATUS_FAILED_DEPENDENCY:

131 return "Failed Dependency";

132 case HTTP_STATUS_TOO_EARLY:

133 return "Too Early";

134 case HTTP_STATUS_UPGRADE_REQUIRED:

135 return "Upgrade Required";

136 case HTTP_STATUS_PRECONDITION_REQUIRED:

137 return "Precondition Required";

138 case HTTP_STATUS_TOO_MANY_REQUESTS:

139 return "Too Many Requests";

140 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

141 return "Request Header Fields Too Large";

142 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

143 return "Unavailable For Legal Reasons";

144 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

145 return "Internal Server Error";

146 case HTTP_STATUS_NOT_IMPLEMENTED:

147 return "Not Implemented";

148 case HTTP_STATUS_BAD_GATEWAY:

149 return "Bad Gateway";

150 case HTTP_STATUS_SERVICE_UNAVAILABLE:

151 return "Service Unavailable";

152 case HTTP_STATUS_GATEWAY_TIMEOUT:

153 return "Gateway Timeout";

154 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

155 return "HTTP Version Not Supported";

156 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

157 return "Variant Also Negotitates";

158 case HTTP_STATUS_INSUFFICIENT_STORAGE:

159 return "Insufficient Storage";

160 case HTTP_STATUS_LOOP_DETECTED:

161 return "Loop Detected";

162 case HTTP_STATUS_NOT_EXTENDED:

163 return "Not Extended";

164 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

165 return "Network Authentication Required";

166 default:

167 return NULL;

168 }

169}

170

171ssize_t http_read(conn_t *conn, void *buffer, size_t len) {

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

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

174 }

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

176}

177

178ssize_t http_write(conn_t *conn, void *buffer, size_t len) {

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

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

181 }

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

183}

184

185char *http_header_get(http_request_t *request, char *key) {

186 if (request->headers_len > 0) {

187 for (int i = 0; i < request->headers_len; i++) {

188 http_header_t *header = &request->headers[i];

189 if (strcmp(header->key, key) == 0) {

190 return header->value;

191 }

192 }

193 }

194 return NULL;

195}

196

197void http_header_set(http_response_t *response, char *key, char *value) {

198 http_header_t *new_header = NULL;

199 if (response->headers_len > 0) {

200 for (int i = 0; i < response->headers_len; i++) {

201 http_header_t *header = &response->headers[i];

202 if (strcmp(header->key, key) == 0) {

203 new_header = header;

204 break;

205 }

206 }

207 }

208 if (new_header == NULL) {

209 response->headers = realloc(response->headers, sizeof(http_header_t) * (response->headers_len + 1));

210 new_header = &response->headers[response->headers_len];

211 response->headers_len++;

212 }

213 int key_len = strlen(key);

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

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

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

217 int value_len = strlen(value);

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

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

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

221}

222

223http_response_t http_response_create(http_status_t status) {

224 char *version = "HTTP/1.1";

225 int version_len = strlen(version);

226 http_response_t response = { NULL, status, NULL, 0, NULL, 0 };

227 response.version = malloc(sizeof(char) * (version_len + 1));

228 memcpy(response.version, version, version_len);

229 response.version[version_len] = '\0';

230 return response;

231}

232

233void http_response_body(http_response_t *response, char *body, long len) {

234 if (response != NULL && body != NULL) {

235 response->body = malloc(sizeof(char) * len);

236 memcpy(response->body, body, len);

237 response->body_len = len;

238 char content_length[50];

239 snprintf(content_length, 50, "%ld", len);

240 http_header_set(response, "Content-Length", content_length);

241 }

242}

243

244void http_response_file(http_response_t *response, char *filename) {

245 char *content = http_read_file(filename);

246 if (content != NULL) {

247 http_response_body(response, content, strlen(content));

248 free(content);

249 }

250}

251

252void http_request_free(http_request_t *request) {

253 if (request->method != NULL) {

254 free(request->method);

255 }

256 if (request->url != NULL) {

257 free(request->url);

258 }

259 if (request->version != NULL) {

260 free(request->version);

261 }

262 if (request->headers_len > 0) {

263 for (int i = 0; i < request->headers_len; i++) {

264 http_header_t *header = &request->headers[i];

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

266 free(header->key);

267 }

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

269 free(header->value);

270 }

271 }

272 }

273 if (request->body != NULL) {

274 free(request->body);

275 }

276 if (request->ext_data != NULL) {

277 free(request->ext_data);

278 }

279}

280

281void http_response_free(http_response_t *response) {

282 if (response->version != NULL) {

283 free(response->version);

284 }

285 if (response->headers_len > 0) {

286 for (int i = 0; i < response->headers_len; i++) {

287 http_header_t *header = &response->headers[i];

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

289 free(header->key);

290 }

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

292 free(header->value);

293 }

294 }

295 }

296 if (response->body != NULL) {

297 free(response->body);

298 }

299}

300

301http_request_t http_read_request(conn_t *conn) {

302 int len = 0;

303 int ln = 0;

304 int start = 0;

305 char buffer[MAX_REQUEST_HEAD_SIZE];

306 http_request_t request = {

307 .conn = conn,

308 .method = NULL,

309 .url = NULL,

310 .version = NULL,

311 .headers = NULL,

312 .headers_len = 0,

313 .body = NULL,

314 .body_len = 0,

315 .ext_data = NULL,

316 };

317 while (true) {

318 char c;

319 int read = http_read(conn, &c, 1);

320 if (read == 0) {

321 break;

322 }

323 // break if too long

324 if (len == MAX_REQUEST_HEAD_SIZE) {

325 perror("request is too long");

326 break;

327 }

328 buffer[len] = c;

329 len++;

330 // read head

331 if (len >= 2) {

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

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

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

335 if (line_len > 0) {

336 // read line

337 char line[line_len + 1];

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

339 line[line_len] = '\0';

340 // read method, url, and version

341 if (ln == 0) {

342 int arg = 0;

343 int start = 0;

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

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

346 // read method

347 if (arg == 0) {

348 int method_length = i - start;

349 request.method = malloc(sizeof(char) * (method_length + 1));

350 memcpy(request.method, line + start, method_length);

351 request.method[method_length] = '\0';

352 }

353 // read url

354 if (arg == 1) {

355 int url_length = i - start;

356 request.url = malloc(sizeof(char) * (url_length + 1));

357 memcpy(request.url, line + start, url_length);

358 request.url[url_length] = '\0';

359 }

360 // read version

361 if (arg == 2) {

362 int version_length = i - start;

363 request.version = malloc(sizeof(char) * (version_length + 1));

364 memcpy(request.version, line + start, version_length);

365 request.version[version_length] = '\0';

366 }

367 start = i + 1;

368 arg++;

369 }

370 }

371 }

372 // read headers

373 else {

374 int sep = 0;

375 request.headers = realloc(request.headers, sizeof(http_header_t) * (request.headers_len + 1));

376 http_header_t *header = &request.headers[request.headers_len];

377 request.headers_len++;

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

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

380 int key_len = i;

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

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

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

384 sep = i + 2;

385 break;

386 }

387 }

388 int value_len = line_len - sep;

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

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

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

392 }

393 }

394 start = len;

395 ln++;

396 }

397 }

398 // read body

399 if (len >= 4) {

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

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

402 char *content_length = http_header_get(&request, "Content-Length");

403 if (content_length != NULL) {

404 request.body_len = strtol(content_length, NULL, 10);

405 request.body = malloc(sizeof(char) * (request.body_len + 1));

406 http_read(conn, request.body, request.body_len);

407 request.body[request.body_len] = '\0';

408 }

409 break;

410 }

411 }

412 }

413 return request;

414}

415

416void http_write_response(conn_t *conn, http_response_t response) {

417 http_write(conn, response.version, strlen(response.version));

418 http_write(conn, " ", 1);

419 char status[4];

420 snprintf(status, 4, "%d", response.status);

421 http_write(conn, status, strlen(status));

422 http_write(conn, " ", 1);

423 char *status_message = http_status_str(response.status);

424 http_write(conn, status_message, strlen(status_message));

425 http_write(conn, "\r\n", 2);

426 if (response.headers_len > 0) {

427 for (int i = 0; i < response.headers_len; i++) {

428 http_header_t *header = &response.headers[i];

429 http_write(conn, header->key, strlen(header->key));

430 http_write(conn, ": ", 2);

431 http_write(conn, header->value, strlen(header->value));

432 http_write(conn, "\r\n", 2);

433 }

434 }

435 http_write(conn, "\r\n", 2);

436 if (response.body != NULL) {

437 http_write(conn, response.body, response.body_len);

438 }

439}

440

441void *http_handle_client(void *ptr) {

442 if (!ptr) {

443 pthread_exit(0);

444 }

445 conn_t *conn = (conn_t *) ptr;

446 if (http_ctx != NULL) {

447 conn->ssl = SSL_new(http_ctx);

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

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

450 perror("cannot SSL handshake");

451 pthread_exit(0);

452 }

453 }

454 http_request_t request = http_read_request(conn);

455 if (request.method != NULL && request.url != NULL) {

456 // long addr = ((struct sockaddr_in *) &request.conn->addr)->sin_addr.s_addr;

457 // printf(

458 // "%ld.%ld.%ld.%ld -> %s %s\n",

459 // (addr ) & 0xff,

460 // (addr >> 8) & 0xff,

461 // (addr >> 16) & 0xff,

462 // (addr >> 24) & 0xff,

463 // request.method,

464 // request.url

465 // );

466 if (on_request_fn != NULL) {

467 http_response_t response = on_request_fn(&request);

468 http_write_response(conn, response);

469 http_response_free(&response);

470 }

471 }

472 http_request_free(&request);

473 if (http_ctx != NULL) {

474 SSL_shutdown(conn->ssl);

475 SSL_free(conn->ssl);

476 }

477 close(conn->sockfd);

478 free(conn);

479 pthread_exit(0);

480}

481

482void *http_handle_server(void *ptr) {

483 if (!ptr) {

484 pthread_exit(0);

485 }

486 int sockfd = *((int *) ptr);

487 struct pollfd fds[1];

488 fds[0].fd = sockfd;

489 fds[0].events = POLLIN | POLLPRI;

490 while (!http_quit) {

491 struct timespec sleep_req, sleep_rem;

492 sleep_req.tv_sec = 0;

493 sleep_req.tv_nsec = 100000000;

494 nanosleep(&sleep_req, &sleep_rem);

495 if (poll(fds, 1, 100)) {

496 conn_t *conn = malloc(sizeof(conn_t));

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

498 conn->sockfd = accept(sockfd, &conn->addr, (socklen_t *) &conn->addr_len);

499 conn->ssl = NULL;

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

501 free(conn);

502 }

503 else {

504 pthread_t thread;

505 pthread_attr_t thread_attr;

506 pthread_attr_init(&thread_attr);

507 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

508 pthread_create(&thread, &thread_attr, http_handle_client, (void *) conn);

509 pthread_attr_destroy(&thread_attr);

510 }

511 }

512 }

513 pthread_exit(0);

514}

515

516void http_tls_enable(char *certificate, char *private_key) {

517 const SSL_METHOD *method = TLS_server_method();

518 http_ctx = SSL_CTX_new(method);

519 if (!http_ctx) {

520 perror("cannot create SSL context");

521 errno = HTTP_ERR_NO_SSL_CONTEXT;

522 http_error = true;

523 return;

524 }

525 if (SSL_CTX_use_certificate_file(http_ctx, certificate, SSL_FILETYPE_PEM) <= 0) {

526 perror("cannot use certificate file");

527 errno = HTTP_ERR_INVALID_CERTIFICATE;

528 http_error = true;

529 }

530 if (SSL_CTX_use_PrivateKey_file(http_ctx, private_key, SSL_FILETYPE_PEM) <= 0) {

531 perror("cannot use private key file");

532 errno = HTTP_ERR_INVALID_PRIVATE_KEY;

533 http_error = true;

534 }

535}

536

537void http_listen(char *hostname, int port) {

538 signal(SIGPIPE, SIG_IGN);

539 if (http_error) {

540 return;

541 }

542 errno = 0;

543 http_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

544 if (http_sockfd <= 0) {

545 perror("cannot create socket");

546 errno = HTTP_ERR_NO_SOCKET;

547 http_error = true;

548 return;

549 }

550 struct hostent *host = gethostbyname(hostname);

551 if (!host) {

552 perror("unknown host");

553 errno = HTTP_ERR_UNKNOWN_HOST;

554 http_error = true;

555 return;

556 }

557 struct sockaddr_in addr;

558 addr.sin_family = AF_INET;

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

560 addr.sin_port = htons(port);

561 int enable = 1;

562 if (setsockopt(http_sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {

563 perror("cannot reuse address");

564 errno = HTTP_ERR_NO_ADDR_REUSE;

565 http_error = true;

566 return;

567 }

568 if (bind(http_sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {

569 perror("cannot bind socket to port");

570 errno = HTTP_ERR_ADDR_IN_USE;

571 http_error = true;

572 return;

573 }

574 if (listen(http_sockfd, 5) < 0) {

575 perror("cannot listen on port");

576 errno = HTTP_ERR_NO_LISTEN;

577 http_error = true;

578 return;

579 }

580 pthread_create(&http_thread, 0, http_handle_server, (void *) &http_sockfd);

581}

582

583void http_close() {

584 http_quit = true;

585 if (!http_error) {

586 pthread_join(http_thread, NULL);

587 }

588 close(http_sockfd);

589 if (http_ctx != NULL) {

590 SSL_CTX_free(http_ctx);

591 }

592}