Add test for "struct in6_addr" to the HAVE_IPV6 configure test.
[jra/samba/.git] / source / lib / util_sock.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Tim Potter      2000-2001
6    Copyright (C) Jeremy Allison  1992-2007
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23
24 /* the following 3 client_*() functions are nasty ways of allowing
25    some generic functions to get info that really should be hidden in
26    particular modules */
27 static int client_fd = -1;
28 /* What to print out on a client disconnect error. */
29 static char client_ip_string[INET6_ADDRSTRLEN];
30
31 /****************************************************************************
32  Return true if a string could be an IPv4 address.
33 ****************************************************************************/
34
35 bool is_ipaddress_v4(const char *str)
36 {
37         int ret = -1;
38         struct in_addr dest;
39
40         ret = inet_pton(AF_INET, str, &dest);
41         if (ret > 0) {
42                 return true;
43         }
44         return false;
45 }
46
47 /****************************************************************************
48  Return true if a string could be an IPv4 or IPv6 address.
49 ****************************************************************************/
50
51 bool is_ipaddress(const char *str)
52 {
53         int ret = -1;
54
55 #if defined(HAVE_IPV6)
56         struct in6_addr dest6;
57
58         ret = inet_pton(AF_INET6, str, &dest6);
59         if (ret > 0) {
60                 return true;
61         }
62 #endif
63         return is_ipaddress_v4(str);
64 }
65
66 /*******************************************************************
67  Wrap getaddrinfo...
68 ******************************************************************/
69
70 static bool interpret_string_addr_internal(struct addrinfo **ppres,
71                                         const char *str, int flags)
72 {
73         int ret;
74         struct addrinfo hints;
75
76         memset(&hints, '\0', sizeof(hints));
77         /* By default make sure it supports TCP. */
78         hints.ai_socktype = SOCK_STREAM;
79         hints.ai_flags = flags;
80
81         ret = getaddrinfo(str, NULL,
82                         &hints,
83                         ppres);
84         if (ret) {
85                 DEBUG(3,("interpret_string_addr_interal: getaddrinfo failed "
86                         "for name %s [%s]\n",
87                         str,
88                         gai_strerror(ret) ));
89                 return false;
90         }
91         return true;
92 }
93
94 /****************************************************************************
95  Interpret an internet address or name into an IP address in 4 byte form.
96  RETURNS IN NETWORK BYTE ORDER (big endian).
97 ****************************************************************************/
98
99 uint32 interpret_addr(const char *str)
100 {
101         uint32 ret;
102
103         /* If it's in the form of an IP address then
104          * get the lib to interpret it */
105         if (is_ipaddress_v4(str)) {
106                 struct in_addr dest;
107
108                 if (inet_pton(AF_INET, str, &dest) <= 0) {
109                         /* Error - this shouldn't happen ! */
110                         DEBUG(0,("interpret_addr: inet_pton failed "
111                                 "host %s\n",
112                                 str));
113                         return 0;
114                 }
115                 ret = dest.s_addr; /* NETWORK BYTE ORDER ! */
116         } else {
117                 /* Otherwise assume it's a network name of some sort and use
118                         getadddrinfo. */
119                 struct addrinfo *res = NULL;
120                 struct addrinfo *res_list = NULL;
121                 if (!interpret_string_addr_internal(&res_list,
122                                         str,
123                                         AI_ADDRCONFIG)) {
124                         DEBUG(3,("interpret_addr: Unknown host. %s\n",str));
125                         return 0;
126                 }
127
128                 /* Find the first IPv4 address. */
129                 for (res = res_list; res; res = res->ai_next) {
130                         if (res->ai_family != AF_INET) {
131                                 continue;
132                         }
133                         if (res->ai_addr == NULL) {
134                                 continue;
135                         }
136                         break;
137                 }
138                 if(res == NULL) {
139                         DEBUG(3,("interpret_addr: host address is "
140                                 "invalid for host %s\n",str));
141                         if (res_list) {
142                                 freeaddrinfo(res_list);
143                         }
144                         return 0;
145                 }
146                 putip((char *)&ret,
147                         &((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr);
148                 if (res_list) {
149                         freeaddrinfo(res_list);
150                 }
151         }
152
153         /* This is so bogus - all callers need fixing... JRA. */
154         if (ret == (uint32)-1) {
155                 return 0;
156         }
157
158         return ret;
159 }
160
161 /*******************************************************************
162  A convenient addition to interpret_addr().
163 ******************************************************************/
164
165 struct in_addr *interpret_addr2(const char *str)
166 {
167         static struct in_addr ret;
168         uint32 a = interpret_addr(str);
169         ret.s_addr = a;
170         return(&ret);
171 }
172
173 /*******************************************************************
174  Map a text hostname or IP address (IPv4 or IPv6) into a
175  struct sockaddr_storage.
176 ******************************************************************/
177
178 bool interpret_string_addr(struct sockaddr_storage *pss,
179                 const char *str,
180                 int flags)
181 {
182         struct addrinfo *res = NULL;
183
184         memset(pss,'\0', sizeof(*pss));
185
186         if (!interpret_string_addr_internal(&res, str, flags|AI_ADDRCONFIG)) {
187                 return false;
188         }
189         if (!res) {
190                 return false;
191         }
192         /* Copy the first sockaddr. */
193         memcpy(pss, res->ai_addr, res->ai_addrlen);
194         freeaddrinfo(res);
195         return true;
196 }
197
198 /*******************************************************************
199  Check if an IPv7 is 127.0.0.1
200 ******************************************************************/
201
202 bool is_loopback_ip_v4(struct in_addr ip)
203 {
204         struct in_addr a;
205         a.s_addr = htonl(INADDR_LOOPBACK);
206         return(ip.s_addr == a.s_addr);
207 }
208
209 /*******************************************************************
210  Check if a struct sockaddr_storage is the loopback address.
211 ******************************************************************/
212
213 bool is_loopback_addr(const struct sockaddr_storage *pss)
214 {
215 #if defined(HAVE_IPV6)
216         if (pss->ss_family == AF_INET) {
217                 struct in6_addr *pin6 =
218                         &((struct sockaddr_in6 *)pss)->sin6_addr;
219                 return IN6_IS_ADDR_LOOPBACK(pin6);
220         }
221 #endif
222         if (pss->ss_family == AF_INET) {
223                 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
224                 return is_loopback_ip_v4(*pin);
225         }
226         return false;
227 }
228
229 /*******************************************************************
230  Check if an IPv4 is 0.0.0.0.
231 ******************************************************************/
232
233 bool is_zero_ip_v4(struct in_addr ip)
234 {
235         uint32 a;
236         putip((char *)&a,(char *)&ip);
237         return(a == 0);
238 }
239
240 /*******************************************************************
241  Check if a struct sockaddr_storage has an unspecified address.
242 ******************************************************************/
243
244 bool is_zero_addr(const struct sockaddr_storage *pss)
245 {
246 #if defined(HAVE_IPV6)
247         if (pss->ss_family == AF_INET) {
248                 struct in6_addr *pin6 =
249                         &((struct sockaddr_in6 *)pss)->sin6_addr;
250                 return IN6_IS_ADDR_UNSPECIFIED(pin6);
251         }
252 #endif
253         if (pss->ss_family == AF_INET) {
254                 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
255                 return is_zero_ip_v4(*pin);
256         }
257         return false;
258 }
259
260 /*******************************************************************
261  Set an IP to 0.0.0.0.
262 ******************************************************************/
263
264 void zero_ip_v4(struct in_addr *ip)
265 {
266         static bool init;
267         static struct in_addr ipzero;
268
269         if (!init) {
270                 ipzero = *interpret_addr2("0.0.0.0");
271                 init = true;
272         }
273
274         *ip = ipzero;
275 }
276
277 /*******************************************************************
278  Are two IPs on the same subnet - IPv4 version ?
279 ********************************************************************/
280
281 bool same_net_v4(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
282 {
283         uint32 net1,net2,nmask;
284
285         nmask = ntohl(mask.s_addr);
286         net1  = ntohl(ip1.s_addr);
287         net2  = ntohl(ip2.s_addr);
288
289         return((net1 & nmask) == (net2 & nmask));
290 }
291
292 /*******************************************************************
293  Convert an IPv4 struct in_addr to a struct sockaddr_storage.
294 ********************************************************************/
295
296 void in_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
297                 struct in_addr ip)
298 {
299         struct sockaddr_in *sa = (struct sockaddr_in *)ss;
300         memset(ss, '\0', sizeof(*ss));
301         ss->ss_family = AF_INET;
302         sa->sin_addr = ip;
303 }
304
305 #if defined(HAVE_IPV6)
306 /*******************************************************************
307  Convert an IPv6 struct in_addr to a struct sockaddr_storage.
308 ********************************************************************/
309
310 void in6_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
311                 struct in6_addr ip)
312 {
313         struct sockaddr_in6 *sa = (struct sockaddr_in6 *)ss;
314         memset(ss, '\0', sizeof(*ss));
315         ss->ss_family = AF_INET6;
316         sa->sin6_addr = ip;
317 }
318 #endif
319
320 /*******************************************************************
321  Are two IPs on the same subnet?
322 ********************************************************************/
323
324 bool same_net(const struct sockaddr_storage *ip1,
325                 const struct sockaddr_storage *ip2,
326                 const struct sockaddr_storage *mask)
327 {
328         if (ip1->ss_family != ip2->ss_family) {
329                 /* Never on the same net. */
330                 return false;
331         }
332
333 #if defined(HAVE_IPV6)
334         if (ip1->ss_family == AF_INET6) {
335                 struct sockaddr_in6 ip1_6 = *(struct sockaddr_in6 *)ip1;
336                 struct sockaddr_in6 ip2_6 = *(struct sockaddr_in6 *)ip2;
337                 struct sockaddr_in6 mask_6 = *(struct sockaddr_in6 *)mask;
338                 char *p1 = (char *)&ip1_6.sin6_addr;
339                 char *p2 = (char *)&ip2_6.sin6_addr;
340                 char *m = (char *)&mask_6.sin6_addr;
341                 int i;
342
343                 for (i = 0; i < sizeof(struct in6_addr); i++) {
344                         *p1++ &= *m;
345                         *p2++ &= *m;
346                         m++;
347                 }
348                 return (memcmp(&ip1_6.sin6_addr,
349                                 &ip2_6.sin6_addr,
350                                 sizeof(struct in6_addr)) == 0);
351         }
352 #endif
353         if (ip1->ss_family == AF_INET) {
354                 return same_net_v4(((const struct sockaddr_in *)ip1)->sin_addr,
355                                 ((const struct sockaddr_in *)ip2)->sin_addr,
356                                 ((const struct sockaddr_in *)mask)->sin_addr);
357         }
358         return false;
359 }
360
361 /*******************************************************************
362  Are two sockaddr_storage's the same family and address ? Ignore port etc.
363 ********************************************************************/
364
365 bool addr_equal(const struct sockaddr_storage *ip1,
366                 const struct sockaddr_storage *ip2)
367 {
368         if (ip1->ss_family != ip2->ss_family) {
369                 /* Never the same. */
370                 return false;
371         }
372
373 #if defined(HAVE_IPV6)
374         if (ip1->ss_family == AF_INET6) {
375                 return (memcmp(&((const struct sockaddr_in6 *)ip1)->sin6_addr,
376                                 &((const struct sockaddr_in6 *)ip2)->sin6_addr,
377                                 sizeof(struct in6_addr)) == 0);
378         }
379 #endif
380         if (ip1->ss_family == AF_INET) {
381                 return (memcmp(&((const struct sockaddr_in *)ip1)->sin_addr,
382                                 &((const struct sockaddr_in *)ip2)->sin_addr,
383                                 sizeof(struct in_addr)) == 0);
384         }
385         return false;
386 }
387
388
389 /****************************************************************************
390  Is an IP address the INADDR_ANY or in6addr_any value ?
391 ****************************************************************************/
392
393 bool is_address_any(const struct sockaddr_storage *psa)
394 {
395 #if defined(HAVE_IPV6)
396         if (psa->ss_family == AF_INET6) {
397                 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)psa;
398                 if (memcmp(&in6addr_any,
399                                 &si6->sin6_addr,
400                                 sizeof(in6addr_any)) == 0) {
401                         return true;
402                 }
403                 return false;
404         }
405 #endif
406         if (psa->ss_family == AF_INET) {
407                 struct sockaddr_in *si = (struct sockaddr_in *)psa;
408                 if (si->sin_addr.s_addr == INADDR_ANY) {
409                         return true;
410                 }
411                 return false;
412         }
413         return false;
414 }
415
416 /****************************************************************************
417  Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
418 ****************************************************************************/
419
420 char *print_sockaddr(char *dest,
421                         size_t destlen,
422                         const struct sockaddr_storage *psa,
423                         socklen_t psalen)
424 {
425         if (destlen > 0) {
426                 dest[0] = '\0';
427         }
428         (void)getnameinfo((const struct sockaddr *)psa,
429                         psalen,
430                         dest, destlen,
431                         NULL, 0,
432                         NI_NUMERICHOST);
433         return dest;
434 }
435
436 /****************************************************************************
437  Set the global client_fd variable.
438 ****************************************************************************/
439
440 void client_setfd(int fd)
441 {
442         client_fd = fd;
443         safe_strcpy(client_ip_string,
444                         get_peer_addr(client_fd),
445                         sizeof(client_ip_string)-1);
446 }
447
448 /****************************************************************************
449  Return a static string of an IP address (IPv4 or IPv6).
450 ****************************************************************************/
451
452 static const char *get_socket_addr(int fd)
453 {
454         struct sockaddr_storage sa;
455         socklen_t length = sizeof(sa);
456         static char addr_buf[INET6_ADDRSTRLEN];
457
458         /* Ok, returning a hard coded IPv4 address
459          * is bogus, but it's just as bogus as a
460          * zero IPv6 address. No good choice here.
461          */
462
463         safe_strcpy(addr_buf, "0.0.0.0", sizeof(addr_buf)-1);
464
465         if (fd == -1) {
466                 return addr_buf;
467         }
468
469         if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
470                 DEBUG(0,("getsockname failed. Error was %s\n",
471                         strerror(errno) ));
472                 return addr_buf;
473         }
474
475         return print_sockaddr(addr_buf, sizeof(addr_buf), &sa, length);
476 }
477
478 /****************************************************************************
479  Return the port number we've bound to on a socket.
480 ****************************************************************************/
481
482 static int get_socket_port(int fd)
483 {
484         struct sockaddr_storage sa;
485         socklen_t length = sizeof(sa);
486
487         if (fd == -1) {
488                 return -1;
489         }
490
491         if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
492                 DEBUG(0,("getpeername failed. Error was %s\n",
493                         strerror(errno) ));
494                 return -1;
495         }
496
497 #if defined(HAVE_IPV6)
498         if (sa.ss_family == AF_INET6) {
499                 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
500         }
501 #endif
502         if (sa.ss_family == AF_INET) {
503                 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
504         }
505         return -1;
506 }
507
508 const char *client_name(void)
509 {
510         return get_peer_name(client_fd,false);
511 }
512
513 const char *client_addr(void)
514 {
515         return get_peer_addr(client_fd);
516 }
517
518 const char *client_socket_addr(void)
519 {
520         return get_socket_addr(client_fd);
521 }
522
523 int client_socket_port(void)
524 {
525         return get_socket_port(client_fd);
526 }
527
528 int smb_read_error = 0;
529
530 /****************************************************************************
531  Determine if a file descriptor is in fact a socket.
532 ****************************************************************************/
533
534 bool is_a_socket(int fd)
535 {
536         int v;
537         socklen_t l;
538         l = sizeof(int);
539         return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
540 }
541
542 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
543
544 typedef struct smb_socket_option {
545         const char *name;
546         int level;
547         int option;
548         int value;
549         int opttype;
550 } smb_socket_option;
551
552 static const smb_socket_option socket_options[] = {
553   {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
554   {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
555   {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
556 #ifdef TCP_NODELAY
557   {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
558 #endif
559 #ifdef TCP_KEEPCNT
560   {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
561 #endif
562 #ifdef TCP_KEEPIDLE
563   {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
564 #endif
565 #ifdef TCP_KEEPINTVL
566   {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
567 #endif
568 #ifdef IPTOS_LOWDELAY
569   {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
570 #endif
571 #ifdef IPTOS_THROUGHPUT
572   {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
573 #endif
574 #ifdef SO_REUSEPORT
575   {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
576 #endif
577 #ifdef SO_SNDBUF
578   {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
579 #endif
580 #ifdef SO_RCVBUF
581   {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
582 #endif
583 #ifdef SO_SNDLOWAT
584   {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
585 #endif
586 #ifdef SO_RCVLOWAT
587   {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
588 #endif
589 #ifdef SO_SNDTIMEO
590   {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
591 #endif
592 #ifdef SO_RCVTIMEO
593   {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
594 #endif
595 #ifdef TCP_FASTACK
596   {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
597 #endif
598   {NULL,0,0,0,0}};
599
600 /****************************************************************************
601  Print socket options.
602 ****************************************************************************/
603
604 static void print_socket_options(int s)
605 {
606         int value;
607         socklen_t vlen = 4;
608         const smb_socket_option *p = &socket_options[0];
609
610         /* wrapped in if statement to prevent streams
611          * leak in SCO Openserver 5.0 */
612         /* reported on samba-technical  --jerry */
613         if ( DEBUGLEVEL >= 5 ) {
614                 for (; p->name != NULL; p++) {
615                         if (getsockopt(s, p->level, p->option,
616                                                 (void *)&value, &vlen) == -1) {
617                                 DEBUG(5,("Could not test socket option %s.\n",
618                                                         p->name));
619                         } else {
620                                 DEBUG(5,("socket option %s = %d\n",
621                                                         p->name,value));
622                         }
623                 }
624         }
625  }
626
627 /****************************************************************************
628  Set user socket options.
629 ****************************************************************************/
630
631 void set_socket_options(int fd, const char *options)
632 {
633         fstring tok;
634
635         while (next_token(&options,tok," \t,", sizeof(tok))) {
636                 int ret=0,i;
637                 int value = 1;
638                 char *p;
639                 bool got_value = false;
640
641                 if ((p = strchr_m(tok,'='))) {
642                         *p = 0;
643                         value = atoi(p+1);
644                         got_value = true;
645                 }
646
647                 for (i=0;socket_options[i].name;i++)
648                         if (strequal(socket_options[i].name,tok))
649                                 break;
650
651                 if (!socket_options[i].name) {
652                         DEBUG(0,("Unknown socket option %s\n",tok));
653                         continue;
654                 }
655
656                 switch (socket_options[i].opttype) {
657                 case OPT_BOOL:
658                 case OPT_INT:
659                         ret = setsockopt(fd,socket_options[i].level,
660                                         socket_options[i].option,
661                                         (char *)&value,sizeof(int));
662                         break;
663
664                 case OPT_ON:
665                         if (got_value)
666                                 DEBUG(0,("syntax error - %s "
667                                         "does not take a value\n",tok));
668
669                         {
670                                 int on = socket_options[i].value;
671                                 ret = setsockopt(fd,socket_options[i].level,
672                                         socket_options[i].option,
673                                         (char *)&on,sizeof(int));
674                         }
675                         break;
676                 }
677
678                 if (ret != 0) {
679                         DEBUG(0,("Failed to set socket option %s (Error %s)\n",
680                                 tok, strerror(errno) ));
681                 }
682         }
683
684         print_socket_options(fd);
685 }
686
687 /****************************************************************************
688  Read from a socket.
689 ****************************************************************************/
690
691 ssize_t read_udp_v4_socket(int fd,
692                         char *buf,
693                         size_t len,
694                         struct sockaddr_storage *psa)
695 {
696         ssize_t ret;
697         socklen_t socklen = sizeof(*psa);
698         struct sockaddr_in *si = (struct sockaddr_in *)psa;
699
700         memset((char *)psa,'\0',socklen);
701
702         ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
703                         (struct sockaddr *)psa,&socklen);
704         if (ret <= 0) {
705                 /* Don't print a low debug error for a non-blocking socket. */
706                 if (errno == EAGAIN) {
707                         DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
708                 } else {
709                         DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
710                                 strerror(errno)));
711                 }
712                 return 0;
713         }
714
715         if (psa->ss_family != AF_INET) {
716                 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
717                         "(not IPv4)\n", (int)psa->ss_family));
718                 return 0;
719         }
720
721         DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
722                         inet_ntoa(si->sin_addr),
723                         si->sin_port,
724                         (unsigned long)ret));
725
726         return ret;
727 }
728
729 /****************************************************************************
730  Read data from a socket with a timout in msec.
731  mincount = if timeout, minimum to read before returning
732  maxcount = number to be read.
733  time_out = timeout in milliseconds
734 ****************************************************************************/
735
736 ssize_t read_socket_with_timeout(int fd,
737                                 char *buf,
738                                 size_t mincnt,
739                                 size_t maxcnt,
740                                 unsigned int time_out)
741 {
742         fd_set fds;
743         int selrtn;
744         ssize_t readret;
745         size_t nread = 0;
746         struct timeval timeout;
747
748         /* just checking .... */
749         if (maxcnt <= 0)
750                 return(0);
751
752         smb_read_error = 0;
753
754         /* Blocking read */
755         if (time_out == 0) {
756                 if (mincnt == 0) {
757                         mincnt = maxcnt;
758                 }
759
760                 while (nread < mincnt) {
761                         readret = sys_read(fd, buf + nread, maxcnt - nread);
762
763                         if (readret == 0) {
764                                 DEBUG(5,("read_socket_with_timeout: "
765                                         "blocking read. EOF from client.\n"));
766                                 smb_read_error = READ_EOF;
767                                 return -1;
768                         }
769
770                         if (readret == -1) {
771                                 if (fd == client_fd) {
772                                         /* Try and give an error message
773                                          * saying what client failed. */
774                                         DEBUG(0,("read_socket_with_timeout: "
775                                                 "client %s read error = %s.\n",
776                                                 client_ip_string,
777                                                 strerror(errno) ));
778                                 } else {
779                                         DEBUG(0,("read_socket_with_timeout: "
780                                                 "read error = %s.\n",
781                                                 strerror(errno) ));
782                                 }
783                                 smb_read_error = READ_ERROR;
784                                 return -1;
785                         }
786                         nread += readret;
787                 }
788                 return((ssize_t)nread);
789         }
790
791         /* Most difficult - timeout read */
792         /* If this is ever called on a disk file and
793            mincnt is greater then the filesize then
794            system performance will suffer severely as
795            select always returns true on disk files */
796
797         /* Set initial timeout */
798         timeout.tv_sec = (time_t)(time_out / 1000);
799         timeout.tv_usec = (long)(1000 * (time_out % 1000));
800
801         for (nread=0; nread < mincnt; ) {
802                 FD_ZERO(&fds);
803                 FD_SET(fd,&fds);
804
805                 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
806
807                 /* Check if error */
808                 if (selrtn == -1) {
809                         /* something is wrong. Maybe the socket is dead? */
810                         if (fd == client_fd) {
811                                 /* Try and give an error message saying
812                                  * what client failed. */
813                                 DEBUG(0,("read_socket_with_timeout: timeout "
814                                 "read for client %s. select error = %s.\n",
815                                 client_ip_string, strerror(errno) ));
816                         } else {
817                                 DEBUG(0,("read_socket_with_timeout: timeout "
818                                 "read. select error = %s.\n",
819                                 strerror(errno) ));
820                         }
821                         smb_read_error = READ_ERROR;
822                         return -1;
823                 }
824
825                 /* Did we timeout ? */
826                 if (selrtn == 0) {
827                         DEBUG(10,("read_socket_with_timeout: timeout read. "
828                                 "select timed out.\n"));
829                         smb_read_error = READ_TIMEOUT;
830                         return -1;
831                 }
832
833                 readret = sys_read(fd, buf+nread, maxcnt-nread);
834
835                 if (readret == 0) {
836                         /* we got EOF on the file descriptor */
837                         DEBUG(5,("read_socket_with_timeout: timeout read. "
838                                 "EOF from client.\n"));
839                         smb_read_error = READ_EOF;
840                         return -1;
841                 }
842
843                 if (readret == -1) {
844                         /* the descriptor is probably dead */
845                         if (fd == client_fd) {
846                                 /* Try and give an error message
847                                  * saying what client failed. */
848                                 DEBUG(0,("read_socket_with_timeout: timeout "
849                                         "read to client %s. read error = %s.\n",
850                                         client_ip_string, strerror(errno) ));
851                         } else {
852                                 DEBUG(0,("read_socket_with_timeout: timeout "
853                                         "read. read error = %s.\n",
854                                         strerror(errno) ));
855                         }
856                         smb_read_error = READ_ERROR;
857                         return -1;
858                 }
859
860                 nread += readret;
861         }
862
863         /* Return the number we got */
864         return (ssize_t)nread;
865 }
866
867 /****************************************************************************
868  Read data from the client, reading exactly N bytes.
869 ****************************************************************************/
870
871 ssize_t read_data(int fd,char *buffer,size_t N)
872 {
873         ssize_t ret;
874         size_t total=0;
875
876         smb_read_error = 0;
877
878         while (total < N) {
879                 ret = sys_read(fd,buffer + total,N - total);
880
881                 if (ret == 0) {
882                         DEBUG(10,("read_data: read of %d returned 0. "
883                                 "Error = %s\n",
884                                 (int)(N - total), strerror(errno) ));
885                         smb_read_error = READ_EOF;
886                         return 0;
887                 }
888
889                 if (ret == -1) {
890                         if (fd == client_fd) {
891                                 /* Try and give an error message saying
892                                  * what client failed. */
893                                 DEBUG(0,("read_data: read failure for %d "
894                                         "bytes to client %s. Error = %s\n",
895                                         (int)(N - total),
896                                         client_ip_string,
897                                         strerror(errno) ));
898                         } else {
899                                 DEBUG(0,("read_data: read failure for %d. "
900                                         "Error = %s\n",
901                                         (int)(N - total),
902                                         strerror(errno) ));
903                         }
904                         smb_read_error = READ_ERROR;
905                         return -1;
906                 }
907                 total += ret;
908         }
909         return (ssize_t)total;
910 }
911
912 /****************************************************************************
913  Write data to a fd.
914 ****************************************************************************/
915
916 ssize_t write_data(int fd, const char *buffer, size_t N)
917 {
918         size_t total=0;
919         ssize_t ret;
920
921         while (total < N) {
922                 ret = sys_write(fd,buffer + total,N - total);
923
924                 if (ret == -1) {
925                         if (fd == client_fd) {
926                                 /* Try and give an error message saying
927                                  * what client failed. */
928                                 DEBUG(0,("write_data: write failure in "
929                                         "writing to client %s. Error %s\n",
930                                         client_ip_string, strerror(errno) ));
931                         } else {
932                                 DEBUG(0,("write_data: write failure. "
933                                         "Error = %s\n", strerror(errno) ));
934                         }
935                         return -1;
936                 }
937
938                 if (ret == 0) {
939                         return total;
940                 }
941
942                 total += ret;
943         }
944         return (ssize_t)total;
945 }
946
947 /****************************************************************************
948  Send a keepalive packet (rfc1002).
949 ****************************************************************************/
950
951 bool send_keepalive(int client)
952 {
953         unsigned char buf[4];
954
955         buf[0] = SMBkeepalive;
956         buf[1] = buf[2] = buf[3] = 0;
957
958         return(write_data(client,(char *)buf,4) == 4);
959 }
960
961 /****************************************************************************
962  Read 4 bytes of a smb packet and return the smb length of the packet.
963  Store the result in the buffer.
964  This version of the function will return a length of zero on receiving
965  a keepalive packet.
966  Timeout is in milliseconds.
967 ****************************************************************************/
968
969 static ssize_t read_smb_length_return_keepalive(int fd,
970                                                 char *inbuf,
971                                                 unsigned int timeout)
972 {
973         ssize_t len=0;
974         int msg_type;
975         bool ok = false;
976
977         while (!ok) {
978                 if (timeout > 0) {
979                         ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout)
980                                         == 4);
981                 } else {
982                         ok = (read_data(fd,inbuf,4) == 4);
983                 }
984                 if (!ok) {
985                         return -1;
986                 }
987
988                 len = smb_len(inbuf);
989                 msg_type = CVAL(inbuf,0);
990
991                 if (msg_type == SMBkeepalive) {
992                         DEBUG(5,("Got keepalive packet\n"));
993                 }
994         }
995
996         DEBUG(10,("got smb length of %lu\n",(unsigned long)len));
997
998         return(len);
999 }
1000
1001 /****************************************************************************
1002  Read 4 bytes of a smb packet and return the smb length of the packet.
1003  Store the result in the buffer. This version of the function will
1004  never return a session keepalive (length of zero).
1005  Timeout is in milliseconds.
1006 ****************************************************************************/
1007
1008 ssize_t read_smb_length(int fd, char *inbuf, unsigned int timeout)
1009 {
1010         ssize_t len;
1011
1012         for(;;) {
1013                 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
1014
1015                 if(len < 0)
1016                         return len;
1017
1018                 /* Ignore session keepalives. */
1019                 if(CVAL(inbuf,0) != SMBkeepalive)
1020                         break;
1021         }
1022
1023         DEBUG(10,("read_smb_length: got smb length of %lu\n",
1024                   (unsigned long)len));
1025
1026         return len;
1027 }
1028
1029 /****************************************************************************
1030  Read an smb from a fd. Note that the buffer *MUST* be of size
1031  BUFFER_SIZE+SAFETY_MARGIN.
1032  The timeout is in milliseconds.
1033  This function will return on receipt of a session keepalive packet.
1034  maxlen is the max number of bytes to return, not including the 4 byte
1035  length. If zero it means BUFFER_SIZE+SAFETY_MARGIN limit.
1036  Doesn't check the MAC on signed packets.
1037 ****************************************************************************/
1038
1039 ssize_t receive_smb_raw(int fd,
1040                         char *buffer,
1041                         unsigned int timeout,
1042                         size_t maxlen)
1043 {
1044         ssize_t len,ret;
1045
1046         smb_read_error = 0;
1047
1048         len = read_smb_length_return_keepalive(fd,buffer,timeout);
1049         if (len < 0) {
1050                 DEBUG(10,("receive_smb_raw: length < 0!\n"));
1051
1052                 /*
1053                  * Correct fix. smb_read_error may have already been
1054                  * set. Only set it here if not already set. Global
1055                  * variables still suck :-). JRA.
1056                  */
1057
1058                 if (smb_read_error == 0)
1059                         smb_read_error = READ_ERROR;
1060                 return -1;
1061         }
1062
1063         /*
1064          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
1065          * of header. Don't print the error if this fits.... JRA.
1066          */
1067
1068         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
1069                 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
1070                                         (unsigned long)len));
1071                 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
1072
1073                         /*
1074                          * Correct fix. smb_read_error may have already been
1075                          * set. Only set it here if not already set. Global
1076                          * variables still suck :-). JRA.
1077                          */
1078
1079                         if (smb_read_error == 0)
1080                                 smb_read_error = READ_ERROR;
1081                         return -1;
1082                 }
1083         }
1084
1085         if(len > 0) {
1086                 if (maxlen) {
1087                         len = MIN(len,maxlen);
1088                 }
1089
1090                 if (timeout > 0) {
1091                         ret = read_socket_with_timeout(fd,
1092                                         buffer+4,
1093                                         len,
1094                                         len,
1095                                         timeout);
1096                 } else {
1097                         ret = read_data(fd,buffer+4,len);
1098                 }
1099
1100                 if (ret != len) {
1101                         if (smb_read_error == 0) {
1102                                 smb_read_error = READ_ERROR;
1103                         }
1104                         return -1;
1105                 }
1106
1107                 /* not all of samba3 properly checks for packet-termination
1108                  * of strings. This ensures that we don't run off into
1109                  * empty space. */
1110                 SSVAL(buffer+4,len, 0);
1111         }
1112
1113         return len;
1114 }
1115
1116 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
1117                                       char **buffer, unsigned int timeout)
1118 {
1119         char lenbuf[4];
1120         ssize_t len,ret;
1121
1122         smb_read_error = 0;
1123
1124         len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
1125         if (len < 0) {
1126                 DEBUG(10,("receive_smb_raw: length < 0!\n"));
1127
1128                 /*
1129                  * Correct fix. smb_read_error may have already been
1130                  * set. Only set it here if not already set. Global
1131                  * variables still suck :-). JRA.
1132                  */
1133
1134                 if (smb_read_error == 0)
1135                         smb_read_error = READ_ERROR;
1136                 return -1;
1137         }
1138
1139         /*
1140          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
1141          * of header. Don't print the error if this fits.... JRA.
1142          */
1143
1144         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
1145                 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
1146                                         (unsigned long)len));
1147                 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
1148
1149                         /*
1150                          * Correct fix. smb_read_error may have already been
1151                          * set. Only set it here if not already set. Global
1152                          * variables still suck :-). JRA.
1153                          */
1154
1155                         if (smb_read_error == 0)
1156                                 smb_read_error = READ_ERROR;
1157                         return -1;
1158                 }
1159         }
1160
1161         /*
1162          * The +4 here can't wrap, we've checked the length above already.
1163          */
1164
1165         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
1166
1167         if (*buffer == NULL) {
1168                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
1169                           (int)len+4));
1170                 if (smb_read_error == 0)
1171                         smb_read_error = READ_ERROR;
1172                 return -1;
1173         }
1174
1175         memcpy(*buffer, lenbuf, sizeof(lenbuf));
1176
1177         if(len > 0) {
1178                 if (timeout > 0) {
1179                         ret = read_socket_with_timeout(fd,(*buffer)+4, len,
1180                                                        len, timeout);
1181                 } else {
1182                         ret = read_data(fd, (*buffer)+4, len);
1183                 }
1184
1185                 if (ret != len) {
1186                         if (smb_read_error == 0) {
1187                                 smb_read_error = READ_ERROR;
1188                         }
1189                         return -1;
1190                 }
1191         }
1192
1193         return len + 4;
1194 }
1195
1196 /****************************************************************************
1197  Wrapper for receive_smb_raw().
1198  Checks the MAC on signed packets.
1199 ****************************************************************************/
1200
1201 bool receive_smb(int fd, char *buffer, unsigned int timeout)
1202 {
1203         if (receive_smb_raw(fd, buffer, timeout, 0) < 0) {
1204                 return false;
1205         }
1206
1207         /* Check the incoming SMB signature. */
1208         if (!srv_check_sign_mac(buffer, true)) {
1209                 DEBUG(0, ("receive_smb: SMB Signature verification "
1210                         "failed on incoming packet!\n"));
1211                 if (smb_read_error == 0) {
1212                         smb_read_error = READ_BAD_SIG;
1213                 }
1214                 return false;
1215         }
1216
1217         return true;
1218 }
1219
1220 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
1221                            unsigned int timeout)
1222 {
1223         ssize_t len;
1224
1225         len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
1226
1227         if (len < 0) {
1228                 return -1;
1229         }
1230
1231         /* Check the incoming SMB signature. */
1232         if (!srv_check_sign_mac(*buffer, true)) {
1233                 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
1234                           "incoming packet!\n"));
1235                 if (smb_read_error == 0) {
1236                         smb_read_error = READ_BAD_SIG;
1237                 }
1238                 return -1;
1239         }
1240
1241         return len;
1242 }
1243
1244 /****************************************************************************
1245  Send an smb to a fd.
1246 ****************************************************************************/
1247
1248 bool send_smb(int fd, char *buffer)
1249 {
1250         size_t len;
1251         size_t nwritten=0;
1252         ssize_t ret;
1253
1254         /* Sign the outgoing packet if required. */
1255         srv_calculate_sign_mac(buffer);
1256
1257         len = smb_len(buffer) + 4;
1258
1259         while (nwritten < len) {
1260                 ret = write_data(fd,buffer+nwritten,len - nwritten);
1261                 if (ret <= 0) {
1262                         DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
1263                                 (int)len,(int)ret, strerror(errno) ));
1264                         return false;
1265                 }
1266                 nwritten += ret;
1267         }
1268
1269         return true;
1270 }
1271
1272 /****************************************************************************
1273  Open a socket of the specified type, port, and address for incoming data.
1274 ****************************************************************************/
1275
1276 int open_socket_in(int type,
1277                 int port,
1278                 int dlevel,
1279                 uint32 socket_addr, /* NETWORK BYTE ORDER */
1280                 bool rebind )
1281 {
1282         struct sockaddr_in sock;
1283         int res;
1284
1285         memset( (char *)&sock, '\0', sizeof(sock) );
1286
1287 #ifdef HAVE_SOCK_SIN_LEN
1288         sock.sin_len         = sizeof(sock);
1289 #endif
1290         sock.sin_port        = htons( port );
1291         sock.sin_family      = AF_INET;
1292         sock.sin_addr.s_addr = socket_addr;
1293
1294         res = socket( AF_INET, type, 0 );
1295         if( res == -1 ) {
1296                 if( DEBUGLVL(0) ) {
1297                         dbgtext( "open_socket_in(): socket() call failed: " );
1298                         dbgtext( "%s\n", strerror( errno ) );
1299                 }
1300                 return -1;
1301         }
1302
1303         /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
1304         {
1305                 int val = rebind ? 1 : 0;
1306                 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
1307                                         (char *)&val,sizeof(val)) == -1 ) {
1308                         if( DEBUGLVL( dlevel ) ) {
1309                                 dbgtext( "open_socket_in(): setsockopt: " );
1310                                 dbgtext( "SO_REUSEADDR = %s ",
1311                                                 val?"true":"false" );
1312                                 dbgtext( "on port %d failed ", port );
1313                                 dbgtext( "with error = %s\n", strerror(errno) );
1314                         }
1315                 }
1316 #ifdef SO_REUSEPORT
1317                 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
1318                                         (char *)&val,sizeof(val)) == -1 ) {
1319                         if( DEBUGLVL( dlevel ) ) {
1320                                 dbgtext( "open_socket_in(): setsockopt: ");
1321                                 dbgtext( "SO_REUSEPORT = %s ",
1322                                                 val?"true":"false" );
1323                                 dbgtext( "on port %d failed ", port );
1324                                 dbgtext( "with error = %s\n", strerror(errno) );
1325                         }
1326                 }
1327 #endif /* SO_REUSEPORT */
1328         }
1329
1330         /* now we've got a socket - we need to bind it */
1331         if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
1332                 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
1333                                 port == SMB_PORT2 || port == NMB_PORT) ) {
1334                         dbgtext( "bind failed on port %d ", port );
1335                         dbgtext( "socket_addr = %s.\n",
1336                                         inet_ntoa( sock.sin_addr ) );
1337                         dbgtext( "Error = %s\n", strerror(errno) );
1338                 }
1339                 close( res );
1340                 return -1;
1341         }
1342
1343         DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
1344
1345         return( res );
1346  }
1347
1348 /****************************************************************************
1349  Create an outgoing socket. timeout is in milliseconds.
1350 **************************************************************************/
1351
1352 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
1353 {
1354         struct sockaddr_in sock_out;
1355         int res,ret;
1356         int connect_loop = 10;
1357         int increment = 10;
1358
1359         /* create a socket to write to */
1360         res = socket(PF_INET, type, 0);
1361         if (res == -1) {
1362                 DEBUG(0,("socket error (%s)\n", strerror(errno)));
1363                 return -1;
1364         }
1365
1366         if (type != SOCK_STREAM)
1367                 return(res);
1368
1369         memset((char *)&sock_out,'\0',sizeof(sock_out));
1370         putip((char *)&sock_out.sin_addr,(char *)addr);
1371
1372         sock_out.sin_port = htons( port );
1373         sock_out.sin_family = PF_INET;
1374
1375         /* set it non-blocking */
1376         set_blocking(res,false);
1377
1378         DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
1379
1380         /* and connect it to the destination */
1381   connect_again:
1382
1383         ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
1384
1385         /* Some systems return EAGAIN when they mean EINPROGRESS */
1386         if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1387                         errno == EAGAIN) && (connect_loop < timeout) ) {
1388                 smb_msleep(connect_loop);
1389                 timeout -= connect_loop;
1390                 connect_loop += increment;
1391                 if (increment < 250) {
1392                         /* After 8 rounds we end up at a max of 255 msec */
1393                         increment *= 1.5;
1394                 }
1395                 goto connect_again;
1396         }
1397
1398         if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1399                         errno == EAGAIN)) {
1400                 DEBUG(1,("timeout connecting to %s:%d\n",
1401                                         inet_ntoa(*addr),port));
1402                 close(res);
1403                 return -1;
1404         }
1405
1406 #ifdef EISCONN
1407         if (ret < 0 && errno == EISCONN) {
1408                 errno = 0;
1409                 ret = 0;
1410         }
1411 #endif
1412
1413         if (ret < 0) {
1414                 DEBUG(2,("error connecting to %s:%d (%s)\n",
1415                                 inet_ntoa(*addr),port,strerror(errno)));
1416                 close(res);
1417                 return -1;
1418         }
1419
1420         /* set it blocking again */
1421         set_blocking(res,true);
1422
1423         return res;
1424 }
1425
1426 /****************************************************************************
1427  Create an outgoing TCP socket to any of the addrs. This is for
1428  simultaneous connects to port 445 and 139 of a host or even a variety
1429  of DC's all of which are equivalent for our purposes.
1430 **************************************************************************/
1431
1432 bool open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1433                          int timeout, int *fd_index, int *fd)
1434 {
1435         int i, resulting_index, res;
1436         int *sockets;
1437         bool good_connect;
1438
1439         fd_set r_fds, wr_fds;
1440         struct timeval tv;
1441         int maxfd;
1442
1443         int connect_loop = 10000; /* 10 milliseconds */
1444
1445         timeout *= 1000;        /* convert to microseconds */
1446
1447         sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1448
1449         if (sockets == NULL)
1450                 return false;
1451
1452         resulting_index = -1;
1453
1454         for (i=0; i<num_addrs; i++)
1455                 sockets[i] = -1;
1456
1457         for (i=0; i<num_addrs; i++) {
1458                 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1459                 if (sockets[i] < 0)
1460                         goto done;
1461                 set_blocking(sockets[i], false);
1462         }
1463
1464  connect_again:
1465         good_connect = false;
1466
1467         for (i=0; i<num_addrs; i++) {
1468
1469                 if (sockets[i] == -1)
1470                         continue;
1471
1472                 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1473                             sizeof(*addrs)) == 0) {
1474                         /* Rather unlikely as we are non-blocking, but it
1475                          * might actually happen. */
1476                         resulting_index = i;
1477                         goto done;
1478                 }
1479
1480                 if (errno == EINPROGRESS || errno == EALREADY ||
1481 #ifdef EISCONN
1482                         errno == EISCONN ||
1483 #endif
1484                     errno == EAGAIN || errno == EINTR) {
1485                         /* These are the error messages that something is
1486                            progressing. */
1487                         good_connect = true;
1488                 } else if (errno != 0) {
1489                         /* There was a direct error */
1490                         close(sockets[i]);
1491                         sockets[i] = -1;
1492                 }
1493         }
1494
1495         if (!good_connect) {
1496                 /* All of the connect's resulted in real error conditions */
1497                 goto done;
1498         }
1499
1500         /* Lets see if any of the connect attempts succeeded */
1501
1502         maxfd = 0;
1503         FD_ZERO(&wr_fds);
1504         FD_ZERO(&r_fds);
1505
1506         for (i=0; i<num_addrs; i++) {
1507                 if (sockets[i] == -1)
1508                         continue;
1509                 FD_SET(sockets[i], &wr_fds);
1510                 FD_SET(sockets[i], &r_fds);
1511                 if (sockets[i]>maxfd)
1512                         maxfd = sockets[i];
1513         }
1514
1515         tv.tv_sec = 0;
1516         tv.tv_usec = connect_loop;
1517
1518         res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1519
1520         if (res < 0)
1521                 goto done;
1522
1523         if (res == 0)
1524                 goto next_round;
1525
1526         for (i=0; i<num_addrs; i++) {
1527
1528                 if (sockets[i] == -1)
1529                         continue;
1530
1531                 /* Stevens, Network Programming says that if there's a
1532                  * successful connect, the socket is only writable. Upon an
1533                  * error, it's both readable and writable. */
1534
1535                 if (FD_ISSET(sockets[i], &r_fds) &&
1536                     FD_ISSET(sockets[i], &wr_fds)) {
1537                         /* readable and writable, so it's an error */
1538                         close(sockets[i]);
1539                         sockets[i] = -1;
1540                         continue;
1541                 }
1542
1543                 if (!FD_ISSET(sockets[i], &r_fds) &&
1544                     FD_ISSET(sockets[i], &wr_fds)) {
1545                         /* Only writable, so it's connected */
1546                         resulting_index = i;
1547                         goto done;
1548                 }
1549         }
1550
1551  next_round:
1552
1553         timeout -= connect_loop;
1554         if (timeout <= 0)
1555                 goto done;
1556         connect_loop *= 1.5;
1557         if (connect_loop > timeout)
1558                 connect_loop = timeout;
1559         goto connect_again;
1560
1561  done:
1562         for (i=0; i<num_addrs; i++) {
1563                 if (i == resulting_index)
1564                         continue;
1565                 if (sockets[i] >= 0)
1566                         close(sockets[i]);
1567         }
1568
1569         if (resulting_index >= 0) {
1570                 *fd_index = resulting_index;
1571                 *fd = sockets[*fd_index];
1572                 set_blocking(*fd, true);
1573         }
1574
1575         free(sockets);
1576
1577         return (resulting_index >= 0);
1578 }
1579 /****************************************************************************
1580  Open a connected UDP socket to host on port
1581 **************************************************************************/
1582
1583 int open_udp_socket(const char *host, int port)
1584 {
1585         int type = SOCK_DGRAM;
1586         struct sockaddr_in sock_out;
1587         int res;
1588         struct in_addr *addr;
1589
1590         addr = interpret_addr2(host);
1591
1592         res = socket(PF_INET, type, 0);
1593         if (res == -1) {
1594                 return -1;
1595         }
1596
1597         memset((char *)&sock_out,'\0',sizeof(sock_out));
1598         putip((char *)&sock_out.sin_addr,(char *)addr);
1599         sock_out.sin_port = htons(port);
1600         sock_out.sin_family = PF_INET;
1601
1602         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1603                 close(res);
1604                 return -1;
1605         }
1606
1607         return res;
1608 }
1609
1610 /*******************************************************************
1611  Return the IP addr of the remote end of a socket as a string.
1612  Optionally return the struct sockaddr_storage.
1613  ******************************************************************/
1614
1615 static const char *get_peer_addr_internal(int fd,
1616                                 struct sockaddr_storage *pss,
1617                                 socklen_t *plength)
1618 {
1619         struct sockaddr_storage ss;
1620         socklen_t length = sizeof(ss);
1621         static char addr_buf[INET6_ADDRSTRLEN];
1622
1623         safe_strcpy(addr_buf,"0.0.0.0",sizeof(addr_buf)-1);
1624
1625         if (fd == -1) {
1626                 return addr_buf;
1627         }
1628
1629         if (pss == NULL) {
1630                 pss = &ss;
1631         }
1632         if (plength == NULL) {
1633                 plength = &length;
1634         }
1635
1636         if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1637                 DEBUG(0,("getpeername failed. Error was %s\n",
1638                                         strerror(errno) ));
1639                 return addr_buf;
1640         }
1641
1642         print_sockaddr(addr_buf,
1643                         sizeof(addr_buf),
1644                         pss,
1645                         *plength);
1646         return addr_buf;
1647 }
1648
1649
1650 /*******************************************************************
1651  Matchname - determine if host name matches IP address. Used to
1652  confirm a hostname lookup to prevent spoof attacks.
1653 ******************************************************************/
1654
1655 static bool matchname(const char *remotehost,
1656                 const struct sockaddr_storage *pss,
1657                 socklen_t len)
1658 {
1659         struct addrinfo *res = NULL;
1660         struct addrinfo *ailist = NULL;
1661         char addr_buf[INET6_ADDRSTRLEN];
1662         bool ret = interpret_string_addr_internal(&ailist,
1663                         remotehost,
1664                         AI_ADDRCONFIG|AI_CANONNAME);
1665
1666         if (!ret || ailist == NULL) {
1667                 DEBUG(3,("matchname: getaddrinfo failed for "
1668                         "name %s [%s]\n",
1669                         remotehost,
1670                         gai_strerror(ret) ));
1671                 return false;
1672         }
1673
1674         /*
1675          * Make sure that getaddrinfo() returns the "correct" host name.
1676          */
1677
1678         if (ailist->ai_canonname == NULL ||
1679                 (!strequal(remotehost, ailist->ai_canonname) &&
1680                  !strequal(remotehost, "localhost"))) {
1681                 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1682                          remotehost,
1683                          ailist->ai_canonname ?
1684                                  ailist->ai_canonname : "(NULL)"));
1685                 freeaddrinfo(ailist);
1686                 return false;
1687         }
1688
1689         /* Look up the host address in the address list we just got. */
1690         for (res = ailist; res; res = res->ai_next) {
1691                 if (!res->ai_addr) {
1692                         continue;
1693                 }
1694                 if (addr_equal((const struct sockaddr_storage *)res->ai_addr,
1695                                         pss)) {
1696                         freeaddrinfo(ailist);
1697                         return true;
1698                 }
1699         }
1700
1701         /*
1702          * The host name does not map to the original host address. Perhaps
1703          * someone has compromised a name server. More likely someone botched
1704          * it, but that could be dangerous, too.
1705          */
1706
1707         DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1708                 print_sockaddr(addr_buf,
1709                         sizeof(addr_buf),
1710                         pss,
1711                         len),
1712                  ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1713
1714         if (ailist) {
1715                 freeaddrinfo(ailist);
1716         }
1717         return false;
1718 }
1719
1720 /*******************************************************************
1721  Return the DNS name of the remote end of a socket.
1722 ******************************************************************/
1723
1724 const char *get_peer_name(int fd, bool force_lookup)
1725 {
1726         static fstring addr_buf;
1727         static pstring name_buf;
1728         struct sockaddr_storage ss;
1729         socklen_t length = sizeof(ss);
1730         const char *p;
1731         int ret;
1732         pstring tmp_name;
1733
1734         /* reverse lookups can be *very* expensive, and in many
1735            situations won't work because many networks don't link dhcp
1736            with dns. To avoid the delay we avoid the lookup if
1737            possible */
1738         if (!lp_hostname_lookups() && (force_lookup == false)) {
1739                 return get_peer_addr(fd);
1740         }
1741
1742         p = get_peer_addr_internal(fd, &ss, &length);
1743
1744         /* it might be the same as the last one - save some DNS work */
1745         if (strcmp(p, addr_buf) == 0) {
1746                 return name_buf;
1747         }
1748
1749         pstrcpy(name_buf,"UNKNOWN");
1750         if (fd == -1) {
1751                 return name_buf;
1752         }
1753
1754         fstrcpy(addr_buf, p);
1755
1756         /* Look up the remote host name. */
1757         ret = getnameinfo((struct sockaddr *)&ss,
1758                         length,
1759                         name_buf,
1760                         sizeof(name_buf),
1761                         NULL,
1762                         0,
1763                         NI_NUMERICHOST);
1764
1765         if (ret) {
1766                 DEBUG(1,("get_peer_name: getnameinfo failed "
1767                         "for %s with error %s\n",
1768                         p,
1769                         gai_strerror(ret)));
1770                 pstrcpy(name_buf, p);
1771         } else {
1772                 if (!matchname(name_buf, &ss, length)) {
1773                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1774                         pstrcpy(name_buf,"UNKNOWN");
1775                 }
1776         }
1777
1778         /* can't pass the same source and dest strings in when you
1779            use --enable-developer or the clobber_region() call will
1780            get you */
1781
1782         pstrcpy(tmp_name, name_buf );
1783         alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1784         if (strstr(name_buf,"..")) {
1785                 pstrcpy(name_buf, "UNKNOWN");
1786         }
1787
1788         return name_buf;
1789 }
1790
1791 /*******************************************************************
1792  Return the IP addr of the remote end of a socket as a string.
1793  ******************************************************************/
1794
1795 const char *get_peer_addr(int fd)
1796 {
1797         return get_peer_addr_internal(fd, NULL, NULL);
1798 }
1799
1800 /*******************************************************************
1801  Create protected unix domain socket.
1802
1803  Some unixes cannot set permissions on a ux-dom-sock, so we
1804  have to make sure that the directory contains the protection
1805  permissions instead.
1806  ******************************************************************/
1807
1808 int create_pipe_sock(const char *socket_dir,
1809                      const char *socket_name,
1810                      mode_t dir_perms)
1811 {
1812 #ifdef HAVE_UNIXSOCKET
1813         struct sockaddr_un sunaddr;
1814         struct stat st;
1815         int sock;
1816         mode_t old_umask;
1817         pstring path;
1818
1819         old_umask = umask(0);
1820
1821         /* Create the socket directory or reuse the existing one */
1822
1823         if (lstat(socket_dir, &st) == -1) {
1824                 if (errno == ENOENT) {
1825                         /* Create directory */
1826                         if (mkdir(socket_dir, dir_perms) == -1) {
1827                                 DEBUG(0, ("error creating socket directory "
1828                                         "%s: %s\n", socket_dir,
1829                                         strerror(errno)));
1830                                 goto out_umask;
1831                         }
1832                 } else {
1833                         DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1834                                 socket_dir, strerror(errno)));
1835                         goto out_umask;
1836                 }
1837         } else {
1838                 /* Check ownership and permission on existing directory */
1839                 if (!S_ISDIR(st.st_mode)) {
1840                         DEBUG(0, ("socket directory %s isn't a directory\n",
1841                                 socket_dir));
1842                         goto out_umask;
1843                 }
1844                 if ((st.st_uid != sec_initial_uid()) ||
1845                                 ((st.st_mode & 0777) != dir_perms)) {
1846                         DEBUG(0, ("invalid permissions on socket directory "
1847                                 "%s\n", socket_dir));
1848                         goto out_umask;
1849                 }
1850         }
1851
1852         /* Create the socket file */
1853
1854         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1855
1856         if (sock == -1) {
1857                 perror("socket");
1858                 goto out_umask;
1859         }
1860
1861         pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1862
1863         unlink(path);
1864         memset(&sunaddr, 0, sizeof(sunaddr));
1865         sunaddr.sun_family = AF_UNIX;
1866         safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1867
1868         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1869                 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1870                         strerror(errno)));
1871                 goto out_close;
1872         }
1873
1874         if (listen(sock, 5) == -1) {
1875                 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1876                         strerror(errno)));
1877                 goto out_close;
1878         }
1879
1880         umask(old_umask);
1881         return sock;
1882
1883 out_close:
1884         close(sock);
1885
1886 out_umask:
1887         umask(old_umask);
1888         return -1;
1889
1890 #else
1891         DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1892         return -1;
1893 #endif /* HAVE_UNIXSOCKET */
1894 }
1895
1896 /****************************************************************************
1897  Get my own canonical name, including domain.
1898 ****************************************************************************/
1899
1900 bool get_mydnsfullname(fstring my_dnsname)
1901 {
1902         static fstring dnshostname;
1903
1904         if (!*dnshostname) {
1905                 struct addrinfo *res = NULL;
1906                 bool ret;
1907
1908                 /* get my host name */
1909                 if (gethostname(dnshostname, sizeof(dnshostname)) == -1) {
1910                         *dnshostname = '\0';
1911                         DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1912                         return false;
1913                 }
1914
1915                 /* Ensure null termination. */
1916                 dnshostname[sizeof(dnshostname)-1] = '\0';
1917
1918                 ret = interpret_string_addr_internal(&res,
1919                                         dnshostname,
1920                                         AI_ADDRCONFIG|AI_CANONNAME);
1921
1922                 if (!ret || res == NULL) {
1923                         DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1924                                 "name %s [%s]\n",
1925                                 dnshostname,
1926                                 gai_strerror(ret) ));
1927                         return false;
1928                 }
1929
1930                 /*
1931                  * Make sure that getaddrinfo() returns the "correct" host name.
1932                  */
1933
1934                 if (res->ai_canonname == NULL) {
1935                         DEBUG(3,("get_mydnsfullname: failed to get "
1936                                 "canonical name for %s\n",
1937                                 dnshostname));
1938                         freeaddrinfo(res);
1939                         return false;
1940                 }
1941
1942
1943                 fstrcpy(dnshostname, res->ai_canonname);
1944                 freeaddrinfo(res);
1945         }
1946         fstrcpy(my_dnsname, dnshostname);
1947         return true;
1948 }
1949
1950 /************************************************************
1951  Is this my name ?
1952 ************************************************************/
1953
1954 bool is_myname_or_ipaddr(const char *s)
1955 {
1956         fstring name, dnsname;
1957         char *servername;
1958
1959         if (!s) {
1960                 return false;
1961         }
1962
1963         /* Santize the string from '\\name' */
1964         fstrcpy(name, s);
1965
1966         servername = strrchr_m(name, '\\' );
1967         if (!servername) {
1968                 servername = name;
1969         } else {
1970                 servername++;
1971         }
1972
1973         /* Optimize for the common case */
1974         if (strequal(servername, global_myname())) {
1975                 return true;
1976         }
1977
1978         /* Check for an alias */
1979         if (is_myname(servername)) {
1980                 return true;
1981         }
1982
1983         /* Check for loopback */
1984         if (strequal(servername, "127.0.0.1") ||
1985                         strequal(servername, "::1")) {
1986                 return true;
1987         }
1988
1989         if (strequal(servername, "localhost")) {
1990                 return true;
1991         }
1992
1993         /* Maybe it's my dns name */
1994         if (get_mydnsfullname(dnsname)) {
1995                 if (strequal(servername, dnsname)) {
1996                         return true;
1997                 }
1998         }
1999
2000         /* Handle possible CNAME records - convert to an IP addr. */
2001         if (!is_ipaddress(servername)) {
2002                 /* Use DNS to resolve the name, but only the first address */
2003                 struct sockaddr_storage ss;
2004                 if (interpret_string_addr(&ss, servername,0)) {
2005                         print_sockaddr(name,
2006                                         sizeof(name),
2007                                         &ss,
2008                                         sizeof(ss));
2009                         servername = name;
2010                 }
2011         }
2012
2013         /* Maybe its an IP address? */
2014         if (is_ipaddress(servername)) {
2015                 struct sockaddr_storage ss;
2016                 struct iface_struct nics[MAX_INTERFACES];
2017                 int i, n;
2018
2019                 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
2020                         return false;
2021                 }
2022
2023                 if (is_zero_addr(&ss) || is_loopback_addr(&ss)) {
2024                         return false;
2025                 }
2026
2027                 n = get_interfaces(nics, MAX_INTERFACES);
2028                 for (i=0; i<n; i++) {
2029                         if (addr_equal(&nics[i].ip, &ss)) {
2030                                 return true;
2031                         }
2032                 }
2033         }
2034
2035         /* No match */
2036         return false;
2037 }