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 4392 : tds_socket_set_nonblocking(TDS_SYS_SOCKET sock)
146 : {
147 : #if !defined(_WIN32)
148 4392 : unsigned int ioctl_nonblocking = 1;
149 : #else
150 : u_long ioctl_nonblocking = 1;
151 : #endif
152 :
153 4392 : if (IOCTLSOCKET(sock, FIONBIO, &ioctl_nonblocking) >= 0)
154 : return 0;
155 0 : return sock_errno;
156 : }
157 :
158 : static void
159 3664 : tds_addrinfo_set_port(struct addrinfo *addr, unsigned int port)
160 : {
161 3664 : assert(addr != NULL);
162 :
163 3664 : switch(addr->ai_family) {
164 3664 : case AF_INET:
165 3664 : ((struct sockaddr_in *) addr->ai_addr)->sin_port = htons(port);
166 3664 : 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 3664 : }
175 :
176 : const char*
177 3664 : tds_addrinfo2str(struct addrinfo *addr, char *name, int namemax)
178 : {
179 : #ifndef NI_NUMERICHOST
180 : #define NI_NUMERICHOST 0
181 : #endif
182 3664 : if (!name || namemax <= 0)
183 : return "";
184 3664 : 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 3662 : tds_get_socket_error(TDS_SYS_SOCKET sock)
195 : {
196 : int err;
197 3662 : SOCKLEN_T optlen = sizeof(err);
198 : char *errstr;
199 :
200 : /* check socket error */
201 3662 : 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 3662 : } 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 3662 : 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 3662 : 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 3662 : *p_oserr = 0;
246 :
247 3662 : tds_addrinfo_set_port(addr, port);
248 3662 : tds_addrinfo2str(addr, ipaddr, sizeof(ipaddr));
249 :
250 3662 : *p_sock = sock = socket(addr->ai_family, SOCK_STREAM, 0);
251 3662 : 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 3662 : len = 1;
260 3662 : 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 3662 : len = TDS_SOCKET_KEEPALIVE_IDLE;
272 3662 : setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, (const void *) &len, sizeof(len));
273 3662 : len = TDS_SOCKET_KEEPALIVE_INTERVAL;
274 3662 : 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 3662 : 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 3662 : setsockopt(sock, SOL_TCP, TCP_NODELAY, (const void *) &len, sizeof(len));
290 3662 : setsockopt(sock, SOL_TCP, TCP_CORK, (const void *) &len, sizeof(len));
291 : #else
292 : #error One should be defined
293 : #endif
294 :
295 3662 : 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 3662 : if ((*p_oserr = tds_socket_set_nonblocking(sock)) != 0) {
306 : return TDSEUSCT; /* close enough: "Unable to set communications timer" */
307 : }
308 3662 : retval = connect(sock, addr->ai_addr, addr->ai_addrlen);
309 3662 : 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 3662 : err = *p_oserr = sock_errno;
316 3662 : errstr = sock_strerror(err);
317 3662 : 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 3662 : 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 3662 : tds_open_socket(TDSSOCKET *tds, struct addrinfo *addr, unsigned int port, int timeout, int *p_oserr)
349 : {
350 3662 : 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 3662 : *p_oserr = 0;
365 :
366 3662 : if (!addr)
367 : return TDSECONN;
368 :
369 3666 : tdsdump_log(TDS_DBG_INFO1, "Connecting with protocol version %d.%d\n",
370 4 : TDS_MAJOR(conn), TDS_MINOR(conn));
371 :
372 7324 : for (len = 0, curr_addr = addr; curr_addr != NULL; curr_addr = curr_addr->ai_next)
373 3662 : ++len;
374 :
375 3662 : addresses = (retry_addr *) tds_new0(alloc_addr, len);
376 3662 : if (!addresses)
377 : return TDSEMEM;
378 3662 : fds = (struct pollfd *) &addresses[len];
379 :
380 3662 : tds_error = TDSECONN;
381 :
382 : /* fill all structures */
383 3662 : curr_time = start_time = tds_gettime_ms();
384 7324 : for (len = 0, curr_addr = addr; curr_addr != NULL; curr_addr = curr_addr->ai_next) {
385 3662 : fds[len].fd = INVALID_SOCKET;
386 3662 : addresses[len].addr = curr_addr;
387 3662 : addresses[len].next_retry_time = curr_time;
388 3662 : addresses[len].retry_count = 0;
389 3662 : ++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 3662 : if (len == 1)
395 3662 : addresses[0].retry_count = MAX_RETRY;
396 :
397 3662 : timeout *= 1000;
398 3662 : 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 3662 : while (len) {
405 3662 : int rc, poll_timeout = timeout;
406 :
407 : /* timeout */
408 3662 : if (poll_timeout >= 0) {
409 3662 : if (curr_time - start_time > (unsigned) poll_timeout) {
410 0 : *p_oserr = TDSSOCK_ETIMEDOUT;
411 : goto exit;
412 : }
413 3662 : poll_timeout -= curr_time - start_time;
414 : }
415 :
416 : /* try again if needed */
417 3662 : for (i = 0; i < len; ++i) {
418 : int time_left;
419 :
420 3662 : if (!TDS_IS_SOCKET_INVALID(fds[i].fd))
421 0 : continue;
422 3662 : time_left = addresses[i].next_retry_time - curr_time;
423 3662 : if (time_left <= 0) {
424 : TDS_SYS_SOCKET sock;
425 3662 : tds_error = tds_setup_socket(&sock, addresses[i].addr, port, p_oserr);
426 3662 : 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 3662 : case TDSEINPROGRESS:
434 : /* save socket in the list */
435 3662 : 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 3662 : for (i = 0; i < len; ++i) {
456 3662 : fds[i].revents = 0;
457 3662 : fds[i].events = TDSSELWRITE|TDSSELERR;
458 : }
459 3662 : tds_error = TDSECONN;
460 3662 : rc = poll(fds, len, poll_timeout);
461 3662 : oserr = sock_errno; /* save to avoid overrides */
462 3662 : curr_time = tds_gettime_ms();
463 :
464 : /* error */
465 3662 : 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 3662 : if (TDS_IS_SOCKET_INVALID(fds[i].fd))
475 0 : continue;
476 3662 : if (!fds[i].revents)
477 0 : continue;
478 3662 : *p_oserr = tds_get_socket_error(fds[i].fd);
479 3662 : 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 3662 : if (fds[i].revents & POLLOUT) {
494 3662 : conn->s = fds[i].fd;
495 3662 : fds[i].fd = INVALID_SOCKET;
496 3662 : 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 3662 : tdsdump_log(TDS_DBG_INFO2, "tds_open_socket() succeeded\n");
507 3662 : tds->state = TDS_IDLE;
508 : }
509 :
510 7324 : while (len > 0) {
511 3662 : --len;
512 3662 : if (!TDS_IS_SOCKET_INVALID(fds[len].fd))
513 0 : CLOSESOCKET(fds[len].fd);
514 : }
515 3662 : free(addresses);
516 3662 : 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 5082 : tds_close_socket(TDSSOCKET * tds)
528 : {
529 5082 : if (!IS_TDSDEAD(tds)) {
530 : #if ENABLE_ODBC_MARS
531 1784 : TDSCONNECTION *conn = tds->conn;
532 1784 : unsigned n = 0, count = 0;
533 1784 : tds_mutex_lock(&conn->list_mtx);
534 115960 : for (; n < conn->num_sessions; ++n)
535 114176 : if (TDSSOCKET_VALID(conn->sessions[n]))
536 1784 : ++count;
537 1784 : if (count > 1)
538 0 : tds_append_fin(tds);
539 1784 : tds_mutex_unlock(&conn->list_mtx);
540 1784 : if (count <= 1) {
541 1784 : tds_disconnect(tds);
542 1784 : tds_connection_close(conn);
543 : } else {
544 0 : tds_set_state(tds, TDS_DEAD);
545 : }
546 : #else
547 1784 : tds_disconnect(tds);
548 1784 : 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 1784 : tds_set_s(tds, INVALID_SOCKET);
551 1784 : tds_set_state(tds, TDS_DEAD);
552 : #endif
553 : }
554 5082 : }
555 :
556 : void
557 6574 : tds_connection_close(TDSCONNECTION *conn)
558 : {
559 : #if ENABLE_ODBC_MARS
560 4250 : unsigned n = 0;
561 : #endif
562 :
563 6574 : if (!TDS_IS_SOCKET_INVALID(conn->s)) {
564 : /* TODO check error ?? how to return it ?? */
565 2726 : CLOSESOCKET(conn->s);
566 2726 : conn->s = INVALID_SOCKET;
567 : }
568 :
569 : #if ENABLE_ODBC_MARS
570 4250 : tds_mutex_lock(&conn->list_mtx);
571 276250 : for (; n < conn->num_sessions; ++n)
572 272000 : if (TDSSOCKET_VALID(conn->sessions[n]))
573 1939 : tds_set_state(conn->sessions[n], TDS_DEAD);
574 4250 : tds_mutex_unlock(&conn->list_mtx);
575 : #else
576 2324 : tds_set_state((TDSSOCKET* ) conn, TDS_DEAD);
577 : #endif
578 6574 : }
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 404644 : tds_select(TDSSOCKET * tds, unsigned tds_sel, int timeout_seconds)
590 : {
591 : int rc, seconds;
592 : unsigned int poll_seconds;
593 :
594 404644 : assert(tds != NULL);
595 404644 : 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 404644 : poll_seconds = (tds_get_ctx(tds) && tds_get_ctx(tds)->int_handler)? 1 : timeout_seconds;
613 405201 : for (seconds = timeout_seconds; timeout_seconds == 0 || seconds > 0; seconds -= poll_seconds) {
614 : struct pollfd fds[2];
615 404895 : int timeout = poll_seconds ? poll_seconds * 1000 : -1;
616 :
617 404895 : if (TDS_IS_SOCKET_INVALID(tds_get_s(tds)))
618 404338 : return -1;
619 :
620 556291 : if ((tds_sel & TDSSELREAD) != 0 && tds->conn->tls_session && tds_ssl_pending(tds->conn))
621 : return POLLIN;
622 :
623 376898 : fds[0].fd = tds_get_s(tds);
624 376898 : fds[0].events = tds_sel;
625 376898 : fds[0].revents = 0;
626 376898 : fds[1].fd = tds_wakeup_get_fd(&tds->conn->wakeup);
627 376898 : fds[1].events = POLLIN;
628 376898 : fds[1].revents = 0;
629 376898 : rc = poll(fds, 2, timeout);
630 :
631 376898 : if (rc > 0 ) {
632 376341 : if (fds[0].revents & POLLERR) {
633 4 : set_sock_errno(TDSSOCK_ECONNRESET);
634 4 : return -1;
635 : }
636 376337 : rc = fds[0].revents;
637 376337 : if (fds[1].revents) {
638 : #if ENABLE_ODBC_MARS
639 120 : tds_check_cancel(tds->conn);
640 : #endif
641 277 : rc |= TDSPOLLURG;
642 : }
643 : return rc;
644 : }
645 :
646 557 : if (rc < 0) {
647 : char *errstr;
648 :
649 20 : switch (sock_errno) {
650 20 : case TDSSOCK_EINTR:
651 : case EAGAIN:
652 : case TDSSOCK_EINPROGRESS:
653 : /* FIXME this should be global maximun, not loop one */
654 20 : seconds += poll_seconds;
655 20 : 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 537 : }
664 :
665 557 : assert(rc == 0 || (rc < 0 && (sock_errno == TDSSOCK_EINTR ||
666 : sock_errno == EAGAIN ||
667 : sock_errno == TDSSOCK_EINPROGRESS
668 : )));
669 :
670 557 : 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 331 : int timeout_action = (*tds_get_ctx(tds)->int_handler) (tds_get_parent(tds));
681 331 : switch (timeout_action) {
682 331 : case TDS_INT_CONTINUE: /* keep waiting */
683 331 : 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 226 : 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 ptrdiff_t
709 227286 : tds_socket_read(TDSCONNECTION * conn, TDSSOCKET *tds, unsigned char *buf, size_t buflen)
710 : {
711 : ptrdiff_t len;
712 : int err;
713 :
714 : #if ENABLE_EXTRA_CHECKS
715 : /* this simulate the fact that recv can return less bytes */
716 227286 : if (buflen >= 5) {
717 : static int cnt = 0;
718 195362 : if (++cnt == 5) {
719 38263 : cnt = 0;
720 38263 : buflen -= 3;
721 : }
722 : }
723 : #endif
724 :
725 : /* read directly from socket*/
726 227286 : len = READSOCKET(conn->s, buf, buflen);
727 227286 : if (len > 0)
728 : return len;
729 :
730 22 : err = sock_errno;
731 22 : if (len < 0 && TDSSOCK_WOULDBLOCK(err))
732 : return 0;
733 :
734 : /* detect connection close */
735 22 : tds_connection_close(conn);
736 22 : tdserror(conn->tds_ctx, tds, len == 0 ? TDSESEOF : TDSEREAD, len == 0 ? 0 : err);
737 22 : return -1;
738 : }
739 :
740 : /**
741 : * Write to an OS socket
742 : * @returns 0 if blocking, <0 error >0 bytes readed
743 : */
744 : static ptrdiff_t
745 112151 : tds_socket_write(TDSCONNECTION *conn, TDSSOCKET *tds, const unsigned char *buf, size_t buflen)
746 : {
747 : int err;
748 : ptrdiff_t len;
749 : char *errstr;
750 :
751 : #if ENABLE_EXTRA_CHECKS
752 : /* this simulate the fact that send can return less bytes */
753 112151 : if (buflen >= 11) {
754 : static int cnt = 0;
755 92432 : if (++cnt == 5) {
756 17708 : cnt = 0;
757 17708 : buflen -= 3;
758 : }
759 : }
760 : #endif
761 :
762 : #if defined(SO_NOSIGPIPE)
763 : len = send(conn->s, buf, buflen, 0);
764 : #else
765 112151 : len = WRITESOCKET(conn->s, buf, buflen);
766 : #endif
767 112151 : if (len > 0)
768 : return len;
769 :
770 75 : err = sock_errno;
771 75 : if (0 == len || TDSSOCK_WOULDBLOCK(err) || err == TDSSOCK_EINTR)
772 : return 0;
773 :
774 75 : assert(len < 0);
775 :
776 : /* detect connection close */
777 75 : errstr = sock_strerror(err);
778 75 : tdsdump_log(TDS_DBG_NETWORK, "send(2) failed: %d (%s)\n", err, errstr);
779 : sock_strerror_free(errstr);
780 75 : tds_connection_close(conn);
781 75 : tdserror(conn->tds_ctx, tds, TDSEWRIT, err);
782 75 : return -1;
783 : }
784 :
785 : int
786 4607 : tds_wakeup_init(TDSPOLLWAKEUP *wakeup)
787 : {
788 : TDS_SYS_SOCKET sv[2];
789 : int ret;
790 :
791 4607 : wakeup->s_signal = wakeup->s_signaled = INVALID_SOCKET;
792 : #if defined(__linux__) && HAVE_EVENTFD
793 : # ifdef EFD_CLOEXEC
794 4607 : ret = eventfd(0, EFD_CLOEXEC|EFD_NONBLOCK);
795 : # else
796 : ret = -1;
797 : # endif
798 : /* Linux version up to 2.6.26 do not support flags, try without */
799 4607 : if (ret < 0 && (ret = eventfd(0, 0)) >= 0) {
800 0 : fcntl(ret, F_SETFD, fcntl(ret, F_GETFD, 0) | FD_CLOEXEC);
801 0 : fcntl(ret, F_SETFL, fcntl(ret, F_GETFL, 0) | O_NONBLOCK);
802 : }
803 4607 : if (ret >= 0) {
804 4607 : wakeup->s_signaled = ret;
805 4607 : return 0;
806 : }
807 : #endif
808 0 : ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
809 0 : if (ret)
810 : return ret;
811 0 : wakeup->s_signal = sv[0];
812 0 : wakeup->s_signaled = sv[1];
813 0 : return 0;
814 : }
815 :
816 : void
817 4577 : tds_wakeup_close(TDSPOLLWAKEUP *wakeup)
818 : {
819 4577 : if (!TDS_IS_SOCKET_INVALID(wakeup->s_signal))
820 0 : CLOSESOCKET(wakeup->s_signal);
821 4577 : if (!TDS_IS_SOCKET_INVALID(wakeup->s_signaled))
822 4577 : CLOSESOCKET(wakeup->s_signaled);
823 4577 : }
824 :
825 :
826 : void
827 280 : tds_wakeup_send(TDSPOLLWAKEUP *wakeup, char cancel)
828 : {
829 : #if defined(__linux__) && HAVE_EVENTFD
830 280 : if (wakeup->s_signal == -1) {
831 280 : uint64_t one = 1;
832 280 : (void) write(wakeup->s_signaled, &one, sizeof(one));
833 : return;
834 : }
835 : #endif
836 0 : send(wakeup->s_signal, &cancel, sizeof(cancel), 0);
837 : }
838 :
839 : static int
840 276 : tds_connection_signaled(TDSCONNECTION *conn)
841 : {
842 : ptrdiff_t len;
843 : char to_cancel[16];
844 :
845 : #if defined(__linux__) && HAVE_EVENTFD
846 276 : if (conn->wakeup.s_signal == -1)
847 276 : return read(conn->wakeup.s_signaled, to_cancel, 8) > 0;
848 : #endif
849 :
850 0 : len = READSOCKET(conn->wakeup.s_signaled, to_cancel, sizeof(to_cancel));
851 : do {
852 : /* no cancel found */
853 0 : if (len <= 0)
854 : return 0;
855 0 : } while(!to_cancel[--len]);
856 : return 1;
857 : }
858 :
859 : #if ENABLE_ODBC_MARS
860 : static void
861 120 : tds_check_cancel(TDSCONNECTION *conn)
862 : {
863 : TDSSOCKET *tds;
864 : int rc;
865 :
866 120 : if (!tds_connection_signaled(conn))
867 : return;
868 :
869 : do {
870 120 : unsigned n = 0;
871 :
872 120 : rc = TDS_SUCCESS;
873 120 : tds_mutex_lock(&conn->list_mtx);
874 : /* Here we scan all list searching for sessions that should send cancel packets */
875 7800 : for (; n < conn->num_sessions; ++n)
876 7680 : if (TDSSOCKET_VALID(tds=conn->sessions[n]) && tds->in_cancel == 1) {
877 : /* send cancel */
878 120 : tds->in_cancel = 2;
879 120 : tds_mutex_unlock(&conn->list_mtx);
880 120 : rc = tds_append_cancel(tds);
881 120 : tds_mutex_lock(&conn->list_mtx);
882 120 : if (rc != TDS_SUCCESS)
883 : break;
884 : }
885 120 : tds_mutex_unlock(&conn->list_mtx);
886 : /* for all failed */
887 : /* this must be done outside loop cause it can alter list */
888 : /* this must be done unlocked cause it can lock again */
889 120 : if (rc != TDS_SUCCESS)
890 0 : tds_close_socket(tds);
891 120 : } while(rc != TDS_SUCCESS);
892 : }
893 : #endif
894 :
895 : /**
896 : * Loops until we have received some characters
897 : * return -1 on failure
898 : */
899 : ptrdiff_t
900 153777 : tds_goodread(TDSSOCKET * tds, unsigned char *buf, size_t buflen)
901 : {
902 153777 : if (tds == NULL || buf == NULL || buflen < 1)
903 : return -1;
904 :
905 : for (;;) {
906 : ptrdiff_t len;
907 : int err;
908 :
909 : /* FIXME this block writing from other sessions */
910 154061 : len = tds_select(tds, TDSSELREAD, tds->query_timeout);
911 : #if !ENABLE_ODBC_MARS
912 110388 : if (len > 0 && (len & TDSPOLLURG)) {
913 156 : tds_connection_signaled(tds->conn);
914 : /* send cancel */
915 156 : if (tds->in_cancel == 1)
916 129 : tds_put_cancel(tds);
917 156 : continue;
918 : }
919 : #endif
920 153905 : if (len > 0) {
921 153750 : len = tds_socket_read(tds->conn, tds, buf, buflen);
922 153750 : if (len == 0)
923 0 : continue;
924 : return len;
925 : }
926 :
927 : /* error */
928 155 : if (len < 0) {
929 2 : if (TDSSOCK_WOULDBLOCK(sock_errno)) /* shouldn't happen, but OK */
930 0 : continue;
931 2 : err = sock_errno;
932 2 : tds_connection_close(tds->conn);
933 2 : tdserror(tds_get_ctx(tds), tds, TDSEREAD, err);
934 2 : return -1;
935 : }
936 :
937 : /* timeout */
938 153 : switch (tdserror(tds_get_ctx(tds), tds, TDSETIME, sock_errno)) {
939 : case TDS_INT_CONTINUE:
940 : break;
941 25 : default:
942 : case TDS_INT_CANCEL:
943 25 : tds_close_socket(tds);
944 25 : return -1;
945 : }
946 : }
947 : }
948 :
949 : ptrdiff_t
950 222722 : tds_connection_read(TDSSOCKET * tds, unsigned char *buf, size_t buflen)
951 : {
952 222722 : TDSCONNECTION *conn = tds->conn;
953 :
954 222722 : if (conn->tls_session)
955 164000 : return tds_ssl_read(conn, buf, buflen);
956 :
957 : #if ENABLE_ODBC_MARS
958 73536 : return tds_socket_read(conn, tds, buf, buflen);
959 : #else
960 67186 : return tds_goodread(tds, buf, buflen);
961 : #endif
962 : }
963 :
964 : /**
965 : * \param tds the famous socket
966 : * \param buffer data to send
967 : * \param buflen bytes in buffer
968 : * \param last 1 if this is the last packet, else 0
969 : * \return length written (>0), <0 on failure
970 : */
971 : ptrdiff_t
972 65209 : tds_goodwrite(TDSSOCKET * tds, const unsigned char *buffer, size_t buflen)
973 : {
974 : ptrdiff_t len;
975 65209 : size_t sent = 0;
976 :
977 65209 : assert(tds && buffer);
978 :
979 142835 : while (sent < buflen) {
980 : /* TODO if send buffer is full we block receive !!! */
981 77683 : len = tds_select(tds, TDSSELWRITE, tds->query_timeout);
982 :
983 77683 : if (len > 0) {
984 77673 : len = tds_socket_write(tds->conn, tds, buffer + sent, buflen - sent);
985 77673 : if (len == 0)
986 0 : continue;
987 77673 : if (len < 0)
988 : return len;
989 :
990 77626 : sent += len;
991 77626 : continue;
992 : }
993 :
994 : /* error */
995 10 : if (len < 0) {
996 10 : int err = sock_errno;
997 : char *errstr;
998 :
999 10 : if (TDSSOCK_WOULDBLOCK(err)) /* shouldn't happen, but OK, retry */
1000 0 : continue;
1001 10 : errstr = sock_strerror(err);
1002 10 : tdsdump_log(TDS_DBG_NETWORK, "select(2) failed: %d (%s)\n", err, errstr);
1003 : sock_strerror_free(errstr);
1004 10 : tds_connection_close(tds->conn);
1005 10 : tdserror(tds_get_ctx(tds), tds, TDSEWRIT, err);
1006 10 : return -1;
1007 : }
1008 :
1009 : /* timeout */
1010 0 : tdsdump_log(TDS_DBG_NETWORK, "tds_goodwrite(): timed out, asking client\n");
1011 0 : switch (tdserror(tds_get_ctx(tds), tds, TDSETIME, sock_errno)) {
1012 : case TDS_INT_CONTINUE:
1013 : break;
1014 0 : default:
1015 : case TDS_INT_CANCEL:
1016 0 : tds_close_socket(tds);
1017 0 : return -1;
1018 : }
1019 : }
1020 :
1021 65152 : return (int) sent;
1022 : }
1023 :
1024 : void
1025 123578 : tds_socket_flush(TDS_SYS_SOCKET sock TDS_UNUSED)
1026 : {
1027 : #ifdef USE_CORK
1028 : int opt;
1029 123578 : opt = 0;
1030 123578 : setsockopt(sock, SOL_TCP, TCP_CORK, (const void *) &opt, sizeof(opt));
1031 123578 : opt = 1;
1032 123578 : setsockopt(sock, SOL_TCP, TCP_CORK, (const void *) &opt, sizeof(opt));
1033 : #endif
1034 123578 : }
1035 :
1036 : ptrdiff_t
1037 99687 : tds_connection_write(TDSSOCKET *tds, const unsigned char *buf, size_t buflen, int final)
1038 : {
1039 : ptrdiff_t sent;
1040 99687 : TDSCONNECTION *conn = tds->conn;
1041 :
1042 : #if !defined(_WIN32) && !defined(MSG_NOSIGNAL) && !defined(DOS32X) && !defined(SO_NOSIGPIPE)
1043 : void (*oldsig) (int);
1044 :
1045 : oldsig = signal(SIGPIPE, SIG_IGN);
1046 : if (oldsig == SIG_ERR) {
1047 : tdsdump_log(TDS_DBG_WARN, "TDS: Warning: Couldn't set SIGPIPE signal to be ignored\n");
1048 : }
1049 : #endif
1050 :
1051 99687 : if (conn->tls_session)
1052 72148 : sent = tds_ssl_write(conn, buf, buflen);
1053 : else
1054 : #if ENABLE_ODBC_MARS
1055 34478 : sent = tds_socket_write(conn, tds, buf, buflen);
1056 : #else
1057 29135 : sent = tds_goodwrite(tds, buf, buflen);
1058 : #endif
1059 :
1060 : /* force packet flush */
1061 99687 : if (final && sent >= buflen)
1062 91097 : tds_socket_flush(tds_get_s(tds));
1063 :
1064 : #if !defined(_WIN32) && !defined(MSG_NOSIGNAL) && !defined(DOS32X) && !defined(SO_NOSIGPIPE)
1065 : if (signal(SIGPIPE, oldsig) == SIG_ERR) {
1066 : tdsdump_log(TDS_DBG_WARN, "TDS: Warning: Couldn't reset SIGPIPE signal to previous value\n");
1067 : }
1068 : #endif
1069 99687 : return sent;
1070 : }
1071 :
1072 : /**
1073 : * Get port of all instances
1074 : * @return default port number or 0 if error
1075 : * @remark experimental, cf. MC-SQLR.pdf.
1076 : */
1077 : int
1078 0 : tds7_get_instance_ports(FILE *output, struct addrinfo *addr)
1079 : {
1080 : int num_try;
1081 : struct pollfd fd;
1082 : int retval;
1083 : TDS_SYS_SOCKET s;
1084 : char msg[16*1024];
1085 0 : ptrdiff_t msg_len = 0;
1086 0 : int port = 0;
1087 : char ipaddr[128];
1088 :
1089 :
1090 0 : tds_addrinfo_set_port(addr, 1434);
1091 0 : tds_addrinfo2str(addr, ipaddr, sizeof(ipaddr));
1092 :
1093 0 : tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_ports(%s)\n", ipaddr);
1094 :
1095 : /* create an UDP socket */
1096 0 : if (TDS_IS_SOCKET_INVALID(s = socket(addr->ai_family, SOCK_DGRAM, 0))) {
1097 0 : char *errstr = sock_strerror(sock_errno);
1098 0 : tdsdump_log(TDS_DBG_ERROR, "socket creation error: %s\n", errstr);
1099 : sock_strerror_free(errstr);
1100 : return 0;
1101 : }
1102 :
1103 : /*
1104 : * on cluster environment is possible that reply packet came from
1105 : * different IP so do not filter by ip with connect
1106 : */
1107 :
1108 0 : if (tds_socket_set_nonblocking(s) != 0) {
1109 0 : CLOSESOCKET(s);
1110 0 : return 0;
1111 : }
1112 :
1113 : /*
1114 : * Request the instance's port from the server.
1115 : * There is no easy way to detect if port is closed so we always try to
1116 : * get a reply from server 16 times.
1117 : */
1118 0 : for (num_try = 0; num_try < 16 && msg_len == 0; ++num_try) {
1119 : /* send the request */
1120 0 : msg[0] = 3;
1121 0 : if (sendto(s, msg, 1, 0, addr->ai_addr, addr->ai_addrlen) < 0)
1122 : break;
1123 :
1124 0 : fd.fd = s;
1125 0 : fd.events = POLLIN;
1126 0 : fd.revents = 0;
1127 :
1128 0 : retval = poll(&fd, 1, 1000);
1129 :
1130 : /* on interrupt ignore */
1131 0 : if (retval < 0 && sock_errno == TDSSOCK_EINTR)
1132 0 : continue;
1133 :
1134 0 : if (retval == 0) { /* timed out */
1135 : #if 1
1136 0 : tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_port: timed out on try %d of 16\n", num_try);
1137 0 : continue;
1138 : #else
1139 : int rc;
1140 : tdsdump_log(TDS_DBG_INFO1, "timed out\n");
1141 :
1142 : switch(rc = tdserror(NULL, NULL, TDSETIME, 0)) {
1143 : case TDS_INT_CONTINUE:
1144 : continue; /* try again */
1145 :
1146 : default:
1147 : tdsdump_log(TDS_DBG_ERROR, "error: client error handler returned %d\n", rc);
1148 : case TDS_INT_CANCEL:
1149 : CLOSESOCKET(s);
1150 : return 0;
1151 : }
1152 : #endif
1153 : }
1154 0 : if (retval < 0)
1155 : break;
1156 :
1157 : /* got data, read and parse */
1158 0 : if ((msg_len = recv(s, msg, sizeof(msg) - 1, 0)) > 3 && msg[0] == 5) {
1159 0 : char *name, sep[2] = ";", *save;
1160 :
1161 : /* assure null terminated */
1162 0 : msg[msg_len] = 0;
1163 0 : tdsdump_dump_buf(TDS_DBG_INFO1, "instance info", msg, msg_len);
1164 :
1165 : if (0) { /* To debug, print the whole string. */
1166 : char *p;
1167 :
1168 : for (*sep = '\n', p=msg+3; p < msg + msg_len; p++) {
1169 : if( *p == ';' )
1170 : *p = *sep;
1171 : }
1172 : fputs(msg + 3, output);
1173 : }
1174 :
1175 : /*
1176 : * Parse and print message.
1177 : */
1178 0 : name = strtok_r(msg+3, sep, &save);
1179 0 : while (name && output) {
1180 : int i;
1181 : static const char *const names[] = { "ServerName", "InstanceName", "IsClustered", "Version",
1182 : "tcp", "np", "via" };
1183 :
1184 0 : for (i=0; name && i < TDS_VECTOR_SIZE(names); i++) {
1185 0 : const char *value = strtok_r(NULL, sep, &save);
1186 :
1187 0 : if (strcmp(name, names[i]) != 0)
1188 0 : fprintf(output, "error: expecting '%s', found '%s'\n", names[i], name);
1189 0 : if (value)
1190 0 : fprintf(output, "%15s %s\n", name, value);
1191 : else
1192 : break;
1193 :
1194 0 : name = strtok_r(NULL, sep, &save);
1195 :
1196 0 : if (name && strcmp(name, names[0]) == 0)
1197 : break;
1198 : }
1199 0 : if (name)
1200 0 : fprintf(output, "\n");
1201 : }
1202 : }
1203 : }
1204 0 : CLOSESOCKET(s);
1205 0 : tdsdump_log(TDS_DBG_ERROR, "default instance port is %d\n", port);
1206 : return port;
1207 : }
1208 :
1209 : /**
1210 : * Get port of given instance
1211 : * @return port number or 0 if error
1212 : */
1213 : int
1214 2 : tds7_get_instance_port(struct addrinfo *addr, const char *instance)
1215 : {
1216 : int num_try;
1217 : struct pollfd fd;
1218 : int retval;
1219 : TDS_SYS_SOCKET s;
1220 : char msg[1024];
1221 : ptrdiff_t msg_len;
1222 2 : int port = 0;
1223 : char ipaddr[128];
1224 :
1225 2 : tds_addrinfo_set_port(addr, 1434);
1226 2 : tds_addrinfo2str(addr, ipaddr, sizeof(ipaddr));
1227 :
1228 2 : tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_port(%s, %s)\n", ipaddr, instance);
1229 :
1230 : /* create an UDP socket */
1231 2 : if (TDS_IS_SOCKET_INVALID(s = socket(addr->ai_family, SOCK_DGRAM, 0))) {
1232 0 : char *errstr = sock_strerror(sock_errno);
1233 0 : tdsdump_log(TDS_DBG_ERROR, "socket creation error: %s\n", errstr);
1234 : sock_strerror_free(errstr);
1235 : return 0;
1236 : }
1237 :
1238 : /*
1239 : * on cluster environment is possible that reply packet came from
1240 : * different IP so do not filter by ip with connect
1241 : */
1242 :
1243 2 : if (tds_socket_set_nonblocking(s) != 0) {
1244 0 : CLOSESOCKET(s);
1245 0 : return 0;
1246 : }
1247 :
1248 : /*
1249 : * Request the instance's port from the server.
1250 : * There is no easy way to detect if port is closed so we always try to
1251 : * get a reply from server 16 times.
1252 : */
1253 0 : for (num_try = 0; num_try < 16; ++num_try) {
1254 : /* send the request */
1255 2 : msg[0] = 4;
1256 2 : strlcpy(msg + 1, instance, sizeof(msg) - 1);
1257 2 : if (sendto(s, msg, (int)strlen(msg) + 1, 0, addr->ai_addr, addr->ai_addrlen) < 0)
1258 : break;
1259 :
1260 2 : fd.fd = s;
1261 2 : fd.events = POLLIN;
1262 2 : fd.revents = 0;
1263 :
1264 2 : retval = poll(&fd, 1, 1000);
1265 :
1266 : /* on interrupt ignore */
1267 2 : if (retval < 0 && sock_errno == TDSSOCK_EINTR)
1268 0 : continue;
1269 :
1270 2 : if (retval == 0) { /* timed out */
1271 : #if 1
1272 0 : tdsdump_log(TDS_DBG_ERROR, "tds7_get_instance_port: timed out on try %d of 16\n", num_try);
1273 0 : continue;
1274 : #else
1275 : int rc;
1276 : tdsdump_log(TDS_DBG_INFO1, "timed out\n");
1277 :
1278 : switch(rc = tdserror(NULL, NULL, TDSETIME, 0)) {
1279 : case TDS_INT_CONTINUE:
1280 : continue; /* try again */
1281 :
1282 : default:
1283 : tdsdump_log(TDS_DBG_ERROR, "error: client error handler returned %d\n", rc);
1284 : case TDS_INT_CANCEL:
1285 : CLOSESOCKET(s);
1286 : return 0;
1287 : }
1288 : #endif
1289 : }
1290 2 : if (retval < 0)
1291 : break;
1292 :
1293 : /* TODO pass also connection and set instance/servername ?? */
1294 :
1295 : /* got data, read and parse */
1296 2 : if ((msg_len = recv(s, msg, sizeof(msg) - 1, 0)) > 3 && msg[0] == 5) {
1297 : char *p;
1298 2 : long l = 0;
1299 2 : int instance_ok = 0, port_ok = 0;
1300 :
1301 : /* assure null terminated */
1302 2 : msg[msg_len] = 0;
1303 2 : tdsdump_dump_buf(TDS_DBG_INFO1, "instance info", msg, msg_len);
1304 :
1305 : /*
1306 : * Parse message and check instance name and port.
1307 : * We don't check servername cause it can be very different from the client's.
1308 : */
1309 2 : for (p = msg + 3;;) {
1310 : char *name, *value;
1311 :
1312 12 : name = p;
1313 12 : p = strchr(p, ';');
1314 12 : if (!p)
1315 : break;
1316 10 : *p++ = 0;
1317 :
1318 10 : value = name;
1319 10 : if (*name) {
1320 10 : value = p;
1321 10 : p = strchr(p, ';');
1322 10 : if (!p)
1323 : break;
1324 10 : *p++ = 0;
1325 : }
1326 :
1327 10 : if (strcasecmp(name, "InstanceName") == 0) {
1328 2 : if (strcasecmp(value, instance) != 0)
1329 : break;
1330 : instance_ok = 1;
1331 8 : } else if (strcasecmp(name, "tcp") == 0) {
1332 2 : l = strtol(value, &p, 10);
1333 2 : if (l > 0 && l <= 0xffff && *p == 0)
1334 2 : port_ok = 1;
1335 : }
1336 : }
1337 2 : if (port_ok && instance_ok) {
1338 2 : port = (int) l;
1339 2 : break;
1340 : }
1341 : }
1342 : }
1343 2 : CLOSESOCKET(s);
1344 2 : tdsdump_log(TDS_DBG_ERROR, "instance port is %d\n", port);
1345 : return port;
1346 : }
1347 :
1348 : #if defined(_WIN32)
1349 : static const char tds_unknown_wsaerror[] = "undocumented WSA error code";
1350 :
1351 : char *
1352 : tds_prwsaerror(int erc)
1353 : {
1354 : char *errstr = NULL;
1355 : FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, erc,
1356 : MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (LPTSTR)&errstr, 0, NULL);
1357 : if (errstr) {
1358 : size_t len = strlen(errstr);
1359 : while (len > 0 && (errstr[len-1] == '\r' || errstr[len-1] == '\n'))
1360 : errstr[len-1] = 0;
1361 : return errstr;
1362 : }
1363 : return (char*) tds_unknown_wsaerror;
1364 : }
1365 :
1366 : void
1367 : tds_prwsaerror_free(char *s)
1368 : {
1369 : if (s != tds_unknown_wsaerror)
1370 : LocalFree((HLOCAL) s);
1371 : }
1372 : #endif
1373 :
1374 : /** @} */
1375 :
|