#include #include #include #include #include "pico/cyw43_arch.h" #include "lwip/pbuf.h" #include "lwip/tcp.h" #include "httpserver.h" #define HS_POLL_INTERVAL 20 #define HS_MAX_CONNS 4 #define HS_MAX_ROUTES 16 #define HS_MAX_WS_ROUTES 4 #define HS_REQ_BUF 8192 #define HS_HDR_BUF 512 #define HS_WS_PAYLOAD_MAX 2048 #define HS_SEND_CHUNK 1400 #define HS_WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" typedef enum { CONN_FREE = 0, CONN_HTTP, CONN_WS, } conn_mode_t; typedef struct { const char *method; const char *path; httpserver_handler_t fn; } route_t; typedef struct { const char *path; httpserver_ws_open_t on_open; httpserver_ws_msg_t on_msg; httpserver_ws_close_t on_close; } ws_route_t; struct httpserver_conn { conn_mode_t mode; httpserver_t *server; struct tcp_pcb *pcb; const ws_route_t *ws_route; char buf[HS_REQ_BUF]; int buf_len; int header_end; /* index of first body byte, or -1 */ int content_length; bool headers_complete; bool dispatched; /* streaming static response */ const uint8_t *static_body; size_t static_len; size_t static_sent; /* bytes queued via tcp_write */ size_t tx_acked; /* bytes ACKed (from tcp_sent) */ size_t tx_total; /* hdr_len + static_len */ bool write_done; char hdr[HS_HDR_BUF]; int hdr_len; int hdr_sent; }; struct httpserver { struct tcp_pcb *server_pcb; route_t routes[HS_MAX_ROUTES]; int route_count; ws_route_t ws_routes[HS_MAX_WS_ROUTES]; int ws_route_count; httpserver_conn_t conns[HS_MAX_CONNS]; }; static httpserver_t g_server; /* ---- SHA-1 ---- */ typedef struct { uint32_t state[5]; uint32_t count[2]; uint8_t buffer[64]; } sha1_ctx_t; static uint32_t sha1_rol(uint32_t v, uint32_t bits) { return (v << bits) | (v >> (32 - bits)); } static void sha1_transform(uint32_t state[5], const uint8_t *block) { uint32_t w[80]; for (int i = 0; i < 16; i++) { w[i] = ((uint32_t)block[i * 4] << 24) | ((uint32_t)block[i * 4 + 1] << 16) | ((uint32_t)block[i * 4 + 2] << 8) | ((uint32_t)block[i * 4 + 3]); } for (int i = 16; i < 80; i++) { w[i] = sha1_rol(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1); } uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; for (int i = 0; i < 80; i++) { uint32_t f, k; if (i < 20) { f = (b & c) | ((~b) & d); k = 0x5A827999; } else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; } else { f = b ^ c ^ d; k = 0xCA62C1D6; } uint32_t t = sha1_rol(a, 5) + f + e + k + w[i]; e = d; d = c; c = sha1_rol(b, 30); b = a; a = t; } state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; } static void sha1_init(sha1_ctx_t *ctx) { ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; ctx->state[4] = 0xC3D2E1F0; ctx->count[0] = ctx->count[1] = 0; } static void sha1_update(sha1_ctx_t *ctx, const uint8_t *data, size_t len) { size_t i; size_t idx = (ctx->count[0] >> 3) & 63; ctx->count[0] += (uint32_t)(len << 3); if (ctx->count[0] < (len << 3)) { ctx->count[1]++; } ctx->count[1] += (uint32_t)(len >> 29); size_t part = 64 - idx; if (len >= part) { memcpy(&ctx->buffer[idx], data, part); sha1_transform(ctx->state, ctx->buffer); for (i = part; i + 63 < len; i += 64) { sha1_transform(ctx->state, &data[i]); } idx = 0; } else { i = 0; } memcpy(&ctx->buffer[idx], &data[i], len - i); } static void sha1_final(sha1_ctx_t *ctx, uint8_t digest[20]) { uint8_t finalcount[8]; for (int i = 0; i < 8; i++) { finalcount[i] = (uint8_t)((ctx->count[(i >= 4) ? 0 : 1] >> ((3 - (i & 3)) * 8)) & 255); } uint8_t c = 0x80; sha1_update(ctx, &c, 1); while ((ctx->count[0] & 504) != 448) { c = 0x00; sha1_update(ctx, &c, 1); } sha1_update(ctx, finalcount, 8); for (int i = 0; i < 20; i++) { digest[i] = (uint8_t)((ctx->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); } } static void base64_encode_20(const uint8_t in[20], char out[29]) { static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int o = 0; for (int i = 0; i < 18; i += 3) { uint32_t v = ((uint32_t)in[i] << 16) | ((uint32_t)in[i + 1] << 8) | in[i + 2]; out[o++] = tbl[(v >> 18) & 63]; out[o++] = tbl[(v >> 12) & 63]; out[o++] = tbl[(v >> 6) & 63]; out[o++] = tbl[v & 63]; } uint32_t v = ((uint32_t)in[18] << 16) | ((uint32_t)in[19] << 8); out[o++] = tbl[(v >> 18) & 63]; out[o++] = tbl[(v >> 12) & 63]; out[o++] = tbl[(v >> 6) & 63]; out[o++] = '='; out[o] = '\0'; } static void ws_accept_key(const char *client_key, char out[29]) { char material[80]; snprintf(material, sizeof(material), "%s%s", client_key, HS_WS_GUID); sha1_ctx_t ctx; uint8_t digest[20]; sha1_init(&ctx); sha1_update(&ctx, (const uint8_t *)material, strlen(material)); sha1_final(&ctx, digest); base64_encode_20(digest, out); } static httpserver_conn_t *conn_alloc(httpserver_t *s, struct tcp_pcb *pcb) { for (int i = 0; i < HS_MAX_CONNS; i++) { if (s->conns[i].mode == CONN_FREE) { memset(&s->conns[i], 0, sizeof(s->conns[i])); s->conns[i].mode = CONN_HTTP; s->conns[i].server = s; s->conns[i].pcb = pcb; s->conns[i].header_end = -1; s->conns[i].content_length = -1; return &s->conns[i]; } } return NULL; } static void conn_free(httpserver_conn_t *conn) { if (conn) { memset(conn, 0, sizeof(*conn)); } } static err_t close_conn(httpserver_conn_t *conn, struct tcp_pcb *pcb, err_t err) { if (conn && conn->mode == CONN_WS && conn->ws_route && conn->ws_route->on_close) { conn->ws_route->on_close(conn); } if (!pcb) { conn_free(conn); return err; } tcp_arg(pcb, NULL); tcp_poll(pcb, NULL, 0); tcp_sent(pcb, NULL); tcp_recv(pcb, NULL); tcp_err(pcb, NULL); if (tcp_close(pcb) != ERR_OK) { tcp_abort(pcb); err = ERR_ABRT; } conn_free(conn); return err; } static bool header_has(const char *req, const char *name) { const char *p = req; size_t nlen = strlen(name); while (*p) { const char *eol = strstr(p, "\r\n"); if (!eol) { break; } if ((size_t)(eol - p) >= nlen) { bool match = true; for (size_t i = 0; i < nlen; i++) { if (tolower((unsigned char)p[i]) != tolower((unsigned char)name[i])) { match = false; break; } } if (match) { return true; } } p = eol + 2; } return false; } static bool header_value(const char *req, const char *name, char *out, size_t out_len) { const char *p = req; size_t nlen = strlen(name); while (*p) { const char *eol = strstr(p, "\r\n"); if (!eol) { break; } if ((size_t)(eol - p) > nlen + 1) { bool match = true; for (size_t i = 0; i < nlen; i++) { if (tolower((unsigned char)p[i]) != tolower((unsigned char)name[i])) { match = false; break; } } if (match && p[nlen] == ':') { const char *v = p + nlen + 1; while (v < eol && (*v == ' ' || *v == '\t')) { v++; } size_t len = (size_t)(eol - v); if (len >= out_len) { len = out_len - 1; } memcpy(out, v, len); out[len] = '\0'; return true; } } p = eol + 2; } return false; } static const char *status_text(int status) { switch (status) { case 200: return "OK"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 500: return "Internal Server Error"; default: return "OK"; } } static const ws_route_t *find_ws_route(httpserver_t *s, const char *path) { for (int i = 0; i < s->ws_route_count; i++) { if (strcmp(s->ws_routes[i].path, path) == 0) { return &s->ws_routes[i]; } } return NULL; } static const route_t *find_route(httpserver_t *s, const char *method, const char *path) { for (int i = 0; i < s->route_count; i++) { if (strcmp(s->routes[i].method, method) == 0 && strcmp(s->routes[i].path, path) == 0) { return &s->routes[i]; } } return NULL; } static bool parse_request_line(const char *req, char *method, size_t method_len, char *path, size_t path_len, char *query, size_t query_len) { method[0] = path[0] = query[0] = '\0'; const char *eol = strstr(req, "\r\n"); if (!eol) { return false; } char line[160]; size_t line_len = (size_t)(eol - req); if (line_len >= sizeof(line)) { line_len = sizeof(line) - 1; } memcpy(line, req, line_len); line[line_len] = '\0'; char *sp1 = strchr(line, ' '); if (!sp1) { return false; } *sp1 = '\0'; snprintf(method, method_len, "%s", line); char *uri = sp1 + 1; char *sp2 = strchr(uri, ' '); if (sp2) { *sp2 = '\0'; } char *q = strchr(uri, '?'); if (q) { *q = '\0'; snprintf(query, query_len, "%s", q + 1); } snprintf(path, path_len, "%s", uri); return true; } static err_t pump_static(httpserver_conn_t *conn) { if (!conn->pcb || !conn->static_body) { return ERR_OK; } while (conn->hdr_sent < conn->hdr_len) { size_t left = (size_t)(conn->hdr_len - conn->hdr_sent); u16_t space = tcp_sndbuf(conn->pcb); if (space == 0) { tcp_output(conn->pcb); return ERR_OK; } u16_t n = left < space ? (u16_t)left : space; if (n > HS_SEND_CHUNK) { n = HS_SEND_CHUNK; } err_t err = tcp_write(conn->pcb, conn->hdr + conn->hdr_sent, n, TCP_WRITE_FLAG_COPY); if (err == ERR_MEM) { tcp_output(conn->pcb); return ERR_OK; } if (err != ERR_OK) { return close_conn(conn, conn->pcb, ERR_ABRT); } conn->hdr_sent += n; } while (conn->static_sent < conn->static_len) { size_t left = conn->static_len - conn->static_sent; u16_t space = tcp_sndbuf(conn->pcb); if (space == 0) { tcp_output(conn->pcb); return ERR_OK; } u16_t n = left < space ? (u16_t)left : space; if (n > HS_SEND_CHUNK) { n = HS_SEND_CHUNK; } err_t err = tcp_write(conn->pcb, conn->static_body + conn->static_sent, n, TCP_WRITE_FLAG_COPY); if (err == ERR_MEM) { tcp_output(conn->pcb); return ERR_OK; } if (err != ERR_OK) { return close_conn(conn, conn->pcb, ERR_ABRT); } conn->static_sent += n; } tcp_output(conn->pcb); conn->write_done = true; /* Only close after peer has ACKed every queued byte — closing earlier * truncates the response and triggers ERR_CONTENT_LENGTH_MISMATCH. */ if (conn->tx_acked >= conn->tx_total) { return close_conn(conn, conn->pcb, ERR_OK); } return ERR_OK; } static err_t ws_send_frame(httpserver_conn_t *conn, uint8_t opcode, const void *payload, size_t len) { if (!conn || conn->mode != CONN_WS || !conn->pcb) { return ERR_VAL; } if (len > HS_WS_PAYLOAD_MAX) { return ERR_VAL; } uint8_t frame[4 + HS_WS_PAYLOAD_MAX]; size_t hdr = 2; frame[0] = 0x80 | (opcode & 0x0f); if (len < 126) { frame[1] = (uint8_t)len; } else { frame[1] = 126; frame[2] = (uint8_t)((len >> 8) & 0xff); frame[3] = (uint8_t)(len & 0xff); hdr = 4; } if (len) { memcpy(frame + hdr, payload, len); } if (tcp_write(conn->pcb, frame, (u16_t)(hdr + len), TCP_WRITE_FLAG_COPY) != ERR_OK) { return ERR_MEM; } tcp_output(conn->pcb); return ERR_OK; } static err_t ws_upgrade(httpserver_conn_t *conn, const char *req, const char *path) { const ws_route_t *ws = find_ws_route(conn->server, path); if (!ws) { httpserver_send(conn, 404, "text/plain", "Not Found", 9); return ERR_OK; } char key[64]; char accept[29]; if (!header_value(req, "Sec-WebSocket-Key", key, sizeof(key))) { return close_conn(conn, conn->pcb, ERR_VAL); } ws_accept_key(key, accept); char resp[180]; int n = snprintf(resp, sizeof(resp), "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %s\r\n" "\r\n", accept); if (tcp_write(conn->pcb, resp, n, TCP_WRITE_FLAG_COPY) != ERR_OK) { return close_conn(conn, conn->pcb, ERR_ABRT); } tcp_output(conn->pcb); conn->mode = CONN_WS; conn->ws_route = ws; conn->buf_len = 0; conn->headers_complete = false; if (ws->on_open) { ws->on_open(conn); } return ERR_OK; } static err_t ws_handle_frames(httpserver_conn_t *conn) { while (conn->buf_len >= 2) { uint8_t b0 = (uint8_t)conn->buf[0]; uint8_t b1 = (uint8_t)conn->buf[1]; uint8_t opcode = b0 & 0x0f; bool masked = (b1 & 0x80) != 0; size_t payload_len = b1 & 0x7f; size_t header_len = 2; if (payload_len == 126) { if (conn->buf_len < 4) { break; } payload_len = ((size_t)(uint8_t)conn->buf[2] << 8) | (uint8_t)conn->buf[3]; header_len = 4; } else if (payload_len == 127) { return close_conn(conn, conn->pcb, ERR_VAL); } if (masked) { header_len += 4; } if ((size_t)conn->buf_len < header_len + payload_len) { break; } if (payload_len > HS_WS_PAYLOAD_MAX) { return close_conn(conn, conn->pcb, ERR_VAL); } const uint8_t *mask = masked ? (const uint8_t *)&conn->buf[header_len - 4] : NULL; uint8_t payload[HS_WS_PAYLOAD_MAX + 1]; memcpy(payload, &conn->buf[header_len], payload_len); if (masked) { for (size_t i = 0; i < payload_len; i++) { payload[i] ^= mask[i & 3]; } } payload[payload_len] = '\0'; size_t consumed = header_len + payload_len; memmove(conn->buf, conn->buf + consumed, conn->buf_len - consumed); conn->buf_len -= (int)consumed; if (opcode == 0x8) { ws_send_frame(conn, 0x8, NULL, 0); return close_conn(conn, conn->pcb, ERR_OK); } if (opcode == 0x9) { ws_send_frame(conn, 0xA, payload, payload_len); continue; } if (opcode == 0x1 || opcode == 0x2) { if (conn->ws_route && conn->ws_route->on_msg) { conn->ws_route->on_msg(conn, payload, payload_len, opcode == 0x1); } } } return ERR_OK; } static err_t dispatch_http(httpserver_conn_t *conn) { char method[8]; char path[64]; char query[64]; if (!parse_request_line(conn->buf, method, sizeof(method), path, sizeof(path), query, sizeof(query))) { return close_conn(conn, conn->pcb, ERR_VAL); } bool is_ws = header_has(conn->buf, "Upgrade:") && header_has(conn->buf, "Sec-WebSocket-Key:"); if (is_ws && strcmp(method, "GET") == 0) { return ws_upgrade(conn, conn->buf, path); } const route_t *route = find_route(conn->server, method, path); if (!route) { httpserver_send(conn, 404, "text/plain", "Not Found", 9); return ERR_OK; } conn->dispatched = true; route->fn(conn, path, query); return ERR_OK; } static err_t try_dispatch(httpserver_conn_t *conn) { if (conn->dispatched) { return ERR_OK; } if (!conn->headers_complete) { char *end = strstr(conn->buf, "\r\n\r\n"); if (!end) { return ERR_OK; } conn->header_end = (int)(end - conn->buf) + 4; conn->headers_complete = true; char cl[16]; if (header_value(conn->buf, "Content-Length", cl, sizeof(cl))) { conn->content_length = atoi(cl); } else { conn->content_length = 0; } } int body_have = conn->buf_len - conn->header_end; if (conn->content_length > 0 && body_have < conn->content_length) { return ERR_OK; } return dispatch_http(conn); } static err_t on_sent(void *arg, struct tcp_pcb *pcb, u16_t len) { httpserver_conn_t *conn = arg; (void)pcb; if (conn->mode != CONN_HTTP) { return ERR_OK; } conn->tx_acked += len; if (conn->static_body) { return pump_static(conn); } return ERR_OK; } static err_t on_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { httpserver_conn_t *conn = arg; (void)err; if (!p) { return close_conn(conn, pcb, ERR_OK); } if (p->tot_len > 0) { u16_t space = (u16_t)(sizeof(conn->buf) - 1 - conn->buf_len); u16_t n = p->tot_len > space ? space : p->tot_len; pbuf_copy_partial(p, conn->buf + conn->buf_len, n, 0); conn->buf_len += n; conn->buf[conn->buf_len] = '\0'; tcp_recved(pcb, p->tot_len); err_t r = ERR_OK; if (conn->mode == CONN_WS) { r = ws_handle_frames(conn); } else { r = try_dispatch(conn); } pbuf_free(p); return r; } pbuf_free(p); return ERR_OK; } static err_t on_poll(void *arg, struct tcp_pcb *pcb) { httpserver_conn_t *conn = arg; if (conn->mode == CONN_WS) { return ERR_OK; } /* Keep pumping / waiting for ACK on static responses */ if (conn->static_body) { return pump_static(conn); } if (conn->dispatched) { return close_conn(conn, pcb, ERR_OK); } return close_conn(conn, pcb, ERR_OK); } static void on_err(void *arg, err_t err) { httpserver_conn_t *conn = arg; (void)err; if (conn && conn->mode == CONN_WS && conn->ws_route && conn->ws_route->on_close) { conn->ws_route->on_close(conn); } conn_free(conn); } static err_t on_accept(void *arg, struct tcp_pcb *client_pcb, err_t err) { httpserver_t *s = arg; if (err != ERR_OK || !client_pcb) { return ERR_VAL; } httpserver_conn_t *conn = conn_alloc(s, client_pcb); if (!conn) { tcp_abort(client_pcb); return ERR_MEM; } tcp_arg(client_pcb, conn); tcp_sent(client_pcb, on_sent); tcp_recv(client_pcb, on_recv); tcp_poll(client_pcb, on_poll, HS_POLL_INTERVAL); tcp_err(client_pcb, on_err); tcp_nagle_disable(client_pcb); return ERR_OK; } httpserver_t *httpserver_create(void) { memset(&g_server, 0, sizeof(g_server)); return &g_server; } void httpserver_route(httpserver_t *s, const char *method, const char *path, httpserver_handler_t fn) { if (!s || s->route_count >= HS_MAX_ROUTES || !method || !path || !fn) { return; } s->routes[s->route_count].method = method; s->routes[s->route_count].path = path; s->routes[s->route_count].fn = fn; s->route_count++; } void httpserver_websocket(httpserver_t *s, const char *path, httpserver_ws_open_t on_open, httpserver_ws_msg_t on_msg, httpserver_ws_close_t on_close) { if (!s || s->ws_route_count >= HS_MAX_WS_ROUTES || !path) { return; } s->ws_routes[s->ws_route_count].path = path; s->ws_routes[s->ws_route_count].on_open = on_open; s->ws_routes[s->ws_route_count].on_msg = on_msg; s->ws_routes[s->ws_route_count].on_close = on_close; s->ws_route_count++; } bool httpserver_listen(httpserver_t *s, uint16_t port) { if (!s) { return false; } cyw43_arch_lwip_begin(); struct tcp_pcb *pcb = tcp_new_ip_type(IPADDR_TYPE_ANY); if (!pcb) { cyw43_arch_lwip_end(); return false; } if (tcp_bind(pcb, IP_ANY_TYPE, port) != ERR_OK) { tcp_close(pcb); cyw43_arch_lwip_end(); return false; } s->server_pcb = tcp_listen_with_backlog(pcb, HS_MAX_CONNS); if (!s->server_pcb) { tcp_close(pcb); cyw43_arch_lwip_end(); return false; } tcp_arg(s->server_pcb, s); tcp_accept(s->server_pcb, on_accept); cyw43_arch_lwip_end(); printf("httpserver: listening on port %u\n", port); return true; } void httpserver_send_static(httpserver_conn_t *conn, int status, const char *content_type, const uint8_t *body, size_t body_len, const char *content_encoding) { if (!conn || conn->mode != CONN_HTTP || !conn->pcb) { return; } if (!content_type) { content_type = "application/octet-stream"; } if (content_encoding && content_encoding[0]) { conn->hdr_len = snprintf(conn->hdr, sizeof(conn->hdr), "HTTP/1.1 %d %s\r\n" "Content-Type: %s\r\n" "Content-Encoding: %s\r\n" "Content-Length: %u\r\n" "Connection: close\r\n" "\r\n", status, status_text(status), content_type, content_encoding, (unsigned)body_len); } else { conn->hdr_len = snprintf(conn->hdr, sizeof(conn->hdr), "HTTP/1.1 %d %s\r\n" "Content-Type: %s\r\n" "Content-Length: %u\r\n" "Connection: close\r\n" "\r\n", status, status_text(status), content_type, (unsigned)body_len); } conn->hdr_sent = 0; conn->static_body = body ? body : (const uint8_t *)""; conn->static_len = body_len; conn->static_sent = 0; conn->tx_acked = 0; conn->tx_total = (size_t)conn->hdr_len + body_len; conn->write_done = false; pump_static(conn); } void httpserver_send(httpserver_conn_t *conn, int status, const char *content_type, const void *body, size_t body_len) { httpserver_send_static(conn, status, content_type, (const uint8_t *)body, body_len, NULL); } void httpserver_send_html(httpserver_conn_t *conn, const char *html) { if (!html) { html = ""; } httpserver_send(conn, 200, "text/html; charset=utf-8", html, strlen(html)); } const char *httpserver_request_body(httpserver_conn_t *conn, size_t *len_out) { if (!conn || conn->header_end < 0) { if (len_out) { *len_out = 0; } return ""; } size_t len = (size_t)(conn->buf_len - conn->header_end); if (conn->content_length >= 0 && (size_t)conn->content_length < len) { len = (size_t)conn->content_length; } if (len_out) { *len_out = len; } return conn->buf + conn->header_end; } bool httpserver_ws_send(httpserver_conn_t *ws, const void *data, size_t len, bool text) { return ws_send_frame(ws, text ? 0x1 : 0x2, data, len) == ERR_OK; } void httpserver_ws_broadcast(httpserver_t *s, const void *data, size_t len, bool text) { if (!s) { return; } for (int i = 0; i < HS_MAX_CONNS; i++) { if (s->conns[i].mode == CONN_WS) { httpserver_ws_send(&s->conns[i], data, len, text); } } } httpserver_t *httpserver_conn_server(httpserver_conn_t *conn) { return conn ? conn->server : NULL; }