1
0

tinyhttpd.c 13 KB

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