From 49bbfaf130fa71ea886fba45908a4b488c854fb4 Mon Sep 17 00:00:00 2001
From: Deomid Ryabkov <rojer@cesanta.com>
Date: Fri, 21 Apr 2017 22:16:57 +0300
Subject: [PATCH] Fix mg_lwip_if_get_conn_addr when there's no pcb

Connection may not (yet) have a TCP or UDP PCB associated with it.
mg_lwip_if_get_conn_addr should not crash in this case.

PUBLISHED_FROM=fd0ed683b18b3f549135c9d79eeadfc7348ab05a
---
 mongoose.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/mongoose.c b/mongoose.c
index 3ad2d9e49..43f301300 100644
--- a/mongoose.c
+++ b/mongoose.c
@@ -14562,22 +14562,21 @@ void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
 void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
                               union socket_address *sa) {
   memset(sa, 0, sizeof(*sa));
-  if (nc->sock == INVALID_SOCKET) return;
+  if (nc == NULL || nc->sock == INVALID_SOCKET) return;
   struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
   if (nc->flags & MG_F_UDP) {
     struct udp_pcb *upcb = cs->pcb.udp;
     if (remote) {
       memcpy(sa, &nc->sa, sizeof(*sa));
-    } else {
+    } else if (upcb != NULL) {
       sa->sin.sin_port = htons(upcb->local_port);
       SET_ADDR(sa, &upcb->local_ip);
     }
   } else {
     struct tcp_pcb *tpcb = cs->pcb.tcp;
     if (remote) {
-      sa->sin.sin_port = htons(tpcb->remote_port);
-      SET_ADDR(sa, &tpcb->remote_ip);
-    } else {
+      memcpy(sa, &nc->sa, sizeof(*sa));
+    } else if (tpcb != NULL) {
       sa->sin.sin_port = htons(tpcb->local_port);
       SET_ADDR(sa, &tpcb->local_ip);
     }
-- 
GitLab