Make the s_server command listen on IPv6 only when requested
authorBernd Edlinger <bernd.edlinger@hotmail.de>
Tue, 23 Jan 2018 16:43:45 +0000 (17:43 +0100)
committerBernd Edlinger <bernd.edlinger@hotmail.de>
Thu, 25 Jan 2018 14:21:31 +0000 (15:21 +0100)
Reviewed-by: Rich Salz <rsalz@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/5152)

(cherry picked from commit eee8a40aa5e06841eed6fa8eb4f6109238d59aea)

apps/s_socket.c

index e8fc37f97ccacb4c7605fe195a380fd59e45d8bc..ee7e4ebc280c62b26d1f99ce4303a277dd370d93 100644 (file)
@@ -136,6 +136,10 @@ int do_server(int *accept_sock, const char *host, const char *port,
     int sock;
     int i;
     BIO_ADDRINFO *res = NULL;
+    const BIO_ADDRINFO *next;
+    int sock_family, sock_type, sock_protocol;
+    const BIO_ADDR *sock_address;
+    int sock_options = BIO_SOCK_REUSEADDR;
     int ret = 0;
 
     if (!BIO_sock_init())
@@ -151,10 +155,27 @@ int do_server(int *accept_sock, const char *host, const char *port,
     OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))
                    && (type == 0 || type == BIO_ADDRINFO_socktype(res)));
 
-    asock = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res),
-                       BIO_ADDRINFO_protocol(res), 0);
+    sock_family = BIO_ADDRINFO_family(res);
+    sock_type = BIO_ADDRINFO_socktype(res);
+    sock_protocol = BIO_ADDRINFO_protocol(res);
+    sock_address = BIO_ADDRINFO_address(res);
+    next = BIO_ADDRINFO_next(res);
+    if(sock_family == AF_INET6)
+        sock_options |= BIO_SOCK_V6_ONLY;
+    if (next != NULL
+        && BIO_ADDRINFO_socktype(next) == sock_type
+        && BIO_ADDRINFO_protocol(next) == sock_protocol) {
+        if (sock_family == AF_INET && BIO_ADDRINFO_family(next) == AF_INET6) {
+            sock_family = AF_INET6;
+            sock_address = BIO_ADDRINFO_address(next);
+        }
+        else if (sock_family == AF_INET6 && BIO_ADDRINFO_family(next) == AF_INET)
+            sock_options &= ~BIO_SOCK_V6_ONLY;
+    }
+
+    asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
     if (asock == INVALID_SOCKET
-        || !BIO_listen(asock, BIO_ADDRINFO_address(res), BIO_SOCK_REUSEADDR)) {
+        || !BIO_listen(asock, sock_address, sock_options)) {
         BIO_ADDRINFO_free(res);
         ERR_print_errors(bio_err);
         if (asock != INVALID_SOCKET)