LCOV - code coverage report
Current view: top level - src/tds - net.c (source / functions) Hit Total Coverage
Test: FreeTDS coverage Lines: 334 465 71.8 %
Date: 2025-01-18 11:50:39 Functions: 22 23 95.7 %

          Line data    Source code
       1             : /* FreeTDS - Library of routines accessing Sybase and Microsoft databases
       2             :  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003  Brian Bruns
       3             :  * Copyright (C) 2004-2015  Ziglio Frediano
       4             :  *
       5             :  * This library is free software; you can redistribute it and/or
       6             :  * modify it under the terms of the GNU Library General Public
       7             :  * License as published by the Free Software Foundation; either
       8             :  * version 2 of the License, or (at your option) any later version.
       9             :  *
      10             :  * This library is distributed in the hope that it will be useful,
      11             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      12             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      13             :  * Library General Public License for more details.
      14             :  *
      15             :  * You should have received a copy of the GNU Library General Public
      16             :  * License along with this library; if not, write to the
      17             :  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
      18             :  * Boston, MA 02111-1307, USA.
      19             :  */
      20             : 
      21             : #include <config.h>
      22             : 
      23             : #include <stdarg.h>
      24             : #include <stdio.h>
      25             : 
      26             : #include <freetds/time.h>
      27             : 
      28             : #if HAVE_SYS_TYPES_H
      29             : #include <sys/types.h>
      30             : #endif /* HAVE_SYS_TYPES_H */
      31             : 
      32             : #if HAVE_ERRNO_H
      33             : #include <errno.h>
      34             : #endif /* HAVE_ERRNO_H */
      35             : 
      36             : #if HAVE_UNISTD_H
      37             : #include <unistd.h>
      38             : #endif /* HAVE_UNISTD_H */
      39             : 
      40             : #if HAVE_STDLIB_H
      41             : #include <stdlib.h>
      42             : #endif /* HAVE_STDLIB_H */
      43             : 
      44             : #if HAVE_STRING_H
      45             : #include <string.h>
      46             : #endif /* HAVE_STRING_H */
      47             : 
      48             : #if HAVE_SYS_SOCKET_H
      49             : #include <sys/socket.h>
      50             : #endif /* HAVE_SYS_SOCKET_H */
      51             : 
      52             : #if HAVE_NETINET_IN_H
      53             : #include <netinet/in.h>
      54             : #endif /* HAVE_NETINET_IN_H */
      55             : 
      56             : #if HAVE_NETINET_TCP_H
      57             : #include <netinet/tcp.h>
      58             : #endif /* HAVE_NETINET_TCP_H */
      59             : 
      60             : #if HAVE_ARPA_INET_H
      61             : #include <arpa/inet.h>
      62             : #endif /* HAVE_ARPA_INET_H */
      63             : 
      64             : #if HAVE_SYS_IOCTL_H
      65             : #include <sys/ioctl.h>
      66             : #endif /* HAVE_SYS_IOCTL_H */
      67             : 
      68             : #if HAVE_SELECT_H
      69             : #include <sys/select.h>
      70             : #endif /* HAVE_SELECT_H */
      71             : 
      72             : #if HAVE_FCNTL_H
      73             : #include <fcntl.h>
      74             : #endif /* HAVE_FCNTL_H */
      75             : 
      76             : #ifdef HAVE_SYS_EVENTFD_H
      77             : #include <sys/eventfd.h>
      78             : #endif /* HAVE_SYS_EVENTFD_H */
      79             : 
      80             : #ifdef _WIN32
      81             : #include <winsock2.h>
      82             : #include <ws2tcpip.h>
      83             : #include <mstcpip.h>
      84             : #endif
      85             : 
      86             : #include <freetds/tds.h>
      87             : #include <freetds/utils/string.h>
      88             : #include <freetds/utils/nosigpipe.h>
      89             : #include <freetds/tls.h>
      90             : #include <freetds/replacements.h>
      91             : 
      92             : #include <signal.h>
      93             : #include <assert.h>
      94             : 
      95             : /* error is always returned */
      96             : #define TDSSELERR   0
      97             : #define TDSPOLLURG 0x8000u
      98             : 
      99             : #if ENABLE_ODBC_MARS
     100             : static void tds_check_cancel(TDSCONNECTION *conn);
     101             : #endif
     102             : 
     103             : 
     104             : /**
     105             :  * \addtogroup network
     106             :  * @{ 
     107             :  */
     108             : 
     109             : #if !defined(SOL_TCP) && (defined(IPPROTO_TCP) || defined(_WIN32))
     110             : /* fix incompatibility between MS headers */
     111             : # ifndef IPPROTO_TCP
     112             : #  define IPPROTO_TCP IPPROTO_TCP
     113             : # endif
     114             : # define SOL_TCP IPPROTO_TCP
     115             : #endif
     116             : 
     117             : /* Optimize the way we send packets */
     118             : #undef USE_CORK
     119             : #undef USE_NODELAY
     120             : /* On early Linux use TCP_CORK if available */
     121             : #if defined(__linux__) && defined(TCP_CORK)
     122             : #define USE_CORK 1
     123             : /* On *BSD try to use TCP_CORK */
     124             : /*
     125             :  * NOPUSH flag do not behave in the same way
     126             :  * cf ML "FreeBSD 5.0 performance problems with TCP_NOPUSH"
     127             :  */
     128             : #elif (defined(__FreeBSD__) || defined(__GNU_FreeBSD__) || defined(__OpenBSD__)) && defined(TCP_CORK)
     129             : #define USE_CORK 1
     130             : /* otherwise use NODELAY */
     131             : #elif defined(TCP_NODELAY) && defined(SOL_TCP)
     132             : #define USE_NODELAY 1
     133             : /* under VMS we have to define TCP_NODELAY */
     134             : #elif defined(__VMS)
     135             : #define TCP_NODELAY 1
     136             : #define USE_NODELAY 1
     137             : #endif
     138             : 
     139             : /**
     140             :  * Set socket to non-blocking
     141             :  * @param sock socket to set
     142             :  * @return 0 on success or error code
     143             :  */
     144             : int
     145        3659 : tds_socket_set_nonblocking(TDS_SYS_SOCKET sock)
     146             : {
     147             : #if !defined(_WIN32)
     148        3659 :         unsigned int ioctl_nonblocking = 1;
     149             : #else
     150             :         u_long ioctl_nonblocking = 1;
     151             : #endif
     152             : 
     153        3659 :         if (IOCTLSOCKET(sock, FIONBIO, &ioctl_nonblocking) >= 0)
     154             :                 return 0;
     155           0 :         return sock_errno;
     156             : }
     157             : 
     158             : static void
     159        2933 : tds_addrinfo_set_port(struct addrinfo *addr, unsigned int port)
     160             : {
     161        2933 :         assert(addr != NULL);
     162             : 
     163        2933 :         switch(addr->ai_family) {
     164        2933 :         case AF_INET:
     165        2933 :                 ((struct sockaddr_in *) addr->ai_addr)->sin_port = htons(port);
     166        2933 :                 break;
     167             : 
     168             : #ifdef AF_INET6
     169           0 :         case AF_INET6:
     170           0 :                 ((struct sockaddr_in6 *) addr->ai_addr)->sin6_port = htons(port);
     171           0 :                 break;
     172             : #endif
     173             :         }
     174        2933 : }
     175             : 
     176             : const char*
     177        2933 : tds_addrinfo2str(struct addrinfo *addr, char *name, int namemax)
     178             : {
     179             : #ifndef NI_NUMERICHOST
     180             : #define NI_NUMERICHOST 0
     181             : #endif
     182        2933 :         if (!name || namemax <= 0)
     183             :                 return "";
     184        2933 :         if (getnameinfo(addr->ai_addr, addr->ai_addrlen, name, namemax, NULL, 0, NI_NUMERICHOST) == 0)
     185             :                 return name;
     186           0 :         name[0] = 0;
     187           0 :         return name;
     188             : }
     189             : 
     190             : /**
     191             :  * Returns error stored in the socket
     192             :  */
     193             : static int
     194        2931 : tds_get_socket_error(TDS_SYS_SOCKET sock)
     195             : {
     196             :         int err;
     197        2931 :         SOCKLEN_T optlen = sizeof(err);
     198             :         char *errstr;
     199             : 
     200             :         /* check socket error */
     201        2931 :         if (tds_getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *) &err, &optlen) != 0) {
     202           0 :                 err = sock_errno;
     203           0 :                 errstr = sock_strerror(err);
     204           0 :                 tdsdump_log(TDS_DBG_ERROR, "getsockopt(2) failed: %s\n", errstr);
     205             :                 sock_strerror_free(errstr);
     206        2931 :         } else if (err != 0) {
     207           0 :                 errstr = sock_strerror(err);
     208           0 :                 tdsdump_log(TDS_DBG_ERROR, "getsockopt(2) reported: %s\n", errstr);
     209             :                 sock_strerror_free(errstr);
     210             :         }
     211        2931 :         return err;
     212             : }
     213             : 
     214             : /**
     215             :  * Setup the socket and attempt a connection.
     216             :  * Function allocate the socket in *p_sock and try to start a connection.
     217             :  * @param p_sock where returned socket is stored. Socket is stored even on error.
     218             :  *        Can be INVALID_SOCKET.
     219             :  * @param addr address to use for attempting the connection
     220             :  * @param port port to connect to
     221             :  * @param p_oserr where system error is returned
     222             :  * @returns TDSEOK is success, TDSEINPROGRESS if connection attempt is started
     223             :  *          or any other error.
     224             :  */
     225             : static TDSERRNO
     226        2931 : tds_setup_socket(TDS_SYS_SOCKET *p_sock, struct addrinfo *addr, unsigned int port, int *p_oserr)
     227             : {
     228             :         enum {
     229             :                 TDS_SOCKET_KEEPALIVE_IDLE = 40,
     230             :                 TDS_SOCKET_KEEPALIVE_INTERVAL = 2
     231             :         };
     232             :         TDS_SYS_SOCKET sock;
     233             :         char ipaddr[128];
     234             :         int retval, len, err;
     235             :         char *errstr;
     236             : #if defined(_WIN32)
     237             :         struct tcp_keepalive keepalive = {
     238             :                 TRUE,
     239             :                 TDS_SOCKET_KEEPALIVE_IDLE * 1000,
     240             :                 TDS_SOCKET_KEEPALIVE_INTERVAL * 1000
     241             :         };
     242             :         DWORD written;
     243             : #endif
     244             : 
     245        2931 :         *p_oserr = 0;
     246             : 
     247        2931 :         tds_addrinfo_set_port(addr, port);
     248        2931 :         tds_addrinfo2str(addr, ipaddr, sizeof(ipaddr));
     249             : 
     250        2931 :         *p_sock = sock = socket(addr->ai_family, SOCK_STREAM, 0);
     251        2931 :         if (TDS_IS_SOCKET_INVALID(sock)) {
     252           0 :                 errstr = sock_strerror(*p_oserr = sock_errno);
     253           0 :                 tdsdump_log(TDS_DBG_ERROR, "socket creation error: %s\n", errstr);
     254             :                 sock_strerror_free(errstr);
     255             :                 return TDSESOCK;
     256             :         }
     257             : 
     258             : #ifdef SO_KEEPALIVE
     259        2931 :         len = 1;
     260        2931 :         setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (const void *) &len, sizeof(len));
     261             : #endif
     262             : 
     263             : #if defined(_WIN32)
     264             :         if (WSAIoctl(sock, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive),
     265             :                      NULL, 0, &written, NULL, NULL) != 0) {
     266             :                 errstr = sock_strerror(*p_oserr = sock_errno);
     267             :                 tdsdump_log(TDS_DBG_ERROR, "error setting keepalive: %s\n", errstr);
     268             :                 sock_strerror_free(errstr);
     269             :         }
     270             : #elif defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
     271        2931 :         len = TDS_SOCKET_KEEPALIVE_IDLE;
     272        2931 :         setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, (const void *) &len, sizeof(len));
     273        2931 :         len = TDS_SOCKET_KEEPALIVE_INTERVAL;
     274        2931 :         setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, (const void *) &len, sizeof(len));
     275             : #endif
     276             : 
     277             : #if defined(SO_NOSIGPIPE)
     278             :         len = 1;
     279             :         if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (const void *) &len, sizeof(len))) {
     280             :                 *p_oserr = sock_errno;
     281             :                 return TDSESOCK;
     282             :         }
     283             : #endif
     284             : 
     285        2931 :         len = 1;
     286             : #if defined(USE_NODELAY)
     287             :         setsockopt(sock, SOL_TCP, TCP_NODELAY, (const void *) &len, sizeof(len));
     288             : #elif defined(USE_CORK)
     289        2931 :         setsockopt(sock, SOL_TCP, TCP_NODELAY, (const void *) &len, sizeof(len));
     290        2931 :         setsockopt(sock, SOL_TCP, TCP_CORK, (const void *) &len, sizeof(len));
     291             : #else
     292             : #error One should be defined
     293             : #endif
     294             : 
     295        2931 :         tdsdump_log(TDS_DBG_INFO1, "Connecting to %s port %d\n", ipaddr, port);
     296             : 
     297             : #ifdef  DOS32X                  /* the other connection doesn't work  on WATTCP32 */
     298             :         if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
     299             :                 *p_oserr = sock_errno;
     300             :                 tdsdump_log(TDS_DBG_ERROR, "tds_setup_socket(): %s:%d", ipaddr, port);
     301             :                 return TDSECONN;
     302             :         }
     303             :         return TDSEOK;
     304             : #else
     305        2931 :         if ((*p_oserr = tds_socket_set_nonblocking(sock)) != 0) {
     306             :                 return TDSEUSCT;        /* close enough: "Unable to set communications timer" */
     307             :         }
     308        2931 :         retval = connect(sock, addr->ai_addr, addr->ai_addrlen);
     309        2931 :         if (retval == 0) {
     310           0 :                 tdsdump_log(TDS_DBG_INFO2, "connection established\n");
     311             :                 return TDSEOK;
     312             :         }
     313             : 
     314             :         /* got some kind of error */
     315        2931 :         err = *p_oserr = sock_errno;
     316        2931 :         errstr = sock_strerror(err);
     317        2931 :         tdsdump_log(TDS_DBG_ERROR, "tds_setup_socket: connect(2) returned \"%s\"\n", errstr);
     318             :         sock_strerror_free(errstr);
     319             : 
     320             :         /* connection attempt started */
     321        2931 :         if (err == TDSSOCK_EINPROGRESS)
     322             :                 return TDSEINPROGRESS;
     323             : 
     324             : #if DEBUGGING_CONNECTING_PROBLEM
     325             :         if (err != ECONNREFUSED && err != ENETUNREACH) {
     326             :                 tdsdump_dump_buf(TDS_DBG_ERROR, "Contents of sockaddr_in", addr->ai_addr, addr->ai_addrlen);
     327             :                 tdsdump_log(TDS_DBG_ERROR,      " sockaddr_in:\t"
     328             :                                                       "%s = %x\n" 
     329             :                                                 "\t\t\t%s = %x\n" 
     330             :                                                 "\t\t\t%s = %s\n"
     331             :                                                 , "sin_family", addr->ai_family
     332             :                                                 , "port", port
     333             :                                                 , "address", ipaddr
     334             :                                                 );
     335             :         }
     336             : #endif
     337           0 :         return TDSECONN;
     338             : #endif  /* not DOS32X */
     339             : }
     340             : 
     341             : typedef struct {
     342             :         struct addrinfo *addr;
     343             :         unsigned next_retry_time;
     344             :         unsigned retry_count;
     345             : } retry_addr;
     346             : 
     347             : TDSERRNO
     348        2931 : tds_open_socket(TDSSOCKET *tds, struct addrinfo *addr, unsigned int port, int timeout, int *p_oserr)
     349             : {
     350        2931 :         TDSCONNECTION *conn = tds->conn;
     351             :         size_t len, i;
     352             :         int oserr;
     353             :         TDSERRNO tds_error;
     354             :         struct addrinfo *curr_addr;
     355             :         struct pollfd *fds;
     356             :         retry_addr *addresses;
     357             :         unsigned curr_time, start_time;
     358             :         typedef struct {
     359             :                 retry_addr retry;
     360             :                 struct pollfd fd;
     361             :         } alloc_addr;
     362             :         enum { MAX_RETRY = 10 };
     363             : 
     364        2931 :         *p_oserr = 0;
     365             : 
     366        2931 :         if (!addr)
     367             :                 return TDSECONN;
     368             : 
     369        2935 :         tdsdump_log(TDS_DBG_INFO1, "Connecting with protocol version %d.%d\n",
     370           4 :                     TDS_MAJOR(conn), TDS_MINOR(conn));
     371             : 
     372        5862 :         for (len = 0, curr_addr = addr; curr_addr != NULL; curr_addr = curr_addr->ai_next)
     373        2931 :                 ++len;
     374             : 
     375        2931 :         addresses = (retry_addr *) tds_new0(alloc_addr, len);
     376        2931 :         if (!addresses)
     377             :                 return TDSEMEM;
     378        2931 :         fds = (struct pollfd *) &addresses[len];
     379             : 
     380        2931 :         tds_error = TDSECONN;
     381             : 
     382             :         /* fill all structures */
     383        2931 :         curr_time = start_time = tds_gettime_ms();
     384        5862 :         for (len = 0, curr_addr = addr; curr_addr != NULL; curr_addr = curr_addr->ai_next) {
     385        2931 :                 fds[len].fd = INVALID_SOCKET;
     386        2931 :                 addresses[len].addr = curr_addr;
     387        2931 :                 addresses[len].next_retry_time = curr_time;
     388        2931 :                 addresses[len].retry_count = 0;
     389        2931 :                 ++len;
     390             :         }
     391             : 
     392             :         /* if we have only one address means that availability groups feature is not
     393             :          * present, avoid to check the addresses multiple times */
     394        2931 :         if (len == 1)
     395        2931 :                 addresses[0].retry_count = MAX_RETRY;
     396             : 
     397        2931 :         timeout *= 1000;
     398        2931 :         if (!timeout) {
     399             :                 /* A timeout of zero means wait forever */
     400           0 :                 timeout = -1;
     401             :         }
     402             : 
     403             :         /* now the list is full with sockets trying to connect */
     404        2931 :         while (len) {
     405        2931 :                 int rc, poll_timeout = timeout;
     406             : 
     407             :                 /* timeout */
     408        2931 :                 if (poll_timeout >= 0) {
     409        2931 :                         if (curr_time - start_time > (unsigned) poll_timeout) {
     410           0 :                                 *p_oserr = TDSSOCK_ETIMEDOUT;
     411             :                                 goto exit;
     412             :                         }
     413        2931 :                         poll_timeout -= curr_time - start_time;
     414             :                 }
     415             : 
     416             :                 /* try again if needed */
     417        2931 :                 for (i = 0; i < len; ++i) {
     418             :                         int time_left;
     419             : 
     420        2931 :                         if (!TDS_IS_SOCKET_INVALID(fds[i].fd))
     421           0 :                                 continue;
     422        2931 :                         time_left = addresses[i].next_retry_time - curr_time;
     423        2931 :                         if (time_left <= 0) {
     424             :                                 TDS_SYS_SOCKET sock;
     425        2931 :                                 tds_error = tds_setup_socket(&sock, addresses[i].addr, port, p_oserr);
     426        2931 :                                 switch (tds_error) {
     427           0 :                                 case TDSEOK:
     428             :                                         /* connected! */
     429             :                                         /* free other sockets and continue with this one */
     430           0 :                                         conn->s = sock;
     431           0 :                                         tds_error = TDSEOK;
     432           0 :                                         goto exit;
     433        2931 :                                 case TDSEINPROGRESS:
     434             :                                         /* save socket in the list */
     435        2931 :                                         fds[i].fd = sock;
     436             :                                         break;
     437           0 :                                 default:
     438             :                                         /* error, continue with other addresses */
     439           0 :                                         if (!TDS_IS_SOCKET_INVALID(sock))
     440           0 :                                                 CLOSESOCKET(sock);
     441           0 :                                         --len;
     442           0 :                                         fds[i] = fds[len];
     443           0 :                                         addresses[i] = addresses[len];
     444           0 :                                         --i;
     445           0 :                                         continue;
     446             :                                 }
     447             :                         } else {
     448             :                                 /* update timeout */
     449           0 :                                 if (time_left < poll_timeout || poll_timeout < 0)
     450           0 :                                         poll_timeout = time_left;
     451             :                         }
     452             :                 }
     453             : 
     454             :                 /* wait activities on file descriptors */
     455        2931 :                 for (i = 0; i < len; ++i) {
     456        2931 :                         fds[i].revents = 0;
     457        2931 :                         fds[i].events = TDSSELWRITE|TDSSELERR;
     458             :                 }
     459        2931 :                 tds_error = TDSECONN;
     460        2931 :                 rc = poll(fds, len, poll_timeout);
     461        2931 :                 oserr = sock_errno; /* save to avoid overrides */
     462        2931 :                 curr_time = tds_gettime_ms();
     463             : 
     464             :                 /* error */
     465        2931 :                 if (rc < 0) {
     466           0 :                         *p_oserr = oserr;
     467           0 :                         if (*p_oserr == TDSSOCK_EINTR)
     468           0 :                                 continue;
     469             :                         goto exit;
     470             :                 }
     471             : 
     472             :                 /* got some event on file descriptors */
     473           0 :                 for (i = 0; i < len; ++i) {
     474        2931 :                         if (TDS_IS_SOCKET_INVALID(fds[i].fd))
     475           0 :                                 continue;
     476        2931 :                         if (!fds[i].revents)
     477           0 :                                 continue;
     478        2931 :                         *p_oserr = tds_get_socket_error(fds[i].fd);
     479        2931 :                         if (*p_oserr || (fds[i].revents & POLLERR) != 0) {
     480             :                                 /* error, remove from list and possibly make
     481             :                                  * the loop exit */
     482           0 :                                 CLOSESOCKET(fds[i].fd);
     483           0 :                                 fds[i].fd = INVALID_SOCKET;
     484           0 :                                 addresses[i].next_retry_time = curr_time + 1000;
     485           0 :                                 if (++addresses[i].retry_count >= MAX_RETRY || len == 1) {
     486           0 :                                         --len;
     487           0 :                                         fds[i] = fds[len];
     488           0 :                                         addresses[i] = addresses[len];
     489           0 :                                         --i;
     490             :                                 }
     491           0 :                                 continue;
     492             :                         }
     493        2931 :                         if (fds[i].revents & POLLOUT) {
     494        2931 :                                 conn->s = fds[i].fd;
     495        2931 :                                 fds[i].fd = INVALID_SOCKET;
     496        2931 :                                 tds_error = TDSEOK;
     497             :                                 goto exit;
     498             :                         }
     499             :                 }
     500             :         }
     501             : 
     502           0 : exit:
     503             :         if (tds_error != TDSEOK) {
     504           0 :                 tdsdump_log(TDS_DBG_ERROR, "tds_open_socket() failed\n");
     505             :         } else {
     506        2931 :                 tdsdump_log(TDS_DBG_INFO2, "tds_open_socket() succeeded\n");
     507        2931 :                 tds->state = TDS_IDLE;
     508             :         }
     509             : 
     510        5862 :         while (len > 0) {
     511        2931 :                 --len;
     512        2931 :                 if (!TDS_IS_SOCKET_INVALID(fds[len].fd))
     513           0 :                         CLOSESOCKET(fds[len].fd);
     514             :         }
     515        2931 :         free(addresses);
     516        2931 :         return tds_error;
     517             : }
     518             : 
     519             : /**
     520             :  * Close current socket.
     521             :  * For last socket close entire connection.
     522             :  * For MARS send FIN request.
     523             :  * This attempts a graceful disconnection, for ungraceful call
     524             :  * tds_connection_close.
     525             :  */
     526             : void
     527        4058 : tds_close_socket(TDSSOCKET * tds)
     528             : {
     529        4058 :         if (!IS_TDSDEAD(tds)) {
     530             : #if ENABLE_ODBC_MARS
     531        1428 :                 TDSCONNECTION *conn = tds->conn;
     532        1428 :                 unsigned n = 0, count = 0;
     533        1428 :                 tds_mutex_lock(&conn->list_mtx);
     534       92820 :                 for (; n < conn->num_sessions; ++n)
     535       91392 :                         if (TDSSOCKET_VALID(conn->sessions[n]))
     536        1428 :                                 ++count;
     537        1428 :                 if (count > 1)
     538           0 :                         tds_append_fin(tds);
     539        1428 :                 tds_mutex_unlock(&conn->list_mtx);
     540        1428 :                 if (count <= 1) {
     541        1428 :                         tds_disconnect(tds);
     542        1428 :                         tds_connection_close(conn);
     543             :                 } else {
     544           0 :                         tds_set_state(tds, TDS_DEAD);
     545             :                 }
     546             : #else
     547        1427 :                 tds_disconnect(tds);
     548        1427 :                 if (!TDS_IS_SOCKET_INVALID(tds_get_s(tds)) && CLOSESOCKET(tds_get_s(tds)) == -1)
     549           0 :                         tdserror(tds_get_ctx(tds), tds,  TDSECLOS, sock_errno);
     550        1427 :                 tds_set_s(tds, INVALID_SOCKET);
     551        1427 :                 tds_set_state(tds, TDS_DEAD);
     552             : #endif
     553             :         }
     554        4058 : }
     555             : 
     556             : void
     557        5405 : tds_connection_close(TDSCONNECTION *conn)
     558             : {
     559             : #if ENABLE_ODBC_MARS
     560        3474 :         unsigned n = 0;
     561             : #endif
     562             : 
     563        5405 :         if (!TDS_IS_SOCKET_INVALID(conn->s)) {
     564             :                 /* TODO check error ?? how to return it ?? */
     565        2325 :                 CLOSESOCKET(conn->s);
     566        2325 :                 conn->s = INVALID_SOCKET;
     567             :         }
     568             : 
     569             : #if ENABLE_ODBC_MARS
     570        3474 :         tds_mutex_lock(&conn->list_mtx);
     571      225810 :         for (; n < conn->num_sessions; ++n)
     572      222336 :                 if (TDSSOCKET_VALID(conn->sessions[n]))
     573        1553 :                         tds_set_state(conn->sessions[n], TDS_DEAD);
     574        3474 :         tds_mutex_unlock(&conn->list_mtx);
     575             : #else
     576        1931 :         tds_set_state((TDSSOCKET* ) conn, TDS_DEAD);
     577             : #endif
     578        5405 : }
     579             : 
     580             : /**
     581             :  * Select on a socket until it's available or the timeout expires. 
     582             :  * Meanwhile, call the interrupt function. 
     583             :  * \return      >0 ready descriptors
     584             :  *               0 timeout 
     585             :  *              <0 error (cf. errno).  Caller should  close socket and return failure. 
     586             :  * This function does not call tdserror or close the socket because it can't know the context in which it's being called.   
     587             :  */
     588             : int
     589      299671 : tds_select(TDSSOCKET * tds, unsigned tds_sel, int timeout_seconds)
     590             : {
     591             :         int rc, seconds;
     592             :         unsigned int poll_seconds;
     593             : 
     594      299671 :         assert(tds != NULL);
     595      299671 :         assert(timeout_seconds >= 0);
     596             : 
     597             :         /* 
     598             :          * The select loop.  
     599             :          * If an interrupt handler is installed, we iterate once per second, 
     600             :          *      else we try once, timing out after timeout_seconds (0 == never). 
     601             :          * If select(2) is interrupted by a signal (e.g. press ^C in sqsh), we timeout.
     602             :          *      (The application can retry if desired by installing a signal handler.)
     603             :          *
     604             :          * We do not measure current time against end time, to avoid being tricked by ntpd(8) or similar. 
     605             :          * Instead, we just count down.  
     606             :          *
     607             :          * We exit on the first of these events:
     608             :          * 1.  a descriptor is ready. (return to caller)
     609             :          * 2.  select(2) returns an important error.  (return to caller)
     610             :          * A timeout of zero says "wait forever".  We do that by passing a NULL timeval pointer to select(2). 
     611             :          */
     612      299671 :         poll_seconds = (tds_get_ctx(tds) && tds_get_ctx(tds)->int_handler)? 1 : timeout_seconds;
     613      300119 :         for (seconds = timeout_seconds; timeout_seconds == 0 || seconds > 0; seconds -= poll_seconds) {
     614             :                 struct pollfd fds[2];
     615      299871 :                 int timeout = poll_seconds ? poll_seconds * 1000 : -1;
     616             : 
     617      299871 :                 if (TDS_IS_SOCKET_INVALID(tds_get_s(tds)))
     618      299423 :                         return -1;
     619             : 
     620      376066 :                 if ((tds_sel & TDSSELREAD) != 0 && tds->conn->tls_session && tds_ssl_pending(tds->conn))
     621             :                         return POLLIN;
     622             : 
     623      285866 :                 fds[0].fd = tds_get_s(tds);
     624      285866 :                 fds[0].events = tds_sel;
     625      285866 :                 fds[0].revents = 0;
     626      285866 :                 fds[1].fd = tds_wakeup_get_fd(&tds->conn->wakeup);
     627      285866 :                 fds[1].events = POLLIN;
     628      285866 :                 fds[1].revents = 0;
     629      285866 :                 rc = poll(fds, 2, timeout);
     630             : 
     631      285866 :                 if (rc > 0 ) {
     632      285418 :                         if (fds[0].revents & POLLERR) {
     633           4 :                                 set_sock_errno(TDSSOCK_ECONNRESET);
     634           4 :                                 return -1;
     635             :                         }
     636      285414 :                         rc = fds[0].revents;
     637      285414 :                         if (fds[1].revents) {
     638             : #if ENABLE_ODBC_MARS
     639          98 :                                 tds_check_cancel(tds->conn);
     640             : #endif
     641         224 :                                 rc |= TDSPOLLURG;
     642             :                         }
     643             :                         return rc;
     644             :                 }
     645             : 
     646         448 :                 if (rc < 0) {
     647             :                         char *errstr;
     648             : 
     649          16 :                         switch (sock_errno) {
     650          16 :                         case TDSSOCK_EINTR:
     651             :                         case EAGAIN:
     652             :                         case TDSSOCK_EINPROGRESS:
     653             :                                 /* FIXME this should be global maximun, not loop one */
     654          16 :                                 seconds += poll_seconds;
     655          16 :                                 break;  /* let interrupt handler be called */
     656           0 :                         default: /* documented: EFAULT, EBADF, EINVAL */
     657           0 :                                 errstr = sock_strerror(sock_errno);
     658           0 :                                 tdsdump_log(TDS_DBG_ERROR, "error: poll(2) returned %d, \"%s\"\n",
     659             :                                                 sock_errno, errstr);
     660             :                                 sock_strerror_free(errstr);
     661             :                                 return rc;
     662             :                         }
     663         432 :                 }
     664             : 
     665         448 :                 assert(rc == 0 || (rc < 0 && (sock_errno == TDSSOCK_EINTR ||
     666             :                                               sock_errno == EAGAIN ||
     667             :                                               sock_errno == TDSSOCK_EINPROGRESS
     668             :                                               )));
     669             : 
     670         448 :                 if (tds_get_ctx(tds) && tds_get_ctx(tds)->int_handler) {     /* interrupt handler installed */
     671             :                         /*
     672             :                          * "If hndlintr() returns INT_CANCEL, DB-Library sends an attention token [TDS_BUFSTAT_ATTN]
     673             :                          * to the server. This causes the server to discontinue command processing. 
     674             :                          * The server may send additional results that have already been computed. 
     675             :                          * When control returns to the mainline code, the mainline code should do 
     676             :                          * one of the following: 
     677             :                          * - Flush the results using dbcancel 
     678             :                          * - Process the results normally"
     679             :                          */
     680         264 :                         int timeout_action = (*tds_get_ctx(tds)->int_handler) (tds_get_parent(tds));
     681         264 :                         switch (timeout_action) {
     682         264 :                         case TDS_INT_CONTINUE:          /* keep waiting */
     683         264 :                                 continue;
     684             :                         case TDS_INT_CANCEL:            /* abort the current command batch */
     685             :                                                         /* FIXME tell tds_goodread() not to call tdserror() */
     686             :                                 return 0;
     687           0 :                         default:
     688           0 :                                 tdsdump_log(TDS_DBG_NETWORK, 
     689             :                                         "tds_select: invalid interrupt handler return code: %d\n", timeout_action);
     690             :                                 return -1;
     691             :                         }
     692             :                 }
     693             :                 /* 
     694             :                  * We can reach here if no interrupt handler was installed and we either timed out or got EINTR. 
     695             :                  * We cannot be polling, so we are about to drop out of the loop. 
     696             :                  */
     697         184 :                 assert(poll_seconds == timeout_seconds);
     698             :         }
     699             :         
     700             :         return 0;
     701             : }
     702             : 
     703             : /**
     704             :  * Read from an OS socket
     705             :  * @TODO remove tds, save error somewhere, report error in another way
     706             :  * @returns 0 if blocking, <0 error >0 bytes read
     707             :  */
     708             : static int
     709      178372 : tds_socket_read(TDSCONNECTION * conn, TDSSOCKET *tds, unsigned char *buf, int buflen)
     710             : {
     711             :         int len, err;
     712             : 
     713             : #if ENABLE_EXTRA_CHECKS
     714             :         /* this simulate the fact that recv can return less bytes */
     715      178372 :         if (buflen >= 5) {
     716             :                 static int cnt = 0;
     717      154170 :                 if (++cnt == 5) {
     718       30184 :                         cnt = 0;
     719       30184 :                         buflen -= 3;
     720             :                 }
     721             :         }
     722             : #endif
     723             : 
     724             :         /* read directly from socket*/
     725      178372 :         len = READSOCKET(conn->s, buf, buflen);
     726      178372 :         if (len > 0)
     727             :                 return len;
     728             : 
     729          18 :         err = sock_errno;
     730          18 :         if (len < 0 && TDSSOCK_WOULDBLOCK(err))
     731             :                 return 0;
     732             : 
     733             :         /* detect connection close */
     734          18 :         tds_connection_close(conn);
     735          18 :         tdserror(conn->tds_ctx, tds, len == 0 ? TDSESEOF : TDSEREAD, len == 0 ? 0 : err);
     736          18 :         return -1;
     737             : }
     738             : 
     739             : /**
     740             :  * Write to an OS socket
     741             :  * @returns 0 if blocking, <0 error >0 bytes readed
     742             :  */
     743             : static int
     744       88165 : tds_socket_write(TDSCONNECTION *conn, TDSSOCKET *tds, const unsigned char *buf, int buflen)
     745             : {
     746             :         int err, len;
     747             :         char *errstr;
     748             : 
     749             : #if ENABLE_EXTRA_CHECKS
     750             :         /* this simulate the fact that send can return less bytes */
     751       88165 :         if (buflen >= 11) {
     752             :                 static int cnt = 0;
     753       72321 :                 if (++cnt == 5) {
     754       13838 :                         cnt = 0;
     755       13838 :                         buflen -= 3;
     756             :                 }
     757             :         }
     758             : #endif
     759             : 
     760             : #if defined(SO_NOSIGPIPE)
     761             :         len = send(conn->s, buf, buflen, 0);
     762             : #else
     763       88165 :         len = WRITESOCKET(conn->s, buf, buflen);
     764             : #endif
     765       88165 :         if (len > 0)
     766             :                 return len;
     767             : 
     768          60 :         err = sock_errno;
     769          60 :         if (0 == len || TDSSOCK_WOULDBLOCK(err) || err == TDSSOCK_EINTR)
     770             :                 return 0;
     771             : 
     772          60 :         assert(len < 0);
     773             : 
     774             :         /* detect connection close */
     775          60 :         errstr = sock_strerror(err);
     776          60 :         tdsdump_log(TDS_DBG_NETWORK, "send(2) failed: %d (%s)\n", err, errstr);
     777             :         sock_strerror_free(errstr);
     778          60 :         tds_connection_close(conn);
     779          60 :         tdserror(conn->tds_ctx, tds, TDSEWRIT, err);
     780          60 :         return -1;
     781             : }
     782             : 
     783             : int
     784        3829 : tds_wakeup_init(TDSPOLLWAKEUP *wakeup)
     785             : {
     786             :         TDS_SYS_SOCKET sv[2];
     787             :         int ret;
     788             : 
     789        3829 :         wakeup->s_signal = wakeup->s_signaled = INVALID_SOCKET;
     790             : #if defined(__linux__) && HAVE_EVENTFD
     791             : #  ifdef EFD_CLOEXEC
     792        3829 :         ret = eventfd(0, EFD_CLOEXEC|EFD_NONBLOCK);
     793             : #  else
     794             :         ret = -1;
     795             : #  endif
     796             :         /* Linux version up to 2.6.26 do not support flags, try without */
     797        3829 :         if (ret < 0 && (ret = eventfd(0, 0)) >= 0) {
     798           0 :                 fcntl(ret, F_SETFD, fcntl(ret, F_GETFD, 0) | FD_CLOEXEC);
     799           0 :                 fcntl(ret, F_SETFL, fcntl(ret, F_GETFL, 0) | O_NONBLOCK);
     800             :         }
     801        3829 :         if (ret >= 0) {
     802        3829 :                 wakeup->s_signaled = ret;
     803        3829 :                 return 0;
     804             :         }
     805             : #endif
     806           0 :         ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
     807           0 :         if (ret)
     808             :                 return ret;
     809           0 :         wakeup->s_signal   = sv[0];
     810           0 :         wakeup->s_signaled = sv[1];
     811           0 :         return 0;
     812             : }
     813             : 
     814             : void
     815        3805 : tds_wakeup_close(TDSPOLLWAKEUP *wakeup)
     816             : {
     817        3805 :         if (!TDS_IS_SOCKET_INVALID(wakeup->s_signal))
     818           0 :                 CLOSESOCKET(wakeup->s_signal);
     819        3805 :         if (!TDS_IS_SOCKET_INVALID(wakeup->s_signaled))
     820        3805 :                 CLOSESOCKET(wakeup->s_signaled);
     821        3805 : }
     822             : 
     823             : 
     824             : void
     825         226 : tds_wakeup_send(TDSPOLLWAKEUP *wakeup, char cancel)
     826             : {
     827             : #if defined(__linux__) && HAVE_EVENTFD
     828         226 :         if (wakeup->s_signal == -1) {
     829         226 :                 uint64_t one = 1;
     830         226 :                 (void) write(wakeup->s_signaled, &one, sizeof(one));
     831             :                 return;
     832             :         }
     833             : #endif
     834           0 :         send(wakeup->s_signal, &cancel, sizeof(cancel), 0);
     835             : }
     836             : 
     837             : static int
     838         223 : tds_connection_signaled(TDSCONNECTION *conn)
     839             : {
     840             :         int len;
     841             :         char to_cancel[16];
     842             : 
     843             : #if defined(__linux__) && HAVE_EVENTFD
     844         223 :         if (conn->wakeup.s_signal == -1)
     845         223 :                 return read(conn->wakeup.s_signaled, to_cancel, 8) > 0;
     846             : #endif
     847             : 
     848           0 :         len = READSOCKET(conn->wakeup.s_signaled, to_cancel, sizeof(to_cancel));
     849             :         do {
     850             :                 /* no cancel found */
     851           0 :                 if (len <= 0)
     852             :                         return 0;
     853           0 :         } while(!to_cancel[--len]);
     854             :         return 1;
     855             : }
     856             : 
     857             : #if ENABLE_ODBC_MARS
     858             : static void
     859          98 : tds_check_cancel(TDSCONNECTION *conn)
     860             : {
     861             :         TDSSOCKET *tds;
     862             :         int rc;
     863             : 
     864          98 :         if (!tds_connection_signaled(conn))
     865             :                 return;
     866             : 
     867             :         do {
     868          98 :                 unsigned n = 0;
     869             : 
     870          98 :                 rc = TDS_SUCCESS;
     871          98 :                 tds_mutex_lock(&conn->list_mtx);
     872             :                 /* Here we scan all list searching for sessions that should send cancel packets */
     873        6370 :                 for (; n < conn->num_sessions; ++n)
     874        6272 :                         if (TDSSOCKET_VALID(tds=conn->sessions[n]) && tds->in_cancel == 1) {
     875             :                                 /* send cancel */
     876          98 :                                 tds->in_cancel = 2;
     877          98 :                                 tds_mutex_unlock(&conn->list_mtx);
     878          98 :                                 rc = tds_append_cancel(tds);
     879          98 :                                 tds_mutex_lock(&conn->list_mtx);
     880          98 :                                 if (rc != TDS_SUCCESS)
     881             :                                         break;
     882             :                         }
     883          98 :                 tds_mutex_unlock(&conn->list_mtx);
     884             :                 /* for all failed */
     885             :                 /* this must be done outside loop cause it can alter list */
     886             :                 /* this must be done unlocked cause it can lock again */
     887          98 :                 if (rc != TDS_SUCCESS)
     888           0 :                         tds_close_socket(tds);
     889          98 :         } while(rc != TDS_SUCCESS);
     890             : }
     891             : #endif
     892             : 
     893             : /**
     894             :  * Loops until we have received some characters
     895             :  * return -1 on failure
     896             :  */
     897             : int
     898      107945 : tds_goodread(TDSSOCKET * tds, unsigned char *buf, int buflen)
     899             : {
     900      107945 :         if (tds == NULL || buf == NULL || buflen < 1)
     901             :                 return -1;
     902             : 
     903             :         for (;;) {
     904             :                 int len, err;
     905             : 
     906             :                 /* FIXME this block writing from other sessions */
     907      108174 :                 len = tds_select(tds, TDSSELREAD, tds->query_timeout);
     908             : #if !ENABLE_ODBC_MARS
     909       86232 :                 if (len > 0 && (len & TDSPOLLURG)) {
     910         125 :                         tds_connection_signaled(tds->conn);
     911             :                         /* send cancel */
     912         125 :                         if (tds->in_cancel == 1)
     913         105 :                                 tds_put_cancel(tds);
     914         125 :                         continue;
     915             :                 }
     916             : #endif
     917      108049 :                 if (len > 0) {
     918      107923 :                         len = tds_socket_read(tds->conn, tds, buf, buflen);
     919      107923 :                         if (len == 0)
     920           0 :                                 continue;
     921             :                         return len;
     922             :                 }
     923             : 
     924             :                 /* error */
     925         126 :                 if (len < 0) {
     926           2 :                         if (TDSSOCK_WOULDBLOCK(sock_errno)) /* shouldn't happen, but OK */
     927           0 :                                 continue;
     928           2 :                         err = sock_errno;
     929           2 :                         tds_connection_close(tds->conn);
     930           2 :                         tdserror(tds_get_ctx(tds), tds, TDSEREAD, err);
     931           2 :                         return -1;
     932             :                 }
     933             : 
     934             :                 /* timeout */
     935         124 :                 switch (tdserror(tds_get_ctx(tds), tds, TDSETIME, sock_errno)) {
     936             :                 case TDS_INT_CONTINUE:
     937             :                         break;
     938          20 :                 default:
     939             :                 case TDS_INT_CANCEL:
     940          20 :                         tds_close_socket(tds);
     941          20 :                         return -1;
     942             :                 }
     943             :         }
     944             : }
     945             : 
     946             : int
     947      176016 : tds_connection_read(TDSSOCKET * tds, unsigned char *buf, int buflen)
     948             : {
     949      176016 :         TDSCONNECTION *conn = tds->conn;
     950             : 
     951      176016 :         if (conn->tls_session)
     952       41105 :                 return tds_ssl_read(conn, buf, buflen);
     953             : 
     954             : #if ENABLE_ODBC_MARS
     955       70449 :         return tds_socket_read(conn, tds, buf, buflen);
     956             : #else
     957       64462 :         return tds_goodread(tds, buf, buflen);
     958             : #endif
     959             : }
     960             : 
     961             : /**
     962             :  * \param tds the famous socket
     963             :  * \param buffer data to send
     964             :  * \param buflen bytes in buffer
     965             :  * \param last 1 if this is the last packet, else 0
     966             :  * \return length written (>0), <0 on failure
     967             :  */
     968             : int
     969       46442 : tds_goodwrite(TDSSOCKET * tds, const unsigned char *buffer, size_t buflen)
     970             : {
     971             :         int len;
     972       46442 :         size_t sent = 0;
     973             : 
     974       46442 :         assert(tds && buffer);
     975             : 
     976      101600 :         while (sent < buflen) {
     977             :                 /* TODO if send buffer is full we block receive !!! */
     978       55200 :                 len = tds_select(tds, TDSSELWRITE, tds->query_timeout);
     979             : 
     980       55200 :                 if (len > 0) {
     981       55192 :                         len = tds_socket_write(tds->conn, tds, buffer + sent, buflen - sent);
     982       55192 :                         if (len == 0)
     983           0 :                                 continue;
     984       55192 :                         if (len < 0)
     985             :                                 return len;
     986             : 
     987       55158 :                         sent += len;
     988       55158 :                         continue;
     989             :                 }
     990             : 
     991             :                 /* error */
     992           8 :                 if (len < 0) {
     993           8 :                         int err = sock_errno;
     994             :                         char *errstr;
     995             : 
     996           8 :                         if (TDSSOCK_WOULDBLOCK(err)) /* shouldn't happen, but OK, retry */
     997           0 :                                 continue;
     998           8 :                         errstr = sock_strerror(err);
     999           8 :                         tdsdump_log(TDS_DBG_NETWORK, "select(2) failed: %d (%s)\n", err, errstr);
    1000             :                         sock_strerror_free(errstr);
    1001           8 :                         tds_connection_close(tds->conn);
    1002           8 :                         tdserror(tds_get_ctx(tds), tds, TDSEWRIT, err);
    1003           8 :                         return -1;
    1004             :                 }
    1005             : 
    1006             :                 /* timeout */
    1007           0 :                 tdsdump_log(TDS_DBG_NETWORK, "tds_goodwrite(): timed out, asking client\n");
    1008           0 :                 switch (tdserror(tds_get_ctx(tds), tds, TDSETIME, sock_errno)) {
    1009             :                 case TDS_INT_CONTINUE:
    1010             :                         break;
    1011           0 :                 default:
    1012             :                 case TDS_INT_CANCEL:
    1013           0 :                         tds_close_socket(tds);
    1014           0 :                         return -1;
    1015             :                 }
    1016             :         }
    1017             : 
    1018       46400 :         return (int) sent;
    1019             : }
    1020             : 
    1021             : void
    1022      103474 : tds_socket_flush(TDS_SYS_SOCKET sock TDS_UNUSED)
    1023             : {
    1024             : #ifdef USE_CORK
    1025             :         int opt;
    1026      103474 :         opt = 0;
    1027      103474 :         setsockopt(sock, SOL_TCP, TCP_CORK, (const void *) &opt, sizeof(opt));
    1028      103474 :         opt = 1;
    1029      103474 :         setsockopt(sock, SOL_TCP, TCP_CORK, (const void *) &opt, sizeof(opt));
    1030             : #endif
    1031      103474 : }
    1032             : 
    1033             : int
    1034       79415 : tds_connection_write(TDSSOCKET *tds, const unsigned char *buf, int buflen, int final)
    1035             : {
    1036             :         int sent;
    1037       79415 :         TDSCONNECTION *conn = tds->conn;
    1038             : 
    1039             : #if !defined(_WIN32) && !defined(MSG_NOSIGNAL) && !defined(DOS32X) && !defined(SO_NOSIGPIPE)
    1040             :         void (*oldsig) (int);
    1041             : 
    1042             :         oldsig = signal(SIGPIPE, SIG_IGN);
    1043             :         if (oldsig == SIG_ERR) {
    1044             :                 tdsdump_log(TDS_DBG_WARN, "TDS: Warning: Couldn't set SIGPIPE signal to be ignored\n");
    1045             :         }
    1046             : #endif
    1047             : 
    1048       79415 :         if (conn->tls_session)
    1049       18635 :                 sent = tds_ssl_write(conn, buf, buflen);
    1050             :         else
    1051             : #if ENABLE_ODBC_MARS
    1052       32973 :                 sent = tds_socket_write(conn, tds, buf, buflen);
    1053             : #else
    1054       27807 :                 sent = tds_goodwrite(tds, buf, buflen);
    1055             : #endif
    1056             : 
    1057             :         /* force packet flush */
    1058       79415 :         if (final && sent >= buflen)
    1059       71255 :                 tds_socket_flush(tds_get_s(tds));
    1060             : 
    1061             : #if !defined(_WIN32) && !defined(MSG_NOSIGNAL) && !defined(DOS32X) && !defined(SO_NOSIGPIPE)
    1062             :         if (signal(SIGPIPE, oldsig) == SIG_ERR) {
    1063             :                 tdsdump_log(TDS_DBG_WARN, "TDS: Warning: Couldn't reset SIGPIPE signal to previous value\n");
    1064             :         }
    1065             : #endif
    1066       79415 :         return sent;
    1067             : }
    1068             : 
    1069             : /**
    1070             :  * Get port of all instances
    1071             :  * @return default port number or 0 if error
    1072             :  * @remark experimental, cf. MC-SQLR.pdf.
    1073             :  */
    1074             : int
    1075           0 : tds7_get_instance_ports(FILE *output, struct addrinfo *addr)
    1076             : {
    1077             :         int num_try;
    1078             :         struct pollfd fd;
    1079             :         int retval;
    1080             :         TDS_SYS_SOCKET s;
    1081             :         char msg[16*1024];
    1082           0 :         int msg_len = 0;
    1083           0 :         int port = 0;
    1084             :         char ipaddr[128];
    1085             : 
    1086             : 
    1087           0 :         tds_addrinfo_set_port(addr, 1434);
    1088           0 :         tds_addrinfo2str(addr, ipaddr, sizeof(ipaddr));
    1089             : 
    1090           0 :         tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_ports(%s)\n", ipaddr);
    1091             : 
    1092             :         /* create an UDP socket */
    1093           0 :         if (TDS_IS_SOCKET_INVALID(s = socket(addr->ai_family, SOCK_DGRAM, 0))) {
    1094           0 :                 char *errstr = sock_strerror(sock_errno);
    1095           0 :                 tdsdump_log(TDS_DBG_ERROR, "socket creation error: %s\n", errstr);
    1096             :                 sock_strerror_free(errstr);
    1097             :                 return 0;
    1098             :         }
    1099             : 
    1100             :         /*
    1101             :          * on cluster environment is possible that reply packet came from
    1102             :          * different IP so do not filter by ip with connect
    1103             :          */
    1104             : 
    1105           0 :         if (tds_socket_set_nonblocking(s) != 0) {
    1106           0 :                 CLOSESOCKET(s);
    1107           0 :                 return 0;
    1108             :         }
    1109             : 
    1110             :         /* 
    1111             :          * Request the instance's port from the server.  
    1112             :          * There is no easy way to detect if port is closed so we always try to
    1113             :          * get a reply from server 16 times. 
    1114             :          */
    1115           0 :         for (num_try = 0; num_try < 16 && msg_len == 0; ++num_try) {
    1116             :                 /* send the request */
    1117           0 :                 msg[0] = 3;
    1118           0 :                 if (sendto(s, msg, 1, 0, addr->ai_addr, addr->ai_addrlen) < 0)
    1119             :                         break;
    1120             : 
    1121           0 :                 fd.fd = s;
    1122           0 :                 fd.events = POLLIN;
    1123           0 :                 fd.revents = 0;
    1124             : 
    1125           0 :                 retval = poll(&fd, 1, 1000);
    1126             :                 
    1127             :                 /* on interrupt ignore */
    1128           0 :                 if (retval < 0 && sock_errno == TDSSOCK_EINTR)
    1129           0 :                         continue;
    1130             :                 
    1131           0 :                 if (retval == 0) { /* timed out */
    1132             : #if 1
    1133           0 :                         tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_port: timed out on try %d of 16\n", num_try);
    1134           0 :                         continue;
    1135             : #else
    1136             :                         int rc;
    1137             :                         tdsdump_log(TDS_DBG_INFO1, "timed out\n");
    1138             : 
    1139             :                         switch(rc = tdserror(NULL, NULL, TDSETIME, 0)) {
    1140             :                         case TDS_INT_CONTINUE:
    1141             :                                 continue;       /* try again */
    1142             : 
    1143             :                         default:
    1144             :                                 tdsdump_log(TDS_DBG_ERROR, "error: client error handler returned %d\n", rc);
    1145             :                         case TDS_INT_CANCEL: 
    1146             :                                 CLOSESOCKET(s);
    1147             :                                 return 0;
    1148             :                         }
    1149             : #endif
    1150             :                 }
    1151           0 :                 if (retval < 0)
    1152             :                         break;
    1153             : 
    1154             :                 /* got data, read and parse */
    1155           0 :                 if ((msg_len = recv(s, msg, sizeof(msg) - 1, 0)) > 3 && msg[0] == 5) {
    1156           0 :                         char *name, sep[2] = ";", *save;
    1157             : 
    1158             :                         /* assure null terminated */
    1159           0 :                         msg[msg_len] = 0;
    1160           0 :                         tdsdump_dump_buf(TDS_DBG_INFO1, "instance info", msg, msg_len);
    1161             :                         
    1162             :                         if (0) {        /* To debug, print the whole string. */
    1163             :                                 char *p;
    1164             : 
    1165             :                                 for (*sep = '\n', p=msg+3; p < msg + msg_len; p++) {
    1166             :                                         if( *p == ';' )
    1167             :                                                 *p = *sep;
    1168             :                                 }
    1169             :                                 fputs(msg + 3, output);
    1170             :                         }
    1171             : 
    1172             :                         /*
    1173             :                          * Parse and print message.
    1174             :                          */
    1175           0 :                         name = strtok_r(msg+3, sep, &save);
    1176           0 :                         while (name && output) {
    1177             :                                 int i;
    1178             :                                 static const char *const names[] = { "ServerName", "InstanceName", "IsClustered", "Version",
    1179             :                                                                "tcp", "np", "via" };
    1180             : 
    1181           0 :                                 for (i=0; name && i < TDS_VECTOR_SIZE(names); i++) {
    1182           0 :                                         const char *value = strtok_r(NULL, sep, &save);
    1183             :                                         
    1184           0 :                                         if (strcmp(name, names[i]) != 0)
    1185           0 :                                                 fprintf(output, "error: expecting '%s', found '%s'\n", names[i], name);
    1186           0 :                                         if (value) 
    1187           0 :                                                 fprintf(output, "%15s %s\n", name, value);
    1188             :                                         else 
    1189             :                                                 break;
    1190             : 
    1191           0 :                                         name = strtok_r(NULL, sep, &save);
    1192             : 
    1193           0 :                                         if (name && strcmp(name, names[0]) == 0)
    1194             :                                                 break;
    1195             :                                 }
    1196           0 :                                 if (name) 
    1197           0 :                                         fprintf(output, "\n");
    1198             :                         }
    1199             :                 }
    1200             :         }
    1201           0 :         CLOSESOCKET(s);
    1202           0 :         tdsdump_log(TDS_DBG_ERROR, "default instance port is %d\n", port);
    1203             :         return port;
    1204             : }
    1205             : 
    1206             : /**
    1207             :  * Get port of given instance
    1208             :  * @return port number or 0 if error
    1209             :  */
    1210             : int
    1211           2 : tds7_get_instance_port(struct addrinfo *addr, const char *instance)
    1212             : {
    1213             :         int num_try;
    1214             :         struct pollfd fd;
    1215             :         int retval;
    1216             :         TDS_SYS_SOCKET s;
    1217             :         char msg[1024];
    1218             :         int msg_len;
    1219           2 :         int port = 0;
    1220             :         char ipaddr[128];
    1221             : 
    1222           2 :         tds_addrinfo_set_port(addr, 1434);
    1223           2 :         tds_addrinfo2str(addr, ipaddr, sizeof(ipaddr));
    1224             : 
    1225           2 :         tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_port(%s, %s)\n", ipaddr, instance);
    1226             : 
    1227             :         /* create an UDP socket */
    1228           2 :         if (TDS_IS_SOCKET_INVALID(s = socket(addr->ai_family, SOCK_DGRAM, 0))) {
    1229           0 :                 char *errstr = sock_strerror(sock_errno);
    1230           0 :                 tdsdump_log(TDS_DBG_ERROR, "socket creation error: %s\n", errstr);
    1231             :                 sock_strerror_free(errstr);
    1232             :                 return 0;
    1233             :         }
    1234             : 
    1235             :         /*
    1236             :          * on cluster environment is possible that reply packet came from
    1237             :          * different IP so do not filter by ip with connect
    1238             :          */
    1239             : 
    1240           2 :         if (tds_socket_set_nonblocking(s) != 0) {
    1241           0 :                 CLOSESOCKET(s);
    1242           0 :                 return 0;
    1243             :         }
    1244             : 
    1245             :         /* 
    1246             :          * Request the instance's port from the server.  
    1247             :          * There is no easy way to detect if port is closed so we always try to
    1248             :          * get a reply from server 16 times. 
    1249             :          */
    1250           0 :         for (num_try = 0; num_try < 16; ++num_try) {
    1251             :                 /* send the request */
    1252           2 :                 msg[0] = 4;
    1253           2 :                 strlcpy(msg + 1, instance, sizeof(msg) - 1);
    1254           2 :                 if (sendto(s, msg, (int)strlen(msg) + 1, 0, addr->ai_addr, addr->ai_addrlen) < 0)
    1255             :                         break;
    1256             : 
    1257           2 :                 fd.fd = s;
    1258           2 :                 fd.events = POLLIN;
    1259           2 :                 fd.revents = 0;
    1260             : 
    1261           2 :                 retval = poll(&fd, 1, 1000);
    1262             :                 
    1263             :                 /* on interrupt ignore */
    1264           2 :                 if (retval < 0 && sock_errno == TDSSOCK_EINTR)
    1265           0 :                         continue;
    1266             :                 
    1267           2 :                 if (retval == 0) { /* timed out */
    1268             : #if 1
    1269           0 :                         tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_port: timed out on try %d of 16\n", num_try);
    1270           0 :                         continue;
    1271             : #else
    1272             :                         int rc;
    1273             :                         tdsdump_log(TDS_DBG_INFO1, "timed out\n");
    1274             : 
    1275             :                         switch(rc = tdserror(NULL, NULL, TDSETIME, 0)) {
    1276             :                         case TDS_INT_CONTINUE:
    1277             :                                 continue;       /* try again */
    1278             : 
    1279             :                         default:
    1280             :                                 tdsdump_log(TDS_DBG_ERROR, "error: client error handler returned %d\n", rc);
    1281             :                         case TDS_INT_CANCEL: 
    1282             :                                 CLOSESOCKET(s);
    1283             :                                 return 0;
    1284             :                         }
    1285             : #endif
    1286             :                 }
    1287           2 :                 if (retval < 0)
    1288             :                         break;
    1289             : 
    1290             :                 /* TODO pass also connection and set instance/servername ?? */
    1291             : 
    1292             :                 /* got data, read and parse */
    1293           2 :                 if ((msg_len = recv(s, msg, sizeof(msg) - 1, 0)) > 3 && msg[0] == 5) {
    1294             :                         char *p;
    1295           2 :                         long l = 0;
    1296           2 :                         int instance_ok = 0, port_ok = 0;
    1297             : 
    1298             :                         /* assure null terminated */
    1299           2 :                         msg[msg_len] = 0;
    1300           2 :                         tdsdump_dump_buf(TDS_DBG_INFO1, "instance info", msg, msg_len);
    1301             : 
    1302             :                         /*
    1303             :                          * Parse message and check instance name and port.
    1304             :                          * We don't check servername cause it can be very different from the client's. 
    1305             :                          */
    1306           2 :                         for (p = msg + 3;;) {
    1307             :                                 char *name, *value;
    1308             : 
    1309          12 :                                 name = p;
    1310          12 :                                 p = strchr(p, ';');
    1311          12 :                                 if (!p)
    1312             :                                         break;
    1313          10 :                                 *p++ = 0;
    1314             : 
    1315          10 :                                 value = name;
    1316          10 :                                 if (*name) {
    1317          10 :                                         value = p;
    1318          10 :                                         p = strchr(p, ';');
    1319          10 :                                         if (!p)
    1320             :                                                 break;
    1321          10 :                                         *p++ = 0;
    1322             :                                 }
    1323             : 
    1324          10 :                                 if (strcasecmp(name, "InstanceName") == 0) {
    1325           2 :                                         if (strcasecmp(value, instance) != 0)
    1326             :                                                 break;
    1327             :                                         instance_ok = 1;
    1328           8 :                                 } else if (strcasecmp(name, "tcp") == 0) {
    1329           2 :                                         l = strtol(value, &p, 10);
    1330           2 :                                         if (l > 0 && l <= 0xffff && *p == 0)
    1331           2 :                                                 port_ok = 1;
    1332             :                                 }
    1333             :                         }
    1334           2 :                         if (port_ok && instance_ok) {
    1335           2 :                                 port = l;
    1336           2 :                                 break;
    1337             :                         }
    1338             :                 }
    1339             :         }
    1340           2 :         CLOSESOCKET(s);
    1341           2 :         tdsdump_log(TDS_DBG_ERROR, "instance port is %d\n", port);
    1342             :         return port;
    1343             : }
    1344             : 
    1345             : #if defined(_WIN32)
    1346             : static const char tds_unknown_wsaerror[] = "undocumented WSA error code";
    1347             : 
    1348             : char *
    1349             : tds_prwsaerror(int erc)
    1350             : {
    1351             :         char *errstr = NULL;
    1352             :         FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, erc,
    1353             :                       MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (LPTSTR)&errstr, 0, NULL);
    1354             :         if (errstr) {
    1355             :                 size_t len = strlen(errstr);
    1356             :                 while (len > 0 && (errstr[len-1] == '\r' || errstr[len-1] == '\n'))
    1357             :                         errstr[len-1] = 0;
    1358             :                 return errstr;
    1359             :         }
    1360             :         return (char*) tds_unknown_wsaerror;
    1361             : }
    1362             : 
    1363             : void
    1364             : tds_prwsaerror_free(char *s)
    1365             : {
    1366             :         if (s != tds_unknown_wsaerror)
    1367             :                 LocalFree((HLOCAL) s);
    1368             : }
    1369             : #endif
    1370             : 
    1371             : /** @} */
    1372             : 

Generated by: LCOV version 1.13