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