Close socket if TCP connecting fails to avoid leaking sockets
[runtime.git] / lib / silcutil / unix / silcunixnet.c
index 706af5c0421ae0236977f58100987542b19be2ae..2332672d4643d125180f7923315020246153c51c 100644 (file)
@@ -164,8 +164,8 @@ silc_net_tcp_create_listener(const char **local_ip_addr,
 
   /* Bind to local addresses */
   for (i = 0; i < local_ip_count; i++) {
-    SILC_LOG_DEBUG(("Binding to local address %s",
-                   local_ip_addr ? local_ip_addr[i] : ipany));
+    SILC_LOG_DEBUG(("Binding to local address %s:%d",
+                   local_ip_addr ? local_ip_addr[i] : ipany, port));
 
     /* Set sockaddr for server */
     if (!silc_net_set_sockaddr(&server,
@@ -363,8 +363,10 @@ int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
 
   if (remote_ip_addr && remote_port) {
     if (sock->ipv6) {
+#ifdef HAVE_IPV6
       from = (struct sockaddr *)&s.sin6;
       flen = sizeof(s.sin6);
+#endif /* HAVE_IPV6 */
     } else {
       from = (struct sockaddr *)&s.sin;
       flen = sizeof(s.sin);
@@ -395,9 +397,13 @@ int silc_net_udp_receive(SilcStream stream, char *remote_ip_addr,
   /* Return remote address */
   if (remote_ip_addr && remote_port) {
     if (sock->ipv6) {
+#ifdef HAVE_IPV6
       *remote_port = ntohs(s.sin6.sin6_port);
       inet_ntop(AF_INET6, &s.sin6.sin6_addr, remote_ip_addr,
                remote_ip_addr_size);
+#else
+      *remote_port = 0;
+#endif /* HAVE_IPV6 */
     } else {
       *remote_port = ntohs(s.sin.sin_port);
       inet_ntop(AF_INET, &s.sin.sin_addr, remote_ip_addr,
@@ -628,20 +634,20 @@ SILC_FSM_STATE(silc_net_connect_st_connected)
     }
 
 #if defined(ECONNREFUSED)
-    if (errno == ECONNREFUSED)
+    if (opt == ECONNREFUSED)
       conn->status = SILC_NET_CONNECTION_REFUSED;
 #endif /* ECONNREFUSED */
 #if defined(ETIMEDOUT)
-    if (errno == ETIMEDOUT)
+    if (opt == ETIMEDOUT)
       conn->status = SILC_NET_CONNECTION_TIMEOUT;
 #endif /* ETIMEDOUT */
 #if defined(ENETUNREACH)
-    if (errno == ENETUNREACH)
+    if (opt == ENETUNREACH)
       conn->status = SILC_NET_HOST_UNREACHABLE;
 #endif /* ENETUNREACH */
 
     /** Connecting failed */
-    SILC_LOG_DEBUG(("Connecting failed"));
+    SILC_LOG_DEBUG(("Connecting failed, error %s", strerror(opt)));
     silc_fsm_next(fsm, silc_net_connect_st_finish);
     return SILC_FSM_CONTINUE;
   }
@@ -695,6 +701,9 @@ SILC_FSM_STATE(silc_net_connect_st_finish)
       silc_async_free(conn->op);
   }
 
+  if (conn->sock && conn->status != SILC_NET_OK)
+    silc_net_close_connection(conn->sock);
+
   return SILC_FSM_FINISH;
 }