Ignore port when pulling IP addr from struct sockaddr_storage.
[Samba.git] / source / lib / util_sock.c
blob2d72ca852bfdbb49adfb991d04ecd7f49997513b
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
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.
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.
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/>.
22 #include "includes.h"
24 /****************************************************************************
25 Return true if a string could be an IPv4 address.
26 ****************************************************************************/
28 bool is_ipaddress_v4(const char *str)
30 int ret = -1;
31 struct in_addr dest;
33 ret = inet_pton(AF_INET, str, &dest);
34 if (ret > 0) {
35 return true;
37 return false;
40 /****************************************************************************
41 Return true if a string could be an IPv4 or IPv6 address.
42 ****************************************************************************/
44 bool is_ipaddress(const char *str)
46 int ret = -1;
48 #if defined(HAVE_IPV6)
49 if (strchr_m(str, ':')) {
50 char addr[INET6_ADDRSTRLEN];
51 struct in6_addr dest6;
52 const char *sp = str;
53 char *p = strchr_m(str, '%');
56 * Cope with link-local.
57 * This is IP:v6:addr%ifname.
60 if (p && (p > str) && (if_nametoindex(p+1) != 0)) {
61 strlcpy(addr, str,
62 MIN(PTR_DIFF(p,str)+1,
63 sizeof(addr)));
64 sp = addr;
66 ret = inet_pton(AF_INET6, sp, &dest6);
67 if (ret > 0) {
68 return true;
71 #endif
72 return is_ipaddress_v4(str);
75 /****************************************************************************
76 Is a sockaddr_storage a broadcast address ?
77 ****************************************************************************/
79 bool is_broadcast_addr(const struct sockaddr_storage *pss)
81 #if defined(HAVE_IPV6)
82 if (pss->ss_family == AF_INET6) {
83 const struct in6_addr *sin6 =
84 &((const struct sockaddr_in6 *)pss)->sin6_addr;
85 return IN6_IS_ADDR_MULTICAST(sin6);
87 #endif
88 if (pss->ss_family == AF_INET) {
89 uint32_t addr =
90 ntohl(((const struct sockaddr_in *)pss)->sin_addr.s_addr);
91 return addr == INADDR_BROADCAST;
93 return false;
96 /*******************************************************************
97 Wrap getaddrinfo...
98 ******************************************************************/
100 static bool interpret_string_addr_internal(struct addrinfo **ppres,
101 const char *str, int flags)
103 int ret;
104 struct addrinfo hints;
106 memset(&hints, '\0', sizeof(hints));
107 /* By default make sure it supports TCP. */
108 hints.ai_socktype = SOCK_STREAM;
109 hints.ai_flags = flags;
111 /* Linux man page on getaddinfo() says port will be
112 uninitialized when service string in NULL */
114 ret = getaddrinfo(str, NULL,
115 &hints,
116 ppres);
118 if (ret) {
119 DEBUG(3,("interpret_string_addr_internal: getaddrinfo failed "
120 "for name %s [%s]\n",
121 str,
122 gai_strerror(ret) ));
123 return false;
125 return true;
128 /****************************************************************************
129 Interpret an internet address or name into an IP address in 4 byte form.
130 RETURNS IN NETWORK BYTE ORDER (big endian).
131 ****************************************************************************/
133 uint32 interpret_addr(const char *str)
135 uint32 ret;
137 /* If it's in the form of an IP address then
138 * get the lib to interpret it */
139 if (is_ipaddress_v4(str)) {
140 struct in_addr dest;
142 if (inet_pton(AF_INET, str, &dest) <= 0) {
143 /* Error - this shouldn't happen ! */
144 DEBUG(0,("interpret_addr: inet_pton failed "
145 "host %s\n",
146 str));
147 return 0;
149 ret = dest.s_addr; /* NETWORK BYTE ORDER ! */
150 } else {
151 /* Otherwise assume it's a network name of some sort and use
152 getadddrinfo. */
153 struct addrinfo *res = NULL;
154 struct addrinfo *res_list = NULL;
155 if (!interpret_string_addr_internal(&res_list,
156 str,
157 AI_ADDRCONFIG)) {
158 DEBUG(3,("interpret_addr: Unknown host. %s\n",str));
159 return 0;
162 /* Find the first IPv4 address. */
163 for (res = res_list; res; res = res->ai_next) {
164 if (res->ai_family != AF_INET) {
165 continue;
167 if (res->ai_addr == NULL) {
168 continue;
170 break;
172 if(res == NULL) {
173 DEBUG(3,("interpret_addr: host address is "
174 "invalid for host %s\n",str));
175 if (res_list) {
176 freeaddrinfo(res_list);
178 return 0;
180 putip((char *)&ret,
181 &((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr);
182 if (res_list) {
183 freeaddrinfo(res_list);
187 /* This is so bogus - all callers need fixing... JRA. */
188 if (ret == (uint32)-1) {
189 return 0;
192 return ret;
195 /*******************************************************************
196 A convenient addition to interpret_addr().
197 ******************************************************************/
199 struct in_addr *interpret_addr2(struct in_addr *ip, const char *str)
201 uint32 a = interpret_addr(str);
202 ip->s_addr = a;
203 return ip;
206 /*******************************************************************
207 Map a text hostname or IP address (IPv4 or IPv6) into a
208 struct sockaddr_storage.
209 ******************************************************************/
211 bool interpret_string_addr(struct sockaddr_storage *pss,
212 const char *str,
213 int flags)
215 char addr[INET6_ADDRSTRLEN];
216 struct addrinfo *res = NULL;
217 #if defined(HAVE_IPV6)
218 unsigned int scope_id = 0;
220 if (strchr_m(str, ':')) {
221 char *p = strchr_m(str, '%');
224 * Cope with link-local.
225 * This is IP:v6:addr%ifname.
228 if (p && (p > str) && ((scope_id = if_nametoindex(p+1)) != 0)) {
229 strlcpy(addr, str,
230 MIN(PTR_DIFF(p,str)+1,
231 sizeof(addr)));
232 str = addr;
235 #endif
237 zero_addr(pss);
239 if (!interpret_string_addr_internal(&res, str, flags|AI_ADDRCONFIG)) {
240 return false;
242 if (!res) {
243 return false;
245 /* Copy the first sockaddr. */
246 memcpy(pss, res->ai_addr, res->ai_addrlen);
248 #if defined(HAVE_IPV6)
249 if (pss->ss_family == AF_INET6 && scope_id) {
250 struct sockaddr_in6 *ps6 = (struct sockaddr_in6 *)pss;
251 if (IN6_IS_ADDR_LINKLOCAL(&ps6->sin6_addr) &&
252 ps6->sin6_scope_id == 0) {
253 ps6->sin6_scope_id = scope_id;
256 #endif
258 freeaddrinfo(res);
259 return true;
262 /*******************************************************************
263 Check if an IPv7 is 127.0.0.1
264 ******************************************************************/
266 bool is_loopback_ip_v4(struct in_addr ip)
268 struct in_addr a;
269 a.s_addr = htonl(INADDR_LOOPBACK);
270 return(ip.s_addr == a.s_addr);
273 /*******************************************************************
274 Check if a struct sockaddr_storage is the loopback address.
275 ******************************************************************/
277 bool is_loopback_addr(const struct sockaddr_storage *pss)
279 #if defined(HAVE_IPV6)
280 if (pss->ss_family == AF_INET6) {
281 struct in6_addr *pin6 =
282 &((struct sockaddr_in6 *)pss)->sin6_addr;
283 return IN6_IS_ADDR_LOOPBACK(pin6);
285 #endif
286 if (pss->ss_family == AF_INET) {
287 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
288 return is_loopback_ip_v4(*pin);
290 return false;
293 /*******************************************************************
294 Check if an IPv4 is 0.0.0.0.
295 ******************************************************************/
297 bool is_zero_ip_v4(struct in_addr ip)
299 uint32 a;
300 putip((char *)&a,(char *)&ip);
301 return(a == 0);
304 /*******************************************************************
305 Check if a struct sockaddr_storage has an unspecified address.
306 ******************************************************************/
308 bool is_zero_addr(const struct sockaddr_storage *pss)
310 #if defined(HAVE_IPV6)
311 if (pss->ss_family == AF_INET6) {
312 struct in6_addr *pin6 =
313 &((struct sockaddr_in6 *)pss)->sin6_addr;
314 return IN6_IS_ADDR_UNSPECIFIED(pin6);
316 #endif
317 if (pss->ss_family == AF_INET) {
318 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
319 return is_zero_ip_v4(*pin);
321 return false;
324 /*******************************************************************
325 Set an IP to 0.0.0.0.
326 ******************************************************************/
328 void zero_ip_v4(struct in_addr *ip)
330 memset(ip, '\0', sizeof(struct in_addr));
333 /*******************************************************************
334 Set an address to INADDR_ANY.
335 ******************************************************************/
337 void zero_addr(struct sockaddr_storage *pss)
339 memset(pss, '\0', sizeof(*pss));
340 /* Ensure we're at least a valid sockaddr-storage. */
341 pss->ss_family = AF_INET;
344 /*******************************************************************
345 Are two IPs on the same subnet - IPv4 version ?
346 ********************************************************************/
348 bool same_net_v4(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
350 uint32 net1,net2,nmask;
352 nmask = ntohl(mask.s_addr);
353 net1 = ntohl(ip1.s_addr);
354 net2 = ntohl(ip2.s_addr);
356 return((net1 & nmask) == (net2 & nmask));
359 /*******************************************************************
360 Convert an IPv4 struct in_addr to a struct sockaddr_storage.
361 ********************************************************************/
363 void in_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
364 struct in_addr ip)
366 struct sockaddr_in *sa = (struct sockaddr_in *)ss;
367 memset(ss, '\0', sizeof(*ss));
368 ss->ss_family = AF_INET;
369 sa->sin_addr = ip;
372 #if defined(HAVE_IPV6)
373 /*******************************************************************
374 Convert an IPv6 struct in_addr to a struct sockaddr_storage.
375 ********************************************************************/
377 void in6_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
378 struct in6_addr ip)
380 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)ss;
381 memset(ss, '\0', sizeof(*ss));
382 ss->ss_family = AF_INET6;
383 sa->sin6_addr = ip;
385 #endif
387 /*******************************************************************
388 Are two IPs on the same subnet?
389 ********************************************************************/
391 bool same_net(const struct sockaddr_storage *ip1,
392 const struct sockaddr_storage *ip2,
393 const struct sockaddr_storage *mask)
395 if (ip1->ss_family != ip2->ss_family) {
396 /* Never on the same net. */
397 return false;
400 #if defined(HAVE_IPV6)
401 if (ip1->ss_family == AF_INET6) {
402 struct sockaddr_in6 ip1_6 = *(struct sockaddr_in6 *)ip1;
403 struct sockaddr_in6 ip2_6 = *(struct sockaddr_in6 *)ip2;
404 struct sockaddr_in6 mask_6 = *(struct sockaddr_in6 *)mask;
405 char *p1 = (char *)&ip1_6.sin6_addr;
406 char *p2 = (char *)&ip2_6.sin6_addr;
407 char *m = (char *)&mask_6.sin6_addr;
408 int i;
410 for (i = 0; i < sizeof(struct in6_addr); i++) {
411 *p1++ &= *m;
412 *p2++ &= *m;
413 m++;
415 return (memcmp(&ip1_6.sin6_addr,
416 &ip2_6.sin6_addr,
417 sizeof(struct in6_addr)) == 0);
419 #endif
420 if (ip1->ss_family == AF_INET) {
421 return same_net_v4(((const struct sockaddr_in *)ip1)->sin_addr,
422 ((const struct sockaddr_in *)ip2)->sin_addr,
423 ((const struct sockaddr_in *)mask)->sin_addr);
425 return false;
428 /*******************************************************************
429 Are two sockaddr_storage's the same family and address ? Ignore port etc.
430 ********************************************************************/
432 bool addr_equal(const struct sockaddr_storage *ip1,
433 const struct sockaddr_storage *ip2)
435 if (ip1->ss_family != ip2->ss_family) {
436 /* Never the same. */
437 return false;
440 #if defined(HAVE_IPV6)
441 if (ip1->ss_family == AF_INET6) {
442 return (memcmp(&((const struct sockaddr_in6 *)ip1)->sin6_addr,
443 &((const struct sockaddr_in6 *)ip2)->sin6_addr,
444 sizeof(struct in6_addr)) == 0);
446 #endif
447 if (ip1->ss_family == AF_INET) {
448 return (memcmp(&((const struct sockaddr_in *)ip1)->sin_addr,
449 &((const struct sockaddr_in *)ip2)->sin_addr,
450 sizeof(struct in_addr)) == 0);
452 return false;
455 /****************************************************************************
456 Is an IP address the INADDR_ANY or in6addr_any value ?
457 ****************************************************************************/
459 bool is_address_any(const struct sockaddr_storage *psa)
461 #if defined(HAVE_IPV6)
462 if (psa->ss_family == AF_INET6) {
463 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)psa;
464 if (memcmp(&in6addr_any,
465 &si6->sin6_addr,
466 sizeof(in6addr_any)) == 0) {
467 return true;
469 return false;
471 #endif
472 if (psa->ss_family == AF_INET) {
473 struct sockaddr_in *si = (struct sockaddr_in *)psa;
474 if (si->sin_addr.s_addr == INADDR_ANY) {
475 return true;
477 return false;
479 return false;
482 /****************************************************************************
483 Get a port number in host byte order from a sockaddr_storage.
484 ****************************************************************************/
486 uint16_t get_sockaddr_port(const struct sockaddr_storage *pss)
488 uint16_t port = 0;
490 if (pss->ss_family != AF_INET) {
491 #if defined(HAVE_IPV6)
492 /* IPv6 */
493 const struct sockaddr_in6 *sa6 =
494 (const struct sockaddr_in6 *)pss;
495 port = ntohs(sa6->sin6_port);
496 #endif
497 } else {
498 const struct sockaddr_in *sa =
499 (const struct sockaddr_in *)pss;
500 port = ntohs(sa->sin_port);
502 return port;
505 /****************************************************************************
506 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
507 ****************************************************************************/
509 static char *print_sockaddr_len(char *dest,
510 size_t destlen,
511 const struct sockaddr_storage *psa,
512 socklen_t psalen)
514 if (destlen > 0) {
515 dest[0] = '\0';
517 (void)sys_getnameinfo((const struct sockaddr *)psa,
518 psalen,
519 dest, destlen,
520 NULL, 0,
521 NI_NUMERICHOST);
522 return dest;
525 /****************************************************************************
526 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
527 ****************************************************************************/
529 char *print_sockaddr(char *dest,
530 size_t destlen,
531 const struct sockaddr_storage *psa)
533 return print_sockaddr_len(dest, destlen, psa,
534 sizeof(struct sockaddr_storage));
537 /****************************************************************************
538 Print out a canonical IPv4 or IPv6 address from a struct sockaddr_storage.
539 ****************************************************************************/
541 char *print_canonical_sockaddr(TALLOC_CTX *ctx,
542 const struct sockaddr_storage *pss)
544 char addr[INET6_ADDRSTRLEN];
545 char *dest = NULL;
546 int ret;
548 /* Linux getnameinfo() man pages says port is unitialized if
549 service name is NULL. */
551 ret = sys_getnameinfo((const struct sockaddr *)pss,
552 sizeof(struct sockaddr_storage),
553 addr, sizeof(addr),
554 NULL, 0,
555 NI_NUMERICHOST);
556 if (ret != 0) {
557 return NULL;
559 #if defined(HAVE_IPV6)
560 dest = talloc_asprintf(ctx, "[%s]", addr);
561 #else
562 dest = talloc_asprintf(ctx, "%s", addr);
563 #endif
564 return dest;
567 /****************************************************************************
568 Return the string of an IP address (IPv4 or IPv6).
569 ****************************************************************************/
571 static const char *get_socket_addr(int fd, char *addr_buf, size_t addr_len)
573 struct sockaddr_storage sa;
574 socklen_t length = sizeof(sa);
576 /* Ok, returning a hard coded IPv4 address
577 * is bogus, but it's just as bogus as a
578 * zero IPv6 address. No good choice here.
581 strlcpy(addr_buf, "0.0.0.0", addr_len);
583 if (fd == -1) {
584 return addr_buf;
587 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
588 DEBUG(0,("getsockname failed. Error was %s\n",
589 strerror(errno) ));
590 return addr_buf;
593 return print_sockaddr_len(addr_buf, addr_len, &sa, length);
596 #if 0
597 /* Not currently used. JRA. */
598 /****************************************************************************
599 Return the port number we've bound to on a socket.
600 ****************************************************************************/
602 static int get_socket_port(int fd)
604 struct sockaddr_storage sa;
605 socklen_t length = sizeof(sa);
607 if (fd == -1) {
608 return -1;
611 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
612 DEBUG(0,("getpeername failed. Error was %s\n",
613 strerror(errno) ));
614 return -1;
617 #if defined(HAVE_IPV6)
618 if (sa.ss_family == AF_INET6) {
619 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
621 #endif
622 if (sa.ss_family == AF_INET) {
623 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
625 return -1;
627 #endif
629 void set_sockaddr_port(struct sockaddr_storage *psa, uint16 port)
631 #if defined(HAVE_IPV6)
632 if (psa->ss_family == AF_INET6) {
633 ((struct sockaddr_in6 *)psa)->sin6_port = htons(port);
635 #endif
636 if (psa->ss_family == AF_INET) {
637 ((struct sockaddr_in *)psa)->sin_port = htons(port);
641 const char *client_name(int fd)
643 return get_peer_name(fd,false);
646 const char *client_addr(int fd, char *addr, size_t addrlen)
648 return get_peer_addr(fd,addr,addrlen);
651 const char *client_socket_addr(int fd, char *addr, size_t addr_len)
653 return get_socket_addr(fd, addr, addr_len);
656 #if 0
657 /* Not currently used. JRA. */
658 int client_socket_port(int fd)
660 return get_socket_port(fd);
662 #endif
664 /****************************************************************************
665 Accessor functions to make thread-safe code easier later...
666 ****************************************************************************/
668 void set_smb_read_error(enum smb_read_errors *pre,
669 enum smb_read_errors newerr)
671 if (pre) {
672 *pre = newerr;
676 void cond_set_smb_read_error(enum smb_read_errors *pre,
677 enum smb_read_errors newerr)
679 if (pre && *pre == SMB_READ_OK) {
680 *pre = newerr;
684 /****************************************************************************
685 Determine if a file descriptor is in fact a socket.
686 ****************************************************************************/
688 bool is_a_socket(int fd)
690 int v;
691 socklen_t l;
692 l = sizeof(int);
693 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
696 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
698 typedef struct smb_socket_option {
699 const char *name;
700 int level;
701 int option;
702 int value;
703 int opttype;
704 } smb_socket_option;
706 static const smb_socket_option socket_options[] = {
707 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
708 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
709 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
710 #ifdef TCP_NODELAY
711 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
712 #endif
713 #ifdef TCP_KEEPCNT
714 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
715 #endif
716 #ifdef TCP_KEEPIDLE
717 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
718 #endif
719 #ifdef TCP_KEEPINTVL
720 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
721 #endif
722 #ifdef IPTOS_LOWDELAY
723 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
724 #endif
725 #ifdef IPTOS_THROUGHPUT
726 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
727 #endif
728 #ifdef SO_REUSEPORT
729 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
730 #endif
731 #ifdef SO_SNDBUF
732 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
733 #endif
734 #ifdef SO_RCVBUF
735 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
736 #endif
737 #ifdef SO_SNDLOWAT
738 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
739 #endif
740 #ifdef SO_RCVLOWAT
741 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
742 #endif
743 #ifdef SO_SNDTIMEO
744 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
745 #endif
746 #ifdef SO_RCVTIMEO
747 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
748 #endif
749 #ifdef TCP_FASTACK
750 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
751 #endif
752 {NULL,0,0,0,0}};
754 /****************************************************************************
755 Print socket options.
756 ****************************************************************************/
758 static void print_socket_options(int s)
760 int value;
761 socklen_t vlen = 4;
762 const smb_socket_option *p = &socket_options[0];
764 /* wrapped in if statement to prevent streams
765 * leak in SCO Openserver 5.0 */
766 /* reported on samba-technical --jerry */
767 if ( DEBUGLEVEL >= 5 ) {
768 for (; p->name != NULL; p++) {
769 if (getsockopt(s, p->level, p->option,
770 (void *)&value, &vlen) == -1) {
771 DEBUG(5,("Could not test socket option %s.\n",
772 p->name));
773 } else {
774 DEBUG(5,("socket option %s = %d\n",
775 p->name,value));
781 /****************************************************************************
782 Set user socket options.
783 ****************************************************************************/
785 void set_socket_options(int fd, const char *options)
787 TALLOC_CTX *ctx = talloc_stackframe();
788 char *tok;
790 while (next_token_talloc(ctx, &options, &tok," \t,")) {
791 int ret=0,i;
792 int value = 1;
793 char *p;
794 bool got_value = false;
796 if ((p = strchr_m(tok,'='))) {
797 *p = 0;
798 value = atoi(p+1);
799 got_value = true;
802 for (i=0;socket_options[i].name;i++)
803 if (strequal(socket_options[i].name,tok))
804 break;
806 if (!socket_options[i].name) {
807 DEBUG(0,("Unknown socket option %s\n",tok));
808 continue;
811 switch (socket_options[i].opttype) {
812 case OPT_BOOL:
813 case OPT_INT:
814 ret = setsockopt(fd,socket_options[i].level,
815 socket_options[i].option,
816 (char *)&value,sizeof(int));
817 break;
819 case OPT_ON:
820 if (got_value)
821 DEBUG(0,("syntax error - %s "
822 "does not take a value\n",tok));
825 int on = socket_options[i].value;
826 ret = setsockopt(fd,socket_options[i].level,
827 socket_options[i].option,
828 (char *)&on,sizeof(int));
830 break;
833 if (ret != 0) {
834 DEBUG(0,("Failed to set socket option %s (Error %s)\n",
835 tok, strerror(errno) ));
839 TALLOC_FREE(ctx);
840 print_socket_options(fd);
843 /****************************************************************************
844 Read from a socket.
845 ****************************************************************************/
847 ssize_t read_udp_v4_socket(int fd,
848 char *buf,
849 size_t len,
850 struct sockaddr_storage *psa)
852 ssize_t ret;
853 socklen_t socklen = sizeof(*psa);
854 struct sockaddr_in *si = (struct sockaddr_in *)psa;
856 memset((char *)psa,'\0',socklen);
858 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
859 (struct sockaddr *)psa,&socklen);
860 if (ret <= 0) {
861 /* Don't print a low debug error for a non-blocking socket. */
862 if (errno == EAGAIN) {
863 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
864 } else {
865 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
866 strerror(errno)));
868 return 0;
871 if (psa->ss_family != AF_INET) {
872 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
873 "(not IPv4)\n", (int)psa->ss_family));
874 return 0;
877 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
878 inet_ntoa(si->sin_addr),
879 si->sin_port,
880 (unsigned long)ret));
882 return ret;
885 /****************************************************************************
886 Read data from a socket with a timout in msec.
887 mincount = if timeout, minimum to read before returning
888 maxcount = number to be read.
889 time_out = timeout in milliseconds
890 ****************************************************************************/
892 NTSTATUS read_socket_with_timeout(int fd, char *buf,
893 size_t mincnt, size_t maxcnt,
894 unsigned int time_out,
895 size_t *size_ret)
897 fd_set fds;
898 int selrtn;
899 ssize_t readret;
900 size_t nread = 0;
901 struct timeval timeout;
902 char addr[INET6_ADDRSTRLEN];
904 /* just checking .... */
905 if (maxcnt <= 0)
906 return NT_STATUS_OK;
908 /* Blocking read */
909 if (time_out == 0) {
910 if (mincnt == 0) {
911 mincnt = maxcnt;
914 while (nread < mincnt) {
915 readret = sys_read(fd, buf + nread, maxcnt - nread);
917 if (readret == 0) {
918 DEBUG(5,("read_socket_with_timeout: "
919 "blocking read. EOF from client.\n"));
920 return NT_STATUS_END_OF_FILE;
923 if (readret == -1) {
924 if (fd == get_client_fd()) {
925 /* Try and give an error message
926 * saying what client failed. */
927 DEBUG(0,("read_socket_with_timeout: "
928 "client %s read error = %s.\n",
929 get_peer_addr(fd,addr,sizeof(addr)),
930 strerror(errno) ));
931 } else {
932 DEBUG(0,("read_socket_with_timeout: "
933 "read error = %s.\n",
934 strerror(errno) ));
936 return map_nt_error_from_unix(errno);
938 nread += readret;
940 goto done;
943 /* Most difficult - timeout read */
944 /* If this is ever called on a disk file and
945 mincnt is greater then the filesize then
946 system performance will suffer severely as
947 select always returns true on disk files */
949 /* Set initial timeout */
950 timeout.tv_sec = (time_t)(time_out / 1000);
951 timeout.tv_usec = (long)(1000 * (time_out % 1000));
953 for (nread=0; nread < mincnt; ) {
954 FD_ZERO(&fds);
955 FD_SET(fd,&fds);
957 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
959 /* Check if error */
960 if (selrtn == -1) {
961 /* something is wrong. Maybe the socket is dead? */
962 if (fd == get_client_fd()) {
963 /* Try and give an error message saying
964 * what client failed. */
965 DEBUG(0,("read_socket_with_timeout: timeout "
966 "read for client %s. select error = %s.\n",
967 get_peer_addr(fd,addr,sizeof(addr)),
968 strerror(errno) ));
969 } else {
970 DEBUG(0,("read_socket_with_timeout: timeout "
971 "read. select error = %s.\n",
972 strerror(errno) ));
974 return map_nt_error_from_unix(errno);
977 /* Did we timeout ? */
978 if (selrtn == 0) {
979 DEBUG(10,("read_socket_with_timeout: timeout read. "
980 "select timed out.\n"));
981 return NT_STATUS_IO_TIMEOUT;
984 readret = sys_read(fd, buf+nread, maxcnt-nread);
986 if (readret == 0) {
987 /* we got EOF on the file descriptor */
988 DEBUG(5,("read_socket_with_timeout: timeout read. "
989 "EOF from client.\n"));
990 return NT_STATUS_END_OF_FILE;
993 if (readret == -1) {
994 /* the descriptor is probably dead */
995 if (fd == get_client_fd()) {
996 /* Try and give an error message
997 * saying what client failed. */
998 DEBUG(0,("read_socket_with_timeout: timeout "
999 "read to client %s. read error = %s.\n",
1000 get_peer_addr(fd,addr,sizeof(addr)),
1001 strerror(errno) ));
1002 } else {
1003 DEBUG(0,("read_socket_with_timeout: timeout "
1004 "read. read error = %s.\n",
1005 strerror(errno) ));
1007 return map_nt_error_from_unix(errno);
1010 nread += readret;
1013 done:
1014 /* Return the number we got */
1015 if (size_ret) {
1016 *size_ret = nread;
1018 return NT_STATUS_OK;
1021 /****************************************************************************
1022 Read data from the client, reading exactly N bytes.
1023 ****************************************************************************/
1025 NTSTATUS read_data(int fd, char *buffer, size_t N)
1027 return read_socket_with_timeout(fd, buffer, N, N, 0, NULL);
1030 /****************************************************************************
1031 Write data to a fd.
1032 ****************************************************************************/
1034 ssize_t write_data(int fd, const char *buffer, size_t N)
1036 size_t total=0;
1037 ssize_t ret;
1038 char addr[INET6_ADDRSTRLEN];
1040 while (total < N) {
1041 ret = sys_write(fd,buffer + total,N - total);
1043 if (ret == -1) {
1044 if (fd == get_client_fd()) {
1045 /* Try and give an error message saying
1046 * what client failed. */
1047 DEBUG(0,("write_data: write failure in "
1048 "writing to client %s. Error %s\n",
1049 get_peer_addr(fd,addr,sizeof(addr)),
1050 strerror(errno) ));
1051 } else {
1052 DEBUG(0,("write_data: write failure. "
1053 "Error = %s\n", strerror(errno) ));
1055 return -1;
1058 if (ret == 0) {
1059 return total;
1062 total += ret;
1064 return (ssize_t)total;
1067 /****************************************************************************
1068 Send a keepalive packet (rfc1002).
1069 ****************************************************************************/
1071 bool send_keepalive(int client)
1073 unsigned char buf[4];
1075 buf[0] = SMBkeepalive;
1076 buf[1] = buf[2] = buf[3] = 0;
1078 return(write_data(client,(char *)buf,4) == 4);
1081 /****************************************************************************
1082 Read 4 bytes of a smb packet and return the smb length of the packet.
1083 Store the result in the buffer.
1084 This version of the function will return a length of zero on receiving
1085 a keepalive packet.
1086 Timeout is in milliseconds.
1087 ****************************************************************************/
1089 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
1090 unsigned int timeout,
1091 size_t *len)
1093 int msg_type;
1094 NTSTATUS status;
1096 status = read_socket_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
1098 if (!NT_STATUS_IS_OK(status)) {
1099 return status;
1102 *len = smb_len(inbuf);
1103 msg_type = CVAL(inbuf,0);
1105 if (msg_type == SMBkeepalive) {
1106 DEBUG(5,("Got keepalive packet\n"));
1109 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
1111 return NT_STATUS_OK;
1114 /****************************************************************************
1115 Read 4 bytes of a smb packet and return the smb length of the packet.
1116 Store the result in the buffer. This version of the function will
1117 never return a session keepalive (length of zero).
1118 Timeout is in milliseconds.
1119 ****************************************************************************/
1121 NTSTATUS read_smb_length(int fd, char *inbuf, unsigned int timeout,
1122 size_t *len)
1124 uint8_t msgtype = SMBkeepalive;
1126 while (msgtype == SMBkeepalive) {
1127 NTSTATUS status;
1129 status = read_smb_length_return_keepalive(fd, inbuf, timeout,
1130 len);
1131 if (!NT_STATUS_IS_OK(status)) {
1132 return status;
1135 msgtype = CVAL(inbuf, 0);
1138 DEBUG(10,("read_smb_length: got smb length of %lu\n",
1139 (unsigned long)len));
1141 return NT_STATUS_OK;
1144 /****************************************************************************
1145 Read an smb from a fd. Note that the buffer *MUST* be of size
1146 BUFFER_SIZE+SAFETY_MARGIN.
1147 The timeout is in milliseconds.
1148 This function will return on receipt of a session keepalive packet.
1149 maxlen is the max number of bytes to return, not including the 4 byte
1150 length. If zero it means BUFFER_SIZE+SAFETY_MARGIN limit.
1151 Doesn't check the MAC on signed packets.
1152 ****************************************************************************/
1154 NTSTATUS receive_smb_raw(int fd, char *buffer, unsigned int timeout,
1155 size_t maxlen, size_t *p_len)
1157 size_t len;
1158 NTSTATUS status;
1160 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
1162 if (!NT_STATUS_IS_OK(status)) {
1163 DEBUG(10, ("receive_smb_raw: %s!\n", nt_errstr(status)));
1164 return status;
1168 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
1169 * of header. Don't print the error if this fits.... JRA.
1172 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
1173 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
1174 (unsigned long)len));
1175 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
1176 return NT_STATUS_INVALID_PARAMETER;
1180 if(len > 0) {
1181 if (maxlen) {
1182 len = MIN(len,maxlen);
1185 status = read_socket_with_timeout(
1186 fd, buffer+4, len, len, timeout, &len);
1188 if (!NT_STATUS_IS_OK(status)) {
1189 return status;
1192 /* not all of samba3 properly checks for packet-termination
1193 * of strings. This ensures that we don't run off into
1194 * empty space. */
1195 SSVAL(buffer+4,len, 0);
1198 *p_len = len;
1199 return NT_STATUS_OK;
1202 /****************************************************************************
1203 Open a socket of the specified type, port, and address for incoming data.
1204 ****************************************************************************/
1206 int open_socket_in(int type,
1207 uint16_t port,
1208 int dlevel,
1209 const struct sockaddr_storage *psock,
1210 bool rebind)
1212 struct sockaddr_storage sock;
1213 int res;
1214 socklen_t slen = sizeof(struct sockaddr_in);
1216 sock = *psock;
1218 #if defined(HAVE_IPV6)
1219 if (sock.ss_family == AF_INET6) {
1220 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
1221 slen = sizeof(struct sockaddr_in6);
1223 #endif
1224 if (sock.ss_family == AF_INET) {
1225 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
1228 res = socket(sock.ss_family, type, 0 );
1229 if( res == -1 ) {
1230 if( DEBUGLVL(0) ) {
1231 dbgtext( "open_socket_in(): socket() call failed: " );
1232 dbgtext( "%s\n", strerror( errno ) );
1234 return -1;
1237 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
1239 int val = rebind ? 1 : 0;
1240 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
1241 (char *)&val,sizeof(val)) == -1 ) {
1242 if( DEBUGLVL( dlevel ) ) {
1243 dbgtext( "open_socket_in(): setsockopt: " );
1244 dbgtext( "SO_REUSEADDR = %s ",
1245 val?"true":"false" );
1246 dbgtext( "on port %d failed ", port );
1247 dbgtext( "with error = %s\n", strerror(errno) );
1250 #ifdef SO_REUSEPORT
1251 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
1252 (char *)&val,sizeof(val)) == -1 ) {
1253 if( DEBUGLVL( dlevel ) ) {
1254 dbgtext( "open_socket_in(): setsockopt: ");
1255 dbgtext( "SO_REUSEPORT = %s ",
1256 val?"true":"false");
1257 dbgtext( "on port %d failed ", port);
1258 dbgtext( "with error = %s\n", strerror(errno));
1261 #endif /* SO_REUSEPORT */
1264 /* now we've got a socket - we need to bind it */
1265 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
1266 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
1267 port == SMB_PORT2 || port == NMB_PORT) ) {
1268 char addr[INET6_ADDRSTRLEN];
1269 print_sockaddr(addr, sizeof(addr),
1270 &sock);
1271 dbgtext( "bind failed on port %d ", port);
1272 dbgtext( "socket_addr = %s.\n", addr);
1273 dbgtext( "Error = %s\n", strerror(errno));
1275 close(res);
1276 return -1;
1279 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
1280 return( res );
1283 /****************************************************************************
1284 Create an outgoing socket. timeout is in milliseconds.
1285 **************************************************************************/
1287 int open_socket_out(int type,
1288 const struct sockaddr_storage *pss,
1289 uint16_t port,
1290 int timeout)
1292 char addr[INET6_ADDRSTRLEN];
1293 struct sockaddr_storage sock_out = *pss;
1294 int res,ret;
1295 int connect_loop = 10;
1296 int increment = 10;
1298 /* create a socket to write to */
1299 res = socket(pss->ss_family, type, 0);
1300 if (res == -1) {
1301 DEBUG(0,("socket error (%s)\n", strerror(errno)));
1302 return -1;
1305 if (type != SOCK_STREAM) {
1306 return res;
1309 #if defined(HAVE_IPV6)
1310 if (pss->ss_family == AF_INET6) {
1311 struct sockaddr_in6 *psa6 = (struct sockaddr_in6 *)&sock_out;
1312 psa6->sin6_port = htons(port);
1313 if (psa6->sin6_scope_id == 0 &&
1314 IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1315 setup_linklocal_scope_id(&sock_out);
1318 #endif
1319 if (pss->ss_family == AF_INET) {
1320 struct sockaddr_in *psa = (struct sockaddr_in *)&sock_out;
1321 psa->sin_port = htons(port);
1324 /* set it non-blocking */
1325 set_blocking(res,false);
1327 print_sockaddr(addr, sizeof(addr), &sock_out);
1328 DEBUG(3,("Connecting to %s at port %u\n",
1329 addr,
1330 (unsigned int)port));
1332 /* and connect it to the destination */
1333 connect_again:
1335 ret = sys_connect(res, (struct sockaddr *)&sock_out);
1337 /* Some systems return EAGAIN when they mean EINPROGRESS */
1338 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1339 errno == EAGAIN) && (connect_loop < timeout) ) {
1340 smb_msleep(connect_loop);
1341 timeout -= connect_loop;
1342 connect_loop += increment;
1343 if (increment < 250) {
1344 /* After 8 rounds we end up at a max of 255 msec */
1345 increment *= 1.5;
1347 goto connect_again;
1350 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1351 errno == EAGAIN)) {
1352 DEBUG(1,("timeout connecting to %s:%u\n",
1353 addr,
1354 (unsigned int)port));
1355 close(res);
1356 return -1;
1359 #ifdef EISCONN
1360 if (ret < 0 && errno == EISCONN) {
1361 errno = 0;
1362 ret = 0;
1364 #endif
1366 if (ret < 0) {
1367 DEBUG(2,("error connecting to %s:%d (%s)\n",
1368 addr,
1369 (unsigned int)port,
1370 strerror(errno)));
1371 close(res);
1372 return -1;
1375 /* set it blocking again */
1376 set_blocking(res,true);
1378 return res;
1381 /****************************************************************************
1382 Create an outgoing TCP socket to any of the addrs. This is for
1383 simultaneous connects to port 445 and 139 of a host or even a variety
1384 of DC's all of which are equivalent for our purposes.
1385 **************************************************************************/
1387 bool open_any_socket_out(struct sockaddr_storage *addrs, int num_addrs,
1388 int timeout, int *fd_index, int *fd)
1390 int i, resulting_index, res;
1391 int *sockets;
1392 bool good_connect;
1394 fd_set r_fds, wr_fds;
1395 struct timeval tv;
1396 int maxfd;
1398 int connect_loop = 10000; /* 10 milliseconds */
1400 timeout *= 1000; /* convert to microseconds */
1402 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1404 if (sockets == NULL)
1405 return false;
1407 resulting_index = -1;
1409 for (i=0; i<num_addrs; i++)
1410 sockets[i] = -1;
1412 for (i=0; i<num_addrs; i++) {
1413 sockets[i] = socket(addrs[i].ss_family, SOCK_STREAM, 0);
1414 if (sockets[i] < 0)
1415 goto done;
1416 set_blocking(sockets[i], false);
1419 connect_again:
1420 good_connect = false;
1422 for (i=0; i<num_addrs; i++) {
1423 const struct sockaddr * a =
1424 (const struct sockaddr *)&(addrs[i]);
1426 if (sockets[i] == -1)
1427 continue;
1429 if (sys_connect(sockets[i], a) == 0) {
1430 /* Rather unlikely as we are non-blocking, but it
1431 * might actually happen. */
1432 resulting_index = i;
1433 goto done;
1436 if (errno == EINPROGRESS || errno == EALREADY ||
1437 #ifdef EISCONN
1438 errno == EISCONN ||
1439 #endif
1440 errno == EAGAIN || errno == EINTR) {
1441 /* These are the error messages that something is
1442 progressing. */
1443 good_connect = true;
1444 } else if (errno != 0) {
1445 /* There was a direct error */
1446 close(sockets[i]);
1447 sockets[i] = -1;
1451 if (!good_connect) {
1452 /* All of the connect's resulted in real error conditions */
1453 goto done;
1456 /* Lets see if any of the connect attempts succeeded */
1458 maxfd = 0;
1459 FD_ZERO(&wr_fds);
1460 FD_ZERO(&r_fds);
1462 for (i=0; i<num_addrs; i++) {
1463 if (sockets[i] == -1)
1464 continue;
1465 FD_SET(sockets[i], &wr_fds);
1466 FD_SET(sockets[i], &r_fds);
1467 if (sockets[i]>maxfd)
1468 maxfd = sockets[i];
1471 tv.tv_sec = 0;
1472 tv.tv_usec = connect_loop;
1474 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1476 if (res < 0)
1477 goto done;
1479 if (res == 0)
1480 goto next_round;
1482 for (i=0; i<num_addrs; i++) {
1484 if (sockets[i] == -1)
1485 continue;
1487 /* Stevens, Network Programming says that if there's a
1488 * successful connect, the socket is only writable. Upon an
1489 * error, it's both readable and writable. */
1491 if (FD_ISSET(sockets[i], &r_fds) &&
1492 FD_ISSET(sockets[i], &wr_fds)) {
1493 /* readable and writable, so it's an error */
1494 close(sockets[i]);
1495 sockets[i] = -1;
1496 continue;
1499 if (!FD_ISSET(sockets[i], &r_fds) &&
1500 FD_ISSET(sockets[i], &wr_fds)) {
1501 /* Only writable, so it's connected */
1502 resulting_index = i;
1503 goto done;
1507 next_round:
1509 timeout -= connect_loop;
1510 if (timeout <= 0)
1511 goto done;
1512 connect_loop *= 1.5;
1513 if (connect_loop > timeout)
1514 connect_loop = timeout;
1515 goto connect_again;
1517 done:
1518 for (i=0; i<num_addrs; i++) {
1519 if (i == resulting_index)
1520 continue;
1521 if (sockets[i] >= 0)
1522 close(sockets[i]);
1525 if (resulting_index >= 0) {
1526 *fd_index = resulting_index;
1527 *fd = sockets[*fd_index];
1528 set_blocking(*fd, true);
1531 free(sockets);
1533 return (resulting_index >= 0);
1535 /****************************************************************************
1536 Open a connected UDP socket to host on port
1537 **************************************************************************/
1539 int open_udp_socket(const char *host, int port)
1541 int type = SOCK_DGRAM;
1542 struct sockaddr_in sock_out;
1543 int res;
1544 struct in_addr addr;
1546 (void)interpret_addr2(&addr, host);
1548 res = socket(PF_INET, type, 0);
1549 if (res == -1) {
1550 return -1;
1553 memset((char *)&sock_out,'\0',sizeof(sock_out));
1554 putip((char *)&sock_out.sin_addr,(char *)&addr);
1555 sock_out.sin_port = htons(port);
1556 sock_out.sin_family = PF_INET;
1558 if (sys_connect(res,(struct sockaddr *)&sock_out)) {
1559 close(res);
1560 return -1;
1563 return res;
1566 /*******************************************************************
1567 Return the IP addr of the remote end of a socket as a string.
1568 Optionally return the struct sockaddr_storage.
1569 ******************************************************************/
1571 static const char *get_peer_addr_internal(int fd,
1572 char *addr_buf,
1573 size_t addr_buf_len,
1574 struct sockaddr_storage *pss,
1575 socklen_t *plength)
1577 struct sockaddr_storage ss;
1578 socklen_t length = sizeof(ss);
1580 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1582 if (fd == -1) {
1583 return addr_buf;
1586 if (pss == NULL) {
1587 pss = &ss;
1589 if (plength == NULL) {
1590 plength = &length;
1593 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1594 DEBUG(0,("getpeername failed. Error was %s\n",
1595 strerror(errno) ));
1596 return addr_buf;
1599 print_sockaddr_len(addr_buf,
1600 addr_buf_len,
1601 pss,
1602 *plength);
1603 return addr_buf;
1606 /*******************************************************************
1607 Matchname - determine if host name matches IP address. Used to
1608 confirm a hostname lookup to prevent spoof attacks.
1609 ******************************************************************/
1611 static bool matchname(const char *remotehost,
1612 const struct sockaddr_storage *pss,
1613 socklen_t len)
1615 struct addrinfo *res = NULL;
1616 struct addrinfo *ailist = NULL;
1617 char addr_buf[INET6_ADDRSTRLEN];
1618 bool ret = interpret_string_addr_internal(&ailist,
1619 remotehost,
1620 AI_ADDRCONFIG|AI_CANONNAME);
1622 if (!ret || ailist == NULL) {
1623 DEBUG(3,("matchname: getaddrinfo failed for "
1624 "name %s [%s]\n",
1625 remotehost,
1626 gai_strerror(ret) ));
1627 return false;
1631 * Make sure that getaddrinfo() returns the "correct" host name.
1634 if (ailist->ai_canonname == NULL ||
1635 (!strequal(remotehost, ailist->ai_canonname) &&
1636 !strequal(remotehost, "localhost"))) {
1637 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1638 remotehost,
1639 ailist->ai_canonname ?
1640 ailist->ai_canonname : "(NULL)"));
1641 freeaddrinfo(ailist);
1642 return false;
1645 /* Look up the host address in the address list we just got. */
1646 for (res = ailist; res; res = res->ai_next) {
1647 if (!res->ai_addr) {
1648 continue;
1650 if (addr_equal((const struct sockaddr_storage *)res->ai_addr,
1651 pss)) {
1652 freeaddrinfo(ailist);
1653 return true;
1658 * The host name does not map to the original host address. Perhaps
1659 * someone has compromised a name server. More likely someone botched
1660 * it, but that could be dangerous, too.
1663 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1664 print_sockaddr_len(addr_buf,
1665 sizeof(addr_buf),
1666 pss,
1667 len),
1668 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1670 if (ailist) {
1671 freeaddrinfo(ailist);
1673 return false;
1676 /*******************************************************************
1677 Deal with the singleton cache.
1678 ******************************************************************/
1680 struct name_addr_pair {
1681 struct sockaddr_storage ss;
1682 const char *name;
1685 /*******************************************************************
1686 Lookup a name/addr pair. Returns memory allocated from memcache.
1687 ******************************************************************/
1689 static bool lookup_nc(struct name_addr_pair *nc)
1691 DATA_BLOB tmp;
1693 ZERO_STRUCTP(nc);
1695 if (!memcache_lookup(
1696 NULL, SINGLETON_CACHE,
1697 data_blob_string_const("get_peer_name"),
1698 &tmp)) {
1699 return false;
1702 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1703 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1704 return true;
1707 /*******************************************************************
1708 Save a name/addr pair.
1709 ******************************************************************/
1711 static void store_nc(const struct name_addr_pair *nc)
1713 DATA_BLOB tmp;
1714 size_t namelen = strlen(nc->name);
1716 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1717 if (!tmp.data) {
1718 return;
1720 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1721 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1723 memcache_add(NULL, SINGLETON_CACHE,
1724 data_blob_string_const("get_peer_name"),
1725 tmp);
1726 data_blob_free(&tmp);
1729 /*******************************************************************
1730 Return the DNS name of the remote end of a socket.
1731 ******************************************************************/
1733 const char *get_peer_name(int fd, bool force_lookup)
1735 struct name_addr_pair nc;
1736 char addr_buf[INET6_ADDRSTRLEN];
1737 struct sockaddr_storage ss;
1738 socklen_t length = sizeof(ss);
1739 const char *p;
1740 int ret;
1741 char name_buf[MAX_DNS_NAME_LENGTH];
1742 char tmp_name[MAX_DNS_NAME_LENGTH];
1744 /* reverse lookups can be *very* expensive, and in many
1745 situations won't work because many networks don't link dhcp
1746 with dns. To avoid the delay we avoid the lookup if
1747 possible */
1748 if (!lp_hostname_lookups() && (force_lookup == false)) {
1749 length = sizeof(nc.ss);
1750 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1751 &nc.ss, &length);
1752 store_nc(&nc);
1753 lookup_nc(&nc);
1754 return nc.name ? nc.name : "UNKNOWN";
1757 lookup_nc(&nc);
1759 memset(&ss, '\0', sizeof(ss));
1760 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), &ss, &length);
1762 /* it might be the same as the last one - save some DNS work */
1763 if (addr_equal(&ss, &nc.ss)) {
1764 return nc.name ? nc.name : "UNKNOWN";
1767 /* Not the same. We need to lookup. */
1768 if (fd == -1) {
1769 return "UNKNOWN";
1772 /* Look up the remote host name. */
1773 ret = sys_getnameinfo((struct sockaddr *)&ss,
1774 length,
1775 name_buf,
1776 sizeof(name_buf),
1777 NULL,
1781 if (ret) {
1782 DEBUG(1,("get_peer_name: getnameinfo failed "
1783 "for %s with error %s\n",
1785 gai_strerror(ret)));
1786 strlcpy(name_buf, p, sizeof(name_buf));
1787 } else {
1788 if (!matchname(name_buf, &ss, length)) {
1789 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1790 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1794 /* can't pass the same source and dest strings in when you
1795 use --enable-developer or the clobber_region() call will
1796 get you */
1798 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1799 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1800 if (strstr(name_buf,"..")) {
1801 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1804 nc.name = name_buf;
1805 nc.ss = ss;
1807 store_nc(&nc);
1808 lookup_nc(&nc);
1809 return nc.name ? nc.name : "UNKNOWN";
1812 /*******************************************************************
1813 Return the IP addr of the remote end of a socket as a string.
1814 ******************************************************************/
1816 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1818 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1821 /*******************************************************************
1822 Create protected unix domain socket.
1824 Some unixes cannot set permissions on a ux-dom-sock, so we
1825 have to make sure that the directory contains the protection
1826 permissions instead.
1827 ******************************************************************/
1829 int create_pipe_sock(const char *socket_dir,
1830 const char *socket_name,
1831 mode_t dir_perms)
1833 #ifdef HAVE_UNIXSOCKET
1834 struct sockaddr_un sunaddr;
1835 struct stat st;
1836 int sock;
1837 mode_t old_umask;
1838 char *path = NULL;
1840 old_umask = umask(0);
1842 /* Create the socket directory or reuse the existing one */
1844 if (lstat(socket_dir, &st) == -1) {
1845 if (errno == ENOENT) {
1846 /* Create directory */
1847 if (mkdir(socket_dir, dir_perms) == -1) {
1848 DEBUG(0, ("error creating socket directory "
1849 "%s: %s\n", socket_dir,
1850 strerror(errno)));
1851 goto out_umask;
1853 } else {
1854 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1855 socket_dir, strerror(errno)));
1856 goto out_umask;
1858 } else {
1859 /* Check ownership and permission on existing directory */
1860 if (!S_ISDIR(st.st_mode)) {
1861 DEBUG(0, ("socket directory %s isn't a directory\n",
1862 socket_dir));
1863 goto out_umask;
1865 if ((st.st_uid != sec_initial_uid()) ||
1866 ((st.st_mode & 0777) != dir_perms)) {
1867 DEBUG(0, ("invalid permissions on socket directory "
1868 "%s\n", socket_dir));
1869 goto out_umask;
1873 /* Create the socket file */
1875 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1877 if (sock == -1) {
1878 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1879 strerror(errno) ));
1880 goto out_close;
1883 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1884 goto out_close;
1887 unlink(path);
1888 memset(&sunaddr, 0, sizeof(sunaddr));
1889 sunaddr.sun_family = AF_UNIX;
1890 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1892 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1893 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1894 strerror(errno)));
1895 goto out_close;
1898 if (listen(sock, 5) == -1) {
1899 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1900 strerror(errno)));
1901 goto out_close;
1904 SAFE_FREE(path);
1906 umask(old_umask);
1907 return sock;
1909 out_close:
1910 SAFE_FREE(path);
1911 if (sock != -1)
1912 close(sock);
1914 out_umask:
1915 umask(old_umask);
1916 return -1;
1918 #else
1919 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1920 return -1;
1921 #endif /* HAVE_UNIXSOCKET */
1924 /****************************************************************************
1925 Get my own canonical name, including domain.
1926 ****************************************************************************/
1928 const char *get_mydnsfullname(void)
1930 struct addrinfo *res = NULL;
1931 char my_hostname[HOST_NAME_MAX];
1932 bool ret;
1933 DATA_BLOB tmp;
1935 if (memcache_lookup(NULL, SINGLETON_CACHE,
1936 data_blob_string_const("get_mydnsfullname"),
1937 &tmp)) {
1938 SMB_ASSERT(tmp.length > 0);
1939 return (const char *)tmp.data;
1942 /* get my host name */
1943 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1944 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1945 return NULL;
1948 /* Ensure null termination. */
1949 my_hostname[sizeof(my_hostname)-1] = '\0';
1951 ret = interpret_string_addr_internal(&res,
1952 my_hostname,
1953 AI_ADDRCONFIG|AI_CANONNAME);
1955 if (!ret || res == NULL) {
1956 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1957 "name %s [%s]\n",
1958 my_hostname,
1959 gai_strerror(ret) ));
1960 return NULL;
1964 * Make sure that getaddrinfo() returns the "correct" host name.
1967 if (res->ai_canonname == NULL) {
1968 DEBUG(3,("get_mydnsfullname: failed to get "
1969 "canonical name for %s\n",
1970 my_hostname));
1971 freeaddrinfo(res);
1972 return NULL;
1975 /* This copies the data, so we must do a lookup
1976 * afterwards to find the value to return.
1979 memcache_add(NULL, SINGLETON_CACHE,
1980 data_blob_string_const("get_mydnsfullname"),
1981 data_blob_string_const(res->ai_canonname));
1983 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1984 data_blob_string_const("get_mydnsfullname"),
1985 &tmp)) {
1986 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1987 strlen(res->ai_canonname) + 1);
1990 freeaddrinfo(res);
1992 return (const char *)tmp.data;
1995 /************************************************************
1996 Is this my name ?
1997 ************************************************************/
1999 bool is_myname_or_ipaddr(const char *s)
2001 TALLOC_CTX *ctx = talloc_tos();
2002 char *name = NULL;
2003 const char *dnsname;
2004 char *servername = NULL;
2006 if (!s) {
2007 return false;
2010 /* Santize the string from '\\name' */
2011 name = talloc_strdup(ctx, s);
2012 if (!name) {
2013 return false;
2016 servername = strrchr_m(name, '\\' );
2017 if (!servername) {
2018 servername = name;
2019 } else {
2020 servername++;
2023 /* Optimize for the common case */
2024 if (strequal(servername, global_myname())) {
2025 return true;
2028 /* Check for an alias */
2029 if (is_myname(servername)) {
2030 return true;
2033 /* Check for loopback */
2034 if (strequal(servername, "127.0.0.1") ||
2035 strequal(servername, "::1")) {
2036 return true;
2039 if (strequal(servername, "localhost")) {
2040 return true;
2043 /* Maybe it's my dns name */
2044 dnsname = get_mydnsfullname();
2045 if (dnsname && strequal(servername, dnsname)) {
2046 return true;
2049 /* Handle possible CNAME records - convert to an IP addr. */
2050 if (!is_ipaddress(servername)) {
2051 /* Use DNS to resolve the name, but only the first address */
2052 struct sockaddr_storage ss;
2053 if (interpret_string_addr(&ss, servername,0)) {
2054 print_sockaddr(name,
2055 sizeof(name),
2056 &ss);
2057 servername = name;
2061 /* Maybe its an IP address? */
2062 if (is_ipaddress(servername)) {
2063 struct sockaddr_storage ss;
2064 struct iface_struct *nics;
2065 int i, n;
2067 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
2068 return false;
2071 if (is_zero_addr(&ss) || is_loopback_addr(&ss)) {
2072 return false;
2075 nics = TALLOC_ARRAY(ctx, struct iface_struct,
2076 MAX_INTERFACES);
2077 if (!nics) {
2078 return false;
2080 n = get_interfaces(nics, MAX_INTERFACES);
2081 for (i=0; i<n; i++) {
2082 if (addr_equal(&nics[i].ip, &ss)) {
2083 TALLOC_FREE(nics);
2084 return true;
2087 TALLOC_FREE(nics);
2090 /* No match */
2091 return false;