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