so://phie

tpee

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

blob: 59227840ad4f1b771e859f55ecb7c211cd0b1a63 (17063 bytes)[doc][blame][raw]

1#include <stdio.h>

2#include <stdlib.h>

3#include <stdbool.h>

4#include <string.h>

5#include <unistd.h>

6#include <pthread.h>

7#include <netdb.h>

8#include <errno.h>

9#include <poll.h>

10#include <openssl/ssl.h>

11

12#include "libhttp.h"

13

14#define MAX_REQUEST_HEAD_SIZE 40960

15

16int http_sockfd;

17pthread_t http_thread;

18bool http_quit = false;

19bool http_error = false;

20SSL_CTX *http_ctx = NULL;

21

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

23

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

25 on_request_fn = fn;

26}

27

28char *http_read_file(char *filename) {

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

30 fseek(fp, 0, SEEK_END);

31 long len = ftell(fp);

32 fseek(fp, 0, SEEK_SET);

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

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

35 content[len] = '\0';

36 fclose(fp);

37 return content;

38}

39

40char *http_status_str(http_status_t status) {

41 switch (status) {

42 case HTTP_STATUS_CONTINUE:

43 return "Continue";

44 case HTTP_STATUS_SWITCHING_PROTOCOLS:

45 return "Switching Protocols";

46 case HTTP_STATUS_PROCESSING:

47 return "Processing";

48 case HTTP_STATUS_EARLY_HINTS:

49 return "Early Hints";

50 case HTTP_STATUS_OK:

51 return "OK";

52 case HTTP_STATUS_CREATED:

53 return "Created";

54 case HTTP_STATUS_ACCEPTED:

55 return "Accepted";

56 case HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:

57 return "Non-Authoritative Information";

58 case HTTP_STATUS_NO_CONTENT:

59 return "No Content";

60 case HTTP_STATUS_RESET_CONTENT:

61 return "Reset Content";

62 case HTTP_STATUS_PARTIAL_CONTENT:

63 return "Partial Content";

64 case HTTP_STATUS_MULTI_STATUS:

65 return "Multi-Status";

66 case HTTP_STATUS_ALREADY_REPORTED:

67 return "Already Reported";

68 case HTTP_STATUS_IM_USED:

69 return "IM Used";

70 case HTTP_STATUS_MULTIPLE_CHOICES:

71 return "Multiple Choices";

72 case HTTP_STATUS_MOVED_PERMANENTLY:

73 return "Moved Permanently";

74 case HTTP_STATUS_FOUND:

75 return "Found";

76 case HTTP_STATUS_SEE_OTHER:

77 return "See Other";

78 case HTTP_STATUS_NOT_MODIFIED:

79 return "Not Modified";

80 case HTTP_STATUS_TEMPORARY_REDIRECT:

81 return "Temporary Redirect";

82 case HTTP_STATUS_PERMANENT_REDIRECT:

83 return "Permanent Redirect";

84 case HTTP_STATUS_BAD_REQUEST:

85 return "Bad Request";

86 case HTTP_STATUS_UNAUTHORIZED:

87 return "Unauthorized";

88 case HTTP_STATUS_PAYMENT_REQUIRED:

89 return "Payment Required";

90 case HTTP_STATUS_FORBIDDEN:

91 return "Forbidden";

92 case HTTP_STATUS_NOT_FOUND:

93 return "Not Found";

94 case HTTP_STATUS_METHOD_NOT_ALLOWED:

95 return "Method Not Allowed";

96 case HTTP_STATUS_NOT_ACCEPTABLE:

97 return "Not Acceptable";

98 case HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:

99 return "Proxy Authentication Required";

100 case HTTP_STATUS_REQUEST_TIMEOUT:

101 return "Request Timeout";

102 case HTTP_STATUS_CONFLICT:

103 return "Conflict";

104 case HTTP_STATUS_GONE:

105 return "Gone";

106 case HTTP_STATUS_LENGTH_REQUIRED:

107 return "Length Required";

108 case HTTP_STATUS_PRECONDITION_FAILED:

109 return "Precondition Failed";

110 case HTTP_STATUS_PAYLOAD_TOO_LARGE:

111 return "Payload Too Large";

112 case HTTP_STATUS_URI_TOO_LONG:

113 return "URI Too Long";

114 case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:

115 return "Unsupported Media Type";

116 case HTTP_STATUS_RANGE_NOT_SATISFIABLE:

117 return "Range Not Satisfiable";

118 case HTTP_STATUS_EXPECTATION_FAILED:

119 return "Expectation Failed";

120 case HTTP_STATUS_I_AM_A_TEAPOT:

121 return "I'm a teapot";

122 case HTTP_STATUS_MISDIRECTED_REQUEST:

123 return "Misdirected Request";

124 case HTTP_STATUS_UNPROCESSABLE_CONTENT:

125 return "Unprocessable Content";

126 case HTTP_STATUS_LOCKED:

127 return "Locked";

128 case HTTP_STATUS_FAILED_DEPENDENCY:

129 return "Failed Dependency";

130 case HTTP_STATUS_TOO_EARLY:

131 return "Too Early";

132 case HTTP_STATUS_UPGRADE_REQUIRED:

133 return "Upgrade Required";

134 case HTTP_STATUS_PRECONDITION_REQUIRED:

135 return "Precondition Required";

136 case HTTP_STATUS_TOO_MANY_REQUESTS:

137 return "Too Many Requests";

138 case HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:

139 return "Request Header Fields Too Large";

140 case HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:

141 return "Unavailable For Legal Reasons";

142 case HTTP_STATUS_INTERNAL_SERVER_ERROR:

143 return "Internal Server Error";

144 case HTTP_STATUS_NOT_IMPLEMENTED:

145 return "Not Implemented";

146 case HTTP_STATUS_BAD_GATEWAY:

147 return "Bad Gateway";

148 case HTTP_STATUS_SERVICE_UNAVAILABLE:

149 return "Service Unavailable";

150 case HTTP_STATUS_GATEWAY_TIMEOUT:

151 return "Gateway Timeout";

152 case HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:

153 return "HTTP Version Not Supported";

154 case HTTP_STATUS_VARIANT_ALSO_NEGOTITATES:

155 return "Variant Also Negotitates";

156 case HTTP_STATUS_INSUFFICIENT_STORAGE:

157 return "Insufficient Storage";

158 case HTTP_STATUS_LOOP_DETECTED:

159 return "Loop Detected";

160 case HTTP_STATUS_NOT_EXTENDED:

161 return "Not Extended";

162 case HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:

163 return "Network Authentication Required";

164 default:

165 return NULL;

166 }

167}

