so://phie

tpee

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

blob: 5dbe663ba26ae93626feeb3ffa2a1ec2b31649dc (17615 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 request.body = malloc(sizeof(char) * (request.body_len + 1));

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

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

395 }

396 break;

397 }

398 }

399 }

400 return request;

401}

402

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

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

405 http_write(conn, " ", 1);

406 char status[4];

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

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

409 http_write(conn, " ", 1);

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

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

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

413 if (response.headers_len > 0) {

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

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

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

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

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

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

420 }

421 }

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

423 if (response.body != NULL) {

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

425 }

426}

427

428void *http_handle_client(void *ptr) {

429 if (!ptr) {

430 pthread_exit(0);

431 }

432 conn_t *conn = (conn_t *) ptr;

433 if (http_ctx != NULL) {

434 conn->ssl = SSL_new(http_ctx);

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

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

437 perror("cannot SSL handshake");

438 pthread_exit(0);

439 }

440 }

441 http_request_t request = http_read_request(conn);

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

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

444 printf(

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

446 (addr ) & 0xff,

447 (addr >> 8) & 0xff,

448 (addr >> 16) & 0xff,

449 (addr >> 24) & 0xff,

450 request.method,

451 request.url

452 );

453 if (on_request_fn != NULL) {

454 http_response_t response = on_request_fn(&request);

455 http_write_response(conn, response);

456 http_response_free(&response);

457 }

458 }

459 http_request_free(&request);

460 if (http_ctx != NULL) {

461 SSL_shutdown(conn->ssl);

462 SSL_free(conn->ssl);

463 }

464 close(conn->sockfd);

465 free(conn);

466 pthread_exit(0);

467}

468

469void *http_handle_server(void *ptr) {

470 if (!ptr) {

471 pthread_exit(0);

472 }

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

474 struct pollfd fds[1];

475 fds[0].fd = sockfd;

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

477 while (!http_quit) {

478 struct timespec sleep_req, sleep_rem;

479 sleep_req.tv_sec = 0;

480 sleep_req.tv_nsec = 100000000;

481 nanosleep(&sleep_req, &sleep_rem);

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

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

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

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

486 conn->ssl = NULL;

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

488 free(conn);

489 }

490 else {

491 pthread_t thread;

492 pthread_attr_t thread_attr;

493 pthread_attr_init(&thread_attr);

494 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

496 pthread_attr_destroy(&thread_attr);

497 }

498 }

499 }

500 pthread_exit(0);

501}

502

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

504 const SSL_METHOD *method = TLS_server_method();

505 http_ctx = SSL_CTX_new(method);

506 if (!http_ctx) {

507 perror("cannot create SSL context");

508 errno = HTTP_ERR_NO_SSL_CONTEXT;

509 http_error = true;

510 return;

511 }

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

513 perror("cannot use certificate file");

514 errno = HTTP_ERR_INVALID_CERTIFICATE;

515 http_error = true;

516 }

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

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

519 errno = HTTP_ERR_INVALID_PRIVATE_KEY;

520 http_error = true;

521 }

522}

523

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

525 signal(SIGPIPE, SIG_IGN);

526 if (http_error) {

527 return;

528 }

529 errno = 0;

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

531 if (http_sockfd <= 0) {

532 perror("cannot create socket");

533 errno = HTTP_ERR_NO_SOCKET;

534 http_error = true;

535 return;

536 }

537 struct hostent *host = gethostbyname(hostname);

538 if (!host) {

539 perror("unknown host");

540 errno = HTTP_ERR_UNKNOWN_HOST;

541 http_error = true;

542 return;

543 }

544 struct sockaddr_in addr;

545 addr.sin_family = AF_INET;

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

547 addr.sin_port = htons(port);

548 int enable = 1;

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

550 perror("cannot reuse address");

551 errno = HTTP_ERR_NO_ADDR_REUSE;

552 http_error = true;

553 return;

554 }

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

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

557 errno = HTTP_ERR_ADDR_IN_USE;

558 http_error = true;

559 return;

560 }

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

562 perror("cannot listen on port");

563 errno = HTTP_ERR_NO_LISTEN;

564 http_error = true;

565 return;

566 }

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

568}

569

570void http_close() {

571 http_quit = true;

572 if (!http_error) {

573 pthread_join(http_thread, NULL);

574 }

575 close(http_sockfd);

576 if (http_ctx != NULL) {

577 SSL_CTX_free(http_ctx);

578 }

579}