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/>.
23 #include "system/filesys.h"
25 #include "../lib/async_req/async_sock.h"
26 #include "../lib/util/select.h"
27 #include "interfaces.h"
28 #include "../lib/util/tevent_unix.h"
29 #include "../lib/util/tevent_ntstatus.h"
31 const char *client_name(int fd
)
33 return get_peer_name(fd
,false);
36 const char *client_addr(int fd
, char *addr
, size_t addrlen
)
38 return get_peer_addr(fd
,addr
,addrlen
);
42 /* Not currently used. JRA. */
43 int client_socket_port(int fd
)
45 return get_socket_port(fd
);
49 /****************************************************************************
50 Accessor functions to make thread-safe code easier later...
51 ****************************************************************************/
53 void set_smb_read_error(enum smb_read_errors
*pre
,
54 enum smb_read_errors newerr
)
61 void cond_set_smb_read_error(enum smb_read_errors
*pre
,
62 enum smb_read_errors newerr
)
64 if (pre
&& *pre
== SMB_READ_OK
) {
69 /****************************************************************************
70 Determine if a file descriptor is in fact a socket.
71 ****************************************************************************/
73 bool is_a_socket(int fd
)
78 return(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&v
, &l
) == 0);
81 enum SOCK_OPT_TYPES
{OPT_BOOL
,OPT_INT
,OPT_ON
};
83 typedef struct smb_socket_option
{
91 static const smb_socket_option socket_options
[] = {
92 {"SO_KEEPALIVE", SOL_SOCKET
, SO_KEEPALIVE
, 0, OPT_BOOL
},
93 {"SO_REUSEADDR", SOL_SOCKET
, SO_REUSEADDR
, 0, OPT_BOOL
},
94 {"SO_BROADCAST", SOL_SOCKET
, SO_BROADCAST
, 0, OPT_BOOL
},
96 {"TCP_NODELAY", IPPROTO_TCP
, TCP_NODELAY
, 0, OPT_BOOL
},
99 {"TCP_KEEPCNT", IPPROTO_TCP
, TCP_KEEPCNT
, 0, OPT_INT
},
102 {"TCP_KEEPIDLE", IPPROTO_TCP
, TCP_KEEPIDLE
, 0, OPT_INT
},
105 {"TCP_KEEPINTVL", IPPROTO_TCP
, TCP_KEEPINTVL
, 0, OPT_INT
},
107 #ifdef IPTOS_LOWDELAY
108 {"IPTOS_LOWDELAY", IPPROTO_IP
, IP_TOS
, IPTOS_LOWDELAY
, OPT_ON
},
110 #ifdef IPTOS_THROUGHPUT
111 {"IPTOS_THROUGHPUT", IPPROTO_IP
, IP_TOS
, IPTOS_THROUGHPUT
, OPT_ON
},
114 {"SO_REUSEPORT", SOL_SOCKET
, SO_REUSEPORT
, 0, OPT_BOOL
},
117 {"SO_SNDBUF", SOL_SOCKET
, SO_SNDBUF
, 0, OPT_INT
},
120 {"SO_RCVBUF", SOL_SOCKET
, SO_RCVBUF
, 0, OPT_INT
},
123 {"SO_SNDLOWAT", SOL_SOCKET
, SO_SNDLOWAT
, 0, OPT_INT
},
126 {"SO_RCVLOWAT", SOL_SOCKET
, SO_RCVLOWAT
, 0, OPT_INT
},
129 {"SO_SNDTIMEO", SOL_SOCKET
, SO_SNDTIMEO
, 0, OPT_INT
},
132 {"SO_RCVTIMEO", SOL_SOCKET
, SO_RCVTIMEO
, 0, OPT_INT
},
135 {"TCP_FASTACK", IPPROTO_TCP
, TCP_FASTACK
, 0, OPT_INT
},
138 {"TCP_QUICKACK", IPPROTO_TCP
, TCP_QUICKACK
, 0, OPT_BOOL
},
140 #ifdef TCP_NODELAYACK
141 {"TCP_NODELAYACK", IPPROTO_TCP
, TCP_NODELAYACK
, 0, OPT_BOOL
},
143 #ifdef TCP_KEEPALIVE_THRESHOLD
144 {"TCP_KEEPALIVE_THRESHOLD", IPPROTO_TCP
, TCP_KEEPALIVE_THRESHOLD
, 0, OPT_INT
},
146 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
147 {"TCP_KEEPALIVE_ABORT_THRESHOLD", IPPROTO_TCP
, TCP_KEEPALIVE_ABORT_THRESHOLD
, 0, OPT_INT
},
151 /****************************************************************************
152 Print socket options.
153 ****************************************************************************/
155 static void print_socket_options(int s
)
159 const smb_socket_option
*p
= &socket_options
[0];
161 /* wrapped in if statement to prevent streams
162 * leak in SCO Openserver 5.0 */
163 /* reported on samba-technical --jerry */
164 if ( DEBUGLEVEL
>= 5 ) {
165 DEBUG(5,("Socket options:\n"));
166 for (; p
->name
!= NULL
; p
++) {
167 if (getsockopt(s
, p
->level
, p
->option
,
168 (void *)&value
, &vlen
) == -1) {
169 DEBUGADD(5,("\tCould not test socket option %s.\n",
172 DEBUGADD(5,("\t%s = %d\n",
179 /****************************************************************************
180 Set user socket options.
181 ****************************************************************************/
183 void set_socket_options(int fd
, const char *options
)
185 TALLOC_CTX
*ctx
= talloc_stackframe();
188 while (next_token_talloc(ctx
, &options
, &tok
," \t,")) {
192 bool got_value
= false;
194 if ((p
= strchr_m(tok
,'='))) {
200 for (i
=0;socket_options
[i
].name
;i
++)
201 if (strequal(socket_options
[i
].name
,tok
))
204 if (!socket_options
[i
].name
) {
205 DEBUG(0,("Unknown socket option %s\n",tok
));
209 switch (socket_options
[i
].opttype
) {
212 ret
= setsockopt(fd
,socket_options
[i
].level
,
213 socket_options
[i
].option
,
214 (char *)&value
,sizeof(int));
219 DEBUG(0,("syntax error - %s "
220 "does not take a value\n",tok
));
223 int on
= socket_options
[i
].value
;
224 ret
= setsockopt(fd
,socket_options
[i
].level
,
225 socket_options
[i
].option
,
226 (char *)&on
,sizeof(int));
232 /* be aware that some systems like Solaris return
233 * EINVAL to a setsockopt() call when the client
234 * sent a RST previously - no need to worry */
235 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
236 tok
, strerror(errno
) ));
241 print_socket_options(fd
);
244 /****************************************************************************
246 ****************************************************************************/
248 ssize_t
read_udp_v4_socket(int fd
,
251 struct sockaddr_storage
*psa
)
254 socklen_t socklen
= sizeof(*psa
);
255 struct sockaddr_in
*si
= (struct sockaddr_in
*)psa
;
257 memset((char *)psa
,'\0',socklen
);
259 ret
= (ssize_t
)sys_recvfrom(fd
,buf
,len
,0,
260 (struct sockaddr
*)psa
,&socklen
);
262 /* Don't print a low debug error for a non-blocking socket. */
263 if (errno
== EAGAIN
) {
264 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
266 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
272 if (psa
->ss_family
!= AF_INET
) {
273 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
274 "(not IPv4)\n", (int)psa
->ss_family
));
278 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
279 inet_ntoa(si
->sin_addr
),
281 (unsigned long)ret
));
286 /****************************************************************************
287 Read data from a file descriptor with a timout in msec.
288 mincount = if timeout, minimum to read before returning
289 maxcount = number to be read.
290 time_out = timeout in milliseconds
291 NB. This can be called with a non-socket fd, don't change
292 sys_read() to sys_recv() or other socket call.
293 ****************************************************************************/
295 NTSTATUS
read_fd_with_timeout(int fd
, char *buf
,
296 size_t mincnt
, size_t maxcnt
,
297 unsigned int time_out
,
304 /* just checking .... */
314 while (nread
< mincnt
) {
315 readret
= sys_read(fd
, buf
+ nread
, maxcnt
- nread
);
318 DEBUG(5,("read_fd_with_timeout: "
319 "blocking read. EOF from client.\n"));
320 return NT_STATUS_END_OF_FILE
;
324 return map_nt_error_from_unix(errno
);
331 /* Most difficult - timeout read */
332 /* If this is ever called on a disk file and
333 mincnt is greater then the filesize then
334 system performance will suffer severely as
335 select always returns true on disk files */
337 for (nread
=0; nread
< mincnt
; ) {
340 pollrtn
= poll_intr_one_fd(fd
, POLLIN
|POLLHUP
, time_out
,
345 return map_nt_error_from_unix(errno
);
348 /* Did we timeout ? */
349 if ((pollrtn
== 0) ||
350 ((revents
& (POLLIN
|POLLHUP
|POLLERR
)) == 0)) {
351 DEBUG(10,("read_fd_with_timeout: timeout read. "
352 "select timed out.\n"));
353 return NT_STATUS_IO_TIMEOUT
;
356 readret
= sys_read(fd
, buf
+nread
, maxcnt
-nread
);
359 /* we got EOF on the file descriptor */
360 DEBUG(5,("read_fd_with_timeout: timeout read. "
361 "EOF from client.\n"));
362 return NT_STATUS_END_OF_FILE
;
366 return map_nt_error_from_unix(errno
);
373 /* Return the number we got */
380 /****************************************************************************
381 Read data from an fd, reading exactly N bytes.
382 NB. This can be called with a non-socket fd, don't add dependencies
384 ****************************************************************************/
386 NTSTATUS
read_data(int fd
, char *buffer
, size_t N
)
388 return read_fd_with_timeout(fd
, buffer
, N
, N
, 0, NULL
);
391 /****************************************************************************
392 Write all data from an iov array
393 NB. This can be called with a non-socket fd, don't add dependencies
395 ****************************************************************************/
397 ssize_t
write_data_iov(int fd
, const struct iovec
*orig_iov
, int iovcnt
)
403 struct iovec
*iov_copy
, *iov
;
406 for (i
=0; i
<iovcnt
; i
++) {
407 to_send
+= orig_iov
[i
].iov_len
;
410 thistime
= sys_writev(fd
, orig_iov
, iovcnt
);
411 if ((thistime
<= 0) || (thistime
== to_send
)) {
417 * We could not send everything in one call. Make a copy of iov that
418 * we can mess with. We keep a copy of the array start in iov_copy for
419 * the TALLOC_FREE, because we're going to modify iov later on,
420 * discarding elements.
423 iov_copy
= (struct iovec
*)TALLOC_MEMDUP(
424 talloc_tos(), orig_iov
, sizeof(struct iovec
) * iovcnt
);
426 if (iov_copy
== NULL
) {
432 while (sent
< to_send
) {
434 * We have to discard "thistime" bytes from the beginning
435 * iov array, "thistime" contains the number of bytes sent
438 while (thistime
> 0) {
439 if (thistime
< iov
[0].iov_len
) {
441 (char *)iov
[0].iov_base
+ thistime
;
442 iov
[0].iov_base
= (void *)new_base
;
443 iov
[0].iov_len
-= thistime
;
446 thistime
-= iov
[0].iov_len
;
451 thistime
= sys_writev(fd
, iov
, iovcnt
);
458 TALLOC_FREE(iov_copy
);
462 /****************************************************************************
464 NB. This can be called with a non-socket fd, don't add dependencies
466 ****************************************************************************/
468 ssize_t
write_data(int fd
, const char *buffer
, size_t N
)
472 iov
.iov_base
= CONST_DISCARD(void *, buffer
);
474 return write_data_iov(fd
, &iov
, 1);
477 /****************************************************************************
478 Send a keepalive packet (rfc1002).
479 ****************************************************************************/
481 bool send_keepalive(int client
)
483 unsigned char buf
[4];
485 buf
[0] = SMBkeepalive
;
486 buf
[1] = buf
[2] = buf
[3] = 0;
488 return(write_data(client
,(char *)buf
,4) == 4);
491 /****************************************************************************
492 Read 4 bytes of a smb packet and return the smb length of the packet.
493 Store the result in the buffer.
494 This version of the function will return a length of zero on receiving
496 Timeout is in milliseconds.
497 ****************************************************************************/
499 NTSTATUS
read_smb_length_return_keepalive(int fd
, char *inbuf
,
500 unsigned int timeout
,
506 status
= read_fd_with_timeout(fd
, inbuf
, 4, 4, timeout
, NULL
);
508 if (!NT_STATUS_IS_OK(status
)) {
512 *len
= smb_len(inbuf
);
513 msg_type
= CVAL(inbuf
,0);
515 if (msg_type
== SMBkeepalive
) {
516 DEBUG(5,("Got keepalive packet\n"));
519 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len
)));
524 /****************************************************************************
525 Read an smb from a fd.
526 The timeout is in milliseconds.
527 This function will return on receipt of a session keepalive packet.
528 maxlen is the max number of bytes to return, not including the 4 byte
529 length. If zero it means buflen limit.
530 Doesn't check the MAC on signed packets.
531 ****************************************************************************/
533 NTSTATUS
receive_smb_raw(int fd
, char *buffer
, size_t buflen
, unsigned int timeout
,
534 size_t maxlen
, size_t *p_len
)
539 status
= read_smb_length_return_keepalive(fd
,buffer
,timeout
,&len
);
541 if (!NT_STATUS_IS_OK(status
)) {
542 DEBUG(0, ("read_fd_with_timeout failed, read "
543 "error = %s.\n", nt_errstr(status
)));
548 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
549 (unsigned long)len
));
550 return NT_STATUS_INVALID_PARAMETER
;
555 len
= MIN(len
,maxlen
);
558 status
= read_fd_with_timeout(
559 fd
, buffer
+4, len
, len
, timeout
, &len
);
561 if (!NT_STATUS_IS_OK(status
)) {
562 DEBUG(0, ("read_fd_with_timeout failed, read error = "
563 "%s.\n", nt_errstr(status
)));
567 /* not all of samba3 properly checks for packet-termination
568 * of strings. This ensures that we don't run off into
570 SSVAL(buffer
+4,len
, 0);
577 /****************************************************************************
578 Open a socket of the specified type, port, and address for incoming data.
579 ****************************************************************************/
581 int open_socket_in(int type
,
584 const struct sockaddr_storage
*psock
,
587 struct sockaddr_storage sock
;
589 socklen_t slen
= sizeof(struct sockaddr_in
);
593 #if defined(HAVE_IPV6)
594 if (sock
.ss_family
== AF_INET6
) {
595 ((struct sockaddr_in6
*)&sock
)->sin6_port
= htons(port
);
596 slen
= sizeof(struct sockaddr_in6
);
599 if (sock
.ss_family
== AF_INET
) {
600 ((struct sockaddr_in
*)&sock
)->sin_port
= htons(port
);
603 res
= socket(sock
.ss_family
, type
, 0 );
606 dbgtext( "open_socket_in(): socket() call failed: " );
607 dbgtext( "%s\n", strerror( errno
) );
612 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
614 int val
= rebind
? 1 : 0;
615 if( setsockopt(res
,SOL_SOCKET
,SO_REUSEADDR
,
616 (char *)&val
,sizeof(val
)) == -1 ) {
617 if( DEBUGLVL( dlevel
) ) {
618 dbgtext( "open_socket_in(): setsockopt: " );
619 dbgtext( "SO_REUSEADDR = %s ",
620 val
?"true":"false" );
621 dbgtext( "on port %d failed ", port
);
622 dbgtext( "with error = %s\n", strerror(errno
) );
626 if( setsockopt(res
,SOL_SOCKET
,SO_REUSEPORT
,
627 (char *)&val
,sizeof(val
)) == -1 ) {
628 if( DEBUGLVL( dlevel
) ) {
629 dbgtext( "open_socket_in(): setsockopt: ");
630 dbgtext( "SO_REUSEPORT = %s ",
632 dbgtext( "on port %d failed ", port
);
633 dbgtext( "with error = %s\n", strerror(errno
));
636 #endif /* SO_REUSEPORT */
641 * As IPV6_V6ONLY is the default on some systems,
642 * we better try to be consistent and always use it.
644 * This also avoids using IPv4 via AF_INET6 sockets
645 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
648 if (sock
.ss_family
== AF_INET6
) {
652 ret
= setsockopt(res
, IPPROTO_IPV6
, IPV6_V6ONLY
,
653 (const void *)&val
, sizeof(val
));
656 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
657 dbgtext("%s\n", strerror(errno
));
665 /* now we've got a socket - we need to bind it */
666 if (bind(res
, (struct sockaddr
*)&sock
, slen
) == -1 ) {
667 if( DEBUGLVL(dlevel
) && (port
== SMB_PORT1
||
668 port
== SMB_PORT2
|| port
== NMB_PORT
) ) {
669 char addr
[INET6_ADDRSTRLEN
];
670 print_sockaddr(addr
, sizeof(addr
),
672 dbgtext( "bind failed on port %d ", port
);
673 dbgtext( "socket_addr = %s.\n", addr
);
674 dbgtext( "Error = %s\n", strerror(errno
));
680 DEBUG( 10, ( "bind succeeded on port %d\n", port
) );
684 struct open_socket_out_state
{
686 struct event_context
*ev
;
687 struct sockaddr_storage ss
;
693 static void open_socket_out_connected(struct tevent_req
*subreq
);
695 static int open_socket_out_state_destructor(struct open_socket_out_state
*s
)
703 /****************************************************************************
704 Create an outgoing socket. timeout is in milliseconds.
705 **************************************************************************/
707 struct tevent_req
*open_socket_out_send(TALLOC_CTX
*mem_ctx
,
708 struct event_context
*ev
,
709 const struct sockaddr_storage
*pss
,
713 char addr
[INET6_ADDRSTRLEN
];
714 struct tevent_req
*result
, *subreq
;
715 struct open_socket_out_state
*state
;
718 result
= tevent_req_create(mem_ctx
, &state
,
719 struct open_socket_out_state
);
720 if (result
== NULL
) {
726 state
->wait_nsec
= 10000;
729 state
->fd
= socket(state
->ss
.ss_family
, SOCK_STREAM
, 0);
730 if (state
->fd
== -1) {
731 status
= map_nt_error_from_unix(errno
);
734 talloc_set_destructor(state
, open_socket_out_state_destructor
);
736 if (!tevent_req_set_endtime(
737 result
, ev
, timeval_current_ofs(0, timeout
*1000))) {
741 #if defined(HAVE_IPV6)
742 if (pss
->ss_family
== AF_INET6
) {
743 struct sockaddr_in6
*psa6
;
744 psa6
= (struct sockaddr_in6
*)&state
->ss
;
745 psa6
->sin6_port
= htons(port
);
746 if (psa6
->sin6_scope_id
== 0
747 && IN6_IS_ADDR_LINKLOCAL(&psa6
->sin6_addr
)) {
748 setup_linklocal_scope_id(
749 (struct sockaddr
*)&(state
->ss
));
751 state
->salen
= sizeof(struct sockaddr_in6
);
754 if (pss
->ss_family
== AF_INET
) {
755 struct sockaddr_in
*psa
;
756 psa
= (struct sockaddr_in
*)&state
->ss
;
757 psa
->sin_port
= htons(port
);
758 state
->salen
= sizeof(struct sockaddr_in
);
761 if (pss
->ss_family
== AF_UNIX
) {
762 state
->salen
= sizeof(struct sockaddr_un
);
765 print_sockaddr(addr
, sizeof(addr
), &state
->ss
);
766 DEBUG(3,("Connecting to %s at port %u\n", addr
, (unsigned int)port
));
768 subreq
= async_connect_send(state
, state
->ev
, state
->fd
,
769 (struct sockaddr
*)&state
->ss
,
772 || !tevent_req_set_endtime(
774 timeval_current_ofs(0, state
->wait_nsec
))) {
777 tevent_req_set_callback(subreq
, open_socket_out_connected
, result
);
781 tevent_req_nterror(result
, status
);
782 return tevent_req_post(result
, ev
);
788 static void open_socket_out_connected(struct tevent_req
*subreq
)
790 struct tevent_req
*req
=
791 tevent_req_callback_data(subreq
, struct tevent_req
);
792 struct open_socket_out_state
*state
=
793 tevent_req_data(req
, struct open_socket_out_state
);
797 ret
= async_connect_recv(subreq
, &sys_errno
);
800 tevent_req_done(req
);
806 (sys_errno
== ETIMEDOUT
) ||
808 (sys_errno
== EINPROGRESS
) ||
809 (sys_errno
== EALREADY
) ||
810 (sys_errno
== EAGAIN
)) {
816 if (state
->wait_nsec
< 250000) {
817 state
->wait_nsec
*= 1.5;
820 subreq
= async_connect_send(state
, state
->ev
, state
->fd
,
821 (struct sockaddr
*)&state
->ss
,
823 if (tevent_req_nomem(subreq
, req
)) {
826 if (!tevent_req_set_endtime(
828 timeval_current_ofs(0, state
->wait_nsec
))) {
829 tevent_req_nterror(req
, NT_STATUS_NO_MEMORY
);
832 tevent_req_set_callback(subreq
, open_socket_out_connected
, req
);
837 if (sys_errno
== EISCONN
) {
838 tevent_req_done(req
);
844 tevent_req_nterror(req
, map_nt_error_from_unix(sys_errno
));
847 NTSTATUS
open_socket_out_recv(struct tevent_req
*req
, int *pfd
)
849 struct open_socket_out_state
*state
=
850 tevent_req_data(req
, struct open_socket_out_state
);
853 if (tevent_req_is_nterror(req
, &status
)) {
862 * @brief open a socket
864 * @param pss a struct sockaddr_storage defining the address to connect to
865 * @param port to connect to
866 * @param timeout in MILLISECONDS
867 * @param pfd file descriptor returned
869 * @return NTSTATUS code
871 NTSTATUS
open_socket_out(const struct sockaddr_storage
*pss
, uint16_t port
,
872 int timeout
, int *pfd
)
874 TALLOC_CTX
*frame
= talloc_stackframe();
875 struct event_context
*ev
;
876 struct tevent_req
*req
;
877 NTSTATUS status
= NT_STATUS_NO_MEMORY
;
879 ev
= event_context_init(frame
);
884 req
= open_socket_out_send(frame
, ev
, pss
, port
, timeout
);
888 if (!tevent_req_poll(req
, ev
)) {
889 status
= NT_STATUS_INTERNAL_ERROR
;
892 status
= open_socket_out_recv(req
, pfd
);
898 struct open_socket_out_defer_state
{
899 struct event_context
*ev
;
900 struct sockaddr_storage ss
;
906 static void open_socket_out_defer_waited(struct tevent_req
*subreq
);
907 static void open_socket_out_defer_connected(struct tevent_req
*subreq
);
909 struct tevent_req
*open_socket_out_defer_send(TALLOC_CTX
*mem_ctx
,
910 struct event_context
*ev
,
911 struct timeval wait_time
,
912 const struct sockaddr_storage
*pss
,
916 struct tevent_req
*req
, *subreq
;
917 struct open_socket_out_defer_state
*state
;
919 req
= tevent_req_create(mem_ctx
, &state
,
920 struct open_socket_out_defer_state
);
927 state
->timeout
= timeout
;
929 subreq
= tevent_wakeup_send(
931 timeval_current_ofs(wait_time
.tv_sec
, wait_time
.tv_usec
));
932 if (subreq
== NULL
) {
935 tevent_req_set_callback(subreq
, open_socket_out_defer_waited
, req
);
942 static void open_socket_out_defer_waited(struct tevent_req
*subreq
)
944 struct tevent_req
*req
= tevent_req_callback_data(
945 subreq
, struct tevent_req
);
946 struct open_socket_out_defer_state
*state
= tevent_req_data(
947 req
, struct open_socket_out_defer_state
);
950 ret
= tevent_wakeup_recv(subreq
);
953 tevent_req_nterror(req
, NT_STATUS_INTERNAL_ERROR
);
957 subreq
= open_socket_out_send(state
, state
->ev
, &state
->ss
,
958 state
->port
, state
->timeout
);
959 if (tevent_req_nomem(subreq
, req
)) {
962 tevent_req_set_callback(subreq
, open_socket_out_defer_connected
, req
);
965 static void open_socket_out_defer_connected(struct tevent_req
*subreq
)
967 struct tevent_req
*req
= tevent_req_callback_data(
968 subreq
, struct tevent_req
);
969 struct open_socket_out_defer_state
*state
= tevent_req_data(
970 req
, struct open_socket_out_defer_state
);
973 status
= open_socket_out_recv(subreq
, &state
->fd
);
975 if (!NT_STATUS_IS_OK(status
)) {
976 tevent_req_nterror(req
, status
);
979 tevent_req_done(req
);
982 NTSTATUS
open_socket_out_defer_recv(struct tevent_req
*req
, int *pfd
)
984 struct open_socket_out_defer_state
*state
= tevent_req_data(
985 req
, struct open_socket_out_defer_state
);
988 if (tevent_req_is_nterror(req
, &status
)) {
996 /****************************************************************************
997 Open a connected UDP socket to host on port
998 **************************************************************************/
1000 int open_udp_socket(const char *host
, int port
)
1002 struct sockaddr_storage ss
;
1005 if (!interpret_string_addr(&ss
, host
, 0)) {
1006 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1011 res
= socket(ss
.ss_family
, SOCK_DGRAM
, 0);
1016 #if defined(HAVE_IPV6)
1017 if (ss
.ss_family
== AF_INET6
) {
1018 struct sockaddr_in6
*psa6
;
1019 psa6
= (struct sockaddr_in6
*)&ss
;
1020 psa6
->sin6_port
= htons(port
);
1021 if (psa6
->sin6_scope_id
== 0
1022 && IN6_IS_ADDR_LINKLOCAL(&psa6
->sin6_addr
)) {
1023 setup_linklocal_scope_id(
1024 (struct sockaddr
*)&ss
);
1028 if (ss
.ss_family
== AF_INET
) {
1029 struct sockaddr_in
*psa
;
1030 psa
= (struct sockaddr_in
*)&ss
;
1031 psa
->sin_port
= htons(port
);
1034 if (sys_connect(res
,(struct sockaddr
*)&ss
)) {
1042 /*******************************************************************
1043 Return the IP addr of the remote end of a socket as a string.
1044 Optionally return the struct sockaddr_storage.
1045 ******************************************************************/
1047 static const char *get_peer_addr_internal(int fd
,
1049 size_t addr_buf_len
,
1050 struct sockaddr
*pss
,
1053 struct sockaddr_storage ss
;
1054 socklen_t length
= sizeof(ss
);
1056 strlcpy(addr_buf
,"0.0.0.0",addr_buf_len
);
1063 pss
= (struct sockaddr
*)&ss
;
1067 if (getpeername(fd
, (struct sockaddr
*)pss
, plength
) < 0) {
1068 int level
= (errno
== ENOTCONN
) ? 2 : 0;
1069 DEBUG(level
, ("getpeername failed. Error was %s\n",
1074 print_sockaddr_len(addr_buf
,
1081 /*******************************************************************
1082 Matchname - determine if host name matches IP address. Used to
1083 confirm a hostname lookup to prevent spoof attacks.
1084 ******************************************************************/
1086 static bool matchname(const char *remotehost
,
1087 const struct sockaddr
*pss
,
1090 struct addrinfo
*res
= NULL
;
1091 struct addrinfo
*ailist
= NULL
;
1092 char addr_buf
[INET6_ADDRSTRLEN
];
1093 bool ret
= interpret_string_addr_internal(&ailist
,
1095 AI_ADDRCONFIG
|AI_CANONNAME
);
1097 if (!ret
|| ailist
== NULL
) {
1098 DEBUG(3,("matchname: getaddrinfo failed for "
1101 gai_strerror(ret
) ));
1106 * Make sure that getaddrinfo() returns the "correct" host name.
1109 if (ailist
->ai_canonname
== NULL
||
1110 (!strequal(remotehost
, ailist
->ai_canonname
) &&
1111 !strequal(remotehost
, "localhost"))) {
1112 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1114 ailist
->ai_canonname
?
1115 ailist
->ai_canonname
: "(NULL)"));
1116 freeaddrinfo(ailist
);
1120 /* Look up the host address in the address list we just got. */
1121 for (res
= ailist
; res
; res
= res
->ai_next
) {
1122 if (!res
->ai_addr
) {
1125 if (sockaddr_equal((const struct sockaddr
*)res
->ai_addr
,
1126 (struct sockaddr
*)pss
)) {
1127 freeaddrinfo(ailist
);
1133 * The host name does not map to the original host address. Perhaps
1134 * someone has compromised a name server. More likely someone botched
1135 * it, but that could be dangerous, too.
1138 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1139 print_sockaddr_len(addr_buf
,
1143 ailist
->ai_canonname
? ailist
->ai_canonname
: "(NULL)"));
1146 freeaddrinfo(ailist
);
1151 /*******************************************************************
1152 Deal with the singleton cache.
1153 ******************************************************************/
1155 struct name_addr_pair
{
1156 struct sockaddr_storage ss
;
1160 /*******************************************************************
1161 Lookup a name/addr pair. Returns memory allocated from memcache.
1162 ******************************************************************/
1164 static bool lookup_nc(struct name_addr_pair
*nc
)
1170 if (!memcache_lookup(
1171 NULL
, SINGLETON_CACHE
,
1172 data_blob_string_const_null("get_peer_name"),
1177 memcpy(&nc
->ss
, tmp
.data
, sizeof(nc
->ss
));
1178 nc
->name
= (const char *)tmp
.data
+ sizeof(nc
->ss
);
1182 /*******************************************************************
1183 Save a name/addr pair.
1184 ******************************************************************/
1186 static void store_nc(const struct name_addr_pair
*nc
)
1189 size_t namelen
= strlen(nc
->name
);
1191 tmp
= data_blob(NULL
, sizeof(nc
->ss
) + namelen
+ 1);
1195 memcpy(tmp
.data
, &nc
->ss
, sizeof(nc
->ss
));
1196 memcpy(tmp
.data
+sizeof(nc
->ss
), nc
->name
, namelen
+1);
1198 memcache_add(NULL
, SINGLETON_CACHE
,
1199 data_blob_string_const_null("get_peer_name"),
1201 data_blob_free(&tmp
);
1204 /*******************************************************************
1205 Return the DNS name of the remote end of a socket.
1206 ******************************************************************/
1208 const char *get_peer_name(int fd
, bool force_lookup
)
1210 struct name_addr_pair nc
;
1211 char addr_buf
[INET6_ADDRSTRLEN
];
1212 struct sockaddr_storage ss
;
1213 socklen_t length
= sizeof(ss
);
1216 char name_buf
[MAX_DNS_NAME_LENGTH
];
1217 char tmp_name
[MAX_DNS_NAME_LENGTH
];
1219 /* reverse lookups can be *very* expensive, and in many
1220 situations won't work because many networks don't link dhcp
1221 with dns. To avoid the delay we avoid the lookup if
1223 if (!lp_hostname_lookups() && (force_lookup
== false)) {
1224 length
= sizeof(nc
.ss
);
1225 nc
.name
= get_peer_addr_internal(fd
, addr_buf
, sizeof(addr_buf
),
1226 (struct sockaddr
*)&nc
.ss
, &length
);
1229 return nc
.name
? nc
.name
: "UNKNOWN";
1234 memset(&ss
, '\0', sizeof(ss
));
1235 p
= get_peer_addr_internal(fd
, addr_buf
, sizeof(addr_buf
), (struct sockaddr
*)&ss
, &length
);
1237 /* it might be the same as the last one - save some DNS work */
1238 if (sockaddr_equal((struct sockaddr
*)&ss
, (struct sockaddr
*)&nc
.ss
)) {
1239 return nc
.name
? nc
.name
: "UNKNOWN";
1242 /* Not the same. We need to lookup. */
1247 /* Look up the remote host name. */
1248 ret
= sys_getnameinfo((struct sockaddr
*)&ss
,
1257 DEBUG(1,("get_peer_name: getnameinfo failed "
1258 "for %s with error %s\n",
1260 gai_strerror(ret
)));
1261 strlcpy(name_buf
, p
, sizeof(name_buf
));
1263 if (!matchname(name_buf
, (struct sockaddr
*)&ss
, length
)) {
1264 DEBUG(0,("Matchname failed on %s %s\n",name_buf
,p
));
1265 strlcpy(name_buf
,"UNKNOWN",sizeof(name_buf
));
1269 /* can't pass the same source and dest strings in when you
1270 use --enable-developer or the clobber_region() call will
1273 strlcpy(tmp_name
, name_buf
, sizeof(tmp_name
));
1274 alpha_strcpy(name_buf
, tmp_name
, "_-.", sizeof(name_buf
));
1275 if (strstr(name_buf
,"..")) {
1276 strlcpy(name_buf
, "UNKNOWN", sizeof(name_buf
));
1284 return nc
.name
? nc
.name
: "UNKNOWN";
1287 /*******************************************************************
1288 Return the IP addr of the remote end of a socket as a string.
1289 ******************************************************************/
1291 const char *get_peer_addr(int fd
, char *addr
, size_t addr_len
)
1293 return get_peer_addr_internal(fd
, addr
, addr_len
, NULL
, NULL
);
1296 /*******************************************************************
1297 Create protected unix domain socket.
1299 Some unixes cannot set permissions on a ux-dom-sock, so we
1300 have to make sure that the directory contains the protection
1301 permissions instead.
1302 ******************************************************************/
1304 int create_pipe_sock(const char *socket_dir
,
1305 const char *socket_name
,
1308 #ifdef HAVE_UNIXSOCKET
1309 struct sockaddr_un sunaddr
;
1315 old_umask
= umask(0);
1317 /* Create the socket directory or reuse the existing one */
1319 if (lstat(socket_dir
, &st
) == -1) {
1320 if (errno
== ENOENT
) {
1321 /* Create directory */
1322 if (mkdir(socket_dir
, dir_perms
) == -1) {
1323 DEBUG(0, ("error creating socket directory "
1324 "%s: %s\n", socket_dir
,
1329 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1330 socket_dir
, strerror(errno
)));
1334 /* Check ownership and permission on existing directory */
1335 if (!S_ISDIR(st
.st_mode
)) {
1336 DEBUG(0, ("socket directory %s isn't a directory\n",
1340 if ((st
.st_uid
!= sec_initial_uid()) ||
1341 ((st
.st_mode
& 0777) != dir_perms
)) {
1342 DEBUG(0, ("invalid permissions on socket directory "
1343 "%s\n", socket_dir
));
1348 /* Create the socket file */
1350 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
1353 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1358 if (asprintf(&path
, "%s/%s", socket_dir
, socket_name
) == -1) {
1363 memset(&sunaddr
, 0, sizeof(sunaddr
));
1364 sunaddr
.sun_family
= AF_UNIX
;
1365 strlcpy(sunaddr
.sun_path
, path
, sizeof(sunaddr
.sun_path
));
1367 if (bind(sock
, (struct sockaddr
*)&sunaddr
, sizeof(sunaddr
)) == -1) {
1368 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path
,
1373 if (listen(sock
, 5) == -1) {
1374 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path
,
1394 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1396 #endif /* HAVE_UNIXSOCKET */
1399 /****************************************************************************
1400 Get my own canonical name, including domain.
1401 ****************************************************************************/
1403 const char *get_mydnsfullname(void)
1405 struct addrinfo
*res
= NULL
;
1406 char my_hostname
[HOST_NAME_MAX
];
1410 if (memcache_lookup(NULL
, SINGLETON_CACHE
,
1411 data_blob_string_const_null("get_mydnsfullname"),
1413 SMB_ASSERT(tmp
.length
> 0);
1414 return (const char *)tmp
.data
;
1417 /* get my host name */
1418 if (gethostname(my_hostname
, sizeof(my_hostname
)) == -1) {
1419 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1423 /* Ensure null termination. */
1424 my_hostname
[sizeof(my_hostname
)-1] = '\0';
1426 ret
= interpret_string_addr_internal(&res
,
1428 AI_ADDRCONFIG
|AI_CANONNAME
);
1430 if (!ret
|| res
== NULL
) {
1431 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1434 gai_strerror(ret
) ));
1439 * Make sure that getaddrinfo() returns the "correct" host name.
1442 if (res
->ai_canonname
== NULL
) {
1443 DEBUG(3,("get_mydnsfullname: failed to get "
1444 "canonical name for %s\n",
1450 /* This copies the data, so we must do a lookup
1451 * afterwards to find the value to return.
1454 memcache_add(NULL
, SINGLETON_CACHE
,
1455 data_blob_string_const_null("get_mydnsfullname"),
1456 data_blob_string_const_null(res
->ai_canonname
));
1458 if (!memcache_lookup(NULL
, SINGLETON_CACHE
,
1459 data_blob_string_const_null("get_mydnsfullname"),
1461 tmp
= data_blob_talloc(talloc_tos(), res
->ai_canonname
,
1462 strlen(res
->ai_canonname
) + 1);
1467 return (const char *)tmp
.data
;
1470 /************************************************************
1471 Is this my ip address ?
1472 ************************************************************/
1474 static bool is_my_ipaddr(const char *ipaddr_str
)
1476 struct sockaddr_storage ss
;
1477 struct iface_struct
*nics
;
1480 if (!interpret_string_addr(&ss
, ipaddr_str
, AI_NUMERICHOST
)) {
1484 if (ismyaddr((struct sockaddr
*)&ss
)) {
1488 if (is_zero_addr(&ss
) ||
1489 is_loopback_addr((struct sockaddr
*)&ss
)) {
1493 n
= get_interfaces(talloc_tos(), &nics
);
1494 for (i
=0; i
<n
; i
++) {
1495 if (sockaddr_equal((struct sockaddr
*)&nics
[i
].ip
, (struct sockaddr
*)&ss
)) {
1504 /************************************************************
1506 ************************************************************/
1508 bool is_myname_or_ipaddr(const char *s
)
1510 TALLOC_CTX
*ctx
= talloc_tos();
1512 const char *dnsname
;
1513 char *servername
= NULL
;
1519 /* Santize the string from '\\name' */
1520 name
= talloc_strdup(ctx
, s
);
1525 servername
= strrchr_m(name
, '\\' );
1532 /* Optimize for the common case */
1533 if (strequal(servername
, global_myname())) {
1537 /* Check for an alias */
1538 if (is_myname(servername
)) {
1542 /* Check for loopback */
1543 if (strequal(servername
, "127.0.0.1") ||
1544 strequal(servername
, "::1")) {
1548 if (strequal(servername
, "localhost")) {
1552 /* Maybe it's my dns name */
1553 dnsname
= get_mydnsfullname();
1554 if (dnsname
&& strequal(servername
, dnsname
)) {
1558 /* Maybe its an IP address? */
1559 if (is_ipaddress(servername
)) {
1560 return is_my_ipaddr(servername
);
1563 /* Handle possible CNAME records - convert to an IP addr. list. */
1565 /* Use DNS to resolve the name, check all addresses. */
1566 struct addrinfo
*p
= NULL
;
1567 struct addrinfo
*res
= NULL
;
1569 if (!interpret_string_addr_internal(&res
,
1575 for (p
= res
; p
; p
= p
->ai_next
) {
1576 char addr
[INET6_ADDRSTRLEN
];
1577 struct sockaddr_storage ss
;
1580 memcpy(&ss
, p
->ai_addr
, p
->ai_addrlen
);
1581 print_sockaddr(addr
,
1584 if (is_my_ipaddr(addr
)) {
1596 struct getaddrinfo_state
{
1598 const char *service
;
1599 const struct addrinfo
*hints
;
1600 struct addrinfo
*res
;
1604 static void getaddrinfo_do(void *private_data
);
1605 static void getaddrinfo_done(struct tevent_req
*subreq
);
1607 struct tevent_req
*getaddrinfo_send(TALLOC_CTX
*mem_ctx
,
1608 struct tevent_context
*ev
,
1609 struct fncall_context
*ctx
,
1611 const char *service
,
1612 const struct addrinfo
*hints
)
1614 struct tevent_req
*req
, *subreq
;
1615 struct getaddrinfo_state
*state
;
1617 req
= tevent_req_create(mem_ctx
, &state
, struct getaddrinfo_state
);
1623 state
->service
= service
;
1624 state
->hints
= hints
;
1626 subreq
= fncall_send(state
, ev
, ctx
, getaddrinfo_do
, state
);
1627 if (tevent_req_nomem(subreq
, req
)) {
1628 return tevent_req_post(req
, ev
);
1630 tevent_req_set_callback(subreq
, getaddrinfo_done
, req
);
1634 static void getaddrinfo_do(void *private_data
)
1636 struct getaddrinfo_state
*state
=
1637 (struct getaddrinfo_state
*)private_data
;
1639 state
->ret
= getaddrinfo(state
->node
, state
->service
, state
->hints
,
1643 static void getaddrinfo_done(struct tevent_req
*subreq
)
1645 struct tevent_req
*req
= tevent_req_callback_data(
1646 subreq
, struct tevent_req
);
1649 ret
= fncall_recv(subreq
, &err
);
1650 TALLOC_FREE(subreq
);
1652 tevent_req_error(req
, err
);
1655 tevent_req_done(req
);
1658 int getaddrinfo_recv(struct tevent_req
*req
, struct addrinfo
**res
)
1660 struct getaddrinfo_state
*state
= tevent_req_data(
1661 req
, struct getaddrinfo_state
);
1664 if (tevent_req_is_unix_error(req
, &err
)) {
1672 if (state
->ret
== 0) {
1678 int poll_one_fd(int fd
, int events
, int timeout
, int *revents
)
1684 fds
= TALLOC_ZERO_ARRAY(talloc_tos(), struct pollfd
, 2);
1690 fds
[0].events
= events
;
1692 ret
= sys_poll(fds
, 1, timeout
);
1695 * Assign whatever poll did, even in the ret<=0 case.
1697 *revents
= fds
[0].revents
;
1698 saved_errno
= errno
;
1700 errno
= saved_errno
;
1705 int poll_intr_one_fd(int fd
, int events
, int timeout
, int *revents
)
1711 pfd
.events
= events
;
1713 ret
= sys_poll_intr(&pfd
, 1, timeout
);
1718 *revents
= pfd
.revents
;