168

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

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

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

172 }

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

174}

175

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

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

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

179 }

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

181}

182

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

184 if (request->headers_len > 0) {

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

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

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

188 return header->value;

189 }

190 }

191 }

192 return NULL;

193}

194

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

196 http_header_t *new_header = NULL;

197 if (response->headers_len > 0) {

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

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

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

201 new_header = header;

202 break;

203 }

204 }

205 }

206 if (new_header == NULL) {

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

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

209 response->headers_len++;

210 }

211 int key_len = strlen(key);

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

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

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

215 int value_len = strlen(value);

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

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

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

219}

220

221http_response_t http_response_create(http_status_t status) {

222 char *version = "HTTP/1.1";

223 int version_len = strlen(version);

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

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

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

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

228 return response;

229}

230

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

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

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

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

235 response->body_len = len;

236 char content_length[50];

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

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

239 }

240}

241

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

243 char *content = http_read_file(filename);

244 if (content != NULL) {

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

246 free(content);

247 }

248}

249

250void http_request_free(http_request_t *request) {

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

252 free(request->method);

253 }

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

255 free(request->url);

256 }

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

258 free(request->version);

259 }

260 if (request->headers_len > 0) {

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

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

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

264 free(header->key);

265 }

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

267 free(header->value);

268 }

269 }

270 }

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

272 free(request->body);

273 }

274}

275

276void http_response_free(http_response_t *response) {

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

278 free(response->version);

279 }

280 if (response->headers_len > 0) {

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

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

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

284 free(header->key);

285 }

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

287 free(header->value);

288 }

289 }

290 }

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

292 free(response->body);

293 }

294}

295

296http_request_t http_read_request(conn_t *conn) {

297 int len = 0;

298 int ln = 0;

299 int start = 0;

300 char buffer[10240];

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

302 while (true) {

303 char c;

304 http_read(conn, &c, 1);

305 // break if too long

306 if (len == MAX_REQUEST_HEAD_SIZE) {

307 perror("request is too long");

308 break;

309 }

310 buffer[len] = c;

311 len++;

312 // read head

313 if (len >= 2) {

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

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

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

317 if (line_len > 0) {

318 // read line

319 char line[line_len + 1];

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

321 line[line_len] = '\0';

322 // read method, url, and version

323 if (ln == 0) {

324 int arg = 0;

325 int start = 0;

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

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

328 // read method

329 if (arg == 0) {

330 int method_length = i - start;

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

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

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

334 }

335 // read url

336 if (arg == 1) {

337 int url_length = i - start;

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

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

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

341 }

342 // read version

343 if (arg == 2) {

344 int version_length = i - start;

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

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

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

348 }

349 start = i + 1;

350 arg++;

351 }

352 }

353 }

354 // read headers

355 else {

356 int sep = 0;

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

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

359 request.headers_len++;

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

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

362 int key_len = i;

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

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

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

366 sep = i + 2;

367 break;

368 }

369 }

370 int value_len = line_len - sep;

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

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

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

374 }

