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