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 Pritn out an IPv4 or IPv6 address from a struct sockaddr_storage.
33 ****************************************************************************/
35 char *print_sockaddr(char *dest,
37 struct sockaddr_storage *psa)
43 if (psa->ss_family == AF_INET6) {
45 &((struct sockaddr_in6 *)psa)->sin6_addr,
50 if (psa->ss_family == AF_INET) {
52 &((struct sockaddr_in *)psa)->sin_addr,
59 void client_setfd(int fd)
62 safe_strcpy(client_ip_string,
63 get_peer_addr(client_fd),
64 sizeof(client_ip_string)-1);
67 static char *get_socket_addr(int fd)
69 struct sockaddr_storage sa;
70 socklen_t length = sizeof(sa);
71 static char addr_buf[INET6_ADDRSTRLEN];
73 /* Ok, returning a hard coded IPv4 address
74 * is bogus, but it's just as bogus as a
75 * zero IPv6 address. No good choice here.
78 safe_strcpy(addr_buf, "0.0.0.0", sizeof(addr_buf)-1);
84 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
85 DEBUG(0,("getsockname failed. Error was %s\n",
90 return print_sockaddr(addr_buf, sizeof(addr_buf), &sa);
93 static int get_socket_port(int fd)
95 struct sockaddr_storage sa;
96 socklen_t length = sizeof(sa);
102 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
103 DEBUG(0,("getpeername failed. Error was %s\n",
109 if (sa.ss_family == AF_INET6) {
110 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
113 if (sa.ss_family == AF_INET) {
114 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
119 char *client_name(void)
121 return get_peer_name(client_fd,False);
124 char *client_addr(void)
126 return get_peer_addr(client_fd);
129 char *client_socket_addr(void)
131 return get_socket_addr(client_fd);
134 int client_socket_port(void)
136 return get_socket_port(client_fd);
139 int smb_read_error = 0;
141 /****************************************************************************
142 Determine if a file descriptor is in fact a socket.
143 ****************************************************************************/
145 BOOL is_a_socket(int fd)
150 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
153 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
155 typedef struct smb_socket_option {
163 static const smb_socket_option socket_options[] = {
164 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
165 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
166 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
168 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
171 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
174 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
177 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
179 #ifdef IPTOS_LOWDELAY
180 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
182 #ifdef IPTOS_THROUGHPUT
183 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
186 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
189 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
192 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
195 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
198 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
201 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
204 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
207 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
211 /****************************************************************************
212 Print socket options.
213 ****************************************************************************/
215 static void print_socket_options(int s)
219 const smb_socket_option *p = &socket_options[0];
221 /* wrapped in if statement to prevent streams
222 * leak in SCO Openserver 5.0 */
223 /* reported on samba-technical --jerry */
224 if ( DEBUGLEVEL >= 5 ) {
225 for (; p->name != NULL; p++) {
226 if (getsockopt(s, p->level, p->option,
227 (void *)&value, &vlen) == -1) {
228 DEBUG(5,("Could not test socket option %s.\n",
231 DEBUG(5,("socket option %s = %d\n",
238 /****************************************************************************
239 Set user socket options.
240 ****************************************************************************/
242 void set_socket_options(int fd, const char *options)
246 while (next_token(&options,tok," \t,", sizeof(tok))) {
250 BOOL got_value = False;
252 if ((p = strchr_m(tok,'='))) {
258 for (i=0;socket_options[i].name;i++)
259 if (strequal(socket_options[i].name,tok))
262 if (!socket_options[i].name) {
263 DEBUG(0,("Unknown socket option %s\n",tok));
267 switch (socket_options[i].opttype) {
270 ret = setsockopt(fd,socket_options[i].level,
271 socket_options[i].option,
272 (char *)&value,sizeof(int));
277 DEBUG(0,("syntax error - %s "
278 "does not take a value\n",tok));
281 int on = socket_options[i].value;
282 ret = setsockopt(fd,socket_options[i].level,
283 socket_options[i].option,
284 (char *)&on,sizeof(int));
290 DEBUG(0,("Failed to set socket option %s (Error %s)\n",
291 tok, strerror(errno) ));
295 print_socket_options(fd);
298 /****************************************************************************
300 ****************************************************************************/
302 ssize_t read_udp_v4_socket(int fd,
305 struct sockaddr_storage *psa)
308 socklen_t socklen = sizeof(*psa);
309 struct sockaddr_in *si = (struct sockaddr_in *)psa;
311 memset((char *)psa,'\0',socklen);
313 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
314 (struct sockaddr *)psa,&socklen);
316 /* Don't print a low debug error for a non-blocking socket. */
317 if (errno == EAGAIN) {
318 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
320 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
326 if (psa->ss_family != AF_INET) {
327 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
328 "(not IPv4)\n", (int)psa->ss_family));
332 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
333 inet_ntoa(si->sin_addr),
335 (unsigned long)ret));
340 /****************************************************************************
341 Read data from a socket with a timout in msec.
342 mincount = if timeout, minimum to read before returning
343 maxcount = number to be read.
344 time_out = timeout in milliseconds
345 ****************************************************************************/
347 ssize_t read_socket_with_timeout(int fd,
351 unsigned int time_out)
357 struct timeval timeout;
359 /* just checking .... */
371 while (nread < mincnt) {
372 readret = sys_read(fd, buf + nread, maxcnt - nread);
375 DEBUG(5,("read_socket_with_timeout: "
376 "blocking read. EOF from client.\n"));
377 smb_read_error = READ_EOF;
382 if (fd == client_fd) {
383 /* Try and give an error message
384 * saying what client failed. */
385 DEBUG(0,("read_socket_with_timeout: "
386 "client %s read error = %s.\n",
390 DEBUG(0,("read_socket_with_timeout: "
391 "read error = %s.\n",
394 smb_read_error = READ_ERROR;
399 return((ssize_t)nread);
402 /* Most difficult - timeout read */
403 /* If this is ever called on a disk file and
404 mincnt is greater then the filesize then
405 system performance will suffer severely as
406 select always returns true on disk files */
408 /* Set initial timeout */
409 timeout.tv_sec = (time_t)(time_out / 1000);
410 timeout.tv_usec = (long)(1000 * (time_out % 1000));
412 for (nread=0; nread < mincnt; ) {
416 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
420 /* something is wrong. Maybe the socket is dead? */
421 if (fd == client_fd) {
422 /* Try and give an error message saying
423 * what client failed. */
424 DEBUG(0,("read_socket_with_timeout: timeout "
425 "read for client %s. select error = %s.\n",
426 client_ip_string, strerror(errno) ));
428 DEBUG(0,("read_socket_with_timeout: timeout "
429 "read. select error = %s.\n",
432 smb_read_error = READ_ERROR;
436 /* Did we timeout ? */
438 DEBUG(10,("read_socket_with_timeout: timeout read. "
439 "select timed out.\n"));
440 smb_read_error = READ_TIMEOUT;
444 readret = sys_read(fd, buf+nread, maxcnt-nread);
447 /* we got EOF on the file descriptor */
448 DEBUG(5,("read_socket_with_timeout: timeout read. "
449 "EOF from client.\n"));
450 smb_read_error = READ_EOF;
455 /* the descriptor is probably dead */
456 if (fd == client_fd) {
457 /* Try and give an error message
458 * saying what client failed. */
459 DEBUG(0,("read_socket_with_timeout: timeout "
460 "read to client %s. read error = %s.\n",
461 client_ip_string, strerror(errno) ));
463 DEBUG(0,("read_socket_with_timeout: timeout "
464 "read. read error = %s.\n",
467 smb_read_error = READ_ERROR;
474 /* Return the number we got */
475 return (ssize_t)nread;
478 /****************************************************************************
479 Read data from the client, reading exactly N bytes.
480 ****************************************************************************/
482 ssize_t read_data(int fd,char *buffer,size_t N)
490 ret = sys_read(fd,buffer + total,N - total);
493 DEBUG(10,("read_data: read of %d returned 0. "
495 (int)(N - total), strerror(errno) ));
496 smb_read_error = READ_EOF;
501 if (fd == client_fd) {
502 /* Try and give an error message saying
503 * what client failed. */
504 DEBUG(0,("read_data: read failure for %d "
505 "bytes to client %s. Error = %s\n",
510 DEBUG(0,("read_data: read failure for %d. "
515 smb_read_error = READ_ERROR;
520 return (ssize_t)total;
523 /****************************************************************************
525 ****************************************************************************/
527 ssize_t write_data(int fd, const char *buffer, size_t N)
533 ret = sys_write(fd,buffer + total,N - total);
536 if (fd == client_fd) {
537 /* Try and give an error message saying
538 * what client failed. */
539 DEBUG(0,("write_data: write failure in "
540 "writing to client %s. Error %s\n",
541 client_ip_string, strerror(errno) ));
543 DEBUG(0,("write_data: write failure. "
544 "Error = %s\n", strerror(errno) ));
555 return (ssize_t)total;
558 /****************************************************************************
559 Send a keepalive packet (rfc1002).
560 ****************************************************************************/
562 BOOL send_keepalive(int client)
564 unsigned char buf[4];
566 buf[0] = SMBkeepalive;
567 buf[1] = buf[2] = buf[3] = 0;
569 return(write_data(client,(char *)buf,4) == 4);
572 /****************************************************************************
573 Read 4 bytes of a smb packet and return the smb length of the packet.
574 Store the result in the buffer.
575 This version of the function will return a length of zero on receiving
577 Timeout is in milliseconds.
578 ****************************************************************************/
580 static ssize_t read_smb_length_return_keepalive(int fd,
582 unsigned int timeout)
590 ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout)
593 ok = (read_data(fd,inbuf,4) == 4);
599 len = smb_len(inbuf);
600 msg_type = CVAL(inbuf,0);
602 if (msg_type == SMBkeepalive) {
603 DEBUG(5,("Got keepalive packet\n"));
607 DEBUG(10,("got smb length of %lu\n",(unsigned long)len));
612 /****************************************************************************
613 Read 4 bytes of a smb packet and return the smb length of the packet.
614 Store the result in the buffer. This version of the function will
615 never return a session keepalive (length of zero).
616 Timeout is in milliseconds.
617 ****************************************************************************/
619 ssize_t read_smb_length(int fd, char *inbuf, unsigned int timeout)
624 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
629 /* Ignore session keepalives. */
630 if(CVAL(inbuf,0) != SMBkeepalive)
634 DEBUG(10,("read_smb_length: got smb length of %lu\n",
635 (unsigned long)len));
640 /****************************************************************************
641 Read an smb from a fd. Note that the buffer *MUST* be of size
642 BUFFER_SIZE+SAFETY_MARGIN.
643 The timeout is in milliseconds.
644 This function will return on receipt of a session keepalive packet.
645 maxlen is the max number of bytes to return, not including the 4 byte
646 length. If zero it means BUFFER_SIZE+SAFETY_MARGIN limit.
647 Doesn't check the MAC on signed packets.
648 ****************************************************************************/
650 ssize_t receive_smb_raw(int fd,
652 unsigned int timeout,
659 len = read_smb_length_return_keepalive(fd,buffer,timeout);
661 DEBUG(10,("receive_smb_raw: length < 0!\n"));
664 * Correct fix. smb_read_error may have already been
665 * set. Only set it here if not already set. Global
666 * variables still suck :-). JRA.
669 if (smb_read_error == 0)
670 smb_read_error = READ_ERROR;
675 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
676 * of header. Don't print the error if this fits.... JRA.
679 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
680 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
681 (unsigned long)len));
682 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
685 * Correct fix. smb_read_error may have already been
686 * set. Only set it here if not already set. Global
687 * variables still suck :-). JRA.
690 if (smb_read_error == 0)
691 smb_read_error = READ_ERROR;
698 len = MIN(len,maxlen);
702 ret = read_socket_with_timeout(fd,
708 ret = read_data(fd,buffer+4,len);
712 if (smb_read_error == 0) {
713 smb_read_error = READ_ERROR;
718 /* not all of samba3 properly checks for packet-termination
719 * of strings. This ensures that we don't run off into
721 SSVAL(buffer+4,len, 0);
727 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
728 char **buffer, unsigned int timeout)
735 len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
737 DEBUG(10,("receive_smb_raw: length < 0!\n"));
740 * Correct fix. smb_read_error may have already been
741 * set. Only set it here if not already set. Global
742 * variables still suck :-). JRA.
745 if (smb_read_error == 0)
746 smb_read_error = READ_ERROR;
751 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
752 * of header. Don't print the error if this fits.... JRA.
755 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
756 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
757 (unsigned long)len));
758 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
761 * Correct fix. smb_read_error may have already been
762 * set. Only set it here if not already set. Global
763 * variables still suck :-). JRA.
766 if (smb_read_error == 0)
767 smb_read_error = READ_ERROR;
773 * The +4 here can't wrap, we've checked the length above already.
776 *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
778 if (*buffer == NULL) {
779 DEBUG(0, ("Could not allocate inbuf of length %d\n",
781 if (smb_read_error == 0)
782 smb_read_error = READ_ERROR;
786 memcpy(*buffer, lenbuf, sizeof(lenbuf));
790 ret = read_socket_with_timeout(fd,(*buffer)+4, len,
793 ret = read_data(fd, (*buffer)+4, len);
797 if (smb_read_error == 0) {
798 smb_read_error = READ_ERROR;
807 /****************************************************************************
808 Wrapper for receive_smb_raw().
809 Checks the MAC on signed packets.
810 ****************************************************************************/
812 BOOL receive_smb(int fd, char *buffer, unsigned int timeout)
814 if (receive_smb_raw(fd, buffer, timeout, 0) < 0) {
818 /* Check the incoming SMB signature. */
819 if (!srv_check_sign_mac(buffer, True)) {
820 DEBUG(0, ("receive_smb: SMB Signature verification "
821 "failed on incoming packet!\n"));
822 if (smb_read_error == 0) {
823 smb_read_error = READ_BAD_SIG;
831 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
832 unsigned int timeout)
836 len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
842 /* Check the incoming SMB signature. */
843 if (!srv_check_sign_mac(*buffer, True)) {
844 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
845 "incoming packet!\n"));
846 if (smb_read_error == 0) {
847 smb_read_error = READ_BAD_SIG;
855 /****************************************************************************
857 ****************************************************************************/
859 BOOL send_smb(int fd, char *buffer)
865 /* Sign the outgoing packet if required. */
866 srv_calculate_sign_mac(buffer);
868 len = smb_len(buffer) + 4;
870 while (nwritten < len) {
871 ret = write_data(fd,buffer+nwritten,len - nwritten);
873 DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
874 (int)len,(int)ret, strerror(errno) ));
883 /****************************************************************************
884 Open a socket of the specified type, port, and address for incoming data.
885 ****************************************************************************/
887 int open_socket_in(int type,
893 struct sockaddr_in sock;
896 memset( (char *)&sock, '\0', sizeof(sock) );
898 #ifdef HAVE_SOCK_SIN_LEN
899 sock.sin_len = sizeof(sock);
901 sock.sin_port = htons( port );
902 sock.sin_family = AF_INET;
903 sock.sin_addr.s_addr = socket_addr;
905 res = socket( AF_INET, type, 0 );
908 dbgtext( "open_socket_in(): socket() call failed: " );
909 dbgtext( "%s\n", strerror( errno ) );
914 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
916 int val = rebind ? 1 : 0;
917 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
918 (char *)&val,sizeof(val)) == -1 ) {
919 if( DEBUGLVL( dlevel ) ) {
920 dbgtext( "open_socket_in(): setsockopt: " );
921 dbgtext( "SO_REUSEADDR = %s ",
922 val?"True":"False" );
923 dbgtext( "on port %d failed ", port );
924 dbgtext( "with error = %s\n", strerror(errno) );
928 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
929 (char *)&val,sizeof(val)) == -1 ) {
930 if( DEBUGLVL( dlevel ) ) {
931 dbgtext( "open_socket_in(): setsockopt: ");
932 dbgtext( "SO_REUSEPORT = %s ",
933 val?"True":"False" );
934 dbgtext( "on port %d failed ", port );
935 dbgtext( "with error = %s\n", strerror(errno) );
938 #endif /* SO_REUSEPORT */
941 /* now we've got a socket - we need to bind it */
942 if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
943 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
944 port == SMB_PORT2 || port == NMB_PORT) ) {
945 dbgtext( "bind failed on port %d ", port );
946 dbgtext( "socket_addr = %s.\n",
947 inet_ntoa( sock.sin_addr ) );
948 dbgtext( "Error = %s\n", strerror(errno) );
954 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
959 /****************************************************************************
960 Create an outgoing socket. timeout is in milliseconds.
961 **************************************************************************/
963 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
965 struct sockaddr_in sock_out;
967 int connect_loop = 10;
970 /* create a socket to write to */
971 res = socket(PF_INET, type, 0);
973 DEBUG(0,("socket error (%s)\n", strerror(errno)));
977 if (type != SOCK_STREAM)
980 memset((char *)&sock_out,'\0',sizeof(sock_out));
981 putip((char *)&sock_out.sin_addr,(char *)addr);
983 sock_out.sin_port = htons( port );
984 sock_out.sin_family = PF_INET;
986 /* set it non-blocking */
987 set_blocking(res,False);
989 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
991 /* and connect it to the destination */
994 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
996 /* Some systems return EAGAIN when they mean EINPROGRESS */
997 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
998 errno == EAGAIN) && (connect_loop < timeout) ) {
999 smb_msleep(connect_loop);
1000 timeout -= connect_loop;
1001 connect_loop += increment;
1002 if (increment < 250) {
1003 /* After 8 rounds we end up at a max of 255 msec */
1009 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1011 DEBUG(1,("timeout connecting to %s:%d\n",
1012 inet_ntoa(*addr),port));
1018 if (ret < 0 && errno == EISCONN) {
1025 DEBUG(2,("error connecting to %s:%d (%s)\n",
1026 inet_ntoa(*addr),port,strerror(errno)));
1031 /* set it blocking again */
1032 set_blocking(res,True);
1037 /****************************************************************************
1038 Create an outgoing TCP socket to any of the addrs. This is for
1039 simultaneous connects to port 445 and 139 of a host or even a variety
1040 of DC's all of which are equivalent for our purposes.
1041 **************************************************************************/
1043 BOOL open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1044 int timeout, int *fd_index, int *fd)
1046 int i, resulting_index, res;
1050 fd_set r_fds, wr_fds;
1054 int connect_loop = 10000; /* 10 milliseconds */
1056 timeout *= 1000; /* convert to microseconds */
1058 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1060 if (sockets == NULL)
1063 resulting_index = -1;
1065 for (i=0; i<num_addrs; i++)
1068 for (i=0; i<num_addrs; i++) {
1069 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1072 set_blocking(sockets[i], False);
1076 good_connect = False;
1078 for (i=0; i<num_addrs; i++) {
1080 if (sockets[i] == -1)
1083 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1084 sizeof(*addrs)) == 0) {
1085 /* Rather unlikely as we are non-blocking, but it
1086 * might actually happen. */
1087 resulting_index = i;
1091 if (errno == EINPROGRESS || errno == EALREADY ||
1095 errno == EAGAIN || errno == EINTR) {
1096 /* These are the error messages that something is
1098 good_connect = True;
1099 } else if (errno != 0) {
1100 /* There was a direct error */
1106 if (!good_connect) {
1107 /* All of the connect's resulted in real error conditions */
1111 /* Lets see if any of the connect attempts succeeded */
1117 for (i=0; i<num_addrs; i++) {
1118 if (sockets[i] == -1)
1120 FD_SET(sockets[i], &wr_fds);
1121 FD_SET(sockets[i], &r_fds);
1122 if (sockets[i]>maxfd)
1127 tv.tv_usec = connect_loop;
1129 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1137 for (i=0; i<num_addrs; i++) {
1139 if (sockets[i] == -1)
1142 /* Stevens, Network Programming says that if there's a
1143 * successful connect, the socket is only writable. Upon an
1144 * error, it's both readable and writable. */
1146 if (FD_ISSET(sockets[i], &r_fds) &&
1147 FD_ISSET(sockets[i], &wr_fds)) {
1148 /* readable and writable, so it's an error */
1154 if (!FD_ISSET(sockets[i], &r_fds) &&
1155 FD_ISSET(sockets[i], &wr_fds)) {
1156 /* Only writable, so it's connected */
1157 resulting_index = i;
1164 timeout -= connect_loop;
1167 connect_loop *= 1.5;
1168 if (connect_loop > timeout)
1169 connect_loop = timeout;
1173 for (i=0; i<num_addrs; i++) {
1174 if (i == resulting_index)
1176 if (sockets[i] >= 0)
1180 if (resulting_index >= 0) {
1181 *fd_index = resulting_index;
1182 *fd = sockets[*fd_index];
1183 set_blocking(*fd, True);
1188 return (resulting_index >= 0);
1190 /****************************************************************************
1191 Open a connected UDP socket to host on port
1192 **************************************************************************/
1194 int open_udp_socket(const char *host, int port)
1196 int type = SOCK_DGRAM;
1197 struct sockaddr_in sock_out;
1199 struct in_addr *addr;
1201 addr = interpret_addr2(host);
1203 res = socket(PF_INET, type, 0);
1208 memset((char *)&sock_out,'\0',sizeof(sock_out));
1209 putip((char *)&sock_out.sin_addr,(char *)addr);
1210 sock_out.sin_port = htons(port);
1211 sock_out.sin_family = PF_INET;
1213 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1221 /*******************************************************************
1222 Matchname - determine if host name matches IP address. Used to
1223 confirm a hostname lookup to prevent spoof attacks.
1224 ******************************************************************/
1226 static BOOL matchname(char *remotehost,struct in_addr addr)
1231 if ((hp = sys_gethostbyname(remotehost)) == 0) {
1232 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n",
1238 * Make sure that gethostbyname() returns the "correct" host name.
1239 * Unfortunately, gethostbyname("localhost") sometimes yields
1240 * "localhost.domain". Since the latter host name comes from the
1241 * local DNS, we just have to trust it (all bets are off if the local
1242 * DNS is perverted). We always check the address list, though.
1245 if (!strequal(remotehost, hp->h_name)
1246 && !strequal(remotehost, "localhost")) {
1247 DEBUG(0,("host name/name mismatch: %s != %s\n",
1248 remotehost, hp->h_name));
1252 /* Look up the host address in the address list we just got. */
1253 for (i = 0; hp->h_addr_list[i]; i++) {
1254 if (memcmp(hp->h_addr_list[i], (char *)&addr,sizeof(addr)) == 0)
1259 * The host name does not map to the original host address. Perhaps
1260 * someone has compromised a name server. More likely someone botched
1261 * it, but that could be dangerous, too.
1264 DEBUG(0,("host name/address mismatch: %s != %s\n",
1265 inet_ntoa(addr), hp->h_name));
1269 /*******************************************************************
1270 Return the DNS name of the remote end of a socket.
1271 ******************************************************************/
1273 char *get_peer_name(int fd, BOOL force_lookup)
1275 static pstring name_buf;
1277 static fstring addr_buf;
1279 struct in_addr addr;
1282 /* reverse lookups can be *very* expensive, and in many
1283 situations won't work because many networks don't link dhcp
1284 with dns. To avoid the delay we avoid the lookup if
1286 if (!lp_hostname_lookups() && (force_lookup == False)) {
1287 return get_peer_addr(fd);
1290 p = get_peer_addr(fd);
1292 /* it might be the same as the last one - save some DNS work */
1293 if (strcmp(p, addr_buf) == 0)
1296 pstrcpy(name_buf,"UNKNOWN");
1300 fstrcpy(addr_buf, p);
1302 addr = *interpret_addr2(p);
1304 /* Look up the remote host name. */
1305 if ((hp = gethostbyaddr((char *)&addr.s_addr,
1306 sizeof(addr.s_addr), AF_INET)) == 0) {
1307 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1308 pstrcpy(name_buf, p);
1310 pstrcpy(name_buf,(char *)hp->h_name);
1311 if (!matchname(name_buf, addr)) {
1312 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1313 pstrcpy(name_buf,"UNKNOWN");
1317 /* can't pass the same source and dest strings in when you
1318 use --enable-developer or the clobber_region() call will
1321 pstrcpy( tmp_name, name_buf );
1322 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1323 if (strstr(name_buf,"..")) {
1324 pstrcpy(name_buf, "UNKNOWN");
1330 /*******************************************************************
1331 Return the IP addr of the remote end of a socket as a string.
1332 ******************************************************************/
1334 char *get_peer_addr(int fd)
1337 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1338 socklen_t length = sizeof(sa);
1339 static fstring addr_buf;
1341 fstrcpy(addr_buf,"0.0.0.0");
1347 if (getpeername(fd, &sa, &length) < 0) {
1348 DEBUG(0,("getpeername failed. Error was %s\n",
1353 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1358 /*******************************************************************
1359 Create protected unix domain socket.
1361 Some unixes cannot set permissions on a ux-dom-sock, so we
1362 have to make sure that the directory contains the protection
1363 permissions instead.
1364 ******************************************************************/
1366 int create_pipe_sock(const char *socket_dir,
1367 const char *socket_name,
1370 #ifdef HAVE_UNIXSOCKET
1371 struct sockaddr_un sunaddr;
1377 old_umask = umask(0);
1379 /* Create the socket directory or reuse the existing one */
1381 if (lstat(socket_dir, &st) == -1) {
1382 if (errno == ENOENT) {
1383 /* Create directory */
1384 if (mkdir(socket_dir, dir_perms) == -1) {
1385 DEBUG(0, ("error creating socket directory "
1386 "%s: %s\n", socket_dir,
1391 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1392 socket_dir, strerror(errno)));
1396 /* Check ownership and permission on existing directory */
1397 if (!S_ISDIR(st.st_mode)) {
1398 DEBUG(0, ("socket directory %s isn't a directory\n",
1402 if ((st.st_uid != sec_initial_uid()) ||
1403 ((st.st_mode & 0777) != dir_perms)) {
1404 DEBUG(0, ("invalid permissions on socket directory "
1405 "%s\n", socket_dir));
1410 /* Create the socket file */
1412 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1419 pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1422 memset(&sunaddr, 0, sizeof(sunaddr));
1423 sunaddr.sun_family = AF_UNIX;
1424 safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1426 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1427 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1432 if (listen(sock, 5) == -1) {
1433 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1449 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1451 #endif /* HAVE_UNIXSOCKET */