375 }

376 start = len;

377 ln++;

378 }

379 }

380 // read body

381 if (len >= 4) {

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

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

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

385 if (content_length != NULL) {

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

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

388 }

389 break;

390 }

391 }

392 }

393 return request;

394}

395

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

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

398 http_write(conn, " ", 1);

399 char status[4];

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

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

402 http_write(conn, " ", 1);

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

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

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

406 if (response.headers_len > 0) {

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

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

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

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

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

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

413 }

414 }

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

416 if (response.body != NULL) {

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

418 }

419}

420

421void *http_handle_client(void *ptr) {

422 if (!ptr) {

423 pthread_exit(0);

424 }

425 conn_t *conn = (conn_t *) ptr;

426 if (http_ctx != NULL) {

427 conn->ssl = SSL_new(http_ctx);

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

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

430 perror("cannot SSL handshake");

431 pthread_exit(0);

432 }

433 }

434 http_request_t request = http_read_request(conn);

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

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

437 printf(

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

439 (addr ) & 0xff,

440 (addr >> 8) & 0xff,

441 (addr >> 16) & 0xff,

442 (addr >> 24) & 0xff,

443 request.method,

444 request.url

445 );

446 if (on_request_fn != NULL) {

447 http_response_t response = on_request_fn(&request);

448 http_write_response(conn, response);

449 http_response_free(&response);

450 }

451 }

452 http_request_free(&request);

453 if (http_ctx != NULL) {

454 SSL_shutdown(conn->ssl);

455 SSL_free(conn->ssl);

456 }

457 close(conn->sockfd);

458 free(conn);

459 pthread_exit(0);

460}

461

462void *http_handle_server(void *ptr) {

463 if (!ptr) {

464 pthread_exit(0);

465 }

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

467 struct pollfd fds[1];

468 fds[0].fd = sockfd;

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

470 while (!http_quit) {

471 usleep(100000);

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

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

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

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

476 conn->ssl = NULL;

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

478 free(conn);

479 }

480 else {

481 pthread_t thread;

482 pthread_create(&thread, 0, http_handle_client, (void *) conn);

483 pthread_detach(thread);

484 }

485 }

486 }

487 pthread_exit(0);

488}

489

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

491 const SSL_METHOD *method = TLS_server_method();

492 http_ctx = SSL_CTX_new(method);

493 if (!http_ctx) {

494 perror("cannot create SSL context");

495 errno = HTTP_ERR_NO_SSL_CONTEXT;

496 http_error = true;

497 return;

498 }

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

500 perror("cannot use certificate file");

501 errno = HTTP_ERR_INVALID_CERTIFICATE;

502 http_error = true;

503 }

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

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

506 errno = HTTP_ERR_INVALID_PRIVATE_KEY;

507 http_error = true;

508 }

509}

510

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

512 if (http_error) {

513 return;

514 }

515 errno = 0;

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

517 if (http_sockfd <= 0) {

518 perror("cannot create socket");

519 errno = HTTP_ERR_NO_SOCKET;

520 http_error = true;

521 return;

522 }

523 struct hostent *host = gethostbyname(hostname);

524 if (!host) {

525 perror("unknown host");

526 errno = HTTP_ERR_UNKNOWN_HOST;

527 http_error = true;

528 return;

529 }

530 struct sockaddr_in addr;

531 addr.sin_family = AF_INET;

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

533 addr.sin_port = htons(port);

534 int enable = 1;

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

536 perror("cannot reuse address");

537 errno = HTTP_ERR_NO_ADDR_REUSE;

538 http_error = true;

539 return;

540 }

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

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

543 errno = HTTP_ERR_ADDR_IN_USE;

544 http_error = true;

545 return;

546 }

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

548 perror("cannot listen on port");

549 errno = HTTP_ERR_NO_LISTEN;

550 http_error = true;

551 return;

552 }

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

554}

555

556void http_close() {

557 http_quit = true;

558 if (!http_error) {

559 pthread_join(http_thread, NULL);

560 }

561 close(http_sockfd);

562 if (http_ctx != NULL) {

563 SSL_CTX_free(http_ctx);

564 }

565}