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-2005
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[16];
31 void client_setfd(int fd)
34 safe_strcpy(client_ip_string,
35 get_peer_addr(client_fd),
36 sizeof(client_ip_string)-1);
39 static char *get_socket_addr(int fd)
42 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
43 socklen_t length = sizeof(sa);
44 static fstring addr_buf;
46 fstrcpy(addr_buf,"0.0.0.0");
52 if (getsockname(fd, &sa, &length) < 0) {
53 DEBUG(0,("getsockname failed. Error was %s\n",
58 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
63 static int get_socket_port(int fd)
66 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
67 socklen_t length = sizeof(sa);
72 if (getsockname(fd, &sa, &length) < 0) {
73 DEBUG(0,("getpeername failed. Error was %s\n",
78 return ntohs(sockin->sin_port);
81 char *client_name(void)
83 return get_peer_name(client_fd,False);
86 char *client_addr(void)
88 return get_peer_addr(client_fd);
91 char *client_socket_addr(void)
93 return get_socket_addr(client_fd);
96 int client_socket_port(void)
98 return get_socket_port(client_fd);
101 struct in_addr *client_inaddr(struct sockaddr *sa)
103 struct sockaddr_in *sockin = (struct sockaddr_in *) (sa);
104 socklen_t length = sizeof(*sa);
106 if (getpeername(client_fd, sa, &length) < 0) {
107 DEBUG(0,("getpeername failed. Error was %s\n",
112 return &sockin->sin_addr;
115 /* the last IP received from */
116 struct in_addr lastip;
118 /* the last port received from */
121 int smb_read_error = 0;
123 /****************************************************************************
124 Determine if a file descriptor is in fact a socket.
125 ****************************************************************************/
127 BOOL is_a_socket(int fd)
132 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
135 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
137 typedef struct smb_socket_option {
145 static const smb_socket_option socket_options[] = {
146 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
147 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
148 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
150 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
153 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
156 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
159 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
161 #ifdef IPTOS_LOWDELAY
162 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
164 #ifdef IPTOS_THROUGHPUT
165 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
168 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
171 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
174 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
177 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
180 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
183 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
186 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
189 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
193 /****************************************************************************
194 Print socket options.
195 ****************************************************************************/
197 static void print_socket_options(int s)
201 const smb_socket_option *p = &socket_options[0];
203 /* wrapped in if statement to prevent streams
204 * leak in SCO Openserver 5.0 */
205 /* reported on samba-technical --jerry */
206 if ( DEBUGLEVEL >= 5 ) {
207 for (; p->name != NULL; p++) {
208 if (getsockopt(s, p->level, p->option,
209 (void *)&value, &vlen) == -1) {
210 DEBUG(5,("Could not test socket option %s.\n",
213 DEBUG(5,("socket option %s = %d\n",
220 /****************************************************************************
221 Set user socket options.
222 ****************************************************************************/
224 void set_socket_options(int fd, const char *options)
228 while (next_token(&options,tok," \t,", sizeof(tok))) {
232 BOOL got_value = False;
234 if ((p = strchr_m(tok,'='))) {
240 for (i=0;socket_options[i].name;i++)
241 if (strequal(socket_options[i].name,tok))
244 if (!socket_options[i].name) {
245 DEBUG(0,("Unknown socket option %s\n",tok));
249 switch (socket_options[i].opttype) {
252 ret = setsockopt(fd,socket_options[i].level,
253 socket_options[i].option,
254 (char *)&value,sizeof(int));
259 DEBUG(0,("syntax error - %s "
260 "does not take a value\n",tok));
263 int on = socket_options[i].value;
264 ret = setsockopt(fd,socket_options[i].level,
265 socket_options[i].option,
266 (char *)&on,sizeof(int));
272 DEBUG(0,("Failed to set socket option %s (Error %s)\n",
273 tok, strerror(errno) ));
277 print_socket_options(fd);
280 /****************************************************************************
282 ****************************************************************************/
284 ssize_t read_udp_socket(int fd,char *buf,size_t len)
287 struct sockaddr_in sock;
288 socklen_t socklen = sizeof(sock);
290 memset((char *)&sock,'\0',socklen);
291 memset((char *)&lastip,'\0',sizeof(lastip));
292 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
293 (struct sockaddr *)&sock,&socklen);
295 /* Don't print a low debug error for a non-blocking socket. */
296 if (errno == EAGAIN) {
297 DEBUG(10,("read socket returned EAGAIN. ERRNO=%s\n",
300 DEBUG(2,("read socket failed. ERRNO=%s\n",
306 lastip = sock.sin_addr;
307 lastport = ntohs(sock.sin_port);
309 DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %lu\n",
310 inet_ntoa(lastip), lastport, (unsigned long)ret));
315 /****************************************************************************
316 Read data from a socket with a timout in msec.
317 mincount = if timeout, minimum to read before returning
318 maxcount = number to be read.
319 time_out = timeout in milliseconds
320 ****************************************************************************/
322 ssize_t read_socket_with_timeout(int fd,
326 unsigned int time_out)
332 struct timeval timeout;
334 /* just checking .... */
346 while (nread < mincnt) {
347 readret = sys_read(fd, buf + nread, maxcnt - nread);
350 DEBUG(5,("read_socket_with_timeout: "
351 "blocking read. EOF from client.\n"));
352 smb_read_error = READ_EOF;
357 if (fd == client_fd) {
358 /* Try and give an error message
359 * saying what client failed. */
360 DEBUG(0,("read_socket_with_timeout: "
361 "client %s read error = %s.\n",
365 DEBUG(0,("read_socket_with_timeout: "
366 "read error = %s.\n",
369 smb_read_error = READ_ERROR;
374 return((ssize_t)nread);
377 /* Most difficult - timeout read */
378 /* If this is ever called on a disk file and
379 mincnt is greater then the filesize then
380 system performance will suffer severely as
381 select always returns true on disk files */
383 /* Set initial timeout */
384 timeout.tv_sec = (time_t)(time_out / 1000);
385 timeout.tv_usec = (long)(1000 * (time_out % 1000));
387 for (nread=0; nread < mincnt; ) {
391 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
395 /* something is wrong. Maybe the socket is dead? */
396 if (fd == client_fd) {
397 /* Try and give an error message saying
398 * what client failed. */
399 DEBUG(0,("read_socket_with_timeout: timeout "
400 "read for client %s. select error = %s.\n",
401 client_ip_string, strerror(errno) ));
403 DEBUG(0,("read_socket_with_timeout: timeout "
404 "read. select error = %s.\n",
407 smb_read_error = READ_ERROR;
411 /* Did we timeout ? */
413 DEBUG(10,("read_socket_with_timeout: timeout read. "
414 "select timed out.\n"));
415 smb_read_error = READ_TIMEOUT;
419 readret = sys_read(fd, buf+nread, maxcnt-nread);
422 /* we got EOF on the file descriptor */
423 DEBUG(5,("read_socket_with_timeout: timeout read. "
424 "EOF from client.\n"));
425 smb_read_error = READ_EOF;
430 /* the descriptor is probably dead */
431 if (fd == client_fd) {
432 /* Try and give an error message
433 * saying what client failed. */
434 DEBUG(0,("read_socket_with_timeout: timeout "
435 "read to client %s. read error = %s.\n",
436 client_ip_string, strerror(errno) ));
438 DEBUG(0,("read_socket_with_timeout: timeout "
439 "read. read error = %s.\n",
442 smb_read_error = READ_ERROR;
449 /* Return the number we got */
450 return (ssize_t)nread;
453 /****************************************************************************
454 Read data from the client, reading exactly N bytes.
455 ****************************************************************************/
457 ssize_t read_data(int fd,char *buffer,size_t N)
465 ret = sys_read(fd,buffer + total,N - total);
468 DEBUG(10,("read_data: read of %d returned 0. "
470 (int)(N - total), strerror(errno) ));
471 smb_read_error = READ_EOF;
476 if (fd == client_fd) {
477 /* Try and give an error message saying
478 * what client failed. */
479 DEBUG(0,("read_data: read failure for %d "
480 "bytes to client %s. Error = %s\n",
485 DEBUG(0,("read_data: read failure for %d. "
490 smb_read_error = READ_ERROR;
495 return (ssize_t)total;
498 /****************************************************************************
500 ****************************************************************************/
502 ssize_t write_data(int fd, const char *buffer, size_t N)
508 ret = sys_write(fd,buffer + total,N - total);
511 if (fd == client_fd) {
512 /* Try and give an error message saying
513 * what client failed. */
514 DEBUG(0,("write_data: write failure in "
515 "writing to client %s. Error %s\n",
516 client_ip_string, strerror(errno) ));
518 DEBUG(0,("write_data: write failure. "
519 "Error = %s\n", strerror(errno) ));
530 return (ssize_t)total;
533 /****************************************************************************
534 Send a keepalive packet (rfc1002).
535 ****************************************************************************/
537 BOOL send_keepalive(int client)
539 unsigned char buf[4];
541 buf[0] = SMBkeepalive;
542 buf[1] = buf[2] = buf[3] = 0;
544 return(write_data(client,(char *)buf,4) == 4);
547 /****************************************************************************
548 Read 4 bytes of a smb packet and return the smb length of the packet.
549 Store the result in the buffer.
550 This version of the function will return a length of zero on receiving
552 Timeout is in milliseconds.
553 ****************************************************************************/
555 static ssize_t read_smb_length_return_keepalive(int fd,
557 unsigned int timeout)
565 ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout)
568 ok = (read_data(fd,inbuf,4) == 4);
574 len = smb_len(inbuf);
575 msg_type = CVAL(inbuf,0);
577 if (msg_type == SMBkeepalive) {
578 DEBUG(5,("Got keepalive packet\n"));
582 DEBUG(10,("got smb length of %lu\n",(unsigned long)len));
587 /****************************************************************************
588 Read 4 bytes of a smb packet and return the smb length of the packet.
589 Store the result in the buffer. This version of the function will
590 never return a session keepalive (length of zero).
591 Timeout is in milliseconds.
592 ****************************************************************************/
594 ssize_t read_smb_length(int fd, char *inbuf, unsigned int timeout)
599 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
604 /* Ignore session keepalives. */
605 if(CVAL(inbuf,0) != SMBkeepalive)
609 DEBUG(10,("read_smb_length: got smb length of %lu\n",
610 (unsigned long)len));
615 /****************************************************************************
616 Read an smb from a fd. Note that the buffer *MUST* be of size
617 BUFFER_SIZE+SAFETY_MARGIN.
618 The timeout is in milliseconds.
619 This function will return on receipt of a session keepalive packet.
620 maxlen is the max number of bytes to return, not including the 4 byte
621 length. If zero it means BUFFER_SIZE+SAFETY_MARGIN limit.
622 Doesn't check the MAC on signed packets.
623 ****************************************************************************/
625 ssize_t receive_smb_raw(int fd,
627 unsigned int timeout,
634 len = read_smb_length_return_keepalive(fd,buffer,timeout);
636 DEBUG(10,("receive_smb_raw: length < 0!\n"));
639 * Correct fix. smb_read_error may have already been
640 * set. Only set it here if not already set. Global
641 * variables still suck :-). JRA.
644 if (smb_read_error == 0)
645 smb_read_error = READ_ERROR;
650 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
651 * of header. Don't print the error if this fits.... JRA.
654 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
655 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
656 (unsigned long)len));
657 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
660 * Correct fix. smb_read_error may have already been
661 * set. Only set it here if not already set. Global
662 * variables still suck :-). JRA.
665 if (smb_read_error == 0)
666 smb_read_error = READ_ERROR;
673 len = MIN(len,maxlen);
677 ret = read_socket_with_timeout(fd,
683 ret = read_data(fd,buffer+4,len);
687 if (smb_read_error == 0) {
688 smb_read_error = READ_ERROR;
693 /* not all of samba3 properly checks for packet-termination
694 * of strings. This ensures that we don't run off into
696 SSVAL(buffer+4,len, 0);
702 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
703 char **buffer, unsigned int timeout)
710 len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
712 DEBUG(10,("receive_smb_raw: length < 0!\n"));
715 * Correct fix. smb_read_error may have already been
716 * set. Only set it here if not already set. Global
717 * variables still suck :-). JRA.
720 if (smb_read_error == 0)
721 smb_read_error = READ_ERROR;
726 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
727 * of header. Don't print the error if this fits.... JRA.
730 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
731 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
732 (unsigned long)len));
733 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
736 * Correct fix. smb_read_error may have already been
737 * set. Only set it here if not already set. Global
738 * variables still suck :-). JRA.
741 if (smb_read_error == 0)
742 smb_read_error = READ_ERROR;
748 * The +4 here can't wrap, we've checked the length above already.
751 *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
753 if (*buffer == NULL) {
754 DEBUG(0, ("Could not allocate inbuf of length %d\n",
756 if (smb_read_error == 0)
757 smb_read_error = READ_ERROR;
761 memcpy(*buffer, lenbuf, sizeof(lenbuf));
765 ret = read_socket_with_timeout(fd,(*buffer)+4, len,
768 ret = read_data(fd, (*buffer)+4, len);
772 if (smb_read_error == 0) {
773 smb_read_error = READ_ERROR;
782 /****************************************************************************
783 Wrapper for receive_smb_raw().
784 Checks the MAC on signed packets.
785 ****************************************************************************/
787 BOOL receive_smb(int fd, char *buffer, unsigned int timeout)
789 if (receive_smb_raw(fd, buffer, timeout, 0) < 0) {
793 if (srv_encryption_on()) {
794 NTSTATUS status = srv_decrypt_buffer(buffer);
795 if (!NT_STATUS_IS_OK(status)) {
796 DEBUG(0, ("receive_smb: SMB decryption failed "
797 "on incoming packet! Error %s\n",
798 nt_errstr(status) ));
799 if (smb_read_error == 0) {
800 smb_read_error = READ_BAD_DECRYPT;
806 /* Check the incoming SMB signature. */
807 if (!srv_check_sign_mac(buffer, True)) {
808 DEBUG(0, ("receive_smb: SMB Signature verification "
809 "failed on incoming packet!\n"));
810 if (smb_read_error == 0) {
811 smb_read_error = READ_BAD_SIG;
819 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
820 unsigned int timeout)
824 len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
830 if (srv_encryption_on()) {
831 NTSTATUS status = srv_decrypt_buffer(*buffer);
832 if (!NT_STATUS_IS_OK(status)) {
833 DEBUG(0, ("receive_smb: SMB decryption failed on "
834 "incoming packet! Error %s\n",
835 nt_errstr(status) ));
836 if (smb_read_error == 0) {
837 smb_read_error = READ_BAD_DECRYPT;
843 /* Check the incoming SMB signature. */
844 if (!srv_check_sign_mac(*buffer, True)) {
845 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
846 "incoming packet!\n"));
847 if (smb_read_error == 0) {
848 smb_read_error = READ_BAD_SIG;
856 /****************************************************************************
858 ****************************************************************************/
860 BOOL send_smb(int fd, char *buffer)
865 char *buf_out = buffer;
867 /* Sign the outgoing packet if required. */
868 srv_calculate_sign_mac(buf_out);
870 if (srv_encryption_on()) {
871 NTSTATUS status = srv_encrypt_buffer(buffer, &buf_out);
872 if (!NT_STATUS_IS_OK(status)) {
873 DEBUG(0, ("send_smb: SMB encryption failed "
874 "on outgoing packet! Error %s\n",
875 nt_errstr(status) ));
880 len = smb_len(buf_out) + 4;
882 while (nwritten < len) {
883 ret = write_data(fd,buf_out+nwritten,len - nwritten);
885 DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
886 (int)len,(int)ret, strerror(errno) ));
887 srv_free_enc_buffer(buf_out);
893 srv_free_enc_buffer(buf_out);
897 /****************************************************************************
898 Open a socket of the specified type, port, and address for incoming data.
899 ****************************************************************************/
901 int open_socket_in(int type,
907 struct sockaddr_in sock;
910 memset( (char *)&sock, '\0', sizeof(sock) );
912 #ifdef HAVE_SOCK_SIN_LEN
913 sock.sin_len = sizeof(sock);
915 sock.sin_port = htons( port );
916 sock.sin_family = AF_INET;
917 sock.sin_addr.s_addr = socket_addr;
919 res = socket( AF_INET, type, 0 );
922 dbgtext( "open_socket_in(): socket() call failed: " );
923 dbgtext( "%s\n", strerror( errno ) );
928 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
930 int val = rebind ? 1 : 0;
931 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
932 (char *)&val,sizeof(val)) == -1 ) {
933 if( DEBUGLVL( dlevel ) ) {
934 dbgtext( "open_socket_in(): setsockopt: " );
935 dbgtext( "SO_REUSEADDR = %s ",
936 val?"True":"False" );
937 dbgtext( "on port %d failed ", port );
938 dbgtext( "with error = %s\n", strerror(errno) );
942 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
943 (char *)&val,sizeof(val)) == -1 ) {
944 if( DEBUGLVL( dlevel ) ) {
945 dbgtext( "open_socket_in(): setsockopt: ");
946 dbgtext( "SO_REUSEPORT = %s ",
947 val?"True":"False" );
948 dbgtext( "on port %d failed ", port );
949 dbgtext( "with error = %s\n", strerror(errno) );
952 #endif /* SO_REUSEPORT */
955 /* now we've got a socket - we need to bind it */
956 if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
957 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
958 port == SMB_PORT2 || port == NMB_PORT) ) {
959 dbgtext( "bind failed on port %d ", port );
960 dbgtext( "socket_addr = %s.\n",
961 inet_ntoa( sock.sin_addr ) );
962 dbgtext( "Error = %s\n", strerror(errno) );
968 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
973 /****************************************************************************
974 Create an outgoing socket. timeout is in milliseconds.
975 **************************************************************************/
977 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
979 struct sockaddr_in sock_out;
981 int connect_loop = 10;
984 /* create a socket to write to */
985 res = socket(PF_INET, type, 0);
987 DEBUG(0,("socket error (%s)\n", strerror(errno)));
991 if (type != SOCK_STREAM)
994 memset((char *)&sock_out,'\0',sizeof(sock_out));
995 putip((char *)&sock_out.sin_addr,(char *)addr);
997 sock_out.sin_port = htons( port );
998 sock_out.sin_family = PF_INET;
1000 /* set it non-blocking */
1001 set_blocking(res,False);
1003 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
1005 /* and connect it to the destination */
1008 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
1010 /* Some systems return EAGAIN when they mean EINPROGRESS */
1011 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1012 errno == EAGAIN) && (connect_loop < timeout) ) {
1013 smb_msleep(connect_loop);
1014 timeout -= connect_loop;
1015 connect_loop += increment;
1016 if (increment < 250) {
1017 /* After 8 rounds we end up at a max of 255 msec */
1023 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1025 DEBUG(1,("timeout connecting to %s:%d\n",
1026 inet_ntoa(*addr),port));
1032 if (ret < 0 && errno == EISCONN) {
1039 DEBUG(2,("error connecting to %s:%d (%s)\n",
1040 inet_ntoa(*addr),port,strerror(errno)));
1045 /* set it blocking again */
1046 set_blocking(res,True);
1051 /****************************************************************************
1052 Create an outgoing TCP socket to any of the addrs. This is for
1053 simultaneous connects to port 445 and 139 of a host or even a variety
1054 of DC's all of which are equivalent for our purposes.
1055 **************************************************************************/
1057 BOOL open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1058 int timeout, int *fd_index, int *fd)
1060 int i, resulting_index, res;
1064 fd_set r_fds, wr_fds;
1068 int connect_loop = 10000; /* 10 milliseconds */
1070 timeout *= 1000; /* convert to microseconds */
1072 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1074 if (sockets == NULL)
1077 resulting_index = -1;
1079 for (i=0; i<num_addrs; i++)
1082 for (i=0; i<num_addrs; i++) {
1083 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1086 set_blocking(sockets[i], False);
1090 good_connect = False;
1092 for (i=0; i<num_addrs; i++) {
1094 if (sockets[i] == -1)
1097 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1098 sizeof(*addrs)) == 0) {
1099 /* Rather unlikely as we are non-blocking, but it
1100 * might actually happen. */
1101 resulting_index = i;
1105 if (errno == EINPROGRESS || errno == EALREADY ||
1109 errno == EAGAIN || errno == EINTR) {
1110 /* These are the error messages that something is
1112 good_connect = True;
1113 } else if (errno != 0) {
1114 /* There was a direct error */
1120 if (!good_connect) {
1121 /* All of the connect's resulted in real error conditions */
1125 /* Lets see if any of the connect attempts succeeded */
1131 for (i=0; i<num_addrs; i++) {
1132 if (sockets[i] == -1)
1134 FD_SET(sockets[i], &wr_fds);
1135 FD_SET(sockets[i], &r_fds);
1136 if (sockets[i]>maxfd)
1141 tv.tv_usec = connect_loop;
1143 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1151 for (i=0; i<num_addrs; i++) {
1153 if (sockets[i] == -1)
1156 /* Stevens, Network Programming says that if there's a
1157 * successful connect, the socket is only writable. Upon an
1158 * error, it's both readable and writable. */
1160 if (FD_ISSET(sockets[i], &r_fds) &&
1161 FD_ISSET(sockets[i], &wr_fds)) {
1162 /* readable and writable, so it's an error */
1168 if (!FD_ISSET(sockets[i], &r_fds) &&
1169 FD_ISSET(sockets[i], &wr_fds)) {
1170 /* Only writable, so it's connected */
1171 resulting_index = i;
1178 timeout -= connect_loop;
1181 connect_loop *= 1.5;
1182 if (connect_loop > timeout)
1183 connect_loop = timeout;
1187 for (i=0; i<num_addrs; i++) {
1188 if (i == resulting_index)
1190 if (sockets[i] >= 0)
1194 if (resulting_index >= 0) {
1195 *fd_index = resulting_index;
1196 *fd = sockets[*fd_index];
1197 set_blocking(*fd, True);
1202 return (resulting_index >= 0);
1204 /****************************************************************************
1205 Open a connected UDP socket to host on port
1206 **************************************************************************/
1208 int open_udp_socket(const char *host, int port)
1210 int type = SOCK_DGRAM;
1211 struct sockaddr_in sock_out;
1213 struct in_addr *addr;
1215 addr = interpret_addr2(host);
1217 res = socket(PF_INET, type, 0);
1222 memset((char *)&sock_out,'\0',sizeof(sock_out));
1223 putip((char *)&sock_out.sin_addr,(char *)addr);
1224 sock_out.sin_port = htons(port);
1225 sock_out.sin_family = PF_INET;
1227 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1236 /*******************************************************************
1237 Matchname - determine if host name matches IP address. Used to
1238 confirm a hostname lookup to prevent spoof attacks.
1239 ******************************************************************/
1241 static BOOL matchname(char *remotehost,struct in_addr addr)
1246 if ((hp = sys_gethostbyname(remotehost)) == 0) {
1247 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n",
1253 * Make sure that gethostbyname() returns the "correct" host name.
1254 * Unfortunately, gethostbyname("localhost") sometimes yields
1255 * "localhost.domain". Since the latter host name comes from the
1256 * local DNS, we just have to trust it (all bets are off if the local
1257 * DNS is perverted). We always check the address list, though.
1260 if (!strequal(remotehost, hp->h_name)
1261 && !strequal(remotehost, "localhost")) {
1262 DEBUG(0,("host name/name mismatch: %s != %s\n",
1263 remotehost, hp->h_name));
1267 /* Look up the host address in the address list we just got. */
1268 for (i = 0; hp->h_addr_list[i]; i++) {
1269 if (memcmp(hp->h_addr_list[i], (char *)&addr,sizeof(addr)) == 0)
1274 * The host name does not map to the original host address. Perhaps
1275 * someone has compromised a name server. More likely someone botched
1276 * it, but that could be dangerous, too.
1279 DEBUG(0,("host name/address mismatch: %s != %s\n",
1280 inet_ntoa(addr), hp->h_name));
1284 /*******************************************************************
1285 Return the DNS name of the remote end of a socket.
1286 ******************************************************************/
1288 char *get_peer_name(int fd, BOOL force_lookup)
1290 static pstring name_buf;
1292 static fstring addr_buf;
1294 struct in_addr addr;
1297 /* reverse lookups can be *very* expensive, and in many
1298 situations won't work because many networks don't link dhcp
1299 with dns. To avoid the delay we avoid the lookup if
1301 if (!lp_hostname_lookups() && (force_lookup == False)) {
1302 return get_peer_addr(fd);
1305 p = get_peer_addr(fd);
1307 /* it might be the same as the last one - save some DNS work */
1308 if (strcmp(p, addr_buf) == 0)
1311 pstrcpy(name_buf,"UNKNOWN");
1315 fstrcpy(addr_buf, p);
1317 addr = *interpret_addr2(p);
1319 /* Look up the remote host name. */
1320 if ((hp = gethostbyaddr((char *)&addr.s_addr,
1321 sizeof(addr.s_addr), AF_INET)) == 0) {
1322 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1323 pstrcpy(name_buf, p);
1325 pstrcpy(name_buf,(char *)hp->h_name);
1326 if (!matchname(name_buf, addr)) {
1327 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1328 pstrcpy(name_buf,"UNKNOWN");
1332 /* can't pass the same source and dest strings in when you
1333 use --enable-developer or the clobber_region() call will
1336 pstrcpy( tmp_name, name_buf );
1337 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1338 if (strstr(name_buf,"..")) {
1339 pstrcpy(name_buf, "UNKNOWN");
1345 /*******************************************************************
1346 Return the IP addr of the remote end of a socket as a string.
1347 ******************************************************************/
1349 char *get_peer_addr(int fd)
1352 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1353 socklen_t length = sizeof(sa);
1354 static fstring addr_buf;
1356 fstrcpy(addr_buf,"0.0.0.0");
1362 if (getpeername(fd, &sa, &length) < 0) {
1363 DEBUG(0,("getpeername failed. Error was %s\n",
1368 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1373 /*******************************************************************
1374 Create protected unix domain socket.
1376 Some unixes cannot set permissions on a ux-dom-sock, so we
1377 have to make sure that the directory contains the protection
1378 permissions instead.
1379 ******************************************************************/
1381 int create_pipe_sock(const char *socket_dir,
1382 const char *socket_name,
1385 #ifdef HAVE_UNIXSOCKET
1386 struct sockaddr_un sunaddr;
1392 old_umask = umask(0);
1394 /* Create the socket directory or reuse the existing one */
1396 if (lstat(socket_dir, &st) == -1) {
1397 if (errno == ENOENT) {
1398 /* Create directory */
1399 if (mkdir(socket_dir, dir_perms) == -1) {
1400 DEBUG(0, ("error creating socket directory "
1401 "%s: %s\n", socket_dir,
1406 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1407 socket_dir, strerror(errno)));
1411 /* Check ownership and permission on existing directory */
1412 if (!S_ISDIR(st.st_mode)) {
1413 DEBUG(0, ("socket directory %s isn't a directory\n",
1417 if ((st.st_uid != sec_initial_uid()) ||
1418 ((st.st_mode & 0777) != dir_perms)) {
1419 DEBUG(0, ("invalid permissions on socket directory "
1420 "%s\n", socket_dir));
1425 /* Create the socket file */
1427 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1434 pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1437 memset(&sunaddr, 0, sizeof(sunaddr));
1438 sunaddr.sun_family = AF_UNIX;
1439 safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1441 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1442 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1447 if (listen(sock, 5) == -1) {
1448 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1464 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1466 #endif /* HAVE_UNIXSOCKET */