so://phie

tpee

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

blob: 71ca5c487917183d2f130b15d915b18d5fc24374 (17494 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}

277

278void http_response_free(http_response_t *response) {

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

280 free(response->version);

281 }

282 if (response->headers_len > 0) {

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

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

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

286 free(header->key);

287 }

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

289 free(header->value);

290 }

291 }

292 }

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

294 free(response->body);

295 }

296}

297

298http_request_t http_read_request(conn_t *conn) {

299 int len = 0;

300 int ln = 0;

301 int start = 0;

302 char buffer[MAX_REQUEST_HEAD_SIZE];

303 http_request_t request = { conn, NULL, NULL, NULL, NULL, 0, NULL, 0 };

304 while (true) {

305 char c;

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

307 if (read == 0) {

308 break;

309 }

310 // break if too long

311 if (len == MAX_REQUEST_HEAD_SIZE) {

312 perror("request is too long");

313 break;

314 }

315 buffer[len] = c;

316 len++;

317 // read head

318 if (len >= 2) {

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

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

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

322 if (line_len > 0) {

323 // read line

324 char line[line_len + 1];

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

326 line[line_len] = '\0';

327 // read method, url, and version

328 if (ln == 0) {

329 int arg = 0;

330 int start = 0;

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

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

333 // read method

334 if (arg == 0) {

335 int method_length = i - start;

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

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

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

339 }

340 // read url

341 if (arg == 1) {

342 int url_length = i - start;

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

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

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

346 }

347 // read version

348 if (arg == 2) {

349 int version_length = i - start;

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

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

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

353 }

354 start = i + 1;

355 arg++;

356 }

357 }

358 }

359 // read headers

360 else {

361 int sep = 0;

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

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

364 request.headers_len++;

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

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

367 int key_len = i;

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

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

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

371 sep = i + 2;

372 break;

373 }

374 }

375 int value_len = line_len - sep;

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

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

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

379 }

380 }

381 start = len;

382 ln++;

383 }

384 }

385 // read body

386 if (len >= 4) {

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

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

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

390 if (content_length != NULL) {

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

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

393 }

394 break;

395 }

396 }

397 }

398 return request;

399}

400

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

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

403 http_write(conn, " ", 1);

404 char status[4];

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

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

407 http_write(conn, " ", 1);

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

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

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

411 if (response.headers_len > 0) {

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

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

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

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

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

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

418 }

419 }

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

421 if (response.body != NULL) {

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

423 }

424}

425

426void *http_handle_client(void *ptr) {

427 if (!ptr) {

428 pthread_exit(0);

429 }

430 conn_t *conn = (conn_t *) ptr;

431 if (http_ctx != NULL) {

432 conn->ssl = SSL_new(http_ctx);

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

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

435 perror("cannot SSL handshake");

436 pthread_exit(0);

437 }

438 }

439 http_request_t request = http_read_request(conn);

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

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

442 printf(

443 "%ld.%ld.%ld.%ld -> %s %s\n",

444 (addr ) & 0xff,

445 (addr >> 8) & 0xff,

446 (addr >> 16) & 0xff,

447 (addr >> 24) & 0xff,

448 request.method,

449 request.url

450 );

451 if (on_request_fn != NULL) {

452 http_response_t response = on_request_fn(&request);

453 http_write_response(conn, response);

454 http_response_free(&response);

455 }

456 }

457 http_request_free(&request);

458 if (http_ctx != NULL) {

459 SSL_shutdown(conn->ssl);

460 SSL_free(conn->ssl);

461 }

462 close(conn->sockfd);

463 free(conn);

464 pthread_exit(0);

465}

466

467void *http_handle_server(void *ptr) {

468 if (!ptr) {

469 pthread_exit(0);

470 }

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

472 struct pollfd fds[1];

473 fds[0].fd = sockfd;

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

475 while (!http_quit) {

476 struct timespec sleep_req, sleep_rem;

477 sleep_req.tv_sec = 0;

478 sleep_req.tv_nsec = 100000000;

479 nanosleep(&sleep_req, &sleep_rem);

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

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

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

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

484 conn->ssl = NULL;

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

486 free(conn);

487 }

488 else {

489 pthread_t thread;

490 pthread_attr_t thread_attr;

491 pthread_attr_init(&thread_attr);

492 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

494 pthread_attr_destroy(&thread_attr);

495 }

496 }

497 }

498 pthread_exit(0);

499}

500

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

502 const SSL_METHOD *method = TLS_server_method();

503 http_ctx = SSL_CTX_new(method);

504 if (!http_ctx) {

505 perror("cannot create SSL context");

506 errno = HTTP_ERR_NO_SSL_CONTEXT;

507 http_error = true;

508 return;

509 }

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

511 perror("cannot use certificate file");

512 errno = HTTP_ERR_INVALID_CERTIFICATE;

513 http_error = true;

514 }

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

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

517 errno = HTTP_ERR_INVALID_PRIVATE_KEY;

518 http_error = true;

519 }

520}

521

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

523 signal(SIGPIPE, SIG_IGN);

524 if (http_error) {

525 return;

526 }

527 errno = 0;

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

529 if (http_sockfd <= 0) {

530 perror("cannot create socket");

531 errno = HTTP_ERR_NO_SOCKET;

532 http_error = true;

533 return;

534 }

535 struct hostent *host = gethostbyname(hostname);

536 if (!host) {

537 perror("unknown host");

538 errno = HTTP_ERR_UNKNOWN_HOST;

539 http_error = true;

540 return;

541 }

542 struct sockaddr_in addr;

543 addr.sin_family = AF_INET;

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

545 addr.sin_port = htons(port);

546 int enable = 1;

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

548 perror("cannot reuse address");

549 errno = HTTP_ERR_NO_ADDR_REUSE;

550 http_error = true;

551 return;

552 }

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

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

555 errno = HTTP_ERR_ADDR_IN_USE;

556 http_error = true;

557 return;

558 }

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

560 perror("cannot listen on port");

561 errno = HTTP_ERR_NO_LISTEN;

562 http_error = true;

563 return;

564 }

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

566}

567

568void http_close() {

569 http_quit = true;

570 if (!http_error) {

571 pthread_join(http_thread, NULL);

572 }

573 close(http_sockfd);

574 if (http_ctx != NULL) {

575 SSL_CTX_free(http_ctx);

576 }

577}