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