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/>.
24 /* the following 3 client_*() functions are nasty ways of allowing
25 some generic functions to get info that really should be hidden in
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 a pure IPv4 address.
33 ****************************************************************************/
35 bool is_ipaddress_v4(const char *str)
37 bool pure_address = true;
40 for (i=0; pure_address && str[i]; i++) {
41 if (!(isdigit((int)str[i]) || str[i] == '.')) {
46 /* Check that a pure number is not misinterpreted as an IP */
47 pure_address = pure_address && (strchr_m(str, '.') != NULL);
51 /****************************************************************************
52 Interpret an internet address or name into an IP address in 4 byte form.
53 ****************************************************************************/
55 uint32 interpret_addr(const char *str)
60 if (strcmp(str,"0.0.0.0") == 0)
62 if (strcmp(str,"255.255.255.255") == 0)
65 /* if it's in the form of an IP address then
66 * get the lib to interpret it */
67 if (is_ipaddress_v4(str)) {
70 /* otherwise assume it's a network name of some sort and use
72 if ((hp = sys_gethostbyname(str)) == 0) {
73 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
77 if(hp->h_addr == NULL) {
78 DEBUG(3,("sys_gethostbyname: host address is "
79 "invalid for host %s\n",str));
82 putip((char *)&res,(char *)hp->h_addr);
85 if (res == (uint32)-1)
91 /*******************************************************************
92 A convenient addition to interpret_addr().
93 ******************************************************************/
95 struct in_addr *interpret_addr2(const char *str)
97 static struct in_addr ret;
98 uint32 a = interpret_addr(str);
103 /*******************************************************************
104 Map a text hostname or IP address (IPv4 or IPv6) into a
105 struct sockaddr_storage.
106 ******************************************************************/
108 bool interpret_string_addr(struct sockaddr_storage *pss, const char *str)
111 struct addrinfo *res = NULL;
112 struct addrinfo hints;
114 memset(pss,'\0', sizeof(*pss));
116 memset(&hints, '\0', sizeof(hints));
117 /* By default make sure it supports TCP. */
118 hints.ai_socktype = SOCK_STREAM;
119 hints.ai_flags = AI_ADDRCONFIG;
121 ret = getaddrinfo(str, NULL,
126 DEBUG(3,("interpret_string_addr: getaddrinfo failed for "
129 gai_strerror(ret) ));
133 /* Copy the first sockaddr. */
134 memcpy(pss, res->ai_addr, res->ai_addrlen);
139 /*******************************************************************
140 Check if an IPv7 is 127.0.0.1
141 ******************************************************************/
143 bool is_loopback_ip_v4(struct in_addr ip)
146 a.s_addr = htonl(INADDR_LOOPBACK);
147 return(ip.s_addr == a.s_addr);
150 /*******************************************************************
151 Check if a struct sockaddr_storage is the loopback address.
152 ******************************************************************/
154 bool is_loopback_addr(const struct sockaddr_storage *pss)
156 #if defined(AF_INET6)
157 if (pss->ss_family == AF_INET) {
158 struct in6_addr *pin6 = &((struct sockaddr_in6 *)pss)->sin6_addr;
159 return IN6_IS_ADDR_LOOPBACK(pin6);
162 if (pss->ss_family == AF_INET) {
163 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
164 return is_loopback_ip_v4(*pin);
169 /*******************************************************************
170 Check if an IPv4 is 0.0.0.0.
171 ******************************************************************/
173 bool is_zero_ip_v4(struct in_addr ip)
176 putip((char *)&a,(char *)&ip);
180 /*******************************************************************
181 Check if a struct sockaddr_storage has an unspecified address.
182 ******************************************************************/
184 bool is_zero_addr(const struct sockaddr_storage *pss)
186 #if defined(AF_INET6)
187 if (pss->ss_family == AF_INET) {
188 struct in6_addr *pin6 = &((struct sockaddr_in6 *)pss)->sin6_addr;
189 return IN6_IS_ADDR_UNSPECIFIED(pin6);
192 if (pss->ss_family == AF_INET) {
193 struct in_addr *pin = &((struct sockaddr_in *)pss)->sin_addr;
194 return is_zero_ip_v4(*pin);
199 /*******************************************************************
200 Set an IP to 0.0.0.0.
201 ******************************************************************/
203 void zero_ip_v4(struct in_addr *ip)
206 static struct in_addr ipzero;
209 ipzero = *interpret_addr2("0.0.0.0");
216 /*******************************************************************
217 Are two IPs on the same subnet - IPv4 version ?
218 ********************************************************************/
220 bool same_net_v4(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
222 uint32 net1,net2,nmask;
224 nmask = ntohl(mask.s_addr);
225 net1 = ntohl(ip1.s_addr);
226 net2 = ntohl(ip2.s_addr);
228 return((net1 & nmask) == (net2 & nmask));
231 /*******************************************************************
232 Convert an IPv4 struct in_addr to a struct sockaddr_storage.
233 ********************************************************************/
235 void in_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
238 struct sockaddr_in *sa = (struct sockaddr_in *)ss;
239 memset(ss, '\0', sizeof(*ss));
240 ss->ss_family = AF_INET;
245 /*******************************************************************
246 Convert an IPv6 struct in_addr to a struct sockaddr_storage.
247 ********************************************************************/
249 void in6_addr_to_sockaddr_storage(struct sockaddr_storage *ss,
252 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)ss;
253 memset(ss, '\0', sizeof(*ss));
254 ss->ss_family = AF_INET6;
259 /*******************************************************************
260 Are two IPs on the same subnet?
261 ********************************************************************/
263 bool same_net(const struct sockaddr_storage *ip1,
264 const struct sockaddr_storage *ip2,
265 const struct sockaddr_storage *mask)
267 if (ip1->ss_family != ip2->ss_family) {
268 /* Never on the same net. */
273 if (ip1->ss_family == AF_INET6) {
274 struct sockaddr_in6 ip1_6 = *(struct sockaddr_in6 *)ip1;
275 struct sockaddr_in6 ip2_6 = *(struct sockaddr_in6 *)ip2;
276 struct sockaddr_in6 mask_6 = *(struct sockaddr_in6 *)mask;
277 char *p1 = (char *)&ip1_6.sin6_addr;
278 char *p2 = (char *)&ip2_6.sin6_addr;
279 char *m = (char *)&mask_6.sin6_addr;
282 for (i = 0; i < sizeof(struct in6_addr); i++) {
287 return (memcmp(&ip1_6.sin6_addr,
289 sizeof(struct in6_addr)) == 0);
292 if (ip1->ss_family == AF_INET) {
293 return same_net_v4(((const struct sockaddr_in *)ip1)->sin_addr,
294 ((const struct sockaddr_in *)ip2)->sin_addr,
295 ((const struct sockaddr_in *)mask)->sin_addr);
300 /*******************************************************************
301 Are two sockaddr_storage's the same family and address ? Ignore port etc.
302 ********************************************************************/
304 bool addr_equal(const struct sockaddr_storage *ip1,
305 const struct sockaddr_storage *ip2)
307 if (ip1->ss_family != ip2->ss_family) {
308 /* Never the same. */
313 if (ip1->ss_family == AF_INET6) {
314 return (memcmp(&((const struct sockaddr_in6 *)ip1)->sin6_addr,
315 &((const struct sockaddr_in6 *)ip2)->sin6_addr,
316 sizeof(struct in6_addr)) == 0);
319 if (ip1->ss_family == AF_INET) {
320 return (memcmp(&((const struct sockaddr_in *)ip1)->sin_addr,
321 &((const struct sockaddr_in *)ip2)->sin_addr,
322 sizeof(struct in_addr)) == 0);
328 /****************************************************************************
329 Is an IP address the INADDR_ANY or in6addr_any value ?
330 ****************************************************************************/
332 bool is_address_any(const struct sockaddr_storage *psa)
335 if (psa->ss_family == AF_INET6) {
336 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)psa;
337 if (memcmp(&in6addr_any,
339 sizeof(in6addr_any)) == 0) {
345 if (psa->ss_family == AF_INET) {
346 struct sockaddr_in *si = (struct sockaddr_in *)psa;
347 if (si->sin_addr.s_addr == INADDR_ANY) {
355 /****************************************************************************
356 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
357 ****************************************************************************/
359 char *print_sockaddr(char *dest,
361 const struct sockaddr_storage *psa,
367 (void)getnameinfo((const struct sockaddr *)psa,
375 /****************************************************************************
376 Set the global client_fd variable.
377 ****************************************************************************/
379 void client_setfd(int fd)
382 safe_strcpy(client_ip_string,
383 get_peer_addr(client_fd),
384 sizeof(client_ip_string)-1);
387 /****************************************************************************
388 Return a static string of an IP address (IPv4 or IPv6).
389 ****************************************************************************/
391 static char *get_socket_addr(int fd)
393 struct sockaddr_storage sa;
394 socklen_t length = sizeof(sa);
395 static char addr_buf[INET6_ADDRSTRLEN];
397 /* Ok, returning a hard coded IPv4 address
398 * is bogus, but it's just as bogus as a
399 * zero IPv6 address. No good choice here.
402 safe_strcpy(addr_buf, "0.0.0.0", sizeof(addr_buf)-1);
408 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
409 DEBUG(0,("getsockname failed. Error was %s\n",
414 return print_sockaddr(addr_buf, sizeof(addr_buf), &sa, length);
417 /****************************************************************************
418 Return the port number we've bound to on a socket.
419 ****************************************************************************/
421 static int get_socket_port(int fd)
423 struct sockaddr_storage sa;
424 socklen_t length = sizeof(sa);
430 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
431 DEBUG(0,("getpeername failed. Error was %s\n",
437 if (sa.ss_family == AF_INET6) {
438 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
441 if (sa.ss_family == AF_INET) {
442 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
447 char *client_name(void)
449 return get_peer_name(client_fd,false);
452 char *client_addr(void)
454 return get_peer_addr(client_fd);
457 char *client_socket_addr(void)
459 return get_socket_addr(client_fd);
462 int client_socket_port(void)
464 return get_socket_port(client_fd);
467 int smb_read_error = 0;
469 /****************************************************************************
470 Determine if a file descriptor is in fact a socket.
471 ****************************************************************************/
473 bool is_a_socket(int fd)
478 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
481 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
483 typedef struct smb_socket_option {
491 static const smb_socket_option socket_options[] = {
492 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
493 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
494 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
496 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
499 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
502 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
505 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
507 #ifdef IPTOS_LOWDELAY
508 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
510 #ifdef IPTOS_THROUGHPUT
511 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
514 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
517 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
520 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
523 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
526 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
529 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
532 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
535 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
539 /****************************************************************************
540 Print socket options.
541 ****************************************************************************/
543 static void print_socket_options(int s)
547 const smb_socket_option *p = &socket_options[0];
549 /* wrapped in if statement to prevent streams
550 * leak in SCO Openserver 5.0 */
551 /* reported on samba-technical --jerry */
552 if ( DEBUGLEVEL >= 5 ) {
553 for (; p->name != NULL; p++) {
554 if (getsockopt(s, p->level, p->option,
555 (void *)&value, &vlen) == -1) {
556 DEBUG(5,("Could not test socket option %s.\n",
559 DEBUG(5,("socket option %s = %d\n",
566 /****************************************************************************
567 Set user socket options.
568 ****************************************************************************/
570 void set_socket_options(int fd, const char *options)
574 while (next_token(&options,tok," \t,", sizeof(tok))) {
578 bool got_value = false;
580 if ((p = strchr_m(tok,'='))) {
586 for (i=0;socket_options[i].name;i++)
587 if (strequal(socket_options[i].name,tok))
590 if (!socket_options[i].name) {
591 DEBUG(0,("Unknown socket option %s\n",tok));
595 switch (socket_options[i].opttype) {
598 ret = setsockopt(fd,socket_options[i].level,
599 socket_options[i].option,
600 (char *)&value,sizeof(int));
605 DEBUG(0,("syntax error - %s "
606 "does not take a value\n",tok));
609 int on = socket_options[i].value;
610 ret = setsockopt(fd,socket_options[i].level,
611 socket_options[i].option,
612 (char *)&on,sizeof(int));
618 DEBUG(0,("Failed to set socket option %s (Error %s)\n",
619 tok, strerror(errno) ));
623 print_socket_options(fd);
626 /****************************************************************************
628 ****************************************************************************/
630 ssize_t read_udp_v4_socket(int fd,
633 struct sockaddr_storage *psa)
636 socklen_t socklen = sizeof(*psa);
637 struct sockaddr_in *si = (struct sockaddr_in *)psa;
639 memset((char *)psa,'\0',socklen);
641 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
642 (struct sockaddr *)psa,&socklen);
644 /* Don't print a low debug error for a non-blocking socket. */
645 if (errno == EAGAIN) {
646 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
648 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
654 if (psa->ss_family != AF_INET) {
655 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
656 "(not IPv4)\n", (int)psa->ss_family));
660 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
661 inet_ntoa(si->sin_addr),
663 (unsigned long)ret));
668 /****************************************************************************
669 Read data from a socket with a timout in msec.
670 mincount = if timeout, minimum to read before returning
671 maxcount = number to be read.
672 time_out = timeout in milliseconds
673 ****************************************************************************/
675 ssize_t read_socket_with_timeout(int fd,
679 unsigned int time_out)
685 struct timeval timeout;
687 /* just checking .... */
699 while (nread < mincnt) {
700 readret = sys_read(fd, buf + nread, maxcnt - nread);
703 DEBUG(5,("read_socket_with_timeout: "
704 "blocking read. EOF from client.\n"));
705 smb_read_error = READ_EOF;
710 if (fd == client_fd) {
711 /* Try and give an error message
712 * saying what client failed. */
713 DEBUG(0,("read_socket_with_timeout: "
714 "client %s read error = %s.\n",
718 DEBUG(0,("read_socket_with_timeout: "
719 "read error = %s.\n",
722 smb_read_error = READ_ERROR;
727 return((ssize_t)nread);
730 /* Most difficult - timeout read */
731 /* If this is ever called on a disk file and
732 mincnt is greater then the filesize then
733 system performance will suffer severely as
734 select always returns true on disk files */
736 /* Set initial timeout */
737 timeout.tv_sec = (time_t)(time_out / 1000);
738 timeout.tv_usec = (long)(1000 * (time_out % 1000));
740 for (nread=0; nread < mincnt; ) {
744 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
748 /* something is wrong. Maybe the socket is dead? */
749 if (fd == client_fd) {
750 /* Try and give an error message saying
751 * what client failed. */
752 DEBUG(0,("read_socket_with_timeout: timeout "
753 "read for client %s. select error = %s.\n",
754 client_ip_string, strerror(errno) ));
756 DEBUG(0,("read_socket_with_timeout: timeout "
757 "read. select error = %s.\n",
760 smb_read_error = READ_ERROR;
764 /* Did we timeout ? */
766 DEBUG(10,("read_socket_with_timeout: timeout read. "
767 "select timed out.\n"));
768 smb_read_error = READ_TIMEOUT;
772 readret = sys_read(fd, buf+nread, maxcnt-nread);
775 /* we got EOF on the file descriptor */
776 DEBUG(5,("read_socket_with_timeout: timeout read. "
777 "EOF from client.\n"));
778 smb_read_error = READ_EOF;
783 /* the descriptor is probably dead */
784 if (fd == client_fd) {
785 /* Try and give an error message
786 * saying what client failed. */
787 DEBUG(0,("read_socket_with_timeout: timeout "
788 "read to client %s. read error = %s.\n",
789 client_ip_string, strerror(errno) ));
791 DEBUG(0,("read_socket_with_timeout: timeout "
792 "read. read error = %s.\n",
795 smb_read_error = READ_ERROR;
802 /* Return the number we got */
803 return (ssize_t)nread;
806 /****************************************************************************
807 Read data from the client, reading exactly N bytes.
808 ****************************************************************************/
810 ssize_t read_data(int fd,char *buffer,size_t N)
818 ret = sys_read(fd,buffer + total,N - total);
821 DEBUG(10,("read_data: read of %d returned 0. "
823 (int)(N - total), strerror(errno) ));
824 smb_read_error = READ_EOF;
829 if (fd == client_fd) {
830 /* Try and give an error message saying
831 * what client failed. */
832 DEBUG(0,("read_data: read failure for %d "
833 "bytes to client %s. Error = %s\n",
838 DEBUG(0,("read_data: read failure for %d. "
843 smb_read_error = READ_ERROR;
848 return (ssize_t)total;
851 /****************************************************************************
853 ****************************************************************************/
855 ssize_t write_data(int fd, const char *buffer, size_t N)
861 ret = sys_write(fd,buffer + total,N - total);
864 if (fd == client_fd) {
865 /* Try and give an error message saying
866 * what client failed. */
867 DEBUG(0,("write_data: write failure in "
868 "writing to client %s. Error %s\n",
869 client_ip_string, strerror(errno) ));
871 DEBUG(0,("write_data: write failure. "
872 "Error = %s\n", strerror(errno) ));
883 return (ssize_t)total;
886 /****************************************************************************
887 Send a keepalive packet (rfc1002).
888 ****************************************************************************/
890 bool send_keepalive(int client)
892 unsigned char buf[4];
894 buf[0] = SMBkeepalive;
895 buf[1] = buf[2] = buf[3] = 0;
897 return(write_data(client,(char *)buf,4) == 4);
900 /****************************************************************************
901 Read 4 bytes of a smb packet and return the smb length of the packet.
902 Store the result in the buffer.
903 This version of the function will return a length of zero on receiving
905 Timeout is in milliseconds.
906 ****************************************************************************/
908 static ssize_t read_smb_length_return_keepalive(int fd,
910 unsigned int timeout)
918 ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout)
921 ok = (read_data(fd,inbuf,4) == 4);
927 len = smb_len(inbuf);
928 msg_type = CVAL(inbuf,0);
930 if (msg_type == SMBkeepalive) {
931 DEBUG(5,("Got keepalive packet\n"));
935 DEBUG(10,("got smb length of %lu\n",(unsigned long)len));
940 /****************************************************************************
941 Read 4 bytes of a smb packet and return the smb length of the packet.
942 Store the result in the buffer. This version of the function will
943 never return a session keepalive (length of zero).
944 Timeout is in milliseconds.
945 ****************************************************************************/
947 ssize_t read_smb_length(int fd, char *inbuf, unsigned int timeout)
952 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
957 /* Ignore session keepalives. */
958 if(CVAL(inbuf,0) != SMBkeepalive)
962 DEBUG(10,("read_smb_length: got smb length of %lu\n",
963 (unsigned long)len));
968 /****************************************************************************
969 Read an smb from a fd. Note that the buffer *MUST* be of size
970 BUFFER_SIZE+SAFETY_MARGIN.
971 The timeout is in milliseconds.
972 This function will return on receipt of a session keepalive packet.
973 maxlen is the max number of bytes to return, not including the 4 byte
974 length. If zero it means BUFFER_SIZE+SAFETY_MARGIN limit.
975 Doesn't check the MAC on signed packets.
976 ****************************************************************************/
978 ssize_t receive_smb_raw(int fd,
980 unsigned int timeout,
987 len = read_smb_length_return_keepalive(fd,buffer,timeout);
989 DEBUG(10,("receive_smb_raw: length < 0!\n"));
992 * Correct fix. smb_read_error may have already been
993 * set. Only set it here if not already set. Global
994 * variables still suck :-). JRA.
997 if (smb_read_error == 0)
998 smb_read_error = READ_ERROR;
1003 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
1004 * of header. Don't print the error if this fits.... JRA.
1007 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
1008 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
1009 (unsigned long)len));
1010 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
1013 * Correct fix. smb_read_error may have already been
1014 * set. Only set it here if not already set. Global
1015 * variables still suck :-). JRA.
1018 if (smb_read_error == 0)
1019 smb_read_error = READ_ERROR;
1026 len = MIN(len,maxlen);
1030 ret = read_socket_with_timeout(fd,
1036 ret = read_data(fd,buffer+4,len);
1040 if (smb_read_error == 0) {
1041 smb_read_error = READ_ERROR;
1046 /* not all of samba3 properly checks for packet-termination
1047 * of strings. This ensures that we don't run off into
1049 SSVAL(buffer+4,len, 0);
1055 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
1056 char **buffer, unsigned int timeout)
1063 len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
1065 DEBUG(10,("receive_smb_raw: length < 0!\n"));
1068 * Correct fix. smb_read_error may have already been
1069 * set. Only set it here if not already set. Global
1070 * variables still suck :-). JRA.
1073 if (smb_read_error == 0)
1074 smb_read_error = READ_ERROR;
1079 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
1080 * of header. Don't print the error if this fits.... JRA.
1083 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
1084 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
1085 (unsigned long)len));
1086 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
1089 * Correct fix. smb_read_error may have already been
1090 * set. Only set it here if not already set. Global
1091 * variables still suck :-). JRA.
1094 if (smb_read_error == 0)
1095 smb_read_error = READ_ERROR;
1101 * The +4 here can't wrap, we've checked the length above already.
1104 *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
1106 if (*buffer == NULL) {
1107 DEBUG(0, ("Could not allocate inbuf of length %d\n",
1109 if (smb_read_error == 0)
1110 smb_read_error = READ_ERROR;
1114 memcpy(*buffer, lenbuf, sizeof(lenbuf));
1118 ret = read_socket_with_timeout(fd,(*buffer)+4, len,
1121 ret = read_data(fd, (*buffer)+4, len);
1125 if (smb_read_error == 0) {
1126 smb_read_error = READ_ERROR;
1135 /****************************************************************************
1136 Wrapper for receive_smb_raw().
1137 Checks the MAC on signed packets.
1138 ****************************************************************************/
1140 bool receive_smb(int fd, char *buffer, unsigned int timeout)
1142 if (receive_smb_raw(fd, buffer, timeout, 0) < 0) {
1146 /* Check the incoming SMB signature. */
1147 if (!srv_check_sign_mac(buffer, true)) {
1148 DEBUG(0, ("receive_smb: SMB Signature verification "
1149 "failed on incoming packet!\n"));
1150 if (smb_read_error == 0) {
1151 smb_read_error = READ_BAD_SIG;
1159 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
1160 unsigned int timeout)
1164 len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
1170 /* Check the incoming SMB signature. */
1171 if (!srv_check_sign_mac(*buffer, true)) {
1172 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
1173 "incoming packet!\n"));
1174 if (smb_read_error == 0) {
1175 smb_read_error = READ_BAD_SIG;
1183 /****************************************************************************
1184 Send an smb to a fd.
1185 ****************************************************************************/
1187 bool send_smb(int fd, char *buffer)
1193 /* Sign the outgoing packet if required. */
1194 srv_calculate_sign_mac(buffer);
1196 len = smb_len(buffer) + 4;
1198 while (nwritten < len) {
1199 ret = write_data(fd,buffer+nwritten,len - nwritten);
1201 DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
1202 (int)len,(int)ret, strerror(errno) ));
1211 /****************************************************************************
1212 Open a socket of the specified type, port, and address for incoming data.
1213 ****************************************************************************/
1215 int open_socket_in(int type,
1221 struct sockaddr_in sock;
1224 memset( (char *)&sock, '\0', sizeof(sock) );
1226 #ifdef HAVE_SOCK_SIN_LEN
1227 sock.sin_len = sizeof(sock);
1229 sock.sin_port = htons( port );
1230 sock.sin_family = AF_INET;
1231 sock.sin_addr.s_addr = socket_addr;
1233 res = socket( AF_INET, type, 0 );
1236 dbgtext( "open_socket_in(): socket() call failed: " );
1237 dbgtext( "%s\n", strerror( errno ) );
1242 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
1244 int val = rebind ? 1 : 0;
1245 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
1246 (char *)&val,sizeof(val)) == -1 ) {
1247 if( DEBUGLVL( dlevel ) ) {
1248 dbgtext( "open_socket_in(): setsockopt: " );
1249 dbgtext( "SO_REUSEADDR = %s ",
1250 val?"true":"false" );
1251 dbgtext( "on port %d failed ", port );
1252 dbgtext( "with error = %s\n", strerror(errno) );
1256 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
1257 (char *)&val,sizeof(val)) == -1 ) {
1258 if( DEBUGLVL( dlevel ) ) {
1259 dbgtext( "open_socket_in(): setsockopt: ");
1260 dbgtext( "SO_REUSEPORT = %s ",
1261 val?"true":"false" );
1262 dbgtext( "on port %d failed ", port );
1263 dbgtext( "with error = %s\n", strerror(errno) );
1266 #endif /* SO_REUSEPORT */
1269 /* now we've got a socket - we need to bind it */
1270 if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
1271 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
1272 port == SMB_PORT2 || port == NMB_PORT) ) {
1273 dbgtext( "bind failed on port %d ", port );
1274 dbgtext( "socket_addr = %s.\n",
1275 inet_ntoa( sock.sin_addr ) );
1276 dbgtext( "Error = %s\n", strerror(errno) );
1282 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
1287 /****************************************************************************
1288 Create an outgoing socket. timeout is in milliseconds.
1289 **************************************************************************/
1291 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
1293 struct sockaddr_in sock_out;
1295 int connect_loop = 10;
1298 /* create a socket to write to */
1299 res = socket(PF_INET, type, 0);
1301 DEBUG(0,("socket error (%s)\n", strerror(errno)));
1305 if (type != SOCK_STREAM)
1308 memset((char *)&sock_out,'\0',sizeof(sock_out));
1309 putip((char *)&sock_out.sin_addr,(char *)addr);
1311 sock_out.sin_port = htons( port );
1312 sock_out.sin_family = PF_INET;
1314 /* set it non-blocking */
1315 set_blocking(res,false);
1317 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
1319 /* and connect it to the destination */
1322 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
1324 /* Some systems return EAGAIN when they mean EINPROGRESS */
1325 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1326 errno == EAGAIN) && (connect_loop < timeout) ) {
1327 smb_msleep(connect_loop);
1328 timeout -= connect_loop;
1329 connect_loop += increment;
1330 if (increment < 250) {
1331 /* After 8 rounds we end up at a max of 255 msec */
1337 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1339 DEBUG(1,("timeout connecting to %s:%d\n",
1340 inet_ntoa(*addr),port));
1346 if (ret < 0 && errno == EISCONN) {
1353 DEBUG(2,("error connecting to %s:%d (%s)\n",
1354 inet_ntoa(*addr),port,strerror(errno)));
1359 /* set it blocking again */
1360 set_blocking(res,true);
1365 /****************************************************************************
1366 Create an outgoing TCP socket to any of the addrs. This is for
1367 simultaneous connects to port 445 and 139 of a host or even a variety
1368 of DC's all of which are equivalent for our purposes.
1369 **************************************************************************/
1371 bool open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1372 int timeout, int *fd_index, int *fd)
1374 int i, resulting_index, res;
1378 fd_set r_fds, wr_fds;
1382 int connect_loop = 10000; /* 10 milliseconds */
1384 timeout *= 1000; /* convert to microseconds */
1386 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1388 if (sockets == NULL)
1391 resulting_index = -1;
1393 for (i=0; i<num_addrs; i++)
1396 for (i=0; i<num_addrs; i++) {
1397 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1400 set_blocking(sockets[i], false);
1404 good_connect = false;
1406 for (i=0; i<num_addrs; i++) {
1408 if (sockets[i] == -1)
1411 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1412 sizeof(*addrs)) == 0) {
1413 /* Rather unlikely as we are non-blocking, but it
1414 * might actually happen. */
1415 resulting_index = i;
1419 if (errno == EINPROGRESS || errno == EALREADY ||
1423 errno == EAGAIN || errno == EINTR) {
1424 /* These are the error messages that something is
1426 good_connect = true;
1427 } else if (errno != 0) {
1428 /* There was a direct error */
1434 if (!good_connect) {
1435 /* All of the connect's resulted in real error conditions */
1439 /* Lets see if any of the connect attempts succeeded */
1445 for (i=0; i<num_addrs; i++) {
1446 if (sockets[i] == -1)
1448 FD_SET(sockets[i], &wr_fds);
1449 FD_SET(sockets[i], &r_fds);
1450 if (sockets[i]>maxfd)
1455 tv.tv_usec = connect_loop;
1457 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1465 for (i=0; i<num_addrs; i++) {
1467 if (sockets[i] == -1)
1470 /* Stevens, Network Programming says that if there's a
1471 * successful connect, the socket is only writable. Upon an
1472 * error, it's both readable and writable. */
1474 if (FD_ISSET(sockets[i], &r_fds) &&
1475 FD_ISSET(sockets[i], &wr_fds)) {
1476 /* readable and writable, so it's an error */
1482 if (!FD_ISSET(sockets[i], &r_fds) &&
1483 FD_ISSET(sockets[i], &wr_fds)) {
1484 /* Only writable, so it's connected */
1485 resulting_index = i;
1492 timeout -= connect_loop;
1495 connect_loop *= 1.5;
1496 if (connect_loop > timeout)
1497 connect_loop = timeout;
1501 for (i=0; i<num_addrs; i++) {
1502 if (i == resulting_index)
1504 if (sockets[i] >= 0)
1508 if (resulting_index >= 0) {
1509 *fd_index = resulting_index;
1510 *fd = sockets[*fd_index];
1511 set_blocking(*fd, true);
1516 return (resulting_index >= 0);
1518 /****************************************************************************
1519 Open a connected UDP socket to host on port
1520 **************************************************************************/
1522 int open_udp_socket(const char *host, int port)
1524 int type = SOCK_DGRAM;
1525 struct sockaddr_in sock_out;
1527 struct in_addr *addr;
1529 addr = interpret_addr2(host);
1531 res = socket(PF_INET, type, 0);
1536 memset((char *)&sock_out,'\0',sizeof(sock_out));
1537 putip((char *)&sock_out.sin_addr,(char *)addr);
1538 sock_out.sin_port = htons(port);
1539 sock_out.sin_family = PF_INET;
1541 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1549 /*******************************************************************
1550 Matchname - determine if host name matches IP address. Used to
1551 confirm a hostname lookup to prevent spoof attacks.
1552 ******************************************************************/
1554 static bool matchname(char *remotehost,struct in_addr addr)
1559 if ((hp = sys_gethostbyname(remotehost)) == 0) {
1560 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n",
1566 * Make sure that gethostbyname() returns the "correct" host name.
1567 * Unfortunately, gethostbyname("localhost") sometimes yields
1568 * "localhost.domain". Since the latter host name comes from the
1569 * local DNS, we just have to trust it (all bets are off if the local
1570 * DNS is perverted). We always check the address list, though.
1573 if (!strequal(remotehost, hp->h_name)
1574 && !strequal(remotehost, "localhost")) {
1575 DEBUG(0,("host name/name mismatch: %s != %s\n",
1576 remotehost, hp->h_name));
1580 /* Look up the host address in the address list we just got. */
1581 for (i = 0; hp->h_addr_list[i]; i++) {
1582 if (memcmp(hp->h_addr_list[i], (char *)&addr,sizeof(addr)) == 0)
1587 * The host name does not map to the original host address. Perhaps
1588 * someone has compromised a name server. More likely someone botched
1589 * it, but that could be dangerous, too.
1592 DEBUG(0,("host name/address mismatch: %s != %s\n",
1593 inet_ntoa(addr), hp->h_name));
1597 /*******************************************************************
1598 Return the DNS name of the remote end of a socket.
1599 ******************************************************************/
1601 char *get_peer_name(int fd, bool force_lookup)
1603 static pstring name_buf;
1605 static fstring addr_buf;
1607 struct in_addr addr;
1610 /* reverse lookups can be *very* expensive, and in many
1611 situations won't work because many networks don't link dhcp
1612 with dns. To avoid the delay we avoid the lookup if
1614 if (!lp_hostname_lookups() && (force_lookup == false)) {
1615 return get_peer_addr(fd);
1618 p = get_peer_addr(fd);
1620 /* it might be the same as the last one - save some DNS work */
1621 if (strcmp(p, addr_buf) == 0)
1624 pstrcpy(name_buf,"UNKNOWN");
1628 fstrcpy(addr_buf, p);
1630 addr = *interpret_addr2(p);
1632 /* Look up the remote host name. */
1633 if ((hp = gethostbyaddr((char *)&addr.s_addr,
1634 sizeof(addr.s_addr), AF_INET)) == 0) {
1635 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1636 pstrcpy(name_buf, p);
1638 pstrcpy(name_buf,(char *)hp->h_name);
1639 if (!matchname(name_buf, addr)) {
1640 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1641 pstrcpy(name_buf,"UNKNOWN");
1645 /* can't pass the same source and dest strings in when you
1646 use --enable-developer or the clobber_region() call will
1649 pstrcpy( tmp_name, name_buf );
1650 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1651 if (strstr(name_buf,"..")) {
1652 pstrcpy(name_buf, "UNKNOWN");
1658 /*******************************************************************
1659 Return the IP addr of the remote end of a socket as a string.
1660 ******************************************************************/
1662 char *get_peer_addr(int fd)
1665 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1666 socklen_t length = sizeof(sa);
1667 static fstring addr_buf;
1669 fstrcpy(addr_buf,"0.0.0.0");
1675 if (getpeername(fd, &sa, &length) < 0) {
1676 DEBUG(0,("getpeername failed. Error was %s\n",
1681 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1686 /*******************************************************************
1687 Create protected unix domain socket.
1689 Some unixes cannot set permissions on a ux-dom-sock, so we
1690 have to make sure that the directory contains the protection
1691 permissions instead.
1692 ******************************************************************/
1694 int create_pipe_sock(const char *socket_dir,
1695 const char *socket_name,
1698 #ifdef HAVE_UNIXSOCKET
1699 struct sockaddr_un sunaddr;
1705 old_umask = umask(0);
1707 /* Create the socket directory or reuse the existing one */
1709 if (lstat(socket_dir, &st) == -1) {
1710 if (errno == ENOENT) {
1711 /* Create directory */
1712 if (mkdir(socket_dir, dir_perms) == -1) {
1713 DEBUG(0, ("error creating socket directory "
1714 "%s: %s\n", socket_dir,
1719 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1720 socket_dir, strerror(errno)));
1724 /* Check ownership and permission on existing directory */
1725 if (!S_ISDIR(st.st_mode)) {
1726 DEBUG(0, ("socket directory %s isn't a directory\n",
1730 if ((st.st_uid != sec_initial_uid()) ||
1731 ((st.st_mode & 0777) != dir_perms)) {
1732 DEBUG(0, ("invalid permissions on socket directory "
1733 "%s\n", socket_dir));
1738 /* Create the socket file */
1740 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1747 pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1750 memset(&sunaddr, 0, sizeof(sunaddr));
1751 sunaddr.sun_family = AF_UNIX;
1752 safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1754 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1755 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1760 if (listen(sock, 5) == -1) {
1761 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1777 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1779 #endif /* HAVE_UNIXSOCKET */
1782 /************************************************************
1783 Is this my name ? Needs fixing for IPv6.
1784 ************************************************************/
1786 bool is_myname_or_ipaddr(const char *s)
1788 fstring name, dnsname;
1794 /* santize the string from '\\name' */
1798 servername = strrchr_m( name, '\\' );
1804 /* optimize for the common case */
1806 if (strequal(servername, global_myname()))
1809 /* check for an alias */
1811 if (is_myname(servername))
1814 /* check for loopback */
1816 if (strequal(servername, "127.0.0.1"))
1819 if (strequal(servername, "localhost"))
1822 /* maybe it's my dns name */
1824 if ( get_mydnsfullname( dnsname ) )
1825 if ( strequal( servername, dnsname ) )
1828 /* handle possible CNAME records */
1830 if ( !is_ipaddress_v4( servername ) ) {
1831 /* use DNS to resolve the name, but only the first address */
1834 if (((hp = sys_gethostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
1835 struct in_addr return_ip;
1836 putip( (char*)&return_ip, (char*)hp->h_addr );
1837 fstrcpy( name, inet_ntoa( return_ip ) );
1842 /* maybe its an IP address? */
1843 if (is_ipaddress_v4(servername)) {
1844 struct sockaddr_storage ss;
1845 struct iface_struct nics[MAX_INTERFACES];
1849 ip = *interpret_addr2(servername);
1850 if (is_zero_ip_v4(ip) || is_loopback_ip_v4(ip)) {
1854 in_addr_to_sockaddr_storage(&ss, ip);
1856 n = get_interfaces(nics, MAX_INTERFACES);
1857 for (i=0; i<n; i++) {
1858 if (nics[i].ip.ss_family != AF_INET) {
1861 if (addr_equal(&nics[i].ip, &ss)) {