tinyhttpd.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*
  2. * tinyhttpd tiny http server
  3. *
  4. * @build make examples
  5. *
  6. * @server bin/tinyhttpd 8000
  7. *
  8. * @client bin/curl -v http://127.0.0.1:8000/
  9. * bin/curl -v http://127.0.0.1:8000/plaintext
  10. * bin/curl -v http://127.0.0.1:8000/echo -d "hello,world!"
  11. *
  12. * @webbench bin/wrk http://127.0.0.1:8000/plaintext
  13. *
  14. */
  15. #include "hv.h"
  16. #include "hloop.h"
  17. /*
  18. * workflow:
  19. * hloop_new -> hloop_create_tcp_server -> hloop_run ->
  20. * on_accept -> HV_ALLOC(http_conn_t) -> hio_readline ->
  21. * on_recv -> parse_http_request_line -> hio_readline ->
  22. * on_recv -> parse_http_head -> ... -> hio_readbytes(content_length) ->
  23. * on_recv -> on_request -> http_reply-> hio_write -> hio_close ->
  24. * on_close -> HV_FREE(http_conn_t)
  25. *
  26. */
  27. static const char* host = "0.0.0.0";
  28. static int port = 8000;
  29. static int thread_num = 1;
  30. static hloop_t* accept_loop = NULL;
  31. static hloop_t** worker_loops = NULL;
  32. #define HTTP_KEEPALIVE_TIMEOUT 60000 // ms
  33. #define HTTP_MAX_URL_LENGTH 256
  34. #define HTTP_MAX_HEAD_LENGTH 1024
  35. #define HTML_TAG_BEGIN "<html><body><center><h1>"
  36. #define HTML_TAG_END "</h1></center></body></html>"
  37. // status_message
  38. #define HTTP_OK "OK"
  39. #define NOT_FOUND "Not Found"
  40. #define NOT_IMPLEMENTED "Not Implemented"
  41. // Content-Type
  42. #define TEXT_PLAIN "text/plain"
  43. #define TEXT_HTML "text/html"
  44. typedef enum {
  45. s_begin,
  46. s_first_line,
  47. s_request_line = s_first_line,
  48. s_status_line = s_first_line,
  49. s_head,
  50. s_head_end,
  51. s_body,
  52. s_end
  53. } http_state_e;
  54. typedef struct {
  55. // first line
  56. int major_version;
  57. int minor_version;
  58. union {
  59. // request line
  60. struct {
  61. char method[32];
  62. char path[HTTP_MAX_URL_LENGTH];
  63. };
  64. // status line
  65. struct {
  66. int status_code;
  67. char status_message[64];
  68. };
  69. };
  70. // headers
  71. char host[64];
  72. int content_length;
  73. char content_type[64];
  74. unsigned keepalive: 1;
  75. // char head[HTTP_MAX_HEAD_LENGTH];
  76. // int head_len;
  77. // body
  78. char* body;
  79. int body_len; // body_len = content_length
  80. } http_msg_t;
  81. typedef struct {
  82. hio_t* io;
  83. http_state_e state;
  84. http_msg_t request;
  85. http_msg_t response;
  86. } http_conn_t;
  87. static char s_date[32] = "Sun, 15 May 2022 12:34:56 GMT";
  88. static char s_plaintext_response_str[256] = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\nContent-Type: text/plain\r\nServer: libhv\r\nDate: Sun, 15 May 2022 12:34:56 GMT\r\n\r\nHello, World!";
  89. static int s_plaintext_response_len = 0;
  90. static char* s_plaintext_date = NULL;
  91. static void update_date(htimer_t* timer) {
  92. uint64_t now = hloop_now(hevent_loop(timer));
  93. gmtime_fmt(now, s_date);
  94. if (s_plaintext_date) {
  95. memcpy(s_plaintext_date, s_date, GMTIME_FMT_BUFLEN - 1);
  96. }
  97. }
  98. static int http_response_dump(http_msg_t* msg, char* buf, int len) {
  99. int offset = 0;
  100. // status line
  101. offset += snprintf(buf + offset, len - offset, "HTTP/%d.%d %d %s\r\n", msg->major_version, msg->minor_version, msg->status_code, msg->status_message);
  102. // headers
  103. if (msg->content_length > 0) {
  104. offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length);
  105. }
  106. if (*msg->content_type) {
  107. offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type);
  108. }
  109. offset += snprintf(buf + offset, len - offset, "Server: libhv/%s\r\n", hv_version());
  110. offset += snprintf(buf + offset, len - offset, "Date: %s\r\n", s_date);
  111. // offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close");
  112. // TODO: Add your headers
  113. offset += snprintf(buf + offset, len - offset, "\r\n");
  114. // body
  115. if (msg->body && msg->content_length > 0) {
  116. memcpy(buf + offset, msg->body, msg->content_length);
  117. offset += msg->content_length;
  118. }
  119. return offset;
  120. }
  121. static int http_reply(http_conn_t* conn,
  122. int status_code, const char* status_message,
  123. const char* content_type,
  124. const char* body, int body_len) {
  125. http_msg_t* req = &conn->request;
  126. http_msg_t* resp = &conn->response;
  127. resp->major_version = req->major_version;
  128. resp->minor_version = req->minor_version;
  129. resp->status_code = status_code;
  130. if (status_message) strncpy(resp->status_message, status_message, sizeof(req->status_message) - 1);
  131. if (content_type) strncpy(resp->content_type, content_type, sizeof(req->content_type) - 1);
  132. resp->keepalive = req->keepalive;
  133. if (body) {
  134. if (body_len <= 0) body_len = strlen(body);
  135. resp->content_length = body_len;
  136. resp->body = (char*)body;
  137. }
  138. char* buf = NULL;
  139. STACK_OR_HEAP_ALLOC(buf, HTTP_MAX_HEAD_LENGTH + resp->content_length, HTTP_MAX_HEAD_LENGTH + 1024);
  140. int msglen = http_response_dump(resp, buf, HTTP_MAX_HEAD_LENGTH + resp->content_length);
  141. int nwrite = hio_write(conn->io, buf, msglen);
  142. STACK_OR_HEAP_FREE(buf);
  143. return nwrite < 0 ? nwrite : msglen;
  144. }
  145. static int http_serve_file(http_conn_t* conn) {
  146. http_msg_t* req = &conn->request;
  147. http_msg_t* resp = &conn->response;
  148. // GET / HTTP/1.1\r\n
  149. const char* filepath = req->path + 1;
  150. // homepage
  151. if (*filepath == '\0') {
  152. filepath = "index.html";
  153. }
  154. FILE* fp = fopen(filepath, "rb");
  155. if (!fp) {
  156. http_reply(conn, 404, NOT_FOUND, TEXT_HTML, HTML_TAG_BEGIN NOT_FOUND HTML_TAG_END, 0);
  157. return 404;
  158. }
  159. char buf[4096] = {0};
  160. // send head
  161. size_t filesize = hv_filesize(filepath);
  162. resp->content_length = filesize;
  163. const char* suffix = hv_suffixname(filepath);
  164. const char* content_type = NULL;
  165. if (strcmp(suffix, "html") == 0) {
  166. content_type = TEXT_HTML;
  167. } else {
  168. // TODO: set content_type by suffix
  169. }
  170. int nwrite = http_reply(conn, 200, "OK", content_type, NULL, 0);
  171. if (nwrite < 0) return nwrite; // disconnected
  172. // send file
  173. int nread = 0;
  174. while (1) {
  175. nread = fread(buf, 1, sizeof(buf), fp);
  176. if (nread <= 0) break;
  177. nwrite = hio_write(conn->io, buf, nread);
  178. if (nwrite < 0) return nwrite; // disconnected
  179. if (nwrite == 0) {
  180. // send too fast or peer recv too slow
  181. // WARN: too large file should control sending rate, just delay a while in the demo!
  182. hv_delay(10);
  183. }
  184. }
  185. fclose(fp);
  186. return 200;
  187. }
  188. static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) {
  189. // GET / HTTP/1.1
  190. http_msg_t* req = &conn->request;
  191. // sscanf is slow
  192. // sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version);
  193. // method
  194. char* src = buf;
  195. char* dst = req->method;
  196. while (*src != ' ') *dst++ = *src++;
  197. *dst = '\0';
  198. // path
  199. ++src;
  200. dst = req->path;
  201. while (*src != ' ') *dst++ = *src++;
  202. *dst = '\0';
  203. req->major_version = 1;
  204. req->minor_version = 1;
  205. if (req->major_version != 1) return false;
  206. if (req->minor_version == 1) req->keepalive = 1;
  207. // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version);
  208. return true;
  209. }
  210. static bool parse_http_head(http_conn_t* conn, char* buf, int len) {
  211. http_msg_t* req = &conn->request;
  212. // Content-Type: text/html
  213. const char* key = buf;
  214. const char* val = buf;
  215. char* delim = strchr(buf, ':');
  216. if (!delim) return false;
  217. *delim = '\0';
  218. val = delim + 1;
  219. // trim space
  220. while (*val == ' ') ++val;
  221. // printf("%s: %s\r\n", key, val);
  222. if (stricmp(key, "Content-Length") == 0) {
  223. req->content_length = atoi(val);
  224. } else if (stricmp(key, "Content-Type") == 0) {
  225. strncpy(req->content_type, val, sizeof(req->content_type) - 1);
  226. } else if (stricmp(key, "Connection") == 0) {
  227. if (stricmp(val, "close") == 0) {
  228. req->keepalive = 0;
  229. }
  230. } else {
  231. // TODO: save other head
  232. }
  233. return true;
  234. }
  235. static int on_request(http_conn_t* conn) {
  236. http_msg_t* req = &conn->request;
  237. // TODO: router
  238. if (strcmp(req->method, "GET") == 0) {
  239. // GET /plaintext HTTP/1.1\r\n
  240. if (strcmp(req->path, "/plaintext") == 0) {
  241. // http_reply(conn, 200, "OK", TEXT_PLAIN, "Hello, World!", 13);
  242. hio_write(conn->io, s_plaintext_response_str, s_plaintext_response_len);
  243. return 200;
  244. } else {
  245. // TODO: Add handler for your path
  246. }
  247. return http_serve_file(conn);
  248. } else if (strcmp(req->method, "POST") == 0) {
  249. // POST /echo HTTP/1.1\r\n
  250. if (strcmp(req->path, "/echo") == 0) {
  251. http_reply(conn, 200, "OK", req->content_type, req->body, req->content_length);
  252. return 200;
  253. } else {
  254. // TODO: Add handler for your path
  255. }
  256. } else {
  257. // TODO: handle other method
  258. }
  259. http_reply(conn, 501, NOT_IMPLEMENTED, TEXT_HTML, HTML_TAG_BEGIN NOT_IMPLEMENTED HTML_TAG_END, 0);
  260. return 501;
  261. }
  262. static void on_close(hio_t* io) {
  263. // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
  264. http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
  265. if (conn) {
  266. HV_FREE(conn);
  267. hevent_set_userdata(io, NULL);
  268. }
  269. }
  270. static void on_recv(hio_t* io, void* buf, int readbytes) {
  271. char* str = (char*)buf;
  272. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  273. // printf("%.*s", readbytes, str);
  274. http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
  275. http_msg_t* req = &conn->request;
  276. switch (conn->state) {
  277. case s_begin:
  278. // printf("s_begin");
  279. conn->state = s_first_line;
  280. case s_first_line:
  281. // printf("s_first_line\n");
  282. if (readbytes < 2) {
  283. fprintf(stderr, "Not match \r\n!");
  284. hio_close(io);
  285. return;
  286. }
  287. str[readbytes - 2] = '\0';
  288. if (parse_http_request_line(conn, str, readbytes - 2) == false) {
  289. fprintf(stderr, "Failed to parse http request line:\n%s\n", str);
  290. hio_close(io);
  291. return;
  292. }
  293. // start read head
  294. conn->state = s_head;
  295. hio_readline(io);
  296. break;
  297. case s_head:
  298. // printf("s_head\n");
  299. if (readbytes < 2) {
  300. fprintf(stderr, "Not match \r\n!");
  301. hio_close(io);
  302. return;
  303. }
  304. if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') {
  305. conn->state = s_head_end;
  306. } else {
  307. /*
  308. str[readbytes - 2] = '\0';
  309. if (parse_http_head(conn, str, readbytes - 2) == false) {
  310. fprintf(stderr, "Failed to parse http head:\n%s\n", str);
  311. hio_close(io);
  312. return;
  313. }
  314. */
  315. hio_readline(io);
  316. break;
  317. }
  318. case s_head_end:
  319. // printf("s_head_end\n");
  320. if (req->content_length == 0) {
  321. conn->state = s_end;
  322. goto s_end;
  323. } else {
  324. // start read body
  325. conn->state = s_body;
  326. // WARN: too large content_length should read multiple times!
  327. hio_readbytes(io, req->content_length);
  328. break;
  329. }
  330. case s_body:
  331. // printf("s_body\n");
  332. req->body = str;
  333. req->body_len += readbytes;
  334. if (req->body_len == req->content_length) {
  335. conn->state = s_end;
  336. } else {
  337. // WARN: too large content_length should be handled by streaming!
  338. break;
  339. }
  340. case s_end:
  341. s_end:
  342. // printf("s_end\n");
  343. // received complete request
  344. on_request(conn);
  345. if (hio_is_closed(io)) return;
  346. if (req->keepalive) {
  347. // Connection: keep-alive\r\n
  348. // reset and receive next request
  349. // memset(&conn->request, 0, sizeof(http_msg_t));
  350. // memset(&conn->response, 0, sizeof(http_msg_t));
  351. conn->state = s_first_line;
  352. hio_readline(io);
  353. } else {
  354. // Connection: close\r\n
  355. hio_close(io);
  356. }
  357. break;
  358. default: break;
  359. }
  360. }
  361. static void new_conn_event(hevent_t* ev) {
  362. hloop_t* loop = ev->loop;
  363. hio_t* io = (hio_t*)hevent_userdata(ev);
  364. hio_attach(loop, io);
  365. /*
  366. char localaddrstr[SOCKADDR_STRLEN] = {0};
  367. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  368. printf("tid=%ld connfd=%d [%s] <= [%s]\n",
  369. (long)hv_gettid(),
  370. (int)hio_fd(io),
  371. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  372. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  373. */
  374. hio_setcb_close(io, on_close);
  375. hio_setcb_read(io, on_recv);
  376. // hio_set_keepalive_timeout(io, HTTP_KEEPALIVE_TIMEOUT);
  377. http_conn_t* conn = NULL;
  378. HV_ALLOC_SIZEOF(conn);
  379. conn->io = io;
  380. hevent_set_userdata(io, conn);
  381. // start read first line
  382. conn->state = s_first_line;
  383. hio_readline(io);
  384. }
  385. static hloop_t* get_next_loop() {
  386. static int s_cur_index = 0;
  387. if (s_cur_index == thread_num) {
  388. s_cur_index = 0;
  389. }
  390. return worker_loops[s_cur_index++];
  391. }
  392. static void on_accept(hio_t* io) {
  393. tcp_nodelay(hio_fd(io), 1);
  394. hio_detach(io);
  395. hloop_t* worker_loop = get_next_loop();
  396. hevent_t ev;
  397. memset(&ev, 0, sizeof(ev));
  398. ev.loop = worker_loop;
  399. ev.cb = new_conn_event;
  400. ev.userdata = io;
  401. hloop_post_event(worker_loop, &ev);
  402. }
  403. static HTHREAD_ROUTINE(worker_thread) {
  404. hloop_t* loop = (hloop_t*)userdata;
  405. hloop_run(loop);
  406. return 0;
  407. }
  408. static HTHREAD_ROUTINE(accept_thread) {
  409. hloop_t* loop = (hloop_t*)userdata;
  410. hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept);
  411. if (listenio == NULL) {
  412. exit(1);
  413. }
  414. tcp_nodelay(hio_fd(listenio), 1);
  415. printf("tinyhttpd listening on %s:%d, listenfd=%d, thread_num=%d\n",
  416. host, port, hio_fd(listenio), thread_num);
  417. // NOTE: add timer to update date every 1s
  418. s_plaintext_response_len = strlen(s_plaintext_response_str);
  419. s_plaintext_date = strstr(s_plaintext_response_str, "Date: ") + 6;
  420. htimer_add(loop, update_date, 1000, INFINITE);
  421. hloop_run(loop);
  422. return 0;
  423. }
  424. int main(int argc, char** argv) {
  425. if (argc < 2) {
  426. printf("Usage: %s port [thread_num]\n", argv[0]);
  427. return -10;
  428. }
  429. port = atoi(argv[1]);
  430. if (argc > 2) {
  431. thread_num = atoi(argv[2]);
  432. } else {
  433. thread_num = get_ncpu();
  434. }
  435. if (thread_num == 0) thread_num = 1;
  436. worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num);
  437. for (int i = 0; i < thread_num; ++i) {
  438. worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE);
  439. hthread_t th = hthread_create(worker_thread, worker_loops[i]);
  440. #if defined(OS_LINUX) && HAVE_PTHREAD_H
  441. cpu_set_t mask;
  442. CPU_ZERO(&mask);
  443. CPU_SET(i, &mask);
  444. // printf("pthread_setaffinity_np %d\n", i);
  445. pthread_setaffinity_np(th, sizeof(cpu_set_t), &mask);
  446. #endif
  447. }
  448. accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
  449. accept_thread(accept_loop);
  450. return 0;
  451. }