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 if (srv_encryption_on()) {
819 NTSTATUS status = srv_decrypt_buffer(buffer);
820 if (!NT_STATUS_IS_OK(status)) {
821 DEBUG(0, ("receive_smb: SMB decryption failed "
822 "on incoming packet! Error %s\n",
823 nt_errstr(status) ));
824 if (smb_read_error == 0) {
825 smb_read_error = READ_BAD_DECRYPT;
831 /* Check the incoming SMB signature. */
832 if (!srv_check_sign_mac(buffer, True)) {
833 DEBUG(0, ("receive_smb: SMB Signature verification "
834 "failed on incoming packet!\n"));
835 if (smb_read_error == 0) {
836 smb_read_error = READ_BAD_SIG;
844 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
845 unsigned int timeout)
849 len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
855 if (srv_encryption_on()) {
856 NTSTATUS status = srv_decrypt_buffer(*buffer);
857 if (!NT_STATUS_IS_OK(status)) {
858 DEBUG(0, ("receive_smb: SMB decryption failed on "
859 "incoming packet! Error %s\n",
860 nt_errstr(status) ));
861 if (smb_read_error == 0) {
862 smb_read_error = READ_BAD_DECRYPT;
868 /* Check the incoming SMB signature. */
869 if (!srv_check_sign_mac(*buffer, True)) {
870 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
871 "incoming packet!\n"));
872 if (smb_read_error == 0) {
873 smb_read_error = READ_BAD_SIG;
881 /****************************************************************************
883 ****************************************************************************/
885 BOOL send_smb(int fd, char *buffer)
890 char *buf_out = buffer;
892 /* Sign the outgoing packet if required. */
893 srv_calculate_sign_mac(buf_out);
895 if (srv_encryption_on()) {
896 NTSTATUS status = srv_encrypt_buffer(buffer, &buf_out);
897 if (!NT_STATUS_IS_OK(status)) {
898 DEBUG(0, ("send_smb: SMB encryption failed "
899 "on outgoing packet! Error %s\n",
900 nt_errstr(status) ));
905 len = smb_len(buf_out) + 4;
907 while (nwritten < len) {
908 ret = write_data(fd,buf_out+nwritten,len - nwritten);
910 DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
911 (int)len,(int)ret, strerror(errno) ));
912 srv_free_enc_buffer(buf_out);
918 srv_free_enc_buffer(buf_out);
922 /****************************************************************************
923 Open a socket of the specified type, port, and address for incoming data.
924 ****************************************************************************/
926 int open_socket_in(int type,
932 struct sockaddr_in sock;
935 memset( (char *)&sock, '\0', sizeof(sock) );
937 #ifdef HAVE_SOCK_SIN_LEN
938 sock.sin_len = sizeof(sock);
940 sock.sin_port = htons( port );
941 sock.sin_family = AF_INET;
942 sock.sin_addr.s_addr = socket_addr;
944 res = socket( AF_INET, type, 0 );
947 dbgtext( "open_socket_in(): socket() call failed: " );
948 dbgtext( "%s\n", strerror( errno ) );
953 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
955 int val = rebind ? 1 : 0;
956 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
957 (char *)&val,sizeof(val)) == -1 ) {
958 if( DEBUGLVL( dlevel ) ) {
959 dbgtext( "open_socket_in(): setsockopt: " );
960 dbgtext( "SO_REUSEADDR = %s ",
961 val?"True":"False" );
962 dbgtext( "on port %d failed ", port );
963 dbgtext( "with error = %s\n", strerror(errno) );
967 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
968 (char *)&val,sizeof(val)) == -1 ) {
969 if( DEBUGLVL( dlevel ) ) {
970 dbgtext( "open_socket_in(): setsockopt: ");
971 dbgtext( "SO_REUSEPORT = %s ",
972 val?"True":"False" );
973 dbgtext( "on port %d failed ", port );
974 dbgtext( "with error = %s\n", strerror(errno) );
977 #endif /* SO_REUSEPORT */
980 /* now we've got a socket - we need to bind it */
981 if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
982 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
983 port == SMB_PORT2 || port == NMB_PORT) ) {
984 dbgtext( "bind failed on port %d ", port );
985 dbgtext( "socket_addr = %s.\n",
986 inet_ntoa( sock.sin_addr ) );
987 dbgtext( "Error = %s\n", strerror(errno) );
993 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
998 /****************************************************************************
999 Create an outgoing socket. timeout is in milliseconds.
1000 **************************************************************************/
1002 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
1004 struct sockaddr_in sock_out;
1006 int connect_loop = 10;
1009 /* create a socket to write to */
1010 res = socket(PF_INET, type, 0);
1012 DEBUG(0,("socket error (%s)\n", strerror(errno)));
1016 if (type != SOCK_STREAM)
1019 memset((char *)&sock_out,'\0',sizeof(sock_out));
1020 putip((char *)&sock_out.sin_addr,(char *)addr);
1022 sock_out.sin_port = htons( port );
1023 sock_out.sin_family = PF_INET;
1025 /* set it non-blocking */
1026 set_blocking(res,False);
1028 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
1030 /* and connect it to the destination */
1033 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
1035 /* Some systems return EAGAIN when they mean EINPROGRESS */
1036 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1037 errno == EAGAIN) && (connect_loop < timeout) ) {
1038 smb_msleep(connect_loop);
1039 timeout -= connect_loop;
1040 connect_loop += increment;
1041 if (increment < 250) {
1042 /* After 8 rounds we end up at a max of 255 msec */
1048 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1050 DEBUG(1,("timeout connecting to %s:%d\n",
1051 inet_ntoa(*addr),port));
1057 if (ret < 0 && errno == EISCONN) {
1064 DEBUG(2,("error connecting to %s:%d (%s)\n",
1065 inet_ntoa(*addr),port,strerror(errno)));
1070 /* set it blocking again */
1071 set_blocking(res,True);
1076 /****************************************************************************
1077 Create an outgoing TCP socket to any of the addrs. This is for
1078 simultaneous connects to port 445 and 139 of a host or even a variety
1079 of DC's all of which are equivalent for our purposes.
1080 **************************************************************************/
1082 BOOL open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1083 int timeout, int *fd_index, int *fd)
1085 int i, resulting_index, res;
1089 fd_set r_fds, wr_fds;
1093 int connect_loop = 10000; /* 10 milliseconds */
1095 timeout *= 1000; /* convert to microseconds */
1097 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1099 if (sockets == NULL)
1102 resulting_index = -1;
1104 for (i=0; i<num_addrs; i++)
1107 for (i=0; i<num_addrs; i++) {
1108 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1111 set_blocking(sockets[i], False);
1115 good_connect = False;
1117 for (i=0; i<num_addrs; i++) {
1119 if (sockets[i] == -1)
1122 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1123 sizeof(*addrs)) == 0) {
1124 /* Rather unlikely as we are non-blocking, but it
1125 * might actually happen. */
1126 resulting_index = i;
1130 if (errno == EINPROGRESS || errno == EALREADY ||
1134 errno == EAGAIN || errno == EINTR) {
1135 /* These are the error messages that something is
1137 good_connect = True;
1138 } else if (errno != 0) {
1139 /* There was a direct error */
1145 if (!good_connect) {
1146 /* All of the connect's resulted in real error conditions */
1150 /* Lets see if any of the connect attempts succeeded */
1156 for (i=0; i<num_addrs; i++) {
1157 if (sockets[i] == -1)
1159 FD_SET(sockets[i], &wr_fds);
1160 FD_SET(sockets[i], &r_fds);
1161 if (sockets[i]>maxfd)
1166 tv.tv_usec = connect_loop;
1168 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1176 for (i=0; i<num_addrs; i++) {
1178 if (sockets[i] == -1)
1181 /* Stevens, Network Programming says that if there's a
1182 * successful connect, the socket is only writable. Upon an
1183 * error, it's both readable and writable. */
1185 if (FD_ISSET(sockets[i], &r_fds) &&
1186 FD_ISSET(sockets[i], &wr_fds)) {
1187 /* readable and writable, so it's an error */
1193 if (!FD_ISSET(sockets[i], &r_fds) &&
1194 FD_ISSET(sockets[i], &wr_fds)) {
1195 /* Only writable, so it's connected */
1196 resulting_index = i;
1203 timeout -= connect_loop;
1206 connect_loop *= 1.5;
1207 if (connect_loop > timeout)
1208 connect_loop = timeout;
1212 for (i=0; i<num_addrs; i++) {
1213 if (i == resulting_index)
1215 if (sockets[i] >= 0)
1219 if (resulting_index >= 0) {
1220 *fd_index = resulting_index;
1221 *fd = sockets[*fd_index];
1222 set_blocking(*fd, True);
1227 return (resulting_index >= 0);
1229 /****************************************************************************
1230 Open a connected UDP socket to host on port
1231 **************************************************************************/
1233 int open_udp_socket(const char *host, int port)
1235 int type = SOCK_DGRAM;
1236 struct sockaddr_in sock_out;
1238 struct in_addr *addr;
1240 addr = interpret_addr2(host);
1242 res = socket(PF_INET, type, 0);
1247 memset((char *)&sock_out,'\0',sizeof(sock_out));
1248 putip((char *)&sock_out.sin_addr,(char *)addr);
1249 sock_out.sin_port = htons(port);
1250 sock_out.sin_family = PF_INET;
1252 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1260 /*******************************************************************
1261 Matchname - determine if host name matches IP address. Used to
1262 confirm a hostname lookup to prevent spoof attacks.
1263 ******************************************************************/
1265 static BOOL matchname(char *remotehost,struct in_addr addr)
1270 if ((hp = sys_gethostbyname(remotehost)) == 0) {
1271 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n",
1277 * Make sure that gethostbyname() returns the "correct" host name.
1278 * Unfortunately, gethostbyname("localhost") sometimes yields
1279 * "localhost.domain". Since the latter host name comes from the
1280 * local DNS, we just have to trust it (all bets are off if the local
1281 * DNS is perverted). We always check the address list, though.
1284 if (!strequal(remotehost, hp->h_name)
1285 && !strequal(remotehost, "localhost")) {
1286 DEBUG(0,("host name/name mismatch: %s != %s\n",
1287 remotehost, hp->h_name));
1291 /* Look up the host address in the address list we just got. */
1292 for (i = 0; hp->h_addr_list[i]; i++) {
1293 if (memcmp(hp->h_addr_list[i], (char *)&addr,sizeof(addr)) == 0)
1298 * The host name does not map to the original host address. Perhaps
1299 * someone has compromised a name server. More likely someone botched
1300 * it, but that could be dangerous, too.
1303 DEBUG(0,("host name/address mismatch: %s != %s\n",
1304 inet_ntoa(addr), hp->h_name));
1308 /*******************************************************************
1309 Return the DNS name of the remote end of a socket.
1310 ******************************************************************/
1312 char *get_peer_name(int fd, BOOL force_lookup)
1314 static pstring name_buf;
1316 static fstring addr_buf;
1318 struct in_addr addr;
1321 /* reverse lookups can be *very* expensive, and in many
1322 situations won't work because many networks don't link dhcp
1323 with dns. To avoid the delay we avoid the lookup if
1325 if (!lp_hostname_lookups() && (force_lookup == False)) {
1326 return get_peer_addr(fd);
1329 p = get_peer_addr(fd);
1331 /* it might be the same as the last one - save some DNS work */
1332 if (strcmp(p, addr_buf) == 0)
1335 pstrcpy(name_buf,"UNKNOWN");
1339 fstrcpy(addr_buf, p);
1341 addr = *interpret_addr2(p);
1343 /* Look up the remote host name. */
1344 if ((hp = gethostbyaddr((char *)&addr.s_addr,
1345 sizeof(addr.s_addr), AF_INET)) == 0) {
1346 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1347 pstrcpy(name_buf, p);
1349 pstrcpy(name_buf,(char *)hp->h_name);
1350 if (!matchname(name_buf, addr)) {
1351 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1352 pstrcpy(name_buf,"UNKNOWN");
1356 /* can't pass the same source and dest strings in when you
1357 use --enable-developer or the clobber_region() call will
1360 pstrcpy( tmp_name, name_buf );
1361 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1362 if (strstr(name_buf,"..")) {
1363 pstrcpy(name_buf, "UNKNOWN");
1369 /*******************************************************************
1370 Return the IP addr of the remote end of a socket as a string.
1371 ******************************************************************/
1373 char *get_peer_addr(int fd)
1376 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1377 socklen_t length = sizeof(sa);
1378 static fstring addr_buf;
1380 fstrcpy(addr_buf,"0.0.0.0");
1386 if (getpeername(fd, &sa, &length) < 0) {
1387 DEBUG(0,("getpeername failed. Error was %s\n",
1392 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1397 /*******************************************************************
1398 Create protected unix domain socket.
1400 Some unixes cannot set permissions on a ux-dom-sock, so we
1401 have to make sure that the directory contains the protection
1402 permissions instead.
1403 ******************************************************************/
1405 int create_pipe_sock(const char *socket_dir,
1406 const char *socket_name,
1409 #ifdef HAVE_UNIXSOCKET
1410 struct sockaddr_un sunaddr;
1416 old_umask = umask(0);
1418 /* Create the socket directory or reuse the existing one */
1420 if (lstat(socket_dir, &st) == -1) {
1421 if (errno == ENOENT) {
1422 /* Create directory */
1423 if (mkdir(socket_dir, dir_perms) == -1) {
1424 DEBUG(0, ("error creating socket directory "
1425 "%s: %s\n", socket_dir,
1430 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1431 socket_dir, strerror(errno)));
1435 /* Check ownership and permission on existing directory */
1436 if (!S_ISDIR(st.st_mode)) {
1437 DEBUG(0, ("socket directory %s isn't a directory\n",
1441 if ((st.st_uid != sec_initial_uid()) ||
1442 ((st.st_mode & 0777) != dir_perms)) {
1443 DEBUG(0, ("invalid permissions on socket directory "
1444 "%s\n", socket_dir));
1449 /* Create the socket file */
1451 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1458 pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1461 memset(&sunaddr, 0, sizeof(sunaddr));
1462 sunaddr.sun_family = AF_UNIX;
1463 safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1465 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1466 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1471 if (listen(sock, 5) == -1) {
1472 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1488 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1490 #endif /* HAVE_UNIXSOCKET */