tinyhttpd.c 12 KB

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