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