|
| 1 | +#include "server.h" |
| 2 | +#include "html.h" |
| 3 | + |
| 4 | +int |
| 5 | +callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { |
| 6 | + unsigned char buffer[4096 + LWS_PRE]; |
| 7 | + unsigned char *p; |
| 8 | + unsigned char *end; |
| 9 | + char buf[256]; |
| 10 | + int n; |
| 11 | + |
| 12 | + switch (reason) { |
| 13 | + case LWS_CALLBACK_HTTP: |
| 14 | + lwsl_notice("lws_http_serve: %s\n", in); |
| 15 | + |
| 16 | + { |
| 17 | + char name[100], rip[50]; |
| 18 | + lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name, |
| 19 | + sizeof(name), rip, sizeof(rip)); |
| 20 | + sprintf(buf, "%s (%s)", name, rip); |
| 21 | + lwsl_notice("HTTP connect from %s\n", buf); |
| 22 | + } |
| 23 | + |
| 24 | + if (len < 1) { |
| 25 | + lws_return_http_status(wsi, HTTP_STATUS_BAD_REQUEST, NULL); |
| 26 | + goto try_to_reuse; |
| 27 | + } |
| 28 | + |
| 29 | + if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) |
| 30 | + return 0; |
| 31 | + |
| 32 | + if (strcmp((const char *) in, "/")) { |
| 33 | + lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL); |
| 34 | + goto try_to_reuse; |
| 35 | + } |
| 36 | + |
| 37 | + p = buffer + LWS_PRE; |
| 38 | + end = p + sizeof(buffer) - LWS_PRE; |
| 39 | + |
| 40 | + if (lws_add_http_header_status(wsi, 200, &p, end)) |
| 41 | + return 1; |
| 42 | + if (lws_add_http_header_by_token(wsi, |
| 43 | + WSI_TOKEN_HTTP_CONTENT_TYPE, |
| 44 | + (unsigned char *) "text/html", |
| 45 | + 9, &p, end)) |
| 46 | + return 1; |
| 47 | + if (lws_add_http_header_content_length(wsi, index_html_len, &p, end)) |
| 48 | + return 1; |
| 49 | + if (lws_finalize_http_header(wsi, &p, end)) |
| 50 | + return 1; |
| 51 | + n = lws_write(wsi, buffer + LWS_PRE, p - (buffer + LWS_PRE), LWS_WRITE_HTTP_HEADERS); |
| 52 | + if (n < 0) { |
| 53 | + return 1; |
| 54 | + } |
| 55 | + |
| 56 | + n = lws_write_http(wsi, index_html, index_html_len); |
| 57 | + if (n < 0) |
| 58 | + return 1; |
| 59 | + goto try_to_reuse; |
| 60 | + case LWS_CALLBACK_HTTP_WRITEABLE: |
| 61 | + lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n"); |
| 62 | + break; |
| 63 | + default: |
| 64 | + break; |
| 65 | + } |
| 66 | + |
| 67 | + return 0; |
| 68 | + |
| 69 | + /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */ |
| 70 | + try_to_reuse: |
| 71 | + if (lws_http_transaction_completed(wsi)) |
| 72 | + return -1; |
| 73 | + |
| 74 | + return 0; |
| 75 | +} |
0 commit comments