tinyhttpd.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 void update_date(htimer_t* timer) {
  89. uint64_t now = hloop_now(hevent_loop(timer));
  90. gmtime_fmt(now, s_date);
  91. }
  92. static int http_response_dump(http_msg_t* msg, char* buf, int len) {
  93. int offset = 0;
  94. // status line
  95. 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);
  96. // headers
  97. if (msg->content_length > 0) {
  98. offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length);
  99. }
  100. if (*msg->content_type) {
  101. offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type);
  102. }
  103. offset += snprintf(buf + offset, len - offset, "Server: libhv/%s\r\n", hv_version());
  104. offset += snprintf(buf + offset, len - offset, "Date: %s\r\n", s_date);
  105. // offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close");
  106. // TODO: Add your headers
  107. offset += snprintf(buf + offset, len - offset, "\r\n");
  108. // body
  109. if (msg->body && msg->content_length > 0) {
  110. memcpy(buf + offset, msg->body, msg->content_length);
  111. offset += msg->content_length;
  112. }
  113. return offset;
  114. }
  115. static int http_reply(http_conn_t* conn,
  116. int status_code, const char* status_message,
  117. const char* content_type,
  118. const char* body, int body_len) {
  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) strncpy(resp->status_message, status_message, sizeof(req->status_message) - 1);
  125. if (content_type) strncpy(resp->content_type, content_type, sizeof(req->content_type) - 1);
  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 = (char*)body;
  131. }
  132. char* buf = NULL;
  133. STACK_OR_HEAP_ALLOC(buf, HTTP_MAX_HEAD_LENGTH + resp->content_length, HTTP_MAX_HEAD_LENGTH + 1024);
  134. int msglen = http_response_dump(resp, buf, HTTP_MAX_HEAD_LENGTH + resp->content_length);
  135. int nwrite = hio_write(conn->io, buf, msglen);
  136. STACK_OR_HEAP_FREE(buf);
  137. return nwrite < 0 ? nwrite : msglen;
  138. }
  139. static int http_serve_file(http_conn_t* conn) {
  140. http_msg_t* req = &conn->request;
  141. http_msg_t* resp = &conn->response;
  142. // GET / HTTP/1.1\r\n
  143. const char* filepath = req->path + 1;
  144. // homepage
  145. if (*filepath == '\0') {
  146. filepath = "index.html";
  147. }
  148. FILE* fp = fopen(filepath, "rb");
  149. if (!fp) {
  150. http_reply(conn, 404, NOT_FOUND, TEXT_HTML, HTML_TAG_BEGIN NOT_FOUND HTML_TAG_END, 0);
  151. return 404;
  152. }
  153. char buf[4096] = {0};
  154. // send head
  155. size_t filesize = hv_filesize(filepath);
  156. resp->content_length = filesize;
  157. const char* suffix = hv_suffixname(filepath);
  158. const char* content_type = NULL;
  159. if (strcmp(suffix, "html") == 0) {
  160. content_type = TEXT_HTML;
  161. } else {
  162. // TODO: set content_type by suffix
  163. }
  164. int nwrite = http_reply(conn, 200, "OK", content_type, NULL, 0);
  165. if (nwrite < 0) return nwrite; // disconnected
  166. // send file
  167. int nread = 0;
  168. while (1) {
  169. nread = fread(buf, 1, sizeof(buf), fp);
  170. if (nread <= 0) break;
  171. nwrite = hio_write(conn->io, buf, nread);
  172. if (nwrite < 0) return nwrite; // disconnected
  173. if (nwrite == 0) {
  174. // send too fast or peer recv too slow
  175. // WARN: too large file should control sending rate, just delay a while in the demo!
  176. hv_delay(10);
  177. }
  178. }
  179. fclose(fp);
  180. return 200;
  181. }
  182. static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) {
  183. // GET / HTTP/1.1
  184. http_msg_t* req = &conn->request;
  185. sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version);
  186. if (req->major_version != 1) return false;
  187. if (req->minor_version == 1) req->keepalive = 1;
  188. // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version);
  189. return true;
  190. }
  191. static bool parse_http_head(http_conn_t* conn, char* buf, int len) {
  192. http_msg_t* req = &conn->request;
  193. // Content-Type: text/html
  194. const char* key = buf;
  195. const char* val = buf;
  196. char* delim = strchr(buf, ':');
  197. if (!delim) return false;
  198. *delim = '\0';
  199. val = delim + 1;
  200. // trim space
  201. while (*val == ' ') ++val;
  202. // printf("%s: %s\r\n", key, val);
  203. if (stricmp(key, "Content-Length") == 0) {
  204. req->content_length = atoi(val);
  205. } else if (stricmp(key, "Content-Type") == 0) {
  206. strncpy(req->content_type, val, sizeof(req->content_type) - 1);
  207. } else if (stricmp(key, "Connection") == 0) {
  208. if (stricmp(val, "close") == 0) {
  209. req->keepalive = 0;
  210. }
  211. } else {
  212. // TODO: save other head
  213. }
  214. return true;
  215. }
  216. static int on_request(http_conn_t* conn) {
  217. http_msg_t* req = &conn->request;
  218. // TODO: router
  219. if (strcmp(req->method, "GET") == 0) {
  220. // GET /plaintext HTTP/1.1\r\n
  221. if (strcmp(req->path, "/plaintext") == 0) {
  222. http_reply(conn, 200, "OK", TEXT_PLAIN, "Hello, World!", 13);
  223. return 200;
  224. } else {
  225. // TODO: Add handler for your path
  226. }
  227. return http_serve_file(conn);
  228. } else if (strcmp(req->method, "POST") == 0) {
  229. // POST /echo HTTP/1.1\r\n
  230. if (strcmp(req->path, "/echo") == 0) {
  231. http_reply(conn, 200, "OK", req->content_type, req->body, req->content_length);
  232. return 200;
  233. } else {
  234. // TODO: Add handler for your path
  235. }
  236. } else {
  237. // TODO: handle other method
  238. }
  239. http_reply(conn, 501, NOT_IMPLEMENTED, TEXT_HTML, HTML_TAG_BEGIN NOT_IMPLEMENTED HTML_TAG_END, 0);
  240. return 501;
  241. }
  242. static void on_close(hio_t* io) {
  243. // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
  244. http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
  245. if (conn) {
  246. HV_FREE(conn);
  247. hevent_set_userdata(io, NULL);
  248. }
  249. }
  250. static void on_recv(hio_t* io, void* buf, int readbytes) {
  251. char* str = (char*)buf;
  252. // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  253. // printf("%.*s", readbytes, str);
  254. http_conn_t* conn = (http_conn_t*)hevent_userdata(io);
  255. http_msg_t* req = &conn->request;
  256. switch (conn->state) {
  257. case s_begin:
  258. // printf("s_begin");
  259. conn->state = s_first_line;
  260. case s_first_line:
  261. // printf("s_first_line\n");
  262. if (readbytes < 2) {
  263. fprintf(stderr, "Not match \r\n!");
  264. hio_close(io);
  265. return;
  266. }
  267. str[readbytes - 2] = '\0';
  268. if (parse_http_request_line(conn, str, readbytes - 2) == false) {
  269. fprintf(stderr, "Failed to parse http request line:\n%s\n", str);
  270. hio_close(io);
  271. return;
  272. }
  273. // start read head
  274. conn->state = s_head;
  275. hio_readline(io);
  276. break;
  277. case s_head:
  278. // printf("s_head\n");
  279. if (readbytes < 2) {
  280. fprintf(stderr, "Not match \r\n!");
  281. hio_close(io);
  282. return;
  283. }
  284. if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') {
  285. conn->state = s_head_end;
  286. } else {
  287. str[readbytes - 2] = '\0';
  288. if (parse_http_head(conn, str, readbytes - 2) == false) {
  289. fprintf(stderr, "Failed to parse http head:\n%s\n", str);
  290. hio_close(io);
  291. return;
  292. }
  293. hio_readline(io);
  294. break;
  295. }
  296. case s_head_end:
  297. // printf("s_head_end\n");
  298. if (req->content_length == 0) {
  299. conn->state = s_end;
  300. goto s_end;
  301. } else {
  302. // start read body
  303. conn->state = s_body;
  304. // WARN: too large content_length should read multiple times!
  305. hio_readbytes(io, req->content_length);
  306. break;
  307. }
  308. case s_body:
  309. // printf("s_body\n");
  310. req->body = str;
  311. req->body_len += readbytes;
  312. if (req->body_len == 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. tcp_nodelay(hio_fd(io), 1);
  372. hio_detach(io);
  373. hloop_t* worker_loop = get_next_loop();
  374. hevent_t ev;
  375. memset(&ev, 0, sizeof(ev));
  376. ev.loop = worker_loop;
  377. ev.cb = new_conn_event;
  378. ev.userdata = io;
  379. hloop_post_event(worker_loop, &ev);
  380. }
  381. static HTHREAD_ROUTINE(worker_thread) {
  382. hloop_t* loop = (hloop_t*)userdata;
  383. hloop_run(loop);
  384. return 0;
  385. }
  386. static HTHREAD_ROUTINE(accept_thread) {
  387. hloop_t* loop = (hloop_t*)userdata;
  388. hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept);
  389. if (listenio == NULL) {
  390. exit(1);
  391. }
  392. tcp_nodelay(hio_fd(listenio), 1);
  393. printf("tinyhttpd listening on %s:%d, listenfd=%d, thread_num=%d\n",
  394. host, port, hio_fd(listenio), thread_num);
  395. // NOTE: add timer to update date every 1s
  396. htimer_add(loop, update_date, 1000, INFINITE);
  397. hloop_run(loop);
  398. return 0;
  399. }
  400. int main(int argc, char** argv) {
  401. if (argc < 2) {
  402. printf("Usage: %s port [thread_num]\n", argv[0]);
  403. return -10;
  404. }
  405. port = atoi(argv[1]);
  406. if (argc > 2) {
  407. thread_num = atoi(argv[2]);
  408. } else {
  409. thread_num = get_ncpu();
  410. }
  411. if (thread_num == 0) thread_num = 1;
  412. worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num);
  413. for (int i = 0; i < thread_num; ++i) {
  414. worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE);
  415. hthread_t th = hthread_create(worker_thread, worker_loops[i]);
  416. #if defined(OS_LINUX) && HAVE_PTHREAD_H
  417. cpu_set_t mask;
  418. CPU_ZERO(&mask);
  419. CPU_SET(i, &mask);
  420. // printf("pthread_setaffinity_np %d\n", i);
  421. pthread_setaffinity_np(th, sizeof(cpu_set_t), &mask);
  422. #endif
  423. }
  424. accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
  425. accept_thread(accept_loop);
  426. return 0;
  427. }