Add test for "struct in6_addr" to the HAVE_IPV6 configure test.
[Samba/bb.git] / source3 / lib / util_sock.c
blobc6b1311cf5b8bc494233d22dd28a50f468c4a60b
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 /* 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];
31 /****************************************************************************
32 Return true if a string could be an IPv4 address.
33 ****************************************************************************/
35 bool is_ipaddress_v4(const char *str)
37 int ret = -1;
38 struct in_addr dest;
40 ret = inet_pton(AF_INET, str, &dest);
41 if (ret > 0) {
42 return true;
44 return false;
47 /****************************************************************************
48 Return true if a string could be an IPv4 or IPv6 address.
49 ****************************************************************************/
51 bool is_ipaddress(const char *str)
53 int ret = -1;
55 #if defined(HAVE_IPV6)
56 struct in6_addr dest6;
58 ret = inet_pton(AF_INET6, str, &dest6);
59 if (ret > 0) {
60 return true;
62 #endif
63 return is_ipaddress_v4(str);
66 /*******************************************************************
67 Wrap getaddrinfo...
68 ******************************************************************/
70 static bool interpret_string_addr_internal(struct addrinfo **ppres,
71 const char *str, int flags)
73 int ret;
74 struct addrinfo hints;
76 memset(&hints, '\0', sizeof(hints));
77 /* By default make sure it supports TCP. */
78 hints.ai_socktype = SOCK_STREAM;
79 hints.ai_flags = flags;
81 ret = getaddrinfo(str, NULL,
82 &hints,
83 ppres);
84 if (ret) {
85 DEBUG(3,("interpret_string_addr_interal: getaddrinfo failed "
86 "for name %s [%s]\n",
87 str,
88 gai_strerror(ret) ));
89 return false;
91 return true;
94 /****************************************************************************
95 Interpret an internet address or name into an IP address in 4 byte form.
96 RETURNS IN NETWORK BYTE ORDER (big endian).
97 ****************************************************************************/
99 uint32 interpret_addr(const char *str)
101 uint32 ret;
103 /* If it's in the form of an IP address then
104 * get the lib to interpret it */
105 if (is_ipaddress_v4(str)) {
106 struct in_addr dest;
108 if (inet_pton(AF_INET, str, &dest) <= 0) {
109 /* Error - this shouldn't happen ! */
110 DEBUG(0,("interpret_addr: inet_pton failed "
111 "host %s\n",
112 str));
113 return 0;
115 ret = dest.s_addr; /* NETWORK BYTE ORDER ! */
116 } else {
117 /* Otherwise assume it's a network name of some sort and use
118 getadddrinfo. */
119 struct addrinfo *res = NULL;
120 struct addrinfo *res_list = NULL;
121 if (!interpret_string_addr_internal(&res_list,
122 str,
123 AI_ADDRCONFIG)) {
124 DEBUG(3,("interpret_addr: Unknown host. %s\n",str));
125 return 0;
128 /* Find the first IPv4 address. */
129 for (res = res_list; res; res = res->ai_next) {
130 if (res->ai_family != AF_INET) {
131 continue;
133 if (res->ai_addr == NULL) {
134 continue;
136 break;
138 if(res == NULL) {
139 DEBUG(3,("interpret_addr: host address is "
140 "invalid for host %s\n",str));
141 if (res_list) {
142 freeaddrinfo(res_list);
144 return 0;
146 putip((char *)&ret,
147 &((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr);
148 if (res_list) {
149 freeaddrinfo(res_list);
153 /* This is so bogus - all callers need fixing... JRA. */
154 if (ret == (uint32)-1) {
155 return 0;
158 return ret;
161 /*******************************************************************
162 A convenient addition to interpret_addr().
163 ******************************************************************/
165 struct in_addr *interpret_addr2(const char *str)
167 static struct in_addr ret;
168 uint32 a = interpret_addr(str);
169 ret.s_addr = a;
170 return(&ret);
173 /*******************************************************************
174 Map a text hostname or IP address (IPv4 or IPv6) into a
175 struct sockaddr_storage.
176 ******************************************************************/
178 bool interpret_string_addr(struct sockaddr_storage *pss,
179 const char *str,
180 int flags)
182 struct addrinfo *res = NULL;
184 memset(pss,'\0', sizeof(*pss));
186 if (!interpret_string_addr_internal(&res, str, flags|AI_ADDRCONFIG)) {
187 return false;
189 if (!res) {
190 return false;
192 /* Copy the first sockaddr. */
193 memcpy(pss, res->ai_addr, res->ai_addrlen);
194 freeaddrinfo(res);
195 return true;
198 /*******************************************************************
199 Check if an IPv7 is 127.0.0.1
200 ******************************************************************/
202 bool is_loopback_ip_v4(struct in_addr ip)
204 struct in_addr a;
205 a.s_addr = htonl(INADDR_LOOPBACK);
206 return(ip.s_addr == a.s_addr);
209 /*******************************************************************
210 Check if a struct sockaddr_storage is the loopback address.
211 ******************************************************************/
213 bool is_loopback_addr(const struct sockaddr_storage *pss)
215 #if defined(HAVE_IPV6)
216 if (pss->ss_family == AF_INET) {
217 struct in6_addr *pin6 =
218 &((struct sockaddr_in6 *)pss)->sin6_addr;
219 return IN6_IS_ADDR_LOOPBACK(pin6);
221 #endif
222 if (pss->ss_family == AF_INET) {
223 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
224 return is_loopback_ip_v4(*pin);
226 return false;
229 /*******************************************************************
230 Check if an IPv4 is 0.0.0.0.
231 ******************************************************************/
233 bool is_zero_ip_v4(struct in_addr ip)
235 uint32 a;
236 putip((char *)&a,(char *)&ip);
237 return(a == 0);
240 /*******************************************************************
241 Check if a struct sockaddr_storage has an unspecified address.
242 ******************************************************************/
244 bool is_zero_addr(const struct sockaddr_storage *pss)
246 #if defined(HAVE_IPV6)
247 if (pss->ss_family == AF_INET) {
248 struct in6_addr *pin6 =
249 &((struct sockaddr_in6 *)pss)->sin6_addr;
250 return IN6_IS_ADDR_UNSPECIFIED(pin6);
252 #endif
253 if (pss->ss_family == AF_INET) {
254 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
255 return is_zero_ip_v4(*pin);
257 return false;
260 /*******************************************************************
261 Set an IP to 0.0.0.0.
262 ******************************************************************/
264 void zero_ip_v4(struct in_addr *ip)
266 static bool init;
267 static struct in_addr ipzero;
269 if (!init) {
270 ipzero = *interpret_addr2("0.0.0.0");
271 init = true;
274 *ip = ipzero;
277 /*******************************************************************
278 Are two IPs on the same subnet - IPv4 version ?
279 ********************************************************************/
281 bool same_net_v4(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
283 uint32 net1,net2,nmask;
285 nmask = ntohl(mask.s_addr);
286 net1 = ntohl(ip1.s_addr);
287 net2 = ntohl(ip2.s_addr);
289 return((net1 & nmask) == (net2 & nmask));
292 /*******************************************************************
293 Convert an IPv4 struct in_addr to a struct sockaddr_storage.
294 ********************************************************************/
296 void in_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
297 struct in_addr ip)
299 struct sockaddr_in *sa = (struct sockaddr_in *)ss;
300 memset(ss, '\0', sizeof(*ss));
301 ss->ss_family = AF_INET;
302 sa->sin_addr = ip;
305 #if defined(HAVE_IPV6)
306 /*******************************************************************
307 Convert an IPv6 struct in_addr to a struct sockaddr_storage.
308 ********************************************************************/
310 void in6_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
311 struct in6_addr ip)
313 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)ss;
314 memset(ss, '\0', sizeof(*ss));
315 ss->ss_family = AF_INET6;
316 sa->sin6_addr = ip;
318 #endif
320 /*******************************************************************
321 Are two IPs on the same subnet?
322 ********************************************************************/
324 bool same_net(const struct sockaddr_storage *ip1,
325 const struct sockaddr_storage *ip2,
326 const struct sockaddr_storage *mask)
328 if (ip1->ss_family != ip2->ss_family) {
329 /* Never on the same net. */
330 return false;
333 #if defined(HAVE_IPV6)
334 if (ip1->ss_family == AF_INET6) {
335 struct sockaddr_in6 ip1_6 = *(struct sockaddr_in6 *)ip1;
336 struct sockaddr_in6 ip2_6 = *(struct sockaddr_in6 *)ip2;
337 struct sockaddr_in6 mask_6 = *(struct sockaddr_in6 *)mask;
338 char *p1 = (char *)&ip1_6.sin6_addr;
339 char *p2 = (char *)&ip2_6.sin6_addr;
340 char *m = (char *)&mask_6.sin6_addr;
341 int i;
343 for (i = 0; i < sizeof(struct in6_addr); i++) {
344 *p1++ &= *m;
345 *p2++ &= *m;
346 m++;
348 return (memcmp(&ip1_6.sin6_addr,
349 &ip2_6.sin6_addr,
350 sizeof(struct in6_addr)) == 0);
352 #endif
353 if (ip1->ss_family == AF_INET) {
354 return same_net_v4(((const struct sockaddr_in *)ip1)->sin_addr,
355 ((const struct sockaddr_in *)ip2)->sin_addr,
356 ((const struct sockaddr_in *)mask)->sin_addr);
358 return false;
361 /*******************************************************************
362 Are two sockaddr_storage's the same family and address ? Ignore port etc.
363 ********************************************************************/
365 bool addr_equal(const struct sockaddr_storage *ip1,
366 const struct sockaddr_storage *ip2)
368 if (ip1->ss_family != ip2->ss_family) {
369 /* Never the same. */
370 return false;
373 #if defined(HAVE_IPV6)
374 if (ip1->ss_family == AF_INET6) {
375 return (memcmp(&((const struct sockaddr_in6 *)ip1)->sin6_addr,
376 &((const struct sockaddr_in6 *)ip2)->sin6_addr,
377 sizeof(struct in6_addr)) == 0);
379 #endif
380 if (ip1->ss_family == AF_INET) {
381 return (memcmp(&((const struct sockaddr_in *)ip1)->sin_addr,
382 &((const struct sockaddr_in *)ip2)->sin_addr,
383 sizeof(struct in_addr)) == 0);
385 return false;
389 /****************************************************************************
390 Is an IP address the INADDR_ANY or in6addr_any value ?
391 ****************************************************************************/
393 bool is_address_any(const struct sockaddr_storage *psa)
395 #if defined(HAVE_IPV6)
396 if (psa->ss_family == AF_INET6) {
397 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)psa;
398 if (memcmp(&in6addr_any,
399 &si6->sin6_addr,
400 sizeof(in6addr_any)) == 0) {
401 return true;
403 return false;
405 #endif
406 if (psa->ss_family == AF_INET) {
407 struct sockaddr_in *si = (struct sockaddr_in *)psa;
408 if (si->sin_addr.s_addr == INADDR_ANY) {
409 return true;
411 return false;
413 return false;
416 /****************************************************************************
417 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
418 ****************************************************************************/
420 char *print_sockaddr(char *dest,
421 size_t destlen,
422 const struct sockaddr_storage *psa,
423 socklen_t psalen)
425 if (destlen > 0) {
426 dest[0] = '\0';
428 (void)getnameinfo((const struct sockaddr *)psa,
429 psalen,
430 dest, destlen,
431 NULL, 0,
432 NI_NUMERICHOST);
433 return dest;
436 /****************************************************************************
437 Set the global client_fd variable.
438 ****************************************************************************/
440 void client_setfd(int fd)
442 client_fd = fd;
443 safe_strcpy(client_ip_string,
444 get_peer_addr(client_fd),
445 sizeof(client_ip_string)-1);
448 /****************************************************************************
449 Return a static string of an IP address (IPv4 or IPv6).
450 ****************************************************************************/
452 static const char *get_socket_addr(int fd)
454 struct sockaddr_storage sa;
455 socklen_t length = sizeof(sa);
456 static char addr_buf[INET6_ADDRSTRLEN];
458 /* Ok, returning a hard coded IPv4 address
459 * is bogus, but it's just as bogus as a
460 * zero IPv6 address. No good choice here.
463 safe_strcpy(addr_buf, "0.0.0.0", sizeof(addr_buf)-1);
465 if (fd == -1) {
466 return addr_buf;
469 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
470 DEBUG(0,("getsockname failed. Error was %s\n",
471 strerror(errno) ));
472 return addr_buf;
475 return print_sockaddr(addr_buf, sizeof(addr_buf), &sa, length);
478 /****************************************************************************
479 Return the port number we've bound to on a socket.
480 ****************************************************************************/
482 static int get_socket_port(int fd)
484 struct sockaddr_storage sa;
485 socklen_t length = sizeof(sa);
487 if (fd == -1) {
488 return -1;
491 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
492 DEBUG(0,("getpeername failed. Error was %s\n",
493 strerror(errno) ));
494 return -1;
497 #if defined(HAVE_IPV6)
498 if (sa.ss_family == AF_INET6) {
499 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
501 #endif
502 if (sa.ss_family == AF_INET) {
503 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
505 return -1;
508 const char *client_name(void)
510 return get_peer_name(client_fd,false);
513 const char *client_addr(void)
515 return get_peer_addr(client_fd);
518 const char *client_socket_addr(void)
520 return get_socket_addr(client_fd);
523 int client_socket_port(void)
525 return get_socket_port(client_fd);
528 int smb_read_error = 0;
530 /****************************************************************************
531 Determine if a file descriptor is in fact a socket.
532 ****************************************************************************/
534 bool is_a_socket(int fd)
536 int v;
537 socklen_t l;
538 l = sizeof(int);
539 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
542 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
544 typedef struct smb_socket_option {
545 const char *name;
546 int level;
547 int option;
548 int value;
549 int opttype;
550 } smb_socket_option;
552 static const smb_socket_option socket_options[] = {
553 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
554 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
555 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
556 #ifdef TCP_NODELAY
557 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
558 #endif
559 #ifdef TCP_KEEPCNT
560 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
561 #endif
562 #ifdef TCP_KEEPIDLE
563 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
564 #endif
565 #ifdef TCP_KEEPINTVL
566 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
567 #endif
568 #ifdef IPTOS_LOWDELAY
569 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
570 #endif
571 #ifdef IPTOS_THROUGHPUT
572 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
573 #endif
574 #ifdef SO_REUSEPORT
575 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
576 #endif
577 #ifdef SO_SNDBUF
578 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
579 #endif
580 #ifdef SO_RCVBUF
581 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
582 #endif
583 #ifdef SO_SNDLOWAT
584 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
585 #endif
586 #ifdef SO_RCVLOWAT
587 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
588 #endif
589 #ifdef SO_SNDTIMEO
590 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
591 #endif
592 #ifdef SO_RCVTIMEO
593 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
594 #endif
595 #ifdef TCP_FASTACK
596 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
597 #endif
598 {NULL,0,0,0,0}};
600 /****************************************************************************
601 Print socket options.
602 ****************************************************************************/
604 static void print_socket_options(int s)
606 int value;
607 socklen_t vlen = 4;
608 const smb_socket_option *p = &socket_options[0];
610 /* wrapped in if statement to prevent streams
611 * leak in SCO Openserver 5.0 */
612 /* reported on samba-technical --jerry */
613 if ( DEBUGLEVEL >= 5 ) {
614 for (; p->name != NULL; p++) {
615 if (getsockopt(s, p->level, p->option,
616 (void *)&value, &vlen) == -1) {
617 DEBUG(5,("Could not test socket option %s.\n",
618 p->name));
619 } else {
620 DEBUG(5,("socket option %s = %d\n",
621 p->name,value));
627 /****************************************************************************
628 Set user socket options.
629 ****************************************************************************/
631 void set_socket_options(int fd, const char *options)
633 fstring tok;
635 while (next_token(&options,tok," \t,", sizeof(tok))) {
636 int ret=0,i;
637 int value = 1;
638 char *p;
639 bool got_value = false;
641 if ((p = strchr_m(tok,'='))) {
642 *p = 0;
643 value = atoi(p+1);
644 got_value = true;
647 for (i=0;socket_options[i].name;i++)
648 if (strequal(socket_options[i].name,tok))
649 break;
651 if (!socket_options[i].name) {
652 DEBUG(0,("Unknown socket option %s\n",tok));
653 continue;
656 switch (socket_options[i].opttype) {
657 case OPT_BOOL:
658 case OPT_INT:
659 ret = setsockopt(fd,socket_options[i].level,
660 socket_options[i].option,
661 (char *)&value,sizeof(int));
662 break;
664 case OPT_ON:
665 if (got_value)
666 DEBUG(0,("syntax error - %s "
667 "does not take a value\n",tok));
670 int on = socket_options[i].value;
671 ret = setsockopt(fd,socket_options[i].level,
672 socket_options[i].option,
673 (char *)&on,sizeof(int));
675 break;
678 if (ret != 0) {
679 DEBUG(0,("Failed to set socket option %s (Error %s)\n",
680 tok, strerror(errno) ));
684 print_socket_options(fd);
687 /****************************************************************************
688 Read from a socket.
689 ****************************************************************************/
691 ssize_t read_udp_v4_socket(int fd,
692 char *buf,
693 size_t len,
694 struct sockaddr_storage *psa)
696 ssize_t ret;
697 socklen_t socklen = sizeof(*psa);
698 struct sockaddr_in *si = (struct sockaddr_in *)psa;
700 memset((char *)psa,'\0',socklen);
702 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
703 (struct sockaddr *)psa,&socklen);
704 if (ret <= 0) {
705 /* Don't print a low debug error for a non-blocking socket. */
706 if (errno == EAGAIN) {
707 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
708 } else {
709 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
710 strerror(errno)));
712 return 0;
715 if (psa->ss_family != AF_INET) {
716 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
717 "(not IPv4)\n", (int)psa->ss_family));
718 return 0;
721 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
722 inet_ntoa(si->sin_addr),
723 si->sin_port,
724 (unsigned long)ret));
726 return ret;
729 /****************************************************************************
730 Read data from a socket with a timout in msec.
731 mincount = if timeout, minimum to read before returning
732 maxcount = number to be read.
733 time_out = timeout in milliseconds
734 ****************************************************************************/
736 ssize_t read_socket_with_timeout(int fd,
737 char *buf,
738 size_t mincnt,
739 size_t maxcnt,
740 unsigned int time_out)
742 fd_set fds;
743 int selrtn;
744 ssize_t readret;
745 size_t nread = 0;
746 struct timeval timeout;
748 /* just checking .... */
749 if (maxcnt <= 0)
750 return(0);
752 smb_read_error = 0;
754 /* Blocking read */
755 if (time_out == 0) {
756 if (mincnt == 0) {
757 mincnt = maxcnt;
760 while (nread < mincnt) {
761 readret = sys_read(fd, buf + nread, maxcnt - nread);
763 if (readret == 0) {
764 DEBUG(5,("read_socket_with_timeout: "
765 "blocking read. EOF from client.\n"));
766 smb_read_error = READ_EOF;
767 return -1;
770 if (readret == -1) {
771 if (fd == client_fd) {
772 /* Try and give an error message
773 * saying what client failed. */
774 DEBUG(0,("read_socket_with_timeout: "
775 "client %s read error = %s.\n",
776 client_ip_string,
777 strerror(errno) ));
778 } else {
779 DEBUG(0,("read_socket_with_timeout: "
780 "read error = %s.\n",
781 strerror(errno) ));
783 smb_read_error = READ_ERROR;
784 return -1;
786 nread += readret;
788 return((ssize_t)nread);
791 /* Most difficult - timeout read */
792 /* If this is ever called on a disk file and
793 mincnt is greater then the filesize then
794 system performance will suffer severely as
795 select always returns true on disk files */
797 /* Set initial timeout */
798 timeout.tv_sec = (time_t)(time_out / 1000);
799 timeout.tv_usec = (long)(1000 * (time_out % 1000));
801 for (nread=0; nread < mincnt; ) {
802 FD_ZERO(&fds);
803 FD_SET(fd,&fds);
805 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
807 /* Check if error */
808 if (selrtn == -1) {
809 /* something is wrong. Maybe the socket is dead? */
810 if (fd == client_fd) {
811 /* Try and give an error message saying
812 * what client failed. */
813 DEBUG(0,("read_socket_with_timeout: timeout "
814 "read for client %s. select error = %s.\n",
815 client_ip_string, strerror(errno) ));
816 } else {
817 DEBUG(0,("read_socket_with_timeout: timeout "
818 "read. select error = %s.\n",
819 strerror(errno) ));
821 smb_read_error = READ_ERROR;
822 return -1;
825 /* Did we timeout ? */
826 if (selrtn == 0) {
827 DEBUG(10,("read_socket_with_timeout: timeout read. "
828 "select timed out.\n"));
829 smb_read_error = READ_TIMEOUT;
830 return -1;
833 readret = sys_read(fd, buf+nread, maxcnt-nread);
835 if (readret == 0) {
836 /* we got EOF on the file descriptor */
837 DEBUG(5,("read_socket_with_timeout: timeout read. "
838 "EOF from client.\n"));
839 smb_read_error = READ_EOF;
840 return -1;
843 if (readret == -1) {
844 /* the descriptor is probably dead */
845 if (fd == client_fd) {
846 /* Try and give an error message
847 * saying what client failed. */
848 DEBUG(0,("read_socket_with_timeout: timeout "
849 "read to client %s. read error = %s.\n",
850 client_ip_string, strerror(errno) ));
851 } else {
852 DEBUG(0,("read_socket_with_timeout: timeout "
853 "read. read error = %s.\n",
854 strerror(errno) ));
856 smb_read_error = READ_ERROR;
857 return -1;
860 nread += readret;
863 /* Return the number we got */
864 return (ssize_t)nread;
867 /****************************************************************************
868 Read data from the client, reading exactly N bytes.
869 ****************************************************************************/
871 ssize_t read_data(int fd,char *buffer,size_t N)
873 ssize_t ret;
874 size_t total=0;
876 smb_read_error = 0;
878 while (total < N) {
879 ret = sys_read(fd,buffer + total,N - total);
881 if (ret == 0) {
882 DEBUG(10,("read_data: read of %d returned 0. "
883 "Error = %s\n",
884 (int)(N - total), strerror(errno) ));
885 smb_read_error = READ_EOF;
886 return 0;
889 if (ret == -1) {
890 if (fd == client_fd) {
891 /* Try and give an error message saying
892 * what client failed. */
893 DEBUG(0,("read_data: read failure for %d "
894 "bytes to client %s. Error = %s\n",
895 (int)(N - total),
896 client_ip_string,
897 strerror(errno) ));
898 } else {
899 DEBUG(0,("read_data: read failure for %d. "
900 "Error = %s\n",
901 (int)(N - total),
902 strerror(errno) ));
904 smb_read_error = READ_ERROR;
905 return -1;
907 total += ret;
909 return (ssize_t)total;
912 /****************************************************************************
913 Write data to a fd.
914 ****************************************************************************/
916 ssize_t write_data(int fd, const char *buffer, size_t N)
918 size_t total=0;
919 ssize_t ret;
921 while (total < N) {
922 ret = sys_write(fd,buffer + total,N - total);
924 if (ret == -1) {
925 if (fd == client_fd) {
926 /* Try and give an error message saying
927 * what client failed. */
928 DEBUG(0,("write_data: write failure in "
929 "writing to client %s. Error %s\n",
930 client_ip_string, strerror(errno) ));
931 } else {
932 DEBUG(0,("write_data: write failure. "
933 "Error = %s\n", strerror(errno) ));
935 return -1;
938 if (ret == 0) {
939 return total;
942 total += ret;
944 return (ssize_t)total;
947 /****************************************************************************
948 Send a keepalive packet (rfc1002).
949 ****************************************************************************/
951 bool send_keepalive(int client)
953 unsigned char buf[4];
955 buf[0] = SMBkeepalive;
956 buf[1] = buf[2] = buf[3] = 0;
958 return(write_data(client,(char *)buf,4) == 4);
961 /****************************************************************************
962 Read 4 bytes of a smb packet and return the smb length of the packet.
963 Store the result in the buffer.
964 This version of the function will return a length of zero on receiving
965 a keepalive packet.
966 Timeout is in milliseconds.
967 ****************************************************************************/
969 static ssize_t read_smb_length_return_keepalive(int fd,
970 char *inbuf,
971 unsigned int timeout)
973 ssize_t len=0;
974 int msg_type;
975 bool ok = false;
977 while (!ok) {
978 if (timeout > 0) {
979 ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout)
980 == 4);
981 } else {
982 ok = (read_data(fd,inbuf,4) == 4);
984 if (!ok) {
985 return -1;
988 len = smb_len(inbuf);
989 msg_type = CVAL(inbuf,0);
991 if (msg_type == SMBkeepalive) {
992 DEBUG(5,("Got keepalive packet\n"));
996 DEBUG(10,("got smb length of %lu\n",(unsigned long)len));
998 return(len);
1001 /****************************************************************************
1002 Read 4 bytes of a smb packet and return the smb length of the packet.
1003 Store the result in the buffer. This version of the function will
1004 never return a session keepalive (length of zero).
1005 Timeout is in milliseconds.
1006 ****************************************************************************/
1008 ssize_t read_smb_length(int fd, char *inbuf, unsigned int timeout)
1010 ssize_t len;
1012 for(;;) {
1013 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
1015 if(len < 0)
1016 return len;
1018 /* Ignore session keepalives. */
1019 if(CVAL(inbuf,0) != SMBkeepalive)
1020 break;
1023 DEBUG(10,("read_smb_length: got smb length of %lu\n",
1024 (unsigned long)len));
1026 return len;
1029 /****************************************************************************
1030 Read an smb from a fd. Note that the buffer *MUST* be of size
1031 BUFFER_SIZE+SAFETY_MARGIN.
1032 The timeout is in milliseconds.
1033 This function will return on receipt of a session keepalive packet.
1034 maxlen is the max number of bytes to return, not including the 4 byte
1035 length. If zero it means BUFFER_SIZE+SAFETY_MARGIN limit.
1036 Doesn't check the MAC on signed packets.
1037 ****************************************************************************/
1039 ssize_t receive_smb_raw(int fd,
1040 char *buffer,
1041 unsigned int timeout,
1042 size_t maxlen)
1044 ssize_t len,ret;
1046 smb_read_error = 0;
1048 len = read_smb_length_return_keepalive(fd,buffer,timeout);
1049 if (len < 0) {
1050 DEBUG(10,("receive_smb_raw: length < 0!\n"));
1053 * Correct fix. smb_read_error may have already been
1054 * set. Only set it here if not already set. Global
1055 * variables still suck :-). JRA.
1058 if (smb_read_error == 0)
1059 smb_read_error = READ_ERROR;
1060 return -1;
1064 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
1065 * of header. Don't print the error if this fits.... JRA.
1068 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
1069 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
1070 (unsigned long)len));
1071 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
1074 * Correct fix. smb_read_error may have already been
1075 * set. Only set it here if not already set. Global
1076 * variables still suck :-). JRA.
1079 if (smb_read_error == 0)
1080 smb_read_error = READ_ERROR;
1081 return -1;
1085 if(len > 0) {
1086 if (maxlen) {
1087 len = MIN(len,maxlen);
1090 if (timeout > 0) {
1091 ret = read_socket_with_timeout(fd,
1092 buffer+4,
1093 len,
1094 len,
1095 timeout);
1096 } else {
1097 ret = read_data(fd,buffer+4,len);
1100 if (ret != len) {
1101 if (smb_read_error == 0) {
1102 smb_read_error = READ_ERROR;
1104 return -1;
1107 /* not all of samba3 properly checks for packet-termination
1108 * of strings. This ensures that we don't run off into
1109 * empty space. */
1110 SSVAL(buffer+4,len, 0);
1113 return len;
1116 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
1117 char **buffer, unsigned int timeout)
1119 char lenbuf[4];
1120 ssize_t len,ret;
1122 smb_read_error = 0;
1124 len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
1125 if (len < 0) {
1126 DEBUG(10,("receive_smb_raw: length < 0!\n"));
1129 * Correct fix. smb_read_error may have already been
1130 * set. Only set it here if not already set. Global
1131 * variables still suck :-). JRA.
1134 if (smb_read_error == 0)
1135 smb_read_error = READ_ERROR;
1136 return -1;
1140 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
1141 * of header. Don't print the error if this fits.... JRA.
1144 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
1145 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
1146 (unsigned long)len));
1147 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
1150 * Correct fix. smb_read_error may have already been
1151 * set. Only set it here if not already set. Global
1152 * variables still suck :-). JRA.
1155 if (smb_read_error == 0)
1156 smb_read_error = READ_ERROR;
1157 return -1;
1162 * The +4 here can't wrap, we've checked the length above already.
1165 *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
1167 if (*buffer == NULL) {
1168 DEBUG(0, ("Could not allocate inbuf of length %d\n",
1169 (int)len+4));
1170 if (smb_read_error == 0)
1171 smb_read_error = READ_ERROR;
1172 return -1;
1175 memcpy(*buffer, lenbuf, sizeof(lenbuf));
1177 if(len > 0) {
1178 if (timeout > 0) {
1179 ret = read_socket_with_timeout(fd,(*buffer)+4, len,
1180 len, timeout);
1181 } else {
1182 ret = read_data(fd, (*buffer)+4, len);
1185 if (ret != len) {
1186 if (smb_read_error == 0) {
1187 smb_read_error = READ_ERROR;
1189 return -1;
1193 return len + 4;
1196 /****************************************************************************
1197 Wrapper for receive_smb_raw().
1198 Checks the MAC on signed packets.
1199 ****************************************************************************/
1201 bool receive_smb(int fd, char *buffer, unsigned int timeout)
1203 if (receive_smb_raw(fd, buffer, timeout, 0) < 0) {
1204 return false;
1207 /* Check the incoming SMB signature. */
1208 if (!srv_check_sign_mac(buffer, true)) {
1209 DEBUG(0, ("receive_smb: SMB Signature verification "
1210 "failed on incoming packet!\n"));
1211 if (smb_read_error == 0) {
1212 smb_read_error = READ_BAD_SIG;
1214 return false;
1217 return true;
1220 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
1221 unsigned int timeout)
1223 ssize_t len;
1225 len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
1227 if (len < 0) {
1228 return -1;
1231 /* Check the incoming SMB signature. */
1232 if (!srv_check_sign_mac(*buffer, true)) {
1233 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
1234 "incoming packet!\n"));
1235 if (smb_read_error == 0) {
1236 smb_read_error = READ_BAD_SIG;
1238 return -1;
1241 return len;
1244 /****************************************************************************
1245 Send an smb to a fd.
1246 ****************************************************************************/
1248 bool send_smb(int fd, char *buffer)
1250 size_t len;
1251 size_t nwritten=0;
1252 ssize_t ret;
1254 /* Sign the outgoing packet if required. */
1255 srv_calculate_sign_mac(buffer);
1257 len = smb_len(buffer) + 4;
1259 while (nwritten < len) {
1260 ret = write_data(fd,buffer+nwritten,len - nwritten);
1261 if (ret <= 0) {
1262 DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
1263 (int)len,(int)ret, strerror(errno) ));
1264 return false;
1266 nwritten += ret;
1269 return true;
1272 /****************************************************************************
1273 Open a socket of the specified type, port, and address for incoming data.
1274 ****************************************************************************/
1276 int open_socket_in(int type,
1277 int port,
1278 int dlevel,
1279 uint32 socket_addr, /* NETWORK BYTE ORDER */
1280 bool rebind )
1282 struct sockaddr_in sock;
1283 int res;
1285 memset( (char *)&sock, '\0', sizeof(sock) );
1287 #ifdef HAVE_SOCK_SIN_LEN
1288 sock.sin_len = sizeof(sock);
1289 #endif
1290 sock.sin_port = htons( port );
1291 sock.sin_family = AF_INET;
1292 sock.sin_addr.s_addr = socket_addr;
1294 res = socket( AF_INET, type, 0 );
1295 if( res == -1 ) {
1296 if( DEBUGLVL(0) ) {
1297 dbgtext( "open_socket_in(): socket() call failed: " );
1298 dbgtext( "%s\n", strerror( errno ) );
1300 return -1;
1303 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
1305 int val = rebind ? 1 : 0;
1306 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
1307 (char *)&val,sizeof(val)) == -1 ) {
1308 if( DEBUGLVL( dlevel ) ) {
1309 dbgtext( "open_socket_in(): setsockopt: " );
1310 dbgtext( "SO_REUSEADDR = %s ",
1311 val?"true":"false" );
1312 dbgtext( "on port %d failed ", port );
1313 dbgtext( "with error = %s\n", strerror(errno) );
1316 #ifdef SO_REUSEPORT
1317 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
1318 (char *)&val,sizeof(val)) == -1 ) {
1319 if( DEBUGLVL( dlevel ) ) {
1320 dbgtext( "open_socket_in(): setsockopt: ");
1321 dbgtext( "SO_REUSEPORT = %s ",
1322 val?"true":"false" );
1323 dbgtext( "on port %d failed ", port );
1324 dbgtext( "with error = %s\n", strerror(errno) );
1327 #endif /* SO_REUSEPORT */
1330 /* now we've got a socket - we need to bind it */
1331 if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
1332 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
1333 port == SMB_PORT2 || port == NMB_PORT) ) {
1334 dbgtext( "bind failed on port %d ", port );
1335 dbgtext( "socket_addr = %s.\n",
1336 inet_ntoa( sock.sin_addr ) );
1337 dbgtext( "Error = %s\n", strerror(errno) );
1339 close( res );
1340 return -1;
1343 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
1345 return( res );
1348 /****************************************************************************
1349 Create an outgoing socket. timeout is in milliseconds.
1350 **************************************************************************/
1352 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
1354 struct sockaddr_in sock_out;
1355 int res,ret;
1356 int connect_loop = 10;
1357 int increment = 10;
1359 /* create a socket to write to */
1360 res = socket(PF_INET, type, 0);
1361 if (res == -1) {
1362 DEBUG(0,("socket error (%s)\n", strerror(errno)));
1363 return -1;
1366 if (type != SOCK_STREAM)
1367 return(res);
1369 memset((char *)&sock_out,'\0',sizeof(sock_out));
1370 putip((char *)&sock_out.sin_addr,(char *)addr);
1372 sock_out.sin_port = htons( port );
1373 sock_out.sin_family = PF_INET;
1375 /* set it non-blocking */
1376 set_blocking(res,false);
1378 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
1380 /* and connect it to the destination */
1381 connect_again:
1383 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
1385 /* Some systems return EAGAIN when they mean EINPROGRESS */
1386 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1387 errno == EAGAIN) && (connect_loop < timeout) ) {
1388 smb_msleep(connect_loop);
1389 timeout -= connect_loop;
1390 connect_loop += increment;
1391 if (increment < 250) {
1392 /* After 8 rounds we end up at a max of 255 msec */
1393 increment *= 1.5;
1395 goto connect_again;
1398 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1399 errno == EAGAIN)) {
1400 DEBUG(1,("timeout connecting to %s:%d\n",
1401 inet_ntoa(*addr),port));
1402 close(res);
1403 return -1;
1406 #ifdef EISCONN
1407 if (ret < 0 && errno == EISCONN) {
1408 errno = 0;
1409 ret = 0;
1411 #endif
1413 if (ret < 0) {
1414 DEBUG(2,("error connecting to %s:%d (%s)\n",
1415 inet_ntoa(*addr),port,strerror(errno)));
1416 close(res);
1417 return -1;
1420 /* set it blocking again */
1421 set_blocking(res,true);
1423 return res;
1426 /****************************************************************************
1427 Create an outgoing TCP socket to any of the addrs. This is for
1428 simultaneous connects to port 445 and 139 of a host or even a variety
1429 of DC's all of which are equivalent for our purposes.
1430 **************************************************************************/
1432 bool open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1433 int timeout, int *fd_index, int *fd)
1435 int i, resulting_index, res;
1436 int *sockets;
1437 bool good_connect;
1439 fd_set r_fds, wr_fds;
1440 struct timeval tv;
1441 int maxfd;
1443 int connect_loop = 10000; /* 10 milliseconds */
1445 timeout *= 1000; /* convert to microseconds */
1447 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1449 if (sockets == NULL)
1450 return false;
1452 resulting_index = -1;
1454 for (i=0; i<num_addrs; i++)
1455 sockets[i] = -1;
1457 for (i=0; i<num_addrs; i++) {
1458 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1459 if (sockets[i] < 0)
1460 goto done;
1461 set_blocking(sockets[i], false);
1464 connect_again:
1465 good_connect = false;
1467 for (i=0; i<num_addrs; i++) {
1469 if (sockets[i] == -1)
1470 continue;
1472 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1473 sizeof(*addrs)) == 0) {
1474 /* Rather unlikely as we are non-blocking, but it
1475 * might actually happen. */
1476 resulting_index = i;
1477 goto done;
1480 if (errno == EINPROGRESS || errno == EALREADY ||
1481 #ifdef EISCONN
1482 errno == EISCONN ||
1483 #endif
1484 errno == EAGAIN || errno == EINTR) {
1485 /* These are the error messages that something is
1486 progressing. */
1487 good_connect = true;
1488 } else if (errno != 0) {
1489 /* There was a direct error */
1490 close(sockets[i]);
1491 sockets[i] = -1;
1495 if (!good_connect) {
1496 /* All of the connect's resulted in real error conditions */
1497 goto done;
1500 /* Lets see if any of the connect attempts succeeded */
1502 maxfd = 0;
1503 FD_ZERO(&wr_fds);
1504 FD_ZERO(&r_fds);
1506 for (i=0; i<num_addrs; i++) {
1507 if (sockets[i] == -1)
1508 continue;
1509 FD_SET(sockets[i], &wr_fds);
1510 FD_SET(sockets[i], &r_fds);
1511 if (sockets[i]>maxfd)
1512 maxfd = sockets[i];
1515 tv.tv_sec = 0;
1516 tv.tv_usec = connect_loop;
1518 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1520 if (res < 0)
1521 goto done;
1523 if (res == 0)
1524 goto next_round;
1526 for (i=0; i<num_addrs; i++) {
1528 if (sockets[i] == -1)
1529 continue;
1531 /* Stevens, Network Programming says that if there's a
1532 * successful connect, the socket is only writable. Upon an
1533 * error, it's both readable and writable. */
1535 if (FD_ISSET(sockets[i], &r_fds) &&
1536 FD_ISSET(sockets[i], &wr_fds)) {
1537 /* readable and writable, so it's an error */
1538 close(sockets[i]);
1539 sockets[i] = -1;
1540 continue;
1543 if (!FD_ISSET(sockets[i], &r_fds) &&
1544 FD_ISSET(sockets[i], &wr_fds)) {
1545 /* Only writable, so it's connected */
1546 resulting_index = i;
1547 goto done;
1551 next_round:
1553 timeout -= connect_loop;
1554 if (timeout <= 0)
1555 goto done;
1556 connect_loop *= 1.5;
1557 if (connect_loop > timeout)
1558 connect_loop = timeout;
1559 goto connect_again;
1561 done:
1562 for (i=0; i<num_addrs; i++) {
1563 if (i == resulting_index)
1564 continue;
1565 if (sockets[i] >= 0)
1566 close(sockets[i]);
1569 if (resulting_index >= 0) {
1570 *fd_index = resulting_index;
1571 *fd = sockets[*fd_index];
1572 set_blocking(*fd, true);
1575 free(sockets);
1577 return (resulting_index >= 0);
1579 /****************************************************************************
1580 Open a connected UDP socket to host on port
1581 **************************************************************************/
1583 int open_udp_socket(const char *host, int port)
1585 int type = SOCK_DGRAM;
1586 struct sockaddr_in sock_out;
1587 int res;
1588 struct in_addr *addr;
1590 addr = interpret_addr2(host);
1592 res = socket(PF_INET, type, 0);
1593 if (res == -1) {
1594 return -1;
1597 memset((char *)&sock_out,'\0',sizeof(sock_out));
1598 putip((char *)&sock_out.sin_addr,(char *)addr);
1599 sock_out.sin_port = htons(port);
1600 sock_out.sin_family = PF_INET;
1602 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1603 close(res);
1604 return -1;
1607 return res;
1610 /*******************************************************************
1611 Return the IP addr of the remote end of a socket as a string.
1612 Optionally return the struct sockaddr_storage.
1613 ******************************************************************/
1615 static const char *get_peer_addr_internal(int fd,
1616 struct sockaddr_storage *pss,
1617 socklen_t *plength)
1619 struct sockaddr_storage ss;
1620 socklen_t length = sizeof(ss);
1621 static char addr_buf[INET6_ADDRSTRLEN];
1623 safe_strcpy(addr_buf,"0.0.0.0",sizeof(addr_buf)-1);
1625 if (fd == -1) {
1626 return addr_buf;
1629 if (pss == NULL) {
1630 pss = &ss;
1632 if (plength == NULL) {
1633 plength = &length;
1636 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1637 DEBUG(0,("getpeername failed. Error was %s\n",
1638 strerror(errno) ));
1639 return addr_buf;
1642 print_sockaddr(addr_buf,
1643 sizeof(addr_buf),
1644 pss,
1645 *plength);
1646 return addr_buf;
1650 /*******************************************************************
1651 Matchname - determine if host name matches IP address. Used to
1652 confirm a hostname lookup to prevent spoof attacks.
1653 ******************************************************************/
1655 static bool matchname(const char *remotehost,
1656 const struct sockaddr_storage *pss,
1657 socklen_t len)
1659 struct addrinfo *res = NULL;
1660 struct addrinfo *ailist = NULL;
1661 char addr_buf[INET6_ADDRSTRLEN];
1662 bool ret = interpret_string_addr_internal(&ailist,
1663 remotehost,
1664 AI_ADDRCONFIG|AI_CANONNAME);
1666 if (!ret || ailist == NULL) {
1667 DEBUG(3,("matchname: getaddrinfo failed for "
1668 "name %s [%s]\n",
1669 remotehost,
1670 gai_strerror(ret) ));
1671 return false;
1675 * Make sure that getaddrinfo() returns the "correct" host name.
1678 if (ailist->ai_canonname == NULL ||
1679 (!strequal(remotehost, ailist->ai_canonname) &&
1680 !strequal(remotehost, "localhost"))) {
1681 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1682 remotehost,
1683 ailist->ai_canonname ?
1684 ailist->ai_canonname : "(NULL)"));
1685 freeaddrinfo(ailist);
1686 return false;
1689 /* Look up the host address in the address list we just got. */
1690 for (res = ailist; res; res = res->ai_next) {
1691 if (!res->ai_addr) {
1692 continue;
1694 if (addr_equal((const struct sockaddr_storage *)res->ai_addr,
1695 pss)) {
1696 freeaddrinfo(ailist);
1697 return true;
1702 * The host name does not map to the original host address. Perhaps
1703 * someone has compromised a name server. More likely someone botched
1704 * it, but that could be dangerous, too.
1707 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1708 print_sockaddr(addr_buf,
1709 sizeof(addr_buf),
1710 pss,
1711 len),
1712 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1714 if (ailist) {
1715 freeaddrinfo(ailist);
1717 return false;
1720 /*******************************************************************
1721 Return the DNS name of the remote end of a socket.
1722 ******************************************************************/
1724 const char *get_peer_name(int fd, bool force_lookup)
1726 static fstring addr_buf;
1727 static pstring name_buf;
1728 struct sockaddr_storage ss;
1729 socklen_t length = sizeof(ss);
1730 const char *p;
1731 int ret;
1732 pstring tmp_name;
1734 /* reverse lookups can be *very* expensive, and in many
1735 situations won't work because many networks don't link dhcp
1736 with dns. To avoid the delay we avoid the lookup if
1737 possible */
1738 if (!lp_hostname_lookups() && (force_lookup == false)) {
1739 return get_peer_addr(fd);
1742 p = get_peer_addr_internal(fd, &ss, &length);
1744 /* it might be the same as the last one - save some DNS work */
1745 if (strcmp(p, addr_buf) == 0) {
1746 return name_buf;
1749 pstrcpy(name_buf,"UNKNOWN");
1750 if (fd == -1) {
1751 return name_buf;
1754 fstrcpy(addr_buf, p);
1756 /* Look up the remote host name. */
1757 ret = getnameinfo((struct sockaddr *)&ss,
1758 length,
1759 name_buf,
1760 sizeof(name_buf),
1761 NULL,
1763 NI_NUMERICHOST);
1765 if (ret) {
1766 DEBUG(1,("get_peer_name: getnameinfo failed "
1767 "for %s with error %s\n",
1769 gai_strerror(ret)));
1770 pstrcpy(name_buf, p);
1771 } else {
1772 if (!matchname(name_buf, &ss, length)) {
1773 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1774 pstrcpy(name_buf,"UNKNOWN");
1778 /* can't pass the same source and dest strings in when you
1779 use --enable-developer or the clobber_region() call will
1780 get you */
1782 pstrcpy(tmp_name, name_buf );
1783 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1784 if (strstr(name_buf,"..")) {
1785 pstrcpy(name_buf, "UNKNOWN");
1788 return name_buf;
1791 /*******************************************************************
1792 Return the IP addr of the remote end of a socket as a string.
1793 ******************************************************************/
1795 const char *get_peer_addr(int fd)
1797 return get_peer_addr_internal(fd, NULL, NULL);
1800 /*******************************************************************
1801 Create protected unix domain socket.
1803 Some unixes cannot set permissions on a ux-dom-sock, so we
1804 have to make sure that the directory contains the protection
1805 permissions instead.
1806 ******************************************************************/
1808 int create_pipe_sock(const char *socket_dir,
1809 const char *socket_name,
1810 mode_t dir_perms)
1812 #ifdef HAVE_UNIXSOCKET
1813 struct sockaddr_un sunaddr;
1814 struct stat st;
1815 int sock;
1816 mode_t old_umask;
1817 pstring path;
1819 old_umask = umask(0);
1821 /* Create the socket directory or reuse the existing one */
1823 if (lstat(socket_dir, &st) == -1) {
1824 if (errno == ENOENT) {
1825 /* Create directory */
1826 if (mkdir(socket_dir, dir_perms) == -1) {
1827 DEBUG(0, ("error creating socket directory "
1828 "%s: %s\n", socket_dir,
1829 strerror(errno)));
1830 goto out_umask;
1832 } else {
1833 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1834 socket_dir, strerror(errno)));
1835 goto out_umask;
1837 } else {
1838 /* Check ownership and permission on existing directory */
1839 if (!S_ISDIR(st.st_mode)) {
1840 DEBUG(0, ("socket directory %s isn't a directory\n",
1841 socket_dir));
1842 goto out_umask;
1844 if ((st.st_uid != sec_initial_uid()) ||
1845 ((st.st_mode & 0777) != dir_perms)) {
1846 DEBUG(0, ("invalid permissions on socket directory "
1847 "%s\n", socket_dir));
1848 goto out_umask;
1852 /* Create the socket file */
1854 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1856 if (sock == -1) {
1857 perror("socket");
1858 goto out_umask;
1861 pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1863 unlink(path);
1864 memset(&sunaddr, 0, sizeof(sunaddr));
1865 sunaddr.sun_family = AF_UNIX;
1866 safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1868 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1869 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1870 strerror(errno)));
1871 goto out_close;
1874 if (listen(sock, 5) == -1) {
1875 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1876 strerror(errno)));
1877 goto out_close;
1880 umask(old_umask);
1881 return sock;
1883 out_close:
1884 close(sock);
1886 out_umask:
1887 umask(old_umask);
1888 return -1;
1890 #else
1891 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1892 return -1;
1893 #endif /* HAVE_UNIXSOCKET */
1896 /****************************************************************************
1897 Get my own canonical name, including domain.
1898 ****************************************************************************/
1900 bool get_mydnsfullname(fstring my_dnsname)
1902 static fstring dnshostname;
1904 if (!*dnshostname) {
1905 struct addrinfo *res = NULL;
1906 bool ret;
1908 /* get my host name */
1909 if (gethostname(dnshostname, sizeof(dnshostname)) == -1) {
1910 *dnshostname = '\0';
1911 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1912 return false;
1915 /* Ensure null termination. */
1916 dnshostname[sizeof(dnshostname)-1] = '\0';
1918 ret = interpret_string_addr_internal(&res,
1919 dnshostname,
1920 AI_ADDRCONFIG|AI_CANONNAME);
1922 if (!ret || res == NULL) {
1923 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1924 "name %s [%s]\n",
1925 dnshostname,
1926 gai_strerror(ret) ));
1927 return false;
1931 * Make sure that getaddrinfo() returns the "correct" host name.
1934 if (res->ai_canonname == NULL) {
1935 DEBUG(3,("get_mydnsfullname: failed to get "
1936 "canonical name for %s\n",
1937 dnshostname));
1938 freeaddrinfo(res);
1939 return false;
1943 fstrcpy(dnshostname, res->ai_canonname);
1944 freeaddrinfo(res);
1946 fstrcpy(my_dnsname, dnshostname);
1947 return true;
1950 /************************************************************
1951 Is this my name ?
1952 ************************************************************/
1954 bool is_myname_or_ipaddr(const char *s)
1956 fstring name, dnsname;
1957 char *servername;
1959 if (!s) {
1960 return false;
1963 /* Santize the string from '\\name' */
1964 fstrcpy(name, s);
1966 servername = strrchr_m(name, '\\' );
1967 if (!servername) {
1968 servername = name;
1969 } else {
1970 servername++;
1973 /* Optimize for the common case */
1974 if (strequal(servername, global_myname())) {
1975 return true;
1978 /* Check for an alias */
1979 if (is_myname(servername)) {
1980 return true;
1983 /* Check for loopback */
1984 if (strequal(servername, "127.0.0.1") ||
1985 strequal(servername, "::1")) {
1986 return true;
1989 if (strequal(servername, "localhost")) {
1990 return true;
1993 /* Maybe it's my dns name */
1994 if (get_mydnsfullname(dnsname)) {
1995 if (strequal(servername, dnsname)) {
1996 return true;
2000 /* Handle possible CNAME records - convert to an IP addr. */
2001 if (!is_ipaddress(servername)) {
2002 /* Use DNS to resolve the name, but only the first address */
2003 struct sockaddr_storage ss;
2004 if (interpret_string_addr(&ss, servername,0)) {
2005 print_sockaddr(name,
2006 sizeof(name),
2007 &ss,
2008 sizeof(ss));
2009 servername = name;
2013 /* Maybe its an IP address? */
2014 if (is_ipaddress(servername)) {
2015 struct sockaddr_storage ss;
2016 struct iface_struct nics[MAX_INTERFACES];
2017 int i, n;
2019 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
2020 return false;
2023 if (is_zero_addr(&ss) || is_loopback_addr(&ss)) {
2024 return false;
2027 n = get_interfaces(nics, MAX_INTERFACES);
2028 for (i=0; i<n; i++) {
2029 if (addr_equal(&nics[i].ip, &ss)) {
2030 return true;
2035 /* No match */
2036 return false;