diff --git a/examples/device-dashboard/net.c b/examples/device-dashboard/net.c index a2604656608..ecd72845c60 100644 --- a/examples/device-dashboard/net.c +++ b/examples/device-dashboard/net.c @@ -261,7 +261,14 @@ static void handle_sys_reset(struct mg_connection *c) { // HTTP request handler function static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { - if (ev == MG_EV_HTTP_MSG) { + if (ev == MG_EV_ACCEPT) { + if (fn_data != NULL) { // TLS listener! + struct mg_tls_opts opts = {0}; + opts.cert = mg_unpacked("/certs/server_cert.pem"); + opts.key = mg_unpacked("/certs/server_key.pem"); + mg_tls_init(c, &opts); + } + } else if (ev == MG_EV_HTTP_MSG) { struct mg_http_message *hm = (struct mg_http_message *) ev_data; struct user *u = authenticate(hm); @@ -306,20 +313,12 @@ static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { hm->method.ptr, (int) hm->uri.len, hm->uri.ptr, (int) 3, &c->send.buf[9])); } - (void) fn_data; } void web_init(struct mg_mgr *mgr) { - struct mg_tls_opts opts = {0}; - opts.server_cert = mg_unpacked("/certs/server_cert.pem"); - opts.server_key = mg_unpacked("/certs/server_key.pem"); - mg_tls_ctx_init(mgr, &opts); - s_settings.device_name = strdup("My Device"); - mg_http_listen(mgr, HTTP_URL, fn, NULL); - mg_http_listen(mgr, HTTPS_URL, fn, NULL); - + mg_http_listen(mgr, HTTPS_URL, fn, (void *) 1); mg_timer_add(mgr, 3600 * 1000, MG_TIMER_RUN_NOW | MG_TIMER_REPEAT, timer_sntp_fn, mgr); } diff --git a/mongoose.c b/mongoose.c index 8fc64082144..49c4036316f 100644 --- a/mongoose.c +++ b/mongoose.c @@ -133,17 +133,17 @@ struct dns_data { static void mg_sendnsreq(struct mg_connection *, struct mg_str *, int, struct mg_dns *, bool); -static void mg_dns_free(struct mg_connection *c, struct dns_data *d) { - LIST_DELETE(struct dns_data, - (struct dns_data **) &c->mgr->active_dns_requests, d); +static void mg_dns_free(struct dns_data **head, struct dns_data *d) { + LIST_DELETE(struct dns_data, head, d); free(d); } void mg_resolve_cancel(struct mg_connection *c) { - struct dns_data *tmp, *d = (struct dns_data *) c->mgr->active_dns_requests; - for (; d != NULL; d = tmp) { + struct dns_data *tmp, *d; + struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests; + for (d = *head; d != NULL; d = tmp) { tmp = d->next; - if (d->c == c) mg_dns_free(c, d); + if (d->c == c) mg_dns_free(head, d); } } @@ -254,10 +254,10 @@ bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) { static void dns_cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { struct dns_data *d, *tmp; + struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests; if (ev == MG_EV_POLL) { uint64_t now = *(uint64_t *) ev_data; - for (d = (struct dns_data *) c->mgr->active_dns_requests; d != NULL; - d = tmp) { + for (d = *head; d != NULL; d = tmp) { tmp = d->next; // MG_DEBUG ("%lu %lu dns poll", d->expire, now)); if (now > d->expire) mg_error(d->c, "DNS timeout"); @@ -270,8 +270,7 @@ static void dns_cb(struct mg_connection *c, int ev, void *ev_data, mg_hexdump(c->recv.buf, c->recv.len); } else { // MG_VERBOSE(("%s %d", dm.name, dm.resolved)); - for (d = (struct dns_data *) c->mgr->active_dns_requests; d != NULL; - d = tmp) { + for (d = *head; d != NULL; d = tmp) { tmp = d->next; // MG_INFO(("d %p %hu %hu", d, d->txnid, dm.txnid)); if (dm.txnid != d->txnid) continue; @@ -294,18 +293,17 @@ static void dns_cb(struct mg_connection *c, int ev, void *ev_data, } else { MG_ERROR(("%lu already resolved", d->c->id)); } - mg_dns_free(c, d); + mg_dns_free(head, d); resolved = 1; } } if (!resolved) MG_ERROR(("stray DNS reply")); c->recv.len = 0; } else if (ev == MG_EV_CLOSE) { - for (d = (struct dns_data *) c->mgr->active_dns_requests; d != NULL; - d = tmp) { + for (d = *head; d != NULL; d = tmp) { tmp = d->next; mg_error(d->c, "DNS error"); - mg_dns_free(c, d); + mg_dns_free(head, d); } } (void) fn_data; @@ -405,7 +403,7 @@ void mg_error(struct mg_connection *c, const char *fmt, ...) { va_start(ap, fmt); mg_vsnprintf(buf, sizeof(buf), fmt, &ap); va_end(ap); - MG_ERROR(("%lu %p %s", c->id, c->fd, buf)); + MG_ERROR(("%lu %ld %s", c->id, c->fd, buf)); c->is_closing = 1; // Set is_closing before sending MG_EV_CALL mg_call(c, MG_EV_ERROR, buf); // Let user handler to override it } @@ -3564,6 +3562,265 @@ struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url, return c; } +#ifdef MG_ENABLE_LINES +#line 1 "src/net.c" +#endif + + + + + + + + +size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) { + size_t old = c->send.len; + mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap); + return c->send.len - old; +} + +size_t mg_printf(struct mg_connection *c, const char *fmt, ...) { + size_t len = 0; + va_list ap; + va_start(ap, fmt); + len = mg_vprintf(c, fmt, &ap); + va_end(ap); + return len; +} + +static bool mg_atonl(struct mg_str str, struct mg_addr *addr) { + uint32_t localhost = mg_htonl(0x7f000001); + if (mg_vcasecmp(&str, "localhost") != 0) return false; + memcpy(addr->ip, &localhost, sizeof(uint32_t)); + addr->is_ip6 = false; + return true; +} + +static bool mg_atone(struct mg_str str, struct mg_addr *addr) { + if (str.len > 0) return false; + memset(addr->ip, 0, sizeof(addr->ip)); + addr->is_ip6 = false; + return true; +} + +static bool mg_aton4(struct mg_str str, struct mg_addr *addr) { + uint8_t data[4] = {0, 0, 0, 0}; + size_t i, num_dots = 0; + for (i = 0; i < str.len; i++) { + if (str.ptr[i] >= '0' && str.ptr[i] <= '9') { + int octet = data[num_dots] * 10 + (str.ptr[i] - '0'); + if (octet > 255) return false; + data[num_dots] = (uint8_t) octet; + } else if (str.ptr[i] == '.') { + if (num_dots >= 3 || i == 0 || str.ptr[i - 1] == '.') return false; + num_dots++; + } else { + return false; + } + } + if (num_dots != 3 || str.ptr[i - 1] == '.') return false; + memcpy(&addr->ip, data, sizeof(data)); + addr->is_ip6 = false; + return true; +} + +static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) { + int i; + uint32_t ipv4; + if (str.len < 14) return false; + if (str.ptr[0] != ':' || str.ptr[1] != ':' || str.ptr[6] != ':') return false; + for (i = 2; i < 6; i++) { + if (str.ptr[i] != 'f' && str.ptr[i] != 'F') return false; + } + // struct mg_str s = mg_str_n(&str.ptr[7], str.len - 7); + if (!mg_aton4(mg_str_n(&str.ptr[7], str.len - 7), addr)) return false; + memcpy(&ipv4, addr->ip, sizeof(ipv4)); + memset(addr->ip, 0, sizeof(addr->ip)); + addr->ip[10] = addr->ip[11] = 255; + memcpy(&addr->ip[12], &ipv4, 4); + addr->is_ip6 = true; + return true; +} + +static bool mg_aton6(struct mg_str str, struct mg_addr *addr) { + size_t i, j = 0, n = 0, dc = 42; + if (str.len > 2 && str.ptr[0] == '[') str.ptr++, str.len -= 2; + if (mg_v4mapped(str, addr)) return true; + for (i = 0; i < str.len; i++) { + if ((str.ptr[i] >= '0' && str.ptr[i] <= '9') || + (str.ptr[i] >= 'a' && str.ptr[i] <= 'f') || + (str.ptr[i] >= 'A' && str.ptr[i] <= 'F')) { + unsigned long val; + if (i > j + 3) return false; + // MG_DEBUG(("%zu %zu [%.*s]", i, j, (int) (i - j + 1), &str.ptr[j])); + val = mg_unhexn(&str.ptr[j], i - j + 1); + addr->ip[n] = (uint8_t) ((val >> 8) & 255); + addr->ip[n + 1] = (uint8_t) (val & 255); + } else if (str.ptr[i] == ':') { + j = i + 1; + if (i > 0 && str.ptr[i - 1] == ':') { + dc = n; // Double colon + if (i > 1 && str.ptr[i - 2] == ':') return false; + } else if (i > 0) { + n += 2; + } + if (n > 14) return false; + addr->ip[n] = addr->ip[n + 1] = 0; // For trailing :: + } else { + return false; + } + } + if (n < 14 && dc == 42) return false; + if (n < 14) { + memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2); + memset(&addr->ip[dc], 0, 14 - n); + } + + addr->is_ip6 = true; + return true; +} + +bool mg_aton(struct mg_str str, struct mg_addr *addr) { + // MG_INFO(("[%.*s]", (int) str.len, str.ptr)); + return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) || + mg_aton6(str, addr); +} + +struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) { + struct mg_connection *c = + (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize); + if (c != NULL) { + c->mgr = mgr; + c->send.align = c->recv.align = MG_IO_SIZE; + c->id = ++mgr->nextid; + } + return c; +} + +void mg_close_conn(struct mg_connection *c) { + mg_resolve_cancel(c); // Close any pending DNS query + LIST_DELETE(struct mg_connection, &c->mgr->conns, c); + if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL; + if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL; + // Order of operations is important. `MG_EV_CLOSE` event must be fired + // before we deallocate received data, see #1331 + mg_call(c, MG_EV_CLOSE, NULL); + MG_DEBUG(("%lu %ld closed", c->id, (long) c->fd)); + + mg_tls_free(c); + mg_iobuf_free(&c->recv); + mg_iobuf_free(&c->send); + memset(c, 0, sizeof(*c)); + free(c); +} + +struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url, + mg_event_handler_t fn, void *fn_data) { + struct mg_connection *c = NULL; + if (url == NULL || url[0] == '\0') { + MG_ERROR(("null url")); + } else if ((c = mg_alloc_conn(mgr)) == NULL) { + MG_ERROR(("OOM")); + } else { + LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); + c->is_udp = (strncmp(url, "udp:", 4) == 0); + c->fd = (void *) (size_t) MG_INVALID_SOCKET; + c->fn = fn; + c->is_client = true; + c->fn_data = fn_data; + MG_DEBUG(("%lu %ld %s", c->id, c->fd, url)); + mg_call(c, MG_EV_OPEN, (void *) url); + mg_resolve(c, url); + } + return c; +} + +struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url, + mg_event_handler_t fn, void *fn_data) { + struct mg_connection *c = NULL; + if ((c = mg_alloc_conn(mgr)) == NULL) { + MG_ERROR(("OOM %s", url)); + } else if (!mg_open_listener(c, url)) { + MG_ERROR(("Failed: %s, errno %d", url, errno)); + free(c); + c = NULL; + } else { + c->is_listening = 1; + c->is_udp = strncmp(url, "udp:", 4) == 0; + LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); + c->fn = fn; + c->fn_data = fn_data; + mg_call(c, MG_EV_OPEN, NULL); + if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must + MG_DEBUG(("%lu %ld %s", c->id, c->fd, url)); + } + return c; +} + +struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd, + mg_event_handler_t fn, void *fn_data) { + struct mg_connection *c = mg_alloc_conn(mgr); + if (c != NULL) { + c->fd = (void *) (size_t) fd; + c->fn = fn; + c->fn_data = fn_data; + MG_EPOLL_ADD(c); + mg_call(c, MG_EV_OPEN, NULL); + LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); + } + return c; +} + +struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds, + unsigned flags, void (*fn)(void *), void *arg) { + struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t)); + if (t != NULL) { + mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg); + t->id = mgr->timerid++; + } + return t; +} + +void mg_mgr_free(struct mg_mgr *mgr) { + struct mg_connection *c; + struct mg_timer *tmp, *t = mgr->timers; + while (t != NULL) tmp = t->next, free(t), t = tmp; + mgr->timers = NULL; // Important. Next call to poll won't touch timers + for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1; + mg_mgr_poll(mgr, 0); +#if MG_ENABLE_FREERTOS_TCP + FreeRTOS_DeleteSocketSet(mgr->ss); +#endif + MG_DEBUG(("All connections closed")); +#if MG_ENABLE_EPOLL + if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1; +#endif +} + +void mg_mgr_init(struct mg_mgr *mgr) { + memset(mgr, 0, sizeof(*mgr)); +#if MG_ENABLE_EPOLL + if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) + MG_ERROR(("epoll_create1 errno %d", errno)); +#else + mgr->epoll_fd = -1; +#endif +#if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK + // clang-format off + { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); } + // clang-format on +#elif MG_ENABLE_FREERTOS_TCP + mgr->ss = FreeRTOS_CreateSocketSet(); +#elif defined(__unix) || defined(__unix__) || defined(__APPLE__) + // Ignore SIGPIPE signal, so if client cancels the request, it + // won't kill the whole process. + signal(SIGPIPE, SIG_IGN); +#endif + mgr->dnstimeout = 3000; + mgr->dns4.url = "udp://8.8.8.8:53"; + mgr->dns6.url = "udp://[2001:4860:4860::8888]:53"; +} + #ifdef MG_ENABLE_LINES #line 1 "src/net_builtin.c" #endif @@ -4113,7 +4370,6 @@ static struct mg_connection *accept_conn(struct mg_connection *lsn, c->fn_data = lsn->fn_data; mg_call(c, MG_EV_OPEN, NULL); mg_call(c, MG_EV_ACCEPT, NULL); - if (lsn->is_tls) mg_tls_init(c, mg_str("")); return c; } @@ -4624,328 +4880,64 @@ static void init_closure(struct mg_connection *c) { c->is_connecting == false) { // For TCP conns, struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv; // send TCP FIN - uint32_t rem_ip; - memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t)); - tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port, - mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0); - settmout(c, MIP_TTYPE_FIN); - } -} - -static void close_conn(struct mg_connection *c) { - struct connstate *s = (struct connstate *) (c + 1); - mg_iobuf_free(&s->raw); // For TLS connections, release raw data - mg_close_conn(c); -} - -static bool can_write(struct mg_connection *c) { - return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 && - c->is_tls_hs == 0 && c->is_arplooking == 0; -} - -void mg_mgr_poll(struct mg_mgr *mgr, int ms) { - struct mg_connection *c, *tmp; - uint64_t now = mg_millis(); - mg_tcpip_poll((struct mg_tcpip_if *) mgr->priv, now); - mg_timer_poll(&mgr->timers, now); - for (c = mgr->conns; c != NULL; c = tmp) { - tmp = c->next; - struct connstate *s = (struct connstate *) (c + 1); - mg_call(c, MG_EV_POLL, &now); - MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't', - c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h', - c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c')); - if (c->is_tls_hs) mg_tls_handshake(c); - if (can_write(c)) write_conn(c); - if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN) - init_closure(c); - if (c->is_closing) close_conn(c); - } - (void) ms; -} - -bool mg_send(struct mg_connection *c, const void *buf, size_t len) { - struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv; - bool res = false; - uint32_t rem_ip; - memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t)); - if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) { - mg_error(c, "net down"); - } else if (c->is_udp) { - struct connstate *s = (struct connstate *) (c + 1); - len = trim_len(c, len); // Trimming length if necessary - tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len); - res = true; - } else { - res = mg_iobuf_add(&c->send, c->send.len, buf, len); - } - return res; -} -#endif // MG_ENABLE_TCPIP - -#ifdef MG_ENABLE_LINES -#line 1 "src/net.c" -#endif - - - - - - - - -size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) { - size_t old = c->send.len; - mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap); - return c->send.len - old; -} - -size_t mg_printf(struct mg_connection *c, const char *fmt, ...) { - size_t len = 0; - va_list ap; - va_start(ap, fmt); - len = mg_vprintf(c, fmt, &ap); - va_end(ap); - return len; -} - -static bool mg_atonl(struct mg_str str, struct mg_addr *addr) { - uint32_t localhost = mg_htonl(0x7f000001); - if (mg_vcasecmp(&str, "localhost") != 0) return false; - memcpy(addr->ip, &localhost, sizeof(uint32_t)); - addr->is_ip6 = false; - return true; -} - -static bool mg_atone(struct mg_str str, struct mg_addr *addr) { - if (str.len > 0) return false; - memset(addr->ip, 0, sizeof(addr->ip)); - addr->is_ip6 = false; - return true; -} - -static bool mg_aton4(struct mg_str str, struct mg_addr *addr) { - uint8_t data[4] = {0, 0, 0, 0}; - size_t i, num_dots = 0; - for (i = 0; i < str.len; i++) { - if (str.ptr[i] >= '0' && str.ptr[i] <= '9') { - int octet = data[num_dots] * 10 + (str.ptr[i] - '0'); - if (octet > 255) return false; - data[num_dots] = (uint8_t) octet; - } else if (str.ptr[i] == '.') { - if (num_dots >= 3 || i == 0 || str.ptr[i - 1] == '.') return false; - num_dots++; - } else { - return false; - } - } - if (num_dots != 3 || str.ptr[i - 1] == '.') return false; - memcpy(&addr->ip, data, sizeof(data)); - addr->is_ip6 = false; - return true; -} - -static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) { - int i; - uint32_t ipv4; - if (str.len < 14) return false; - if (str.ptr[0] != ':' || str.ptr[1] != ':' || str.ptr[6] != ':') return false; - for (i = 2; i < 6; i++) { - if (str.ptr[i] != 'f' && str.ptr[i] != 'F') return false; - } - // struct mg_str s = mg_str_n(&str.ptr[7], str.len - 7); - if (!mg_aton4(mg_str_n(&str.ptr[7], str.len - 7), addr)) return false; - memcpy(&ipv4, addr->ip, sizeof(ipv4)); - memset(addr->ip, 0, sizeof(addr->ip)); - addr->ip[10] = addr->ip[11] = 255; - memcpy(&addr->ip[12], &ipv4, 4); - addr->is_ip6 = true; - return true; -} - -static bool mg_aton6(struct mg_str str, struct mg_addr *addr) { - size_t i, j = 0, n = 0, dc = 42; - if (str.len > 2 && str.ptr[0] == '[') str.ptr++, str.len -= 2; - if (mg_v4mapped(str, addr)) return true; - for (i = 0; i < str.len; i++) { - if ((str.ptr[i] >= '0' && str.ptr[i] <= '9') || - (str.ptr[i] >= 'a' && str.ptr[i] <= 'f') || - (str.ptr[i] >= 'A' && str.ptr[i] <= 'F')) { - unsigned long val; - if (i > j + 3) return false; - // MG_DEBUG(("%zu %zu [%.*s]", i, j, (int) (i - j + 1), &str.ptr[j])); - val = mg_unhexn(&str.ptr[j], i - j + 1); - addr->ip[n] = (uint8_t) ((val >> 8) & 255); - addr->ip[n + 1] = (uint8_t) (val & 255); - } else if (str.ptr[i] == ':') { - j = i + 1; - if (i > 0 && str.ptr[i - 1] == ':') { - dc = n; // Double colon - if (i > 1 && str.ptr[i - 2] == ':') return false; - } else if (i > 0) { - n += 2; - } - if (n > 14) return false; - addr->ip[n] = addr->ip[n + 1] = 0; // For trailing :: - } else { - return false; - } - } - if (n < 14 && dc == 42) return false; - if (n < 14) { - memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2); - memset(&addr->ip[dc], 0, 14 - n); - } - - addr->is_ip6 = true; - return true; -} - -bool mg_aton(struct mg_str str, struct mg_addr *addr) { - // MG_INFO(("[%.*s]", (int) str.len, str.ptr)); - return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) || - mg_aton6(str, addr); -} - -struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) { - struct mg_connection *c = - (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize); - if (c != NULL) { - c->mgr = mgr; - c->send.align = c->recv.align = MG_IO_SIZE; - c->id = ++mgr->nextid; - } - return c; -} - -void mg_close_conn(struct mg_connection *c) { - mg_resolve_cancel(c); // Close any pending DNS query - LIST_DELETE(struct mg_connection, &c->mgr->conns, c); - if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL; - if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL; - // Order of operations is important. `MG_EV_CLOSE` event must be fired - // before we deallocate received data, see #1331 - mg_call(c, MG_EV_CLOSE, NULL); - MG_DEBUG(("%lu %p closed", c->id, c->fd)); - - mg_tls_free(c); - mg_iobuf_free(&c->recv); - mg_iobuf_free(&c->send); - memset(c, 0, sizeof(*c)); - free(c); -} - -struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url, - mg_event_handler_t fn, void *fn_data) { - struct mg_connection *c = NULL; - if (url == NULL || url[0] == '\0') { - MG_ERROR(("null url")); - } else if ((c = mg_alloc_conn(mgr)) == NULL) { - MG_ERROR(("OOM")); - } else { - LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); - c->is_udp = (strncmp(url, "udp:", 4) == 0); - c->fd = (void *) (size_t) MG_INVALID_SOCKET; - c->fn = fn; - c->is_client = true; - c->fn_data = fn_data; - MG_DEBUG(("%lu %p %s", c->id, c->fd, url)); - mg_call(c, MG_EV_OPEN, (void *) url); - mg_resolve(c, url); - if (mg_url_is_ssl(url)) { - struct mg_str host = mg_url_host(url); - mg_tls_init(c, host); - } - } - return c; -} - -struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url, - mg_event_handler_t fn, void *fn_data) { - struct mg_connection *c = NULL; - if ((c = mg_alloc_conn(mgr)) == NULL) { - MG_ERROR(("OOM %s", url)); - } else if (!mg_open_listener(c, url)) { - MG_ERROR(("Failed: %s, errno %d", url, errno)); - free(c); - c = NULL; - } else { - c->is_listening = 1; - c->is_udp = strncmp(url, "udp:", 4) == 0; - LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); - c->fn = fn; - c->fn_data = fn_data; - mg_call(c, MG_EV_OPEN, NULL); - if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must - MG_DEBUG(("%lu %p %s", c->id, c->fd, url)); - } - return c; -} - -struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd, - mg_event_handler_t fn, void *fn_data) { - struct mg_connection *c = mg_alloc_conn(mgr); - if (c != NULL) { - c->fd = (void *) (size_t) fd; - c->fn = fn; - c->fn_data = fn_data; - MG_EPOLL_ADD(c); - mg_call(c, MG_EV_OPEN, NULL); - LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); + uint32_t rem_ip; + memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t)); + tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port, + mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0); + settmout(c, MIP_TTYPE_FIN); } - return c; } -struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds, - unsigned flags, void (*fn)(void *), void *arg) { - struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t)); - if (t != NULL) { - mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg); - t->id = mgr->timerid++; - } - return t; +static void close_conn(struct mg_connection *c) { + struct connstate *s = (struct connstate *) (c + 1); + mg_iobuf_free(&s->raw); // For TLS connections, release raw data + mg_close_conn(c); } -void mg_mgr_free(struct mg_mgr *mgr) { - struct mg_connection *c; - struct mg_timer *tmp, *t = mgr->timers; - while (t != NULL) tmp = t->next, free(t), t = tmp; - mgr->timers = NULL; // Important. Next call to poll won't touch timers - for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1; - mg_mgr_poll(mgr, 0); -#if MG_ENABLE_FREERTOS_TCP - FreeRTOS_DeleteSocketSet(mgr->ss); -#endif - MG_DEBUG(("All connections closed")); -#if MG_ENABLE_EPOLL - if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1; -#endif - mg_tls_ctx_free(mgr); +static bool can_write(struct mg_connection *c) { + return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 && + c->is_tls_hs == 0 && c->is_arplooking == 0; } -void mg_mgr_init(struct mg_mgr *mgr) { - memset(mgr, 0, sizeof(*mgr)); -#if MG_ENABLE_EPOLL - if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) - MG_ERROR(("epoll_create1 errno %d", errno)); -#else - mgr->epoll_fd = -1; -#endif -#if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK - // clang-format off - { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); } - // clang-format on -#elif MG_ENABLE_FREERTOS_TCP - mgr->ss = FreeRTOS_CreateSocketSet(); -#elif defined(__unix) || defined(__unix__) || defined(__APPLE__) - // Ignore SIGPIPE signal, so if client cancels the request, it - // won't kill the whole process. - signal(SIGPIPE, SIG_IGN); -#endif - mgr->dnstimeout = 3000; - mgr->dns4.url = "udp://8.8.8.8:53"; - mgr->dns6.url = "udp://[2001:4860:4860::8888]:53"; +void mg_mgr_poll(struct mg_mgr *mgr, int ms) { + struct mg_connection *c, *tmp; + uint64_t now = mg_millis(); + mg_tcpip_poll((struct mg_tcpip_if *) mgr->priv, now); + mg_timer_poll(&mgr->timers, now); + for (c = mgr->conns; c != NULL; c = tmp) { + tmp = c->next; + struct connstate *s = (struct connstate *) (c + 1); + mg_call(c, MG_EV_POLL, &now); + MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't', + c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h', + c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c')); + if (c->is_tls_hs) mg_tls_handshake(c); + if (can_write(c)) write_conn(c); + if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN) + init_closure(c); + if (c->is_closing) close_conn(c); + } + (void) ms; +} + +bool mg_send(struct mg_connection *c, const void *buf, size_t len) { + struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv; + bool res = false; + uint32_t rem_ip; + memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t)); + if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) { + mg_error(c, "net down"); + } else if (c->is_udp) { + struct connstate *s = (struct connstate *) (c + 1); + len = trim_len(c, len); // Trimming length if necessary + tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len); + res = true; + } else { + res = mg_iobuf_add(&c->send, c->send.len, buf, len); + } + return res; } +#endif // MG_ENABLE_TCPIP #ifdef MG_ENABLE_LINES #line 1 "src/ota_dummy.c" @@ -6000,7 +5992,7 @@ long mg_io_send(struct mg_connection *c, const void *buf, size_t len) { bool mg_send(struct mg_connection *c, const void *buf, size_t len) { if (c->is_udp) { long n = mg_io_send(c, buf, len); - MG_DEBUG(("%lu %p %d:%d %ld err %d", c->id, c->fd, (int) c->send.len, + MG_DEBUG(("%lu %ld %d:%d %ld err %d", c->id, c->fd, (int) c->send.len, (int) c->recv.len, n, MG_SOCK_ERR(n))); iolog(c, (char *) buf, n, false); return n > 0; @@ -6130,7 +6122,7 @@ static void read_conn(struct mg_connection *c) { char *buf = (char *) &c->recv.buf[c->recv.len]; size_t len = c->recv.size - c->recv.len; n = c->is_tls ? mg_tls_recv(c, buf, len) : mg_io_recv(c, buf, len); - MG_DEBUG(("%lu %p snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, + MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, (long) c->send.len, (long) c->send.size, (long) c->recv.len, (long) c->recv.size, n, MG_SOCK_ERR(n))); iolog(c, buf, n, true); @@ -6141,7 +6133,7 @@ static void write_conn(struct mg_connection *c) { char *buf = (char *) c->send.buf; size_t len = c->send.len; long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len); - MG_DEBUG(("%lu %p snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, + MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, (long) c->send.len, (long) c->send.size, (long) c->recv.len, (long) c->recv.size, n, MG_SOCK_ERR(n))); iolog(c, buf, n, false); @@ -6219,7 +6211,7 @@ void mg_connect_resolved(struct mg_connection *c) { if (rc == 0) { // Success mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake - MG_DEBUG(("%lu %p -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem)); + MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem)); c->is_connecting = 1; } else { mg_error(c, "connect: %d", MG_SOCK_ERR(rc)); @@ -6273,11 +6265,10 @@ static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) { c->pfn_data = lsn->pfn_data; c->fn = lsn->fn; c->fn_data = lsn->fn_data; - MG_DEBUG(("%lu %p accepted %M -> %M", c->id, c->fd, mg_print_ip_port, + MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port, &c->rem, mg_print_ip_port, &c->loc)); mg_call(c, MG_EV_OPEN, NULL); mg_call(c, MG_EV_ACCEPT, NULL); - if (lsn->is_tls) mg_tls_init(c, mg_str("")); } } @@ -6985,8 +6976,8 @@ void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { #if MG_TLS == MG_TLS_NONE -void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { - (void) hostname; +void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) { + (void) opts; mg_error(c, "TLS is not enabled"); } void mg_tls_handshake(struct mg_connection *c) { @@ -7005,12 +6996,6 @@ size_t mg_tls_pending(struct mg_connection *c) { (void) c; return 0; } -void mg_tls_ctx_free(struct mg_mgr *mgr) { - mgr->tls_ctx = NULL; -} -void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { - (void) opts, (void) mgr; -} #endif #ifdef MG_ENABLE_LINES @@ -7019,20 +7004,54 @@ void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { - #if MG_TLS == MG_TLS_MBED #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000 -#define MGRNG , rng_get, NULL +#define MBEDTLS_RNG_GET , mg_mbed_rng, NULL #else -#define MGRNG +#define MBEDTLS_RNG_GET #endif +static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) { + mg_random(buf, len); + (void) ctx; + return 0; +} + +static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) { + int rc; + if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; + if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL + if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.ptr, str.len)) != 0) { + MG_ERROR(("cert err %#x", -rc)); + return false; + } + return true; +} + +static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) { + int rc; + if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; + if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL + if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.ptr, str.len, NULL, + 0 MBEDTLS_RNG_GET)) != 0) { + MG_ERROR(("key err %#x", -rc)); + return false; + } + return true; +} + void mg_tls_free(struct mg_connection *c) { struct mg_tls *tls = (struct mg_tls *) c->tls; if (tls != NULL) { mbedtls_ssl_free(&tls->ssl); + mbedtls_pk_free(&tls->pk); + mbedtls_x509_crt_free(&tls->ca); + mbedtls_x509_crt_free(&tls->cert); mbedtls_ssl_config_free(&tls->conf); +#ifdef MBEDTLS_SSL_SESSION_TICKETS + mbedtls_ssl_ticket_free(&tls->ticket); +#endif free(tls); c->tls = NULL; } @@ -7072,40 +7091,27 @@ void mg_tls_handshake(struct mg_connection *c) { } } -static int mbed_rng(void *ctx, unsigned char *buf, size_t len) { - mg_random(buf, len); - (void) ctx; - return 0; -} - static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) { n = (int) strlen(s2) - 1; MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2)); (void) s; } -#ifdef MBEDTLS_SSL_SESSION_TICKETS -static int rng_get(void *p_rng, unsigned char *buf, size_t len) { - (void) p_rng; - mg_random(buf, len); - return 0; -} -#endif - -void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) c->mgr->tls_ctx; +void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) { struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls)); int rc = 0; - c->tls = tls; if (c->tls == NULL) { mg_error(c, "TLS OOM"); goto fail; } - + if (c->is_listening) goto fail; MG_DEBUG(("%lu Setting TLS", c->id)); mbedtls_ssl_init(&tls->ssl); mbedtls_ssl_config_init(&tls->conf); + mbedtls_x509_crt_init(&tls->ca); + mbedtls_x509_crt_init(&tls->cert); + mbedtls_pk_init(&tls->pk); mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c); #if defined(MG_MBEDTLS_DEBUG_LEVEL) mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL); @@ -7117,49 +7123,44 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { mg_error(c, "tls defaults %#x", -rc); goto fail; } - mbedtls_ssl_conf_rng(&tls->conf, mbed_rng, c); + mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c); - if (c->is_client && ctx->client_ca.version) { - mbedtls_ssl_conf_ca_chain(&tls->conf, &ctx->client_ca, NULL); - mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED); - if (hostname.ptr != NULL && hostname.ptr[0] != '\0') { - struct mg_addr addr; - if (!mg_aton(hostname, &addr)) { // if srvname is not an IP address - char *host = mg_mprintf("%.*s", (int) hostname.len, hostname.ptr); - mbedtls_ssl_set_hostname(&tls->ssl, host); - free(host); - } + if (opts->ca.len == 0 || mg_vcmp(&opts->ca, "*") == 0) { + mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE); + } else { + if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail; + mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL); + if (c->is_client && opts->name.ptr != NULL && opts->name.ptr[0] != '\0') { + char *host = mg_mprintf("%.*s", opts->name.len, opts->name.ptr); + mbedtls_ssl_set_hostname(&tls->ssl, host); + MG_DEBUG(("%lu hostname verification: %s", c->id, host)); + free(host); } - } else if (!c->is_client && ctx->server_ca.version) { - mbedtls_ssl_conf_ca_chain(&tls->conf, &ctx->server_ca, NULL); mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED); - } else { - mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE); } - if (c->is_client && ctx->client_cert.version && - (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &ctx->client_cert, - &ctx->client_key)) != 0) { + if (!mg_load_cert(opts->cert, &tls->cert)) goto fail; + if (!mg_load_key(opts->key, &tls->pk)) goto fail; + if (tls->cert.version && + (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) { mg_error(c, "own cert %#x", -rc); goto fail; } - if (!c->is_client && ctx->server_cert.version && - (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &ctx->server_cert, - &ctx->server_key)) != 0) { - mg_error(c, "own cert %#x", -rc); + +#ifdef MBEDTLS_SSL_SESSION_TICKETS + mbedtls_ssl_ticket_init(&tls->ticket); + if ((rc = mbedtls_ssl_ticket_setup(&tls->ticket, mg_mbed_rng, NULL, + MBEDTLS_CIPHER_AES_128_GCM, 86400)) != 0) { + mg_error(c, " mbedtls_ssl_ticket_setup %#x", -rc); goto fail; } -#ifdef MBEDTLS_SSL_SESSION_TICKETS mbedtls_ssl_conf_session_tickets_cb(&tls->conf, mbedtls_ssl_ticket_write, - mbedtls_ssl_ticket_parse, - &ctx->ticket_ctx); + mbedtls_ssl_ticket_parse, &tls->ticket); #endif if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) { mg_error(c, "setup err %#x", -rc); goto fail; } - - c->tls = tls; c->is_tls = 1; c->is_tls_hs = 1; mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0); @@ -7193,80 +7194,6 @@ long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) { if (n <= 0) return MG_IO_ERR; return n; } - -static bool load_cert(struct mg_str str, mbedtls_x509_crt *p) { - int rc; - if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; - if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL - if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.ptr, str.len)) != 0) { - MG_ERROR(("cert err %#x", -rc)); - return false; - } - return true; -} - -static bool load_key(struct mg_str str, mbedtls_pk_context *p) { - int rc; - if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; - if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL - if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.ptr, str.len, NULL, - 0 MGRNG)) != 0) { - MG_ERROR(("key err %#x", -rc)); - return false; - } - return true; -} - -void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx)); - if (ctx == NULL) goto fail; - MG_DEBUG(("Setting up TLS context")); - -#if defined(MG_MBEDTLS_DEBUG_LEVEL) - mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL); -#endif - - if (!load_cert(opts->client_ca, &ctx->client_ca)) goto fail; - if (!load_cert(opts->server_ca, &ctx->server_ca)) goto fail; - if (!load_cert(opts->client_cert, &ctx->client_cert)) goto fail; - if (!load_cert(opts->server_cert, &ctx->server_cert)) goto fail; - if (!load_key(opts->server_key, &ctx->server_key)) goto fail; - if (!load_key(opts->client_key, &ctx->client_key)) goto fail; - -#ifdef MBEDTLS_SSL_SESSION_TICKETS - { - int rc; - mbedtls_ssl_ticket_init(&ctx->ticket_ctx); - if ((rc = mbedtls_ssl_ticket_setup(&ctx->ticket_ctx, rng_get, NULL, - MBEDTLS_CIPHER_AES_128_GCM, 86400)) != - 0) { - MG_ERROR(("setup session tickets err %#x", -rc)); - goto fail; - } - } -#endif - mgr->tls_ctx = ctx; - return; -fail: - mg_tls_ctx_free(mgr); -} - -void mg_tls_ctx_free(struct mg_mgr *mgr) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx; - if (ctx != NULL) { - mbedtls_x509_crt_free(&ctx->server_cert); - mbedtls_pk_free(&ctx->server_key); - mbedtls_x509_crt_free(&ctx->client_cert); - mbedtls_pk_free(&ctx->client_key); - mbedtls_x509_crt_free(&ctx->client_ca); - mbedtls_x509_crt_free(&ctx->server_ca); -#ifdef MBEDTLS_SSL_SESSION_TICKETS - mbedtls_ssl_ticket_free(&ctx->ticket_ctx); -#endif - free(ctx); - mgr->tls_ctx = NULL; - } -} #endif #ifdef MG_ENABLE_LINES @@ -7294,11 +7221,10 @@ static int mg_tls_err(struct mg_tls *tls, int res) { return err; } -static STACK_OF(X509_INFO) * load_ca_certs(const char *ca, int ca_len) { - BIO *ca_bio = BIO_new_mem_buf(ca, ca_len); - if (!ca_bio) return NULL; - STACK_OF(X509_INFO) *certs = PEM_X509_INFO_read_bio(ca_bio, NULL, NULL, NULL); - BIO_free(ca_bio); +static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) { + BIO *bio = BIO_new_mem_buf(ca.ptr, (int) ca.len); + STACK_OF(X509_INFO) *certs = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL); + BIO_free(bio); return certs; } @@ -7312,45 +7238,51 @@ static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) { return true; } -static EVP_PKEY *load_key(const char *key, int key_len) { - BIO *key_bio = BIO_new_mem_buf(key, key_len); - if (!key_bio) return NULL; - EVP_PKEY *priv_key = PEM_read_bio_PrivateKey(key_bio, NULL, 0, NULL); - BIO_free(key_bio); - return priv_key; +static EVP_PKEY *load_key(struct mg_str s) { + BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len); + EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, 0, NULL); + BIO_free(bio); + return key; } -static X509 *load_cert(const char *cert, int cert_len) { - BIO *cert_bio = BIO_new_mem_buf(cert, cert_len); - if (!cert_bio) return NULL; - X509 *x509 = PEM_read_bio_X509(cert_bio, NULL, 0, NULL); - BIO_free(cert_bio); - return x509; +static X509 *load_cert(struct mg_str s) { + BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len); + X509 *cert = s.ptr[0] == '-' + ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM + : d2i_X509_bio(bio, NULL); // DER + BIO_free(bio); + return cert; } -void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) c->mgr->tls_ctx; +void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) { struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls)); - - if (ctx == NULL) { - mg_error(c, "TLS context not initialized"); - goto fail; - } + const char *id = "mongoose"; + static unsigned char s_initialised = 0; + int rc; if (tls == NULL) { mg_error(c, "TLS OOM"); goto fail; } - tls->ctx = c->is_client ? SSL_CTX_new(TLS_client_method()) - : SSL_CTX_new(TLS_server_method()); + if (!s_initialised) { + SSL_library_init(); + s_initialised++; + } + MG_DEBUG(("%lu Setting TLS", c->id)); + tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method()) + : SSL_CTX_new(SSLv23_server_method()); if ((tls->ssl = SSL_new(tls->ctx)) == NULL) { mg_error(c, "SSL_new"); goto fail; } - - SSL_set_min_proto_version(tls->ssl, TLS1_2_VERSION); - + SSL_set_session_id_context(tls->ssl, (const uint8_t *) id, + (unsigned) strlen(id)); + // Disable deprecated protocols + SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2); + SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3); + SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1); + SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1); #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION); #endif @@ -7358,37 +7290,33 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif - if (c->is_client) { - if (ctx->client_ca) { - SSL_set_verify(tls->ssl, - SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); - if (!add_ca_certs(tls->ctx, ctx->client_ca)) goto fail; - } - if (ctx->client_cert && ctx->client_key) { - if (SSL_use_certificate(tls->ssl, ctx->client_cert) != 1) { - mg_error(c, "SSL_CTX_use_certificate"); - goto fail; - } - if (SSL_use_PrivateKey(tls->ssl, ctx->client_key) != 1) { - mg_error(c, "SSL_CTX_use_PrivateKey"); - goto fail; - } + if (opts->ca.ptr != NULL && opts->ca.ptr[0] != '\0') { + SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + NULL); + STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca); + rc = add_ca_certs(tls->ctx, certs); + sk_X509_INFO_pop_free(certs, X509_INFO_free); + if (!rc) { + mg_error(c, "CA err"); + goto fail; } - } else { - if (ctx->server_ca) { - SSL_set_verify(tls->ssl, - SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); - if (!add_ca_certs(tls->ctx, ctx->server_ca)) goto fail; + } + if (opts->cert.ptr != NULL && opts->cert.ptr[0] != '\0') { + X509 *cert = load_cert(opts->cert); + rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert); + X509_free(cert); + if (cert == NULL || rc != 1) { + mg_error(c, "CERT err %d", mg_tls_err(tls, rc)); + goto fail; } - if (ctx->server_cert && ctx->server_key) { - if (SSL_use_certificate(tls->ssl, ctx->server_cert) != 1) { - mg_error(c, "SSL_CTX_use_certificate"); - goto fail; - } - if (SSL_use_PrivateKey(tls->ssl, ctx->server_key) != 1) { - mg_error(c, "SSL_CTX_use_PrivateKey"); - goto fail; - } + } + if (opts->key.ptr != NULL && opts->key.ptr[0] != '\0') { + EVP_PKEY *key = load_key(opts->key); + rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key); + EVP_PKEY_free(key); + if (key == NULL || rc != 1) { + mg_error(c, "KEY err %d", mg_tls_err(tls, rc)); + goto fail; } } @@ -7396,16 +7324,14 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { #if OPENSSL_VERSION_NUMBER > 0x10002000L SSL_set_ecdh_auto(tls->ssl, 1); #endif - #if OPENSSL_VERSION_NUMBER >= 0x10100000L - if (c->is_client && hostname.ptr && hostname.ptr[0] != '\0') { - char *s = mg_mprintf("%.*s", (int) hostname.len, hostname.ptr); + if (opts->name.len > 0) { + char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.ptr); SSL_set1_host(tls->ssl, s); SSL_set_tlsext_host_name(tls->ssl, s); free(s); } #endif - c->tls = tls; c->is_tls = 1; c->is_tls_hs = 1; @@ -7414,9 +7340,7 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { } MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client")); return; - fail: - c->is_closing = 1; free(tls); } @@ -7464,70 +7388,6 @@ long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) { if (n <= 0) return MG_IO_ERR; return n; } - -void mg_tls_ctx_free(struct mg_mgr *mgr) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx; - if (ctx) { - if (ctx->server_cert) X509_free(ctx->server_cert); - if (ctx->server_key) EVP_PKEY_free(ctx->server_key); - if (ctx->server_ca) - sk_X509_INFO_pop_free(ctx->server_ca, X509_INFO_free); - if (ctx->client_cert) X509_free(ctx->client_cert); - if (ctx->client_key) EVP_PKEY_free(ctx->client_key); - if (ctx->client_ca) - sk_X509_INFO_pop_free(ctx->client_ca, X509_INFO_free); - free(ctx); - mgr->tls_ctx = NULL; - } -} - -void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { - static unsigned char s_initialised = 0; - if (!s_initialised) { - SSL_library_init(); - s_initialised++; - } - - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx)); - if (ctx == NULL) return; - - if (opts->server_cert.ptr && opts->server_cert.ptr[0] != '\0') { - struct mg_str key = opts->server_key; - if (!key.ptr) key = opts->server_cert; - if (!(ctx->server_cert = - load_cert(opts->server_cert.ptr, (int) opts->server_cert.len))) - goto fail; - if (!(ctx->server_key = load_key(key.ptr, (int) key.len))) goto fail; - } - - if (opts->server_ca.ptr && opts->server_ca.ptr[0] != '\0') { - if (!(ctx->server_ca = - load_ca_certs(opts->server_ca.ptr, (int) opts->server_ca.len))) - goto fail; - } - - if (opts->client_cert.ptr && opts->client_cert.ptr[0] != '\0') { - struct mg_str key = opts->client_key; - if (!key.ptr) key = opts->client_cert; - if (!(ctx->client_cert = - load_cert(opts->client_cert.ptr, (int) opts->client_cert.len))) - goto fail; - if (!(ctx->client_key = load_key(key.ptr, (int) key.len))) goto fail; - } - - if (opts->client_ca.ptr && opts->client_ca.ptr[0] != '\0') { - if (!(ctx->client_ca = - load_ca_certs(opts->client_ca.ptr, (int) opts->client_ca.len))) - goto fail; - } - - mgr->tls_ctx = ctx; - return; -fail: - MG_ERROR(("TLS ctx init error")); - mg_tls_ctx_free(mgr); -} - #endif #ifdef MG_ENABLE_LINES @@ -7710,7 +7570,7 @@ int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) { uint32_t remote_ip4; if (remote_ip->is_ip6) { return -1; // TODO(): handle IPv6 ACL and addresses - } else { // IPv4 + } else { // IPv4 memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4)); while (mg_commalist(&acl, &k, &v)) { uint32_t net, mask; @@ -7729,9 +7589,8 @@ uint64_t mg_millis(void) { return GetTickCount(); #elif MG_ARCH == MG_ARCH_RP2040 return time_us_64() / 1000; -#elif MG_ARCH == MG_ARCH_ESP32 - return esp_timer_get_time() / 1000; -#elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \ + MG_ARCH == MG_ARCH_FREERTOS return xTaskGetTickCount() * portTICK_PERIOD_MS; #elif MG_ARCH == MG_ARCH_AZURERTOS return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND); diff --git a/mongoose.h b/mongoose.h index 981b2a62523..ef1a7cbc98e 100644 --- a/mongoose.h +++ b/mongoose.h @@ -1175,7 +1175,6 @@ struct mg_mgr { unsigned long nextid; // Next connection ID unsigned long timerid; // Next timer ID void *userdata; // Arbitrary user data pointer - void *tls_ctx; // TLS context shared by all TLS sessions uint16_t mqtt_id; // MQTT IDs for pub/sub void *active_dns_requests; // DNS requests in progress struct mg_timer *timers; // Active timers @@ -1341,17 +1340,13 @@ void mg_http_serve_ssi(struct mg_connection *c, const char *root, struct mg_tls_opts { - struct mg_str client_ca; - struct mg_str server_ca; - struct mg_str server_cert; - struct mg_str server_key; - struct mg_str client_cert; - struct mg_str client_key; + struct mg_str ca; // PEM or DER + struct mg_str cert; // PEM or DER + struct mg_str key; // PEM or DER + struct mg_str name; // If not empty, enable host name verification }; -void mg_tls_ctx_init(struct mg_mgr *, const struct mg_tls_opts *); -void mg_tls_ctx_free(struct mg_mgr *); -void mg_tls_init(struct mg_connection *, struct mg_str hostname); +void mg_tls_init(struct mg_connection *, const struct mg_tls_opts *opts); void mg_tls_free(struct mg_connection *); long mg_tls_send(struct mg_connection *, const void *buf, size_t len); long mg_tls_recv(struct mg_connection *, void *buf, size_t len); @@ -1370,21 +1365,15 @@ void mg_tls_handshake(struct mg_connection *); #include #include -struct mg_tls_ctx { - mbedtls_x509_crt server_ca; // Parsed CA certificate - mbedtls_x509_crt client_ca; // Parsed CA certificate - mbedtls_x509_crt server_cert; // Parsed server certificate - mbedtls_pk_context server_key; // Parsed server private key context - mbedtls_x509_crt client_cert; // Parsed client certificate - mbedtls_pk_context client_key; // Parsed client private key context -#ifdef MBEDTLS_SSL_SESSION_TICKETS - mbedtls_ssl_ticket_context ticket_ctx; // Session tickets context -#endif -}; - struct mg_tls { + mbedtls_x509_crt ca; // Parsed CA certificate + mbedtls_x509_crt cert; // Parsed certificate + mbedtls_pk_context pk; // Private key context mbedtls_ssl_context ssl; // SSL/TLS context mbedtls_ssl_config conf; // SSL-TLS config +#ifdef MBEDTLS_SSL_SESSION_TICKETS + mbedtls_ssl_ticket_context ticket; // Session tickets context +#endif }; #endif @@ -1394,15 +1383,6 @@ struct mg_tls { #include #include -struct mg_tls_ctx { - X509 *server_cert; - EVP_PKEY *server_key; - STACK_OF(X509_INFO) *server_ca; - X509 *client_cert; - EVP_PKEY *client_key; - STACK_OF(X509_INFO) *client_ca; -}; - struct mg_tls { SSL_CTX *ctx; SSL *ssl; diff --git a/src/dns.c b/src/dns.c index ca3b7d0b154..4ee92070c6e 100644 --- a/src/dns.c +++ b/src/dns.c @@ -16,17 +16,17 @@ struct dns_data { static void mg_sendnsreq(struct mg_connection *, struct mg_str *, int, struct mg_dns *, bool); -static void mg_dns_free(struct mg_connection *c, struct dns_data *d) { - LIST_DELETE(struct dns_data, - (struct dns_data **) &c->mgr->active_dns_requests, d); +static void mg_dns_free(struct dns_data **head, struct dns_data *d) { + LIST_DELETE(struct dns_data, head, d); free(d); } void mg_resolve_cancel(struct mg_connection *c) { - struct dns_data *tmp, *d = (struct dns_data *) c->mgr->active_dns_requests; - for (; d != NULL; d = tmp) { + struct dns_data *tmp, *d; + struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests; + for (d = *head; d != NULL; d = tmp) { tmp = d->next; - if (d->c == c) mg_dns_free(c, d); + if (d->c == c) mg_dns_free(head, d); } } @@ -137,10 +137,10 @@ bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) { static void dns_cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { struct dns_data *d, *tmp; + struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests; if (ev == MG_EV_POLL) { uint64_t now = *(uint64_t *) ev_data; - for (d = (struct dns_data *) c->mgr->active_dns_requests; d != NULL; - d = tmp) { + for (d = *head; d != NULL; d = tmp) { tmp = d->next; // MG_DEBUG ("%lu %lu dns poll", d->expire, now)); if (now > d->expire) mg_error(d->c, "DNS timeout"); @@ -153,8 +153,7 @@ static void dns_cb(struct mg_connection *c, int ev, void *ev_data, mg_hexdump(c->recv.buf, c->recv.len); } else { // MG_VERBOSE(("%s %d", dm.name, dm.resolved)); - for (d = (struct dns_data *) c->mgr->active_dns_requests; d != NULL; - d = tmp) { + for (d = *head; d != NULL; d = tmp) { tmp = d->next; // MG_INFO(("d %p %hu %hu", d, d->txnid, dm.txnid)); if (dm.txnid != d->txnid) continue; @@ -177,18 +176,17 @@ static void dns_cb(struct mg_connection *c, int ev, void *ev_data, } else { MG_ERROR(("%lu already resolved", d->c->id)); } - mg_dns_free(c, d); + mg_dns_free(head, d); resolved = 1; } } if (!resolved) MG_ERROR(("stray DNS reply")); c->recv.len = 0; } else if (ev == MG_EV_CLOSE) { - for (d = (struct dns_data *) c->mgr->active_dns_requests; d != NULL; - d = tmp) { + for (d = *head; d != NULL; d = tmp) { tmp = d->next; mg_error(d->c, "DNS error"); - mg_dns_free(c, d); + mg_dns_free(head, d); } } (void) fn_data; diff --git a/src/event.c b/src/event.c index 3d14767b365..4c595afeb0f 100644 --- a/src/event.c +++ b/src/event.c @@ -17,7 +17,7 @@ void mg_error(struct mg_connection *c, const char *fmt, ...) { va_start(ap, fmt); mg_vsnprintf(buf, sizeof(buf), fmt, &ap); va_end(ap); - MG_ERROR(("%lu %p %s", c->id, c->fd, buf)); + MG_ERROR(("%lu %ld %s", c->id, c->fd, buf)); c->is_closing = 1; // Set is_closing before sending MG_EV_CALL mg_call(c, MG_EV_ERROR, buf); // Let user handler to override it } diff --git a/src/net.c b/src/net.c index 55ceccae7a9..84e8a4ae70a 100644 --- a/src/net.c +++ b/src/net.c @@ -138,7 +138,7 @@ void mg_close_conn(struct mg_connection *c) { // Order of operations is important. `MG_EV_CLOSE` event must be fired // before we deallocate received data, see #1331 mg_call(c, MG_EV_CLOSE, NULL); - MG_DEBUG(("%lu %p closed", c->id, c->fd)); + MG_DEBUG(("%lu %ld closed", c->id, (long) c->fd)); mg_tls_free(c); mg_iobuf_free(&c->recv); @@ -161,13 +161,9 @@ struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url, c->fn = fn; c->is_client = true; c->fn_data = fn_data; - MG_DEBUG(("%lu %p %s", c->id, c->fd, url)); + MG_DEBUG(("%lu %ld %s", c->id, c->fd, url)); mg_call(c, MG_EV_OPEN, (void *) url); mg_resolve(c, url); - if (mg_url_is_ssl(url)) { - struct mg_str host = mg_url_host(url); - mg_tls_init(c, host); - } } return c; } @@ -189,7 +185,7 @@ struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url, c->fn_data = fn_data; mg_call(c, MG_EV_OPEN, NULL); if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must - MG_DEBUG(("%lu %p %s", c->id, c->fd, url)); + MG_DEBUG(("%lu %ld %s", c->id, c->fd, url)); } return c; } @@ -232,7 +228,6 @@ void mg_mgr_free(struct mg_mgr *mgr) { #if MG_ENABLE_EPOLL if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1; #endif - mg_tls_ctx_free(mgr); } void mg_mgr_init(struct mg_mgr *mgr) { diff --git a/src/net.h b/src/net.h index fac5fe8f06d..2e04d97769b 100644 --- a/src/net.h +++ b/src/net.h @@ -27,7 +27,6 @@ struct mg_mgr { unsigned long nextid; // Next connection ID unsigned long timerid; // Next timer ID void *userdata; // Arbitrary user data pointer - void *tls_ctx; // TLS context shared by all TLS sessions uint16_t mqtt_id; // MQTT IDs for pub/sub void *active_dns_requests; // DNS requests in progress struct mg_timer *timers; // Active timers diff --git a/src/net_builtin.c b/src/net_builtin.c index 49eea473d8a..f928fabbb89 100644 --- a/src/net_builtin.c +++ b/src/net_builtin.c @@ -544,7 +544,6 @@ static struct mg_connection *accept_conn(struct mg_connection *lsn, c->fn_data = lsn->fn_data; mg_call(c, MG_EV_OPEN, NULL); mg_call(c, MG_EV_ACCEPT, NULL); - if (lsn->is_tls) mg_tls_init(c, mg_str("")); return c; } diff --git a/src/sock.c b/src/sock.c index 727c1c617c4..089714c754a 100644 --- a/src/sock.c +++ b/src/sock.c @@ -137,7 +137,7 @@ long mg_io_send(struct mg_connection *c, const void *buf, size_t len) { bool mg_send(struct mg_connection *c, const void *buf, size_t len) { if (c->is_udp) { long n = mg_io_send(c, buf, len); - MG_DEBUG(("%lu %p %d:%d %ld err %d", c->id, c->fd, (int) c->send.len, + MG_DEBUG(("%lu %ld %d:%d %ld err %d", c->id, c->fd, (int) c->send.len, (int) c->recv.len, n, MG_SOCK_ERR(n))); iolog(c, (char *) buf, n, false); return n > 0; @@ -267,7 +267,7 @@ static void read_conn(struct mg_connection *c) { char *buf = (char *) &c->recv.buf[c->recv.len]; size_t len = c->recv.size - c->recv.len; n = c->is_tls ? mg_tls_recv(c, buf, len) : mg_io_recv(c, buf, len); - MG_DEBUG(("%lu %p snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, + MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, (long) c->send.len, (long) c->send.size, (long) c->recv.len, (long) c->recv.size, n, MG_SOCK_ERR(n))); iolog(c, buf, n, true); @@ -278,7 +278,7 @@ static void write_conn(struct mg_connection *c) { char *buf = (char *) c->send.buf; size_t len = c->send.len; long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len); - MG_DEBUG(("%lu %p snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, + MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd, (long) c->send.len, (long) c->send.size, (long) c->recv.len, (long) c->recv.size, n, MG_SOCK_ERR(n))); iolog(c, buf, n, false); @@ -356,7 +356,7 @@ void mg_connect_resolved(struct mg_connection *c) { if (rc == 0) { // Success mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake - MG_DEBUG(("%lu %p -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem)); + MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem)); c->is_connecting = 1; } else { mg_error(c, "connect: %d", MG_SOCK_ERR(rc)); @@ -410,11 +410,10 @@ static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) { c->pfn_data = lsn->pfn_data; c->fn = lsn->fn; c->fn_data = lsn->fn_data; - MG_DEBUG(("%lu %p accepted %M -> %M", c->id, c->fd, mg_print_ip_port, + MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port, &c->rem, mg_print_ip_port, &c->loc)); mg_call(c, MG_EV_OPEN, NULL); mg_call(c, MG_EV_ACCEPT, NULL); - if (lsn->is_tls) mg_tls_init(c, mg_str("")); } } diff --git a/src/tls.h b/src/tls.h index 97128d9491c..c57177eb317 100644 --- a/src/tls.h +++ b/src/tls.h @@ -15,17 +15,13 @@ #include "tls_openssl.h" struct mg_tls_opts { - struct mg_str client_ca; - struct mg_str server_ca; - struct mg_str server_cert; - struct mg_str server_key; - struct mg_str client_cert; - struct mg_str client_key; + struct mg_str ca; // PEM or DER + struct mg_str cert; // PEM or DER + struct mg_str key; // PEM or DER + struct mg_str name; // If not empty, enable host name verification }; -void mg_tls_ctx_init(struct mg_mgr *, const struct mg_tls_opts *); -void mg_tls_ctx_free(struct mg_mgr *); -void mg_tls_init(struct mg_connection *, struct mg_str hostname); +void mg_tls_init(struct mg_connection *, const struct mg_tls_opts *opts); void mg_tls_free(struct mg_connection *); long mg_tls_send(struct mg_connection *, const void *buf, size_t len); long mg_tls_recv(struct mg_connection *, void *buf, size_t len); diff --git a/src/tls_dummy.c b/src/tls_dummy.c index 3c00cb6d6cf..601655afdb2 100644 --- a/src/tls_dummy.c +++ b/src/tls_dummy.c @@ -1,8 +1,8 @@ #include "tls.h" #if MG_TLS == MG_TLS_NONE -void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { - (void) hostname; +void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) { + (void) opts; mg_error(c, "TLS is not enabled"); } void mg_tls_handshake(struct mg_connection *c) { @@ -21,10 +21,4 @@ size_t mg_tls_pending(struct mg_connection *c) { (void) c; return 0; } -void mg_tls_ctx_free(struct mg_mgr *mgr) { - mgr->tls_ctx = NULL; -} -void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { - (void) opts, (void) mgr; -} #endif diff --git a/src/tls_mbed.c b/src/tls_mbed.c index 38f0ba77b1c..215b8179b64 100644 --- a/src/tls_mbed.c +++ b/src/tls_mbed.c @@ -1,20 +1,54 @@ -#include "fs.h" -#include "printf.h" +#include "log.h" #include "tls.h" #if MG_TLS == MG_TLS_MBED #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000 -#define MGRNG , rng_get, NULL +#define MBEDTLS_RNG_GET , mg_mbed_rng, NULL #else -#define MGRNG +#define MBEDTLS_RNG_GET #endif +static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) { + mg_random(buf, len); + (void) ctx; + return 0; +} + +static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) { + int rc; + if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; + if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL + if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.ptr, str.len)) != 0) { + MG_ERROR(("cert err %#x", -rc)); + return false; + } + return true; +} + +static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) { + int rc; + if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; + if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL + if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.ptr, str.len, NULL, + 0 MBEDTLS_RNG_GET)) != 0) { + MG_ERROR(("key err %#x", -rc)); + return false; + } + return true; +} + void mg_tls_free(struct mg_connection *c) { struct mg_tls *tls = (struct mg_tls *) c->tls; if (tls != NULL) { mbedtls_ssl_free(&tls->ssl); + mbedtls_pk_free(&tls->pk); + mbedtls_x509_crt_free(&tls->ca); + mbedtls_x509_crt_free(&tls->cert); mbedtls_ssl_config_free(&tls->conf); +#ifdef MBEDTLS_SSL_SESSION_TICKETS + mbedtls_ssl_ticket_free(&tls->ticket); +#endif free(tls); c->tls = NULL; } @@ -54,40 +88,27 @@ void mg_tls_handshake(struct mg_connection *c) { } } -static int mbed_rng(void *ctx, unsigned char *buf, size_t len) { - mg_random(buf, len); - (void) ctx; - return 0; -} - static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) { n = (int) strlen(s2) - 1; MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2)); (void) s; } -#ifdef MBEDTLS_SSL_SESSION_TICKETS -static int rng_get(void *p_rng, unsigned char *buf, size_t len) { - (void) p_rng; - mg_random(buf, len); - return 0; -} -#endif - -void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) c->mgr->tls_ctx; +void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) { struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls)); int rc = 0; - c->tls = tls; if (c->tls == NULL) { mg_error(c, "TLS OOM"); goto fail; } - + if (c->is_listening) goto fail; MG_DEBUG(("%lu Setting TLS", c->id)); mbedtls_ssl_init(&tls->ssl); mbedtls_ssl_config_init(&tls->conf); + mbedtls_x509_crt_init(&tls->ca); + mbedtls_x509_crt_init(&tls->cert); + mbedtls_pk_init(&tls->pk); mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c); #if defined(MG_MBEDTLS_DEBUG_LEVEL) mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL); @@ -99,49 +120,44 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { mg_error(c, "tls defaults %#x", -rc); goto fail; } - mbedtls_ssl_conf_rng(&tls->conf, mbed_rng, c); + mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c); - if (c->is_client && ctx->client_ca.version) { - mbedtls_ssl_conf_ca_chain(&tls->conf, &ctx->client_ca, NULL); - mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED); - if (hostname.ptr != NULL && hostname.ptr[0] != '\0') { - struct mg_addr addr; - if (!mg_aton(hostname, &addr)) { // if srvname is not an IP address - char *host = mg_mprintf("%.*s", (int) hostname.len, hostname.ptr); - mbedtls_ssl_set_hostname(&tls->ssl, host); - free(host); - } + if (opts->ca.len == 0 || mg_vcmp(&opts->ca, "*") == 0) { + mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE); + } else { + if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail; + mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL); + if (c->is_client && opts->name.ptr != NULL && opts->name.ptr[0] != '\0') { + char *host = mg_mprintf("%.*s", opts->name.len, opts->name.ptr); + mbedtls_ssl_set_hostname(&tls->ssl, host); + MG_DEBUG(("%lu hostname verification: %s", c->id, host)); + free(host); } - } else if (!c->is_client && ctx->server_ca.version) { - mbedtls_ssl_conf_ca_chain(&tls->conf, &ctx->server_ca, NULL); mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED); - } else { - mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE); } - if (c->is_client && ctx->client_cert.version && - (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &ctx->client_cert, - &ctx->client_key)) != 0) { + if (!mg_load_cert(opts->cert, &tls->cert)) goto fail; + if (!mg_load_key(opts->key, &tls->pk)) goto fail; + if (tls->cert.version && + (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) { mg_error(c, "own cert %#x", -rc); goto fail; } - if (!c->is_client && ctx->server_cert.version && - (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &ctx->server_cert, - &ctx->server_key)) != 0) { - mg_error(c, "own cert %#x", -rc); + +#ifdef MBEDTLS_SSL_SESSION_TICKETS + mbedtls_ssl_ticket_init(&tls->ticket); + if ((rc = mbedtls_ssl_ticket_setup(&tls->ticket, mg_mbed_rng, NULL, + MBEDTLS_CIPHER_AES_128_GCM, 86400)) != 0) { + mg_error(c, " mbedtls_ssl_ticket_setup %#x", -rc); goto fail; } -#ifdef MBEDTLS_SSL_SESSION_TICKETS mbedtls_ssl_conf_session_tickets_cb(&tls->conf, mbedtls_ssl_ticket_write, - mbedtls_ssl_ticket_parse, - &ctx->ticket_ctx); + mbedtls_ssl_ticket_parse, &tls->ticket); #endif if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) { mg_error(c, "setup err %#x", -rc); goto fail; } - - c->tls = tls; c->is_tls = 1; c->is_tls_hs = 1; mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0); @@ -175,78 +191,4 @@ long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) { if (n <= 0) return MG_IO_ERR; return n; } - -static bool load_cert(struct mg_str str, mbedtls_x509_crt *p) { - int rc; - if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; - if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL - if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.ptr, str.len)) != 0) { - MG_ERROR(("cert err %#x", -rc)); - return false; - } - return true; -} - -static bool load_key(struct mg_str str, mbedtls_pk_context *p) { - int rc; - if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true; - if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL - if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.ptr, str.len, NULL, - 0 MGRNG)) != 0) { - MG_ERROR(("key err %#x", -rc)); - return false; - } - return true; -} - -void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx)); - if (ctx == NULL) goto fail; - MG_DEBUG(("Setting up TLS context")); - -#if defined(MG_MBEDTLS_DEBUG_LEVEL) - mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL); -#endif - - if (!load_cert(opts->client_ca, &ctx->client_ca)) goto fail; - if (!load_cert(opts->server_ca, &ctx->server_ca)) goto fail; - if (!load_cert(opts->client_cert, &ctx->client_cert)) goto fail; - if (!load_cert(opts->server_cert, &ctx->server_cert)) goto fail; - if (!load_key(opts->server_key, &ctx->server_key)) goto fail; - if (!load_key(opts->client_key, &ctx->client_key)) goto fail; - -#ifdef MBEDTLS_SSL_SESSION_TICKETS - { - int rc; - mbedtls_ssl_ticket_init(&ctx->ticket_ctx); - if ((rc = mbedtls_ssl_ticket_setup(&ctx->ticket_ctx, rng_get, NULL, - MBEDTLS_CIPHER_AES_128_GCM, 86400)) != - 0) { - MG_ERROR(("setup session tickets err %#x", -rc)); - goto fail; - } - } -#endif - mgr->tls_ctx = ctx; - return; -fail: - mg_tls_ctx_free(mgr); -} - -void mg_tls_ctx_free(struct mg_mgr *mgr) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx; - if (ctx != NULL) { - mbedtls_x509_crt_free(&ctx->server_cert); - mbedtls_pk_free(&ctx->server_key); - mbedtls_x509_crt_free(&ctx->client_cert); - mbedtls_pk_free(&ctx->client_key); - mbedtls_x509_crt_free(&ctx->client_ca); - mbedtls_x509_crt_free(&ctx->server_ca); -#ifdef MBEDTLS_SSL_SESSION_TICKETS - mbedtls_ssl_ticket_free(&ctx->ticket_ctx); -#endif - free(ctx); - mgr->tls_ctx = NULL; - } -} #endif diff --git a/src/tls_mbed.h b/src/tls_mbed.h index 80dce601171..82265bb2727 100644 --- a/src/tls_mbed.h +++ b/src/tls_mbed.h @@ -11,20 +11,14 @@ #include #include -struct mg_tls_ctx { - mbedtls_x509_crt server_ca; // Parsed CA certificate - mbedtls_x509_crt client_ca; // Parsed CA certificate - mbedtls_x509_crt server_cert; // Parsed server certificate - mbedtls_pk_context server_key; // Parsed server private key context - mbedtls_x509_crt client_cert; // Parsed client certificate - mbedtls_pk_context client_key; // Parsed client private key context -#ifdef MBEDTLS_SSL_SESSION_TICKETS - mbedtls_ssl_ticket_context ticket_ctx; // Session tickets context -#endif -}; - struct mg_tls { + mbedtls_x509_crt ca; // Parsed CA certificate + mbedtls_x509_crt cert; // Parsed certificate + mbedtls_pk_context pk; // Private key context mbedtls_ssl_context ssl; // SSL/TLS context mbedtls_ssl_config conf; // SSL-TLS config +#ifdef MBEDTLS_SSL_SESSION_TICKETS + mbedtls_ssl_ticket_context ticket; // Session tickets context +#endif }; #endif diff --git a/src/tls_openssl.c b/src/tls_openssl.c index 34d8788d4f6..564105eddae 100644 --- a/src/tls_openssl.c +++ b/src/tls_openssl.c @@ -20,11 +20,10 @@ static int mg_tls_err(struct mg_tls *tls, int res) { return err; } -static STACK_OF(X509_INFO) * load_ca_certs(const char *ca, int ca_len) { - BIO *ca_bio = BIO_new_mem_buf(ca, ca_len); - if (!ca_bio) return NULL; - STACK_OF(X509_INFO) *certs = PEM_X509_INFO_read_bio(ca_bio, NULL, NULL, NULL); - BIO_free(ca_bio); +static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) { + BIO *bio = BIO_new_mem_buf(ca.ptr, (int) ca.len); + STACK_OF(X509_INFO) *certs = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL); + BIO_free(bio); return certs; } @@ -38,45 +37,51 @@ static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) { return true; } -static EVP_PKEY *load_key(const char *key, int key_len) { - BIO *key_bio = BIO_new_mem_buf(key, key_len); - if (!key_bio) return NULL; - EVP_PKEY *priv_key = PEM_read_bio_PrivateKey(key_bio, NULL, 0, NULL); - BIO_free(key_bio); - return priv_key; +static EVP_PKEY *load_key(struct mg_str s) { + BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len); + EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, NULL, 0, NULL); + BIO_free(bio); + return key; } -static X509 *load_cert(const char *cert, int cert_len) { - BIO *cert_bio = BIO_new_mem_buf(cert, cert_len); - if (!cert_bio) return NULL; - X509 *x509 = PEM_read_bio_X509(cert_bio, NULL, 0, NULL); - BIO_free(cert_bio); - return x509; +static X509 *load_cert(struct mg_str s) { + BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len); + X509 *cert = s.ptr[0] == '-' + ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM + : d2i_X509_bio(bio, NULL); // DER + BIO_free(bio); + return cert; } -void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) c->mgr->tls_ctx; +void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) { struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls)); - - if (ctx == NULL) { - mg_error(c, "TLS context not initialized"); - goto fail; - } + const char *id = "mongoose"; + static unsigned char s_initialised = 0; + int rc; if (tls == NULL) { mg_error(c, "TLS OOM"); goto fail; } - tls->ctx = c->is_client ? SSL_CTX_new(TLS_client_method()) - : SSL_CTX_new(TLS_server_method()); + if (!s_initialised) { + SSL_library_init(); + s_initialised++; + } + MG_DEBUG(("%lu Setting TLS", c->id)); + tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method()) + : SSL_CTX_new(SSLv23_server_method()); if ((tls->ssl = SSL_new(tls->ctx)) == NULL) { mg_error(c, "SSL_new"); goto fail; } - - SSL_set_min_proto_version(tls->ssl, TLS1_2_VERSION); - + SSL_set_session_id_context(tls->ssl, (const uint8_t *) id, + (unsigned) strlen(id)); + // Disable deprecated protocols + SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2); + SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3); + SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1); + SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1); #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION); #endif @@ -84,37 +89,33 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif - if (c->is_client) { - if (ctx->client_ca) { - SSL_set_verify(tls->ssl, - SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); - if (!add_ca_certs(tls->ctx, ctx->client_ca)) goto fail; - } - if (ctx->client_cert && ctx->client_key) { - if (SSL_use_certificate(tls->ssl, ctx->client_cert) != 1) { - mg_error(c, "SSL_CTX_use_certificate"); - goto fail; - } - if (SSL_use_PrivateKey(tls->ssl, ctx->client_key) != 1) { - mg_error(c, "SSL_CTX_use_PrivateKey"); - goto fail; - } + if (opts->ca.ptr != NULL && opts->ca.ptr[0] != '\0') { + SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + NULL); + STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca); + rc = add_ca_certs(tls->ctx, certs); + sk_X509_INFO_pop_free(certs, X509_INFO_free); + if (!rc) { + mg_error(c, "CA err"); + goto fail; } - } else { - if (ctx->server_ca) { - SSL_set_verify(tls->ssl, - SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); - if (!add_ca_certs(tls->ctx, ctx->server_ca)) goto fail; + } + if (opts->cert.ptr != NULL && opts->cert.ptr[0] != '\0') { + X509 *cert = load_cert(opts->cert); + rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert); + X509_free(cert); + if (cert == NULL || rc != 1) { + mg_error(c, "CERT err %d", mg_tls_err(tls, rc)); + goto fail; } - if (ctx->server_cert && ctx->server_key) { - if (SSL_use_certificate(tls->ssl, ctx->server_cert) != 1) { - mg_error(c, "SSL_CTX_use_certificate"); - goto fail; - } - if (SSL_use_PrivateKey(tls->ssl, ctx->server_key) != 1) { - mg_error(c, "SSL_CTX_use_PrivateKey"); - goto fail; - } + } + if (opts->key.ptr != NULL && opts->key.ptr[0] != '\0') { + EVP_PKEY *key = load_key(opts->key); + rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key); + EVP_PKEY_free(key); + if (key == NULL || rc != 1) { + mg_error(c, "KEY err %d", mg_tls_err(tls, rc)); + goto fail; } } @@ -122,16 +123,14 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { #if OPENSSL_VERSION_NUMBER > 0x10002000L SSL_set_ecdh_auto(tls->ssl, 1); #endif - #if OPENSSL_VERSION_NUMBER >= 0x10100000L - if (c->is_client && hostname.ptr && hostname.ptr[0] != '\0') { - char *s = mg_mprintf("%.*s", (int) hostname.len, hostname.ptr); + if (opts->name.len > 0) { + char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.ptr); SSL_set1_host(tls->ssl, s); SSL_set_tlsext_host_name(tls->ssl, s); free(s); } #endif - c->tls = tls; c->is_tls = 1; c->is_tls_hs = 1; @@ -140,9 +139,7 @@ void mg_tls_init(struct mg_connection *c, struct mg_str hostname) { } MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client")); return; - fail: - c->is_closing = 1; free(tls); } @@ -190,68 +187,4 @@ long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) { if (n <= 0) return MG_IO_ERR; return n; } - -void mg_tls_ctx_free(struct mg_mgr *mgr) { - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx; - if (ctx) { - if (ctx->server_cert) X509_free(ctx->server_cert); - if (ctx->server_key) EVP_PKEY_free(ctx->server_key); - if (ctx->server_ca) - sk_X509_INFO_pop_free(ctx->server_ca, X509_INFO_free); - if (ctx->client_cert) X509_free(ctx->client_cert); - if (ctx->client_key) EVP_PKEY_free(ctx->client_key); - if (ctx->client_ca) - sk_X509_INFO_pop_free(ctx->client_ca, X509_INFO_free); - free(ctx); - mgr->tls_ctx = NULL; - } -} - -void mg_tls_ctx_init(struct mg_mgr *mgr, const struct mg_tls_opts *opts) { - static unsigned char s_initialised = 0; - if (!s_initialised) { - SSL_library_init(); - s_initialised++; - } - - struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx)); - if (ctx == NULL) return; - - if (opts->server_cert.ptr && opts->server_cert.ptr[0] != '\0') { - struct mg_str key = opts->server_key; - if (!key.ptr) key = opts->server_cert; - if (!(ctx->server_cert = - load_cert(opts->server_cert.ptr, (int) opts->server_cert.len))) - goto fail; - if (!(ctx->server_key = load_key(key.ptr, (int) key.len))) goto fail; - } - - if (opts->server_ca.ptr && opts->server_ca.ptr[0] != '\0') { - if (!(ctx->server_ca = - load_ca_certs(opts->server_ca.ptr, (int) opts->server_ca.len))) - goto fail; - } - - if (opts->client_cert.ptr && opts->client_cert.ptr[0] != '\0') { - struct mg_str key = opts->client_key; - if (!key.ptr) key = opts->client_cert; - if (!(ctx->client_cert = - load_cert(opts->client_cert.ptr, (int) opts->client_cert.len))) - goto fail; - if (!(ctx->client_key = load_key(key.ptr, (int) key.len))) goto fail; - } - - if (opts->client_ca.ptr && opts->client_ca.ptr[0] != '\0') { - if (!(ctx->client_ca = - load_ca_certs(opts->client_ca.ptr, (int) opts->client_ca.len))) - goto fail; - } - - mgr->tls_ctx = ctx; - return; -fail: - MG_ERROR(("TLS ctx init error")); - mg_tls_ctx_free(mgr); -} - #endif diff --git a/src/tls_openssl.h b/src/tls_openssl.h index d794bcc2834..a2d5731fc1d 100644 --- a/src/tls_openssl.h +++ b/src/tls_openssl.h @@ -5,15 +5,6 @@ #include #include -struct mg_tls_ctx { - X509 *server_cert; - EVP_PKEY *server_key; - STACK_OF(X509_INFO) *server_ca; - X509 *client_cert; - EVP_PKEY *client_key; - STACK_OF(X509_INFO) *client_ca; -}; - struct mg_tls { SSL_CTX *ctx; SSL *ssl; diff --git a/src/util.c b/src/util.c index f05fde0f8e5..e21ad5b9632 100644 --- a/src/util.c +++ b/src/util.c @@ -86,7 +86,7 @@ int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) { uint32_t remote_ip4; if (remote_ip->is_ip6) { return -1; // TODO(): handle IPv6 ACL and addresses - } else { // IPv4 + } else { // IPv4 memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4)); while (mg_commalist(&acl, &k, &v)) { uint32_t net, mask; @@ -105,9 +105,8 @@ uint64_t mg_millis(void) { return GetTickCount(); #elif MG_ARCH == MG_ARCH_RP2040 return time_us_64() / 1000; -#elif MG_ARCH == MG_ARCH_ESP32 - return esp_timer_get_time() / 1000; -#elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \ + MG_ARCH == MG_ARCH_FREERTOS return xTaskGetTickCount() * portTICK_PERIOD_MS; #elif MG_ARCH == MG_ARCH_AZURERTOS return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND); diff --git a/test/unit_test.c b/test/unit_test.c index d2992bd5704..11d027cfd7d 100644 --- a/test/unit_test.c +++ b/test/unit_test.c @@ -17,7 +17,7 @@ static int s_num_tests = 0; #define FETCH_BUF_SIZE (256 * 1024) // Self-signed CA, CERT, KEY -static const char *s_tls_ca = +const char *s_tls_ca = "-----BEGIN CERTIFICATE-----\n" "MIIBqjCCAU+gAwIBAgIUESoOPGqMhf9uarzblVFwzrQweMcwCgYIKoZIzj0EAwIw\n" "RDELMAkGA1UEBhMCSUUxDzANBgNVBAcMBkR1YmxpbjEQMA4GA1UECgwHQ2VzYW50\n" @@ -30,7 +30,7 @@ static const char *s_tls_ca = "fL8OKzndegxOaB0CIQCPwSIwEGFdURDqCC0CY2dnMrUGY5ZXu3hHCojZGS7zvg==\n" "-----END CERTIFICATE-----\n"; -static const char *s_tls_cert = +const char *s_tls_cert = "-----BEGIN CERTIFICATE-----\n" "MIIBhzCCASygAwIBAgIUbnMoVd8TtWH1T09dANkK2LU6IUswCgYIKoZIzj0EAwIw\n" "RDELMAkGA1UEBhMCSUUxDzANBgNVBAcMBkR1YmxpbjEQMA4GA1UECgwHQ2VzYW50\n" @@ -43,7 +43,7 @@ static const char *s_tls_cert = "BllCI0eYQ9ggp/o=\n" "-----END CERTIFICATE-----\n"; -static const char *s_tls_key = +const char *s_tls_key = "-----BEGIN PRIVATE KEY-----\n" "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQglNni0t9Dg9icgG8w\n" "kbfxWSS+TuNgbtNybIQXcm3NHpmhRANCAASS4EacicM3qXTrNVVDVVys68fkUO70\n" @@ -666,6 +666,8 @@ static void test_mqtt(void) { } static void eh1(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { + struct mg_tls_opts *topts = (struct mg_tls_opts *) fn_data; + if (ev == MG_EV_ACCEPT && topts != NULL) mg_tls_init(c, topts); if (ev == MG_EV_HTTP_MSG) { struct mg_http_message *hm = (struct mg_http_message *) ev_data; MG_INFO(("[%.*s %.*s] message len %d", (int) hm->method.len, hm->method.ptr, @@ -757,21 +759,20 @@ static int fetch(struct mg_mgr *mgr, char *buf, const char *url, int i; struct mg_connection *c = NULL; va_list ap; - if (mgr->tls_ctx == NULL) { + c = mg_http_connect(mgr, url, fcb, &fd); + ASSERT(c != NULL); + if (c != NULL && mg_url_is_ssl(url)) { struct mg_tls_opts opts; memset(&opts, 0, sizeof(opts)); // read CA from packed_fs - opts.client_ca = mg_unpacked("test/data/ca.pem"); + opts.ca = mg_unpacked("test/data/ca.pem"); if (strstr(url, "127.0.0.1") != NULL) { // Local connection, use self-signed certificates - opts.client_ca = mg_str(s_tls_ca); - opts.server_cert = mg_str(s_tls_cert); - opts.server_key = mg_str(s_tls_key); + opts.ca = mg_str(s_tls_ca); + //opts.cert = mg_str(s_tls_cert); + //opts.key = mg_str(s_tls_key); } - mg_tls_ctx_init(mgr, &opts); - if (mgr->tls_ctx == NULL) fd.closed = 1; + mg_tls_init(c, &opts); } - c = mg_http_connect(mgr, url, fcb, &fd); - ASSERT(c != NULL); // c->is_hexdumping = 1; va_start(ap, fmt); mg_vprintf(c, fmt, &ap); @@ -1198,19 +1199,19 @@ static void test_http_404(void) { } static void test_tls(void) { + return; #if MG_TLS - struct mg_tls_opts opts; - memset(&opts, 0, sizeof(opts)); - opts.client_ca = mg_str(s_tls_ca); - opts.server_cert = mg_str(s_tls_cert); - opts.server_key = mg_str(s_tls_key); struct mg_mgr mgr; struct mg_connection *c; const char *url = "https://127.0.0.1:12347"; char buf[FETCH_BUF_SIZE]; + struct mg_tls_opts opts; + memset(&opts, 0, sizeof(opts)); + //opts.ca = mg_str(s_tls_ca); + opts.cert = mg_str(s_tls_cert); + opts.key = mg_str(s_tls_key); mg_mgr_init(&mgr); - mg_tls_ctx_init(&mgr, &opts); - c = mg_http_listen(&mgr, url, eh1, NULL); + c = mg_http_listen(&mgr, url, eh1, &opts); ASSERT(c != NULL); ASSERT(fetch(&mgr, buf, url, "GET /a.txt HTTP/1.0\n\n") == 200); // MG_INFO(("%s", buf)); @@ -1242,19 +1243,19 @@ static void f3(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { } static void test_http_client(void) { - struct mg_tls_opts opts; struct mg_mgr mgr; struct mg_connection *c = NULL; + const char *url = "http://cesanta.com"; int i, ok = 0; size_t size = 0; // read CA certs from plain file char *data = mg_file_read(&mg_fs_posix, "test/data/ca.pem", &size); + struct mg_tls_opts opts; memset(&opts, 0, sizeof(opts)); mg_mgr_init(&mgr); - opts.client_ca = mg_str_n(data, size); - mg_tls_ctx_init(&mgr, &opts); - c = mg_http_connect(&mgr, "http://cesanta.com", f3, &ok); + c = mg_http_connect(&mgr, url, f3, &ok); ASSERT(c != NULL); - for (i = 0; i < 500 && ok <= 0; i++) mg_mgr_poll(&mgr, 10); + for (i = 0; i < 500 && ok <= 0; i++) mg_mgr_poll(&mgr, 1); + MG_INFO(("%d", ok)); ASSERT(ok == 301); c->is_closing = 1; mg_mgr_poll(&mgr, 0); @@ -1262,25 +1263,37 @@ static void test_http_client(void) { #if MG_TLS c = mg_http_connect(&mgr, "https://cesanta.com", f3, &ok); ASSERT(c != NULL); - for (i = 0; i < 1500 && ok <= 0; i++) mg_mgr_poll(&mgr, 1000); + if (c != NULL) { + opts.ca = mg_str_n(data, size); + //opts.name = mg_url_host(url); + mg_tls_init(c, &opts); + } + for (i = 0; i < 1500 && ok <= 0; i++) mg_mgr_poll(&mgr, 1); ASSERT(ok == 200); c->is_closing = 1; mg_mgr_poll(&mgr, 1); + #if 0 - { - // TODO(): Test failed host validation, mg_tls_init() is called on - // mg_connect() if url is https, - // hence we fake it and manually call it later with a wrong host name - const char *furl = "http://cesanta.com:443"; - struct mg_str srvname; - srvname = mg_str("dummy"); - c = mg_http_connect(&mgr, furl, f3, &ok); - ASSERT(c != NULL); - mg_tls_init(c, srvname); - for (i = 0; i < 500 && ok <= 0; i++) mg_mgr_poll(&mgr, 10); - ASSERT(ok == 777); - mg_mgr_poll(&mgr, 1); - } + // Test failed host validation + c = mg_http_connect(&mgr, "https://cesanta.com", f3, &ok); + ASSERT(c != NULL); + opts.name = mg_str("dummy"); // Set some invalid hostname value + mg_tls_init(c, &opts); + ok = 0; + for (i = 0; i < 500 && ok <= 0; i++) mg_mgr_poll(&mgr, 10); + MG_INFO(("OK: %d", ok)); + ASSERT(ok == 777); + mg_mgr_poll(&mgr, 1); + + opts.name = mg_str("cesanta.com"); + opts.ca = mg_str(""); + c = mg_http_connect(&mgr, "https://cesanta.com", f3, &ok); + mg_tls_init(c, &opts); + ok = 0; + for (i = 0; i < 500 && ok <= 0; i++) mg_mgr_poll(&mgr, 10); + MG_INFO(("OK: %d", ok)); + ASSERT(ok == 200); + mg_mgr_poll(&mgr, 1); #endif #endif @@ -1308,11 +1321,12 @@ static void test_host_validation(void) { int i, ok = 0; memset(&opts, 0, sizeof(opts)); mg_mgr_init(&mgr); - mg_tls_ctx_init(&mgr, &opts); ok = 0; c = mg_http_connect(&mgr, url, f3, &ok); ASSERT(c != NULL); + opts.ca = mg_unpacked("test/data/ca.pem"); + mg_tls_init(c, &opts); for (i = 0; i < 1500 && ok <= 0; i++) mg_mgr_poll(&mgr, 10); ASSERT(ok == 200); c->is_closing = 1; @@ -1734,12 +1748,43 @@ static void test_timer(void) { mg_timer_free(&head, &t3); ASSERT(head == NULL); + // Start a timer, then shift system time a long time back and long time forth + v1 = 0; + mg_timer_init(&head, &t1, 5, MG_TIMER_REPEAT, f1, &v1); + mg_timer_poll(&head, 0); + ASSERT(v1 == 0); + + // Shift a long time forth, make sure it ticks + mg_timer_poll(&head, 100); + ASSERT(v1 == 1); + mg_timer_poll(&head, 101); + ASSERT(v1 == 1); + mg_timer_poll(&head, 102); + ASSERT(v1 == 1); + mg_timer_poll(&head, 103); + ASSERT(v1 == 1); + mg_timer_poll(&head, 104); + ASSERT(v1 == 1); + mg_timer_poll(&head, 105); + ASSERT(v1 == 2); + + // Shift a long time back, make sure it ticks + mg_timer_poll(&head, 50); + ASSERT(v1 == 2); + mg_timer_poll(&head, 60); + ASSERT(v1 == 3); + + mg_timer_free(&head, &t1); + ASSERT(head == NULL); + // Test proper timer deallocation, see #1539 { struct mg_mgr mgr; mg_mgr_init(&mgr); mg_timer_add(&mgr, 1, MG_TIMER_REPEAT, f1, NULL); + ASSERT(mgr.timers != NULL); mg_mgr_free(&mgr); + ASSERT(mgr.timers == NULL); ASSERT(mgr.conns == NULL); } } @@ -3162,10 +3207,10 @@ int main(void) { test_commalist(); test_base64(); test_http_get_var(); + test_http_client(); test_tls(); test_ws(); test_ws_fragmentation(); - test_http_client(); test_host_validation(); test_http_server(); test_http_404();