From c1ceab8f191031a81996035af20685e6f9b7f1b7 Mon Sep 17 00:00:00 2001
From: Guy Harris <gharris@sonic.net>
Date: Sun, 31 Jul 2022 11:54:22 -0700
Subject: [PATCH] rpcap: try to distringuish between host and port errors.

getaddrinfo() won't do it for us, so do it ourselves.

(cherry picked from commit a83992a1bec91661b2f0e1a6fc910343793a97f1)

Upstream-Status: Backport [https://github.com/the-tcpdump-group/libpcap/commit/c1ceab8f191031a81996035af20685e6f9b7f1b7]
CVE: CVE-2023-7256 #Dependency Patch3
Signed-off-by: Vijay Anusuri <vanusuri@mvista.com>
---
 sockutils.c | 40 ++++++++++++++++++++++++++++++++++++++--
 1 file changed, 38 insertions(+), 2 deletions(-)

diff --git a/sockutils.c b/sockutils.c
index ca5b683720..84024ac67d 100644
--- a/sockutils.c
+++ b/sockutils.c
@@ -734,8 +734,44 @@ int sock_initaddress(const char *host, const char *port,
 	{
 		if (errbuf)
 		{
-			get_gai_errstring(errbuf, errbuflen, "", retval,
-			    host, port);
+			if (host != NULL && port != NULL) {
+				/*
+				 * Try with just a host, to distinguish
+				 * between "host is bad" and "port is
+				 * bad".
+				 */
+				int try_retval;
+
+				try_retval = getaddrinfo(host, NULL, hints,
+				    addrinfo);
+				if (try_retval == 0) {
+					/*
+					 * Worked with just the host,
+					 * so assume the problem is
+					 * with the port.
+					 *
+					 * Free up the addres info first.
+					 */
+					freeaddrinfo(*addrinfo);
+					get_gai_errstring(errbuf, errbuflen,
+					    "", retval, NULL, port);
+				} else {
+					/*
+					 * Didn't work with just the host,
+					 * so assume the problem is
+					 * with the host.
+					 */
+					get_gai_errstring(errbuf, errbuflen,
+					    "", retval, host, NULL);
+				}
+			} else {
+				/*
+				 * Either the host or port was null, so
+				 * there's nothing to determine.
+				 */
+				get_gai_errstring(errbuf, errbuflen, "",
+				    retval, host, port);
+			}
 		}
 		return -1;
 	}
