1
0

tinyhttpd.c 12 KB

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