From 82014a5fa9930b0875e57869265acf011772277c Mon Sep 17 00:00:00 2001
From: Stijn Tintel <stijn@linux-ipv6.be>
Date: Sun, 3 May 2020 20:56:58 +0300
Subject: [PATCH] network: avoid segfault in freeaddrinfo

Calling freeaddrinfo(NULL) when using musl libc causes a segfault.

Signed-off-by: Stijn Tintel <stijn@linux-ipv6.be>
---
 anet.c     | 15 ++++++++++++---
 net_io.c   |  5 ++++-
 viewadsb.c |  5 ++++-
 3 files changed, 20 insertions(+), 5 deletions(-)

diff --git a/anet.c b/anet.c
index 5c35ff8..7f01958 100644
--- a/anet.c
+++ b/anet.c
@@ -212,7 +212,10 @@ static int anetTcpGenericConnect(char *err, char *addr, char *service, int flags
             if (ss) {
                 memcpy(ss, p->ai_addr, sizeof(*ss));
             }
-            freeaddrinfo(gai_result);
+            if (gai_result) {
+                freeaddrinfo(gai_result);
+                gai_result = NULL;
+            }
             return s;
         }
 
@@ -220,7 +223,10 @@ static int anetTcpGenericConnect(char *err, char *addr, char *service, int flags
         anetCloseSocket(s);
     }
 
-    freeaddrinfo(gai_result);
+    if (gai_result) {
+        freeaddrinfo(gai_result);
+        gai_result = NULL;
+    }
     return ANET_ERR;
 }
 
@@ -368,7 +374,10 @@ int anetTcpServer(char *err, char *service, char *bindaddr, int *fds, int nfds)
         fds[i++] = s;
     }
 
-    freeaddrinfo(gai_result);
+    if (gai_result) {
+        freeaddrinfo(gai_result);
+        gai_result = NULL;
+    }
     return (i > 0 ? i : ANET_ERR);
 }
 
diff --git a/net_io.c b/net_io.c
index 1f4d848..5f59194 100644
--- a/net_io.c
+++ b/net_io.c
@@ -3285,7 +3285,10 @@ void cleanupNetwork(void) {
     for (int i = 0; i < Modes.net_connectors_count; i++) {
         struct net_connector *con = Modes.net_connectors[i];
         free(con->address);
-        freeaddrinfo(con->addr_info);
+        if (con->addr_info) {
+            freeaddrinfo(con->addr_info);
+            con->addr_info = NULL;
+        }
         if (con->mutex) {
             pthread_mutex_unlock(con->mutex);
             pthread_mutex_destroy(con->mutex);
diff --git a/viewadsb.c b/viewadsb.c
index 5fc5386..ad7b1bd 100644
--- a/viewadsb.c
+++ b/viewadsb.c
@@ -308,7 +308,10 @@ int main(int argc, char **argv) {
     }
     // Free local service and client
     if (s) free(s);
-    freeaddrinfo(con->addr_info);
+    if (con->addr_info) {
+        freeaddrinfo(con->addr_info);
+        con->addr_info = NULL;
+    }
     pthread_mutex_unlock(con->mutex);
     pthread_mutex_destroy(con->mutex);
     free(con->mutex);
-- 
2.26.2

