tinyhttpd.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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/ping
  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/ping
  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. // for http_serve_file
  87. FILE* fp;
  88. hbuf_t filebuf;
  89. } http_conn_t;
  90. static char s_date[32] = {0};
  91. static void update_date(htimer_t* timer) {
  92. uint64_t now = hloop_now(hevent_loop(timer));
  93. gmtime_fmt(now, s_date);
  94. }
  95. static int http_response_dump(http_msg_t* msg, char* buf, int len) {
  96. int offset = 0;
  97. // status line
  98. 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);
  99. // headers
  100. offset += snprintf(buf + offset, len - offset, "Server: libhv/%s\r\n", hv_version());
  101. offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close");
  102. if (msg->content_length > 0) {
  103. offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length);
  104. }
  105. if (*msg->content_type) {
  106. offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type);
  107. }
  108. if (*s_date) {
  109. offset += snprintf(buf + offset, len - offset, "Date: %s\r\n", s_date);
  110. }
  111. // TODO: Add your headers
  112. offset += snprintf(buf + offset, len - offset, "\r\n");
  113. // body
  114. if (msg->body && msg->content_length > 0) {
  115. memcpy(buf + offset, msg->body, msg->content_length);
  116. offset += msg->content_length;
  117. }
  118. return offset;
  119. }
  120. static int http_reply(http_conn_t* conn,
  121. int status_code, const char* status_message,
  122. const char* content_type,
  123. const char* body, int body_len) {
  124. http_msg_t* req = &conn->request;
  125. http_msg_t* resp = &conn->response;
  126. resp->major_version = req->major_version;
  127. resp->minor_version = req->minor_version;
  128. resp->status_code = status_code;
  129. if (status_message) strncpy(resp->status_message, status_message, sizeof(req->status_message) - 1);
  130. if (content_type) strncpy(resp->content_type, content_type, sizeof(req->content_type) - 1);
  131. resp->keepalive = req->keepalive;
  132. if (body) {
  133. if (body_len <= 0) body_len = strlen(body);
  134. resp->content_length = body_len;
  135. resp->body = (char*)body;
  136. }
  137. char* buf = NULL;
  138. STACK_OR_HEAP_ALLOC(buf, HTTP_MAX_HEAD_LENGTH + resp->content_length, HTTP_MAX_HEAD_LENGTH + 1024);
  139. int msglen = http_response_dump(resp, buf, HTTP_MAX_HEAD_LENGTH + resp->content_length);
  140. int nwrite = hio_write(conn->io, buf, msglen);
  141. STACK_OR_HEAP_FREE(buf);
  142. return nwrite < 0 ? nwrite : msglen;
  143. }
  144. static void http_send_file(http_conn_t* conn) {
  145. if (!conn || !conn->fp) return;
  146. // alloc filebuf
  147. if (!conn->filebuf.base) {
  148. conn->filebuf.len = 4096;
  149. HV_ALLOC(conn->filebuf, conn->filebuf.len);
  150. }
  151. char* filebuf = conn->filebuf.base;
  152. size_t filebuflen = conn->filebuf.len;
  153. // read file
  154. int nread = fread(filebuf, 1, filebuflen, conn->fp);
  155. if (nread <= 0) {
  156. // eof or error
  157. hio_close(conn->io);
  158. return;
  159. }
  160. // send file
  161. hio_write(conn->io, filebuf, nread);
  162. }
  163. static void on_write(hio_t* io, const void* buf, int writebytes) {
  164. if (!io) return;
  165. if (!hio_write_is_complete(io)) return;
  166. http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
  167. http_send_file(conn);
  168. }
  169. static int http_serve_file(http_conn_t* conn) {
  170. http_msg_t* req = &conn->request;
  171. http_msg_t* resp = &conn->response;
  172. // GET / HTTP/1.1\r\n
  173. const char* filepath = req->path + 1;
  174. // homepage
  175. if (*filepath == '\0') {
  176. filepath = "index.html";
  177. }
  178. // open file
  179. conn->fp = fopen(filepath, "rb");
  180. if (!conn->fp) {
  181. http_reply(conn, 404, NOT_FOUND, TEXT_HTML, HTML_TAG_BEGIN NOT_FOUND HTML_TAG_END, 0);
  182. return 404;
  183. }
  184. // send head
  185. size_t filesize = hv_filesize(filepath);
  186. resp->content_length = filesize;
  187. const char* suffix = hv_suffixname(filepath);
  188. const char* content_type = NULL;
  189. if (strcmp(suffix, "html") == 0) {
  190. content_type = TEXT_HTML;
  191. } else {
  192. // TODO: set content_type by suffix
  193. }
  194. hio_setcb_write(conn->io, on_write);
  195. int nwrite = http_reply(conn, 200, "OK", content_type, NULL, 0);
  196. if (nwrite < 0) return nwrite; // disconnected
  197. return 200;
  198. }
  199. static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) {
  200. // GET / HTTP/1.1
  201. http_msg_t* req = &conn->request;
  202. sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version);
  203. if (req->major_version != 1) return false;
  204. if (req->minor_version == 1) req->keepalive = 1;
  205. // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version);
  206. return true;
  207. }
  208. static bool parse_http_head(http_conn_t* conn, char* buf, int len) {
  209. http_msg_t* req = &conn->request;
  210. // Content-Type: text/html
  211. const char* key = buf;
  212. const char* val = buf;
  213. char* delim = strchr(buf, ':');
  214. if (!delim) return false;
  215. *delim = '\0';
  216. val = delim + 1;
  217. // trim space
  218. while (*val == ' ') ++val;
  219. // printf("%s: %s\r\n", key, val);
  220. if (stricmp(key, "Content-Length") == 0) {
  221. req->content_length = atoi(val);
  222. } else if (stricmp(key, "Content-Type") == 0) {
  223. strncpy(req->content_type, val, sizeof(req->content_type) - 1);
  224. } else if (stricmp(key, "Connection") == 0) {
  225. if (stricmp(val, "close") == 0) {
  226. req->keepalive = 0;
  227. }
  228. } else {
  229. // TODO: save other head
  230. }
  231. return true;
  232. }
  233. static int on_request(http_conn_t* conn) {
  234. http_msg_t* req = &conn->request;
  235. // TODO: router
  236. if (strcmp(req->method, "GET") == 0) {
  237. // GET /ping HTTP/1.1\r\n
  238. if (strcmp(req->path, "/ping") == 0) {
  239. http_reply(conn, 200, "OK", TEXT_PLAIN, "pong", 4);
  240. return 200;
  241. } else {
  242. // TODO: Add handler for your path
  243. }
  244. return http_serve_file(conn);
  245. } else if (strcmp(req->method, "POST") == 0) {
  246. // POST /echo HTTP/1.1\r\n
  247. if (strcmp(req->path, "/echo") == 0) {
  248. http_reply(conn, 200, "OK", req->content_type, req->body, req->content_length);
  249. return 200;
  250. } else {
  251. // TODO: Add handler for your path
  252. }
  253. } else {
  254. // TODO: handle other method
  255. }
  256. http_reply(conn, 501, NOT_IMPLEMENTED, TEXT_HTML, HTML_TAG_BEGIN NOT_IMPLEMENTED HTML_TAG_END, 0);
  257. return 501;
  258. }
  259. static void on_close(hio_t* io) {
  260. // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
  261. http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
  262. if (conn) {
  263. if (conn->fp) {
  264. // close file
  265. fclose(conn->fp);
  266. conn->fp = NULL;
  267. }
  268. // free filebuf
  269. HV_FREE(conn->filebuf.base);
  270. HV_FREE(conn);
  271. hevent_set_userdata(io, NULL);
  272. }
  273. }
  274. static void on_recv(hio_t* io, void* buf, int readbytes) {
  275. char* str = (char*)buf;
  276. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  277. // printf("%.*s", readbytes, str);
  278. http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
  279. http_msg_t* req = &conn->request;
  280. switch (conn->state) {
  281. case s_begin:
  282. // printf("s_begin");
  283. conn->state = s_first_line;
  284. case s_first_line:
  285. // printf("s_first_line\n");
  286. if (readbytes < 2) {
  287. fprintf(stderr, "Not match \r\n!");
  288. hio_close(io);
  289. return;
  290. }
  291. str[readbytes - 2] = '\0';
  292. if (parse_http_request_line(conn, str, readbytes - 2) == false) {
  293. fprintf(stderr, "Failed to parse http request line:\n%s\n", str);
  294. hio_close(io);
  295. return;
  296. }
  297. // start read head
  298. conn->state = s_head;
  299. hio_readline(io);
  300. break;
  301. case s_head:
  302. // printf("s_head\n");
  303. if (readbytes < 2) {
  304. fprintf(stderr, "Not match \r\n!");
  305. hio_close(io);
  306. return;
  307. }
  308. if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') {
  309. conn->state = s_head_end;
  310. } else {
  311. str[readbytes - 2] = '\0';
  312. if (parse_http_head(conn, str, readbytes - 2) == false) {
  313. fprintf(stderr, "Failed to parse http head:\n%s\n", str);
  314. hio_close(io);
  315. return;
  316. }
  317. hio_readline(io);
  318. break;
  319. }
  320. case s_head_end:
  321. // printf("s_head_end\n");
  322. if (req->content_length == 0) {
  323. conn->state = s_end;
  324. goto s_end;
  325. } else {
  326. // start read body
  327. conn->state = s_body;
  328. // WARN: too large content_length should read multiple times!
  329. hio_readbytes(io, req->content_length);
  330. break;
  331. }
  332. case s_body:
  333. // printf("s_body\n");
  334. req->body = str;
  335. req->body_len += readbytes;
  336. if (req->body_len == req->content_length) {
  337. conn->state = s_end;
  338. } else {
  339. // WARN: too large content_length should be handled by streaming!
  340. break;
  341. }
  342. case s_end:
  343. s_end:
  344. // printf("s_end\n");
  345. // received complete request
  346. on_request(conn);
  347. if (hio_is_closed(io)) return;
  348. if (req->keepalive) {
  349. // Connection: keep-alive\r\n
  350. // reset and receive next request
  351. memset(&conn->request, 0, sizeof(http_msg_t));
  352. memset(&conn->response, 0, sizeof(http_msg_t));
  353. conn->state = s_first_line;
  354. hio_readline(io);
  355. } else {
  356. // Connection: close\r\n
  357. hio_close(io);
  358. }
  359. break;
  360. default: break;
  361. }
  362. }
  363. static void new_conn_event(hevent_t* ev) {
  364. hloop_t* loop = ev->loop;
  365. hio_t* io = (hio_t*)hevent_userdata(ev);
  366. hio_attach(loop, io);
  367. /*
  368. char localaddrstr[SOCKADDR_STRLEN] = {0};
  369. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  370. printf("tid=%ld connfd=%d [%s] <= [%s]\n",
  371. (long)hv_gettid(),
  372. (int)hio_fd(io),
  373. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  374. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  375. */
  376. hio_setcb_close(io, on_close);
  377. hio_setcb_read(io, on_recv);
  378. hio_set_keepalive_timeout(io, HTTP_KEEPALIVE_TIMEOUT);
  379. http_conn_t* conn = NULL;
  380. HV_ALLOC_SIZEOF(conn);
  381. conn->io = io;
  382. hevent_set_userdata(io, conn);
  383. // start read first line
  384. conn->state = s_first_line;
  385. hio_readline(io);
  386. }
  387. static hloop_t* get_next_loop() {
  388. static int s_cur_index = 0;
  389. if (s_cur_index == thread_num) {
  390. s_cur_index = 0;
  391. }
  392. return worker_loops[s_cur_index++];
  393. }
  394. static void on_accept(hio_t* io) {
  395. hio_detach(io);
  396. hloop_t* worker_loop = get_next_loop();
  397. hevent_t ev;
  398. memset(&ev, 0, sizeof(ev));
  399. ev.loop = worker_loop;
  400. ev.cb = new_conn_event;
  401. ev.userdata = io;
  402. hloop_post_event(worker_loop, &ev);
  403. }
  404. static HTHREAD_ROUTINE(worker_thread) {
  405. hloop_t* loop = (hloop_t*)userdata;
  406. hloop_run(loop);
  407. return 0;
  408. }
  409. static HTHREAD_ROUTINE(accept_thread) {
  410. hloop_t* loop = (hloop_t*)userdata;
  411. hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept);
  412. if (listenio == NULL) {
  413. exit(1);
  414. }
  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. htimer_add(loop, update_date, 1000, INFINITE);
  419. hloop_run(loop);
  420. return 0;
  421. }
  422. int main(int argc, char** argv) {
  423. if (argc < 2) {
  424. printf("Usage: %s port [thread_num]\n", argv[0]);
  425. return -10;
  426. }
  427. port = atoi(argv[1]);
  428. if (argc > 2) {
  429. thread_num = atoi(argv[2]);
  430. } else {
  431. thread_num = get_ncpu();
  432. }
  433. if (thread_num == 0) thread_num = 1;
  434. worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num);
  435. for (int i = 0; i < thread_num; ++i) {
  436. worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE);
  437. hthread_create(worker_thread, worker_loops[i]);
  438. }
  439. accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
  440. accept_thread(accept_loop);
  441. return 0;
  442. }