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_KEEPALIVE_THRESHOLD
141 {"TCP_KEEPALIVE_THRESHOLD", IPPROTO_TCP
, TCP_KEEPALIVE_THRESHOLD
, 0, OPT_INT
},
143 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
144 {"TCP_KEEPALIVE_ABORT_THRESHOLD", IPPROTO_TCP
, TCP_KEEPALIVE_ABORT_THRESHOLD
, 0, OPT_INT
},
148 /****************************************************************************
149 Print socket options.
150 ****************************************************************************/
152 static void print_socket_options(int s
)
156 const smb_socket_option
*p
= &socket_options
[0];
158 /* wrapped in if statement to prevent streams
159 * leak in SCO Openserver 5.0 */
160 /* reported on samba-technical --jerry */
161 if ( DEBUGLEVEL
>= 5 ) {
162 DEBUG(5,("Socket options:\n"));
163 for (; p
->name
!= NULL
; p
++) {
164 if (getsockopt(s
, p
->level
, p
->option
,
165 (void *)&value
, &vlen
) == -1) {
166 DEBUGADD(5,("\tCould not test socket option %s.\n",
169 DEBUGADD(5,("\t%s = %d\n",
176 /****************************************************************************
177 Set user socket options.
178 ****************************************************************************/
180 void set_socket_options(int fd
, const char *options
)
182 TALLOC_CTX
*ctx
= talloc_stackframe();
185 while (next_token_talloc(ctx
, &options
, &tok
," \t,")) {
189 bool got_value
= false;
191 if ((p
= strchr_m(tok
,'='))) {
197 for (i
=0;socket_options
[i
].name
;i
++)
198 if (strequal(socket_options
[i
].name
,tok
))
201 if (!socket_options
[i
].name
) {
202 DEBUG(0,("Unknown socket option %s\n",tok
));
206 switch (socket_options
[i
].opttype
) {
209 ret
= setsockopt(fd
,socket_options
[i
].level
,
210 socket_options
[i
].option
,
211 (char *)&value
,sizeof(int));
216 DEBUG(0,("syntax error - %s "
217 "does not take a value\n",tok
));
220 int on
= socket_options
[i
].value
;
221 ret
= setsockopt(fd
,socket_options
[i
].level
,
222 socket_options
[i
].option
,
223 (char *)&on
,sizeof(int));
229 /* be aware that some systems like Solaris return
230 * EINVAL to a setsockopt() call when the client
231 * sent a RST previously - no need to worry */
232 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
233 tok
, strerror(errno
) ));
238 print_socket_options(fd
);
241 /****************************************************************************
243 ****************************************************************************/
245 ssize_t
read_udp_v4_socket(int fd
,
248 struct sockaddr_storage
*psa
)
251 socklen_t socklen
= sizeof(*psa
);
252 struct sockaddr_in
*si
= (struct sockaddr_in
*)psa
;
254 memset((char *)psa
,'\0',socklen
);
256 ret
= (ssize_t
)sys_recvfrom(fd
,buf
,len
,0,
257 (struct sockaddr
*)psa
,&socklen
);
259 /* Don't print a low debug error for a non-blocking socket. */
260 if (errno
== EAGAIN
) {
261 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
263 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
269 if (psa
->ss_family
!= AF_INET
) {
270 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
271 "(not IPv4)\n", (int)psa
->ss_family
));
275 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
276 inet_ntoa(si
->sin_addr
),
278 (unsigned long)ret
));
283 /****************************************************************************
284 Read data from a file descriptor with a timout in msec.
285 mincount = if timeout, minimum to read before returning
286 maxcount = number to be read.
287 time_out = timeout in milliseconds
288 NB. This can be called with a non-socket fd, don't change
289 sys_read() to sys_recv() or other socket call.
290 ****************************************************************************/
292 NTSTATUS
read_fd_with_timeout(int fd
, char *buf
,
293 size_t mincnt
, size_t maxcnt
,
294 unsigned int time_out
,
301 /* just checking .... */
311 while (nread
< mincnt
) {
312 readret
= sys_read(fd
, buf
+ nread
, maxcnt
- nread
);
315 DEBUG(5,("read_fd_with_timeout: "
316 "blocking read. EOF from client.\n"));
317 return NT_STATUS_END_OF_FILE
;
321 return map_nt_error_from_unix(errno
);
328 /* Most difficult - timeout read */
329 /* If this is ever called on a disk file and
330 mincnt is greater then the filesize then
331 system performance will suffer severely as
332 select always returns true on disk files */
334 for (nread
=0; nread
< mincnt
; ) {
337 pollrtn
= poll_intr_one_fd(fd
, POLLIN
|POLLHUP
, time_out
,
342 return map_nt_error_from_unix(errno
);
345 /* Did we timeout ? */
346 if ((pollrtn
== 0) ||
347 ((revents
& (POLLIN
|POLLHUP
|POLLERR
)) == 0)) {
348 DEBUG(10,("read_fd_with_timeout: timeout read. "
349 "select timed out.\n"));
350 return NT_STATUS_IO_TIMEOUT
;
353 readret
= sys_read(fd
, buf
+nread
, maxcnt
-nread
);
356 /* we got EOF on the file descriptor */
357 DEBUG(5,("read_fd_with_timeout: timeout read. "
358 "EOF from client.\n"));
359 return NT_STATUS_END_OF_FILE
;
363 return map_nt_error_from_unix(errno
);
370 /* Return the number we got */
377 /****************************************************************************
378 Read data from an fd, reading exactly N bytes.
379 NB. This can be called with a non-socket fd, don't add dependencies
381 ****************************************************************************/
383 NTSTATUS
read_data(int fd
, char *buffer
, size_t N
)
385 return read_fd_with_timeout(fd
, buffer
, N
, N
, 0, NULL
);
388 /****************************************************************************
389 Write all data from an iov array
390 NB. This can be called with a non-socket fd, don't add dependencies
392 ****************************************************************************/
394 ssize_t
write_data_iov(int fd
, const struct iovec
*orig_iov
, int iovcnt
)
400 struct iovec
*iov_copy
, *iov
;
403 for (i
=0; i
<iovcnt
; i
++) {
404 to_send
+= orig_iov
[i
].iov_len
;
407 thistime
= sys_writev(fd
, orig_iov
, iovcnt
);
408 if ((thistime
<= 0) || (thistime
== to_send
)) {
414 * We could not send everything in one call. Make a copy of iov that
415 * we can mess with. We keep a copy of the array start in iov_copy for
416 * the TALLOC_FREE, because we're going to modify iov later on,
417 * discarding elements.
420 iov_copy
= (struct iovec
*)TALLOC_MEMDUP(
421 talloc_tos(), orig_iov
, sizeof(struct iovec
) * iovcnt
);
423 if (iov_copy
== NULL
) {
429 while (sent
< to_send
) {
431 * We have to discard "thistime" bytes from the beginning
432 * iov array, "thistime" contains the number of bytes sent
435 while (thistime
> 0) {
436 if (thistime
< iov
[0].iov_len
) {
438 (char *)iov
[0].iov_base
+ thistime
;
439 iov
[0].iov_base
= (void *)new_base
;
440 iov
[0].iov_len
-= thistime
;
443 thistime
-= iov
[0].iov_len
;
448 thistime
= sys_writev(fd
, iov
, iovcnt
);
455 TALLOC_FREE(iov_copy
);
459 /****************************************************************************
461 NB. This can be called with a non-socket fd, don't add dependencies
463 ****************************************************************************/
465 ssize_t
write_data(int fd
, const char *buffer
, size_t N
)
469 iov
.iov_base
= CONST_DISCARD(void *, buffer
);
471 return write_data_iov(fd
, &iov
, 1);
474 /****************************************************************************
475 Send a keepalive packet (rfc1002).
476 ****************************************************************************/
478 bool send_keepalive(int client
)
480 unsigned char buf
[4];
482 buf
[0] = SMBkeepalive
;
483 buf
[1] = buf
[2] = buf
[3] = 0;
485 return(write_data(client
,(char *)buf
,4) == 4);
488 /****************************************************************************
489 Read 4 bytes of a smb packet and return the smb length of the packet.
490 Store the result in the buffer.
491 This version of the function will return a length of zero on receiving
493 Timeout is in milliseconds.
494 ****************************************************************************/
496 NTSTATUS
read_smb_length_return_keepalive(int fd
, char *inbuf
,
497 unsigned int timeout
,
503 status
= read_fd_with_timeout(fd
, inbuf
, 4, 4, timeout
, NULL
);
505 if (!NT_STATUS_IS_OK(status
)) {
509 *len
= smb_len(inbuf
);
510 msg_type
= CVAL(inbuf
,0);
512 if (msg_type
== SMBkeepalive
) {
513 DEBUG(5,("Got keepalive packet\n"));
516 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len
)));
521 /****************************************************************************
522 Read an smb from a fd.
523 The timeout is in milliseconds.
524 This function will return on receipt of a session keepalive packet.
525 maxlen is the max number of bytes to return, not including the 4 byte
526 length. If zero it means buflen limit.
527 Doesn't check the MAC on signed packets.
528 ****************************************************************************/
530 NTSTATUS
receive_smb_raw(int fd
, char *buffer
, size_t buflen
, unsigned int timeout
,
531 size_t maxlen
, size_t *p_len
)
536 status
= read_smb_length_return_keepalive(fd
,buffer
,timeout
,&len
);
538 if (!NT_STATUS_IS_OK(status
)) {
539 DEBUG(0, ("read_fd_with_timeout failed, read "
540 "error = %s.\n", nt_errstr(status
)));
545 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
546 (unsigned long)len
));
547 return NT_STATUS_INVALID_PARAMETER
;
552 len
= MIN(len
,maxlen
);
555 status
= read_fd_with_timeout(
556 fd
, buffer
+4, len
, len
, timeout
, &len
);
558 if (!NT_STATUS_IS_OK(status
)) {
559 DEBUG(0, ("read_fd_with_timeout failed, read error = "
560 "%s.\n", nt_errstr(status
)));
564 /* not all of samba3 properly checks for packet-termination
565 * of strings. This ensures that we don't run off into
567 SSVAL(buffer
+4,len
, 0);
574 /****************************************************************************
575 Open a socket of the specified type, port, and address for incoming data.
576 ****************************************************************************/
578 int open_socket_in(int type
,
581 const struct sockaddr_storage
*psock
,
584 struct sockaddr_storage sock
;
586 socklen_t slen
= sizeof(struct sockaddr_in
);
590 #if defined(HAVE_IPV6)
591 if (sock
.ss_family
== AF_INET6
) {
592 ((struct sockaddr_in6
*)&sock
)->sin6_port
= htons(port
);
593 slen
= sizeof(struct sockaddr_in6
);
596 if (sock
.ss_family
== AF_INET
) {
597 ((struct sockaddr_in
*)&sock
)->sin_port
= htons(port
);
600 res
= socket(sock
.ss_family
, type
, 0 );
603 dbgtext( "open_socket_in(): socket() call failed: " );
604 dbgtext( "%s\n", strerror( errno
) );
609 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
611 int val
= rebind
? 1 : 0;
612 if( setsockopt(res
,SOL_SOCKET
,SO_REUSEADDR
,
613 (char *)&val
,sizeof(val
)) == -1 ) {
614 if( DEBUGLVL( dlevel
) ) {
615 dbgtext( "open_socket_in(): setsockopt: " );
616 dbgtext( "SO_REUSEADDR = %s ",
617 val
?"true":"false" );
618 dbgtext( "on port %d failed ", port
);
619 dbgtext( "with error = %s\n", strerror(errno
) );
623 if( setsockopt(res
,SOL_SOCKET
,SO_REUSEPORT
,
624 (char *)&val
,sizeof(val
)) == -1 ) {
625 if( DEBUGLVL( dlevel
) ) {
626 dbgtext( "open_socket_in(): setsockopt: ");
627 dbgtext( "SO_REUSEPORT = %s ",
629 dbgtext( "on port %d failed ", port
);
630 dbgtext( "with error = %s\n", strerror(errno
));
633 #endif /* SO_REUSEPORT */
638 * As IPV6_V6ONLY is the default on some systems,
639 * we better try to be consistent and always use it.
641 * This also avoids using IPv4 via AF_INET6 sockets
642 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
645 if (sock
.ss_family
== AF_INET6
) {
649 ret
= setsockopt(res
, IPPROTO_IPV6
, IPV6_V6ONLY
,
650 (const void *)&val
, sizeof(val
));
653 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
654 dbgtext("%s\n", strerror(errno
));
662 /* now we've got a socket - we need to bind it */
663 if (bind(res
, (struct sockaddr
*)&sock
, slen
) == -1 ) {
664 if( DEBUGLVL(dlevel
) && (port
== SMB_PORT1
||
665 port
== SMB_PORT2
|| port
== NMB_PORT
) ) {
666 char addr
[INET6_ADDRSTRLEN
];
667 print_sockaddr(addr
, sizeof(addr
),
669 dbgtext( "bind failed on port %d ", port
);
670 dbgtext( "socket_addr = %s.\n", addr
);
671 dbgtext( "Error = %s\n", strerror(errno
));
677 DEBUG( 10, ( "bind succeeded on port %d\n", port
) );
681 struct open_socket_out_state
{
683 struct event_context
*ev
;
684 struct sockaddr_storage ss
;
690 static void open_socket_out_connected(struct tevent_req
*subreq
);
692 static int open_socket_out_state_destructor(struct open_socket_out_state
*s
)
700 /****************************************************************************
701 Create an outgoing socket. timeout is in milliseconds.
702 **************************************************************************/
704 struct tevent_req
*open_socket_out_send(TALLOC_CTX
*mem_ctx
,
705 struct event_context
*ev
,
706 const struct sockaddr_storage
*pss
,
710 char addr
[INET6_ADDRSTRLEN
];
711 struct tevent_req
*result
, *subreq
;
712 struct open_socket_out_state
*state
;
715 result
= tevent_req_create(mem_ctx
, &state
,
716 struct open_socket_out_state
);
717 if (result
== NULL
) {
723 state
->wait_nsec
= 10000;
726 state
->fd
= socket(state
->ss
.ss_family
, SOCK_STREAM
, 0);
727 if (state
->fd
== -1) {
728 status
= map_nt_error_from_unix(errno
);
731 talloc_set_destructor(state
, open_socket_out_state_destructor
);
733 if (!tevent_req_set_endtime(
734 result
, ev
, timeval_current_ofs(0, timeout
*1000))) {
738 #if defined(HAVE_IPV6)
739 if (pss
->ss_family
== AF_INET6
) {
740 struct sockaddr_in6
*psa6
;
741 psa6
= (struct sockaddr_in6
*)&state
->ss
;
742 psa6
->sin6_port
= htons(port
);
743 if (psa6
->sin6_scope_id
== 0
744 && IN6_IS_ADDR_LINKLOCAL(&psa6
->sin6_addr
)) {
745 setup_linklocal_scope_id(
746 (struct sockaddr
*)&(state
->ss
));
748 state
->salen
= sizeof(struct sockaddr_in6
);
751 if (pss
->ss_family
== AF_INET
) {
752 struct sockaddr_in
*psa
;
753 psa
= (struct sockaddr_in
*)&state
->ss
;
754 psa
->sin_port
= htons(port
);
755 state
->salen
= sizeof(struct sockaddr_in
);
758 if (pss
->ss_family
== AF_UNIX
) {
759 state
->salen
= sizeof(struct sockaddr_un
);
762 print_sockaddr(addr
, sizeof(addr
), &state
->ss
);
763 DEBUG(3,("Connecting to %s at port %u\n", addr
, (unsigned int)port
));
765 subreq
= async_connect_send(state
, state
->ev
, state
->fd
,
766 (struct sockaddr
*)&state
->ss
,
769 || !tevent_req_set_endtime(
771 timeval_current_ofs(0, state
->wait_nsec
))) {
774 tevent_req_set_callback(subreq
, open_socket_out_connected
, result
);
778 tevent_req_nterror(result
, status
);
779 return tevent_req_post(result
, ev
);
785 static void open_socket_out_connected(struct tevent_req
*subreq
)
787 struct tevent_req
*req
=
788 tevent_req_callback_data(subreq
, struct tevent_req
);
789 struct open_socket_out_state
*state
=
790 tevent_req_data(req
, struct open_socket_out_state
);
794 ret
= async_connect_recv(subreq
, &sys_errno
);
797 tevent_req_done(req
);
803 (sys_errno
== ETIMEDOUT
) ||
805 (sys_errno
== EINPROGRESS
) ||
806 (sys_errno
== EALREADY
) ||
807 (sys_errno
== EAGAIN
)) {
813 if (state
->wait_nsec
< 250000) {
814 state
->wait_nsec
*= 1.5;
817 subreq
= async_connect_send(state
, state
->ev
, state
->fd
,
818 (struct sockaddr
*)&state
->ss
,
820 if (tevent_req_nomem(subreq
, req
)) {
823 if (!tevent_req_set_endtime(
825 timeval_current_ofs(0, state
->wait_nsec
))) {
826 tevent_req_nterror(req
, NT_STATUS_NO_MEMORY
);
829 tevent_req_set_callback(subreq
, open_socket_out_connected
, req
);
834 if (sys_errno
== EISCONN
) {
835 tevent_req_done(req
);
841 tevent_req_nterror(req
, map_nt_error_from_unix(sys_errno
));
844 NTSTATUS
open_socket_out_recv(struct tevent_req
*req
, int *pfd
)
846 struct open_socket_out_state
*state
=
847 tevent_req_data(req
, struct open_socket_out_state
);
850 if (tevent_req_is_nterror(req
, &status
)) {
859 * @brief open a socket
861 * @param pss a struct sockaddr_storage defining the address to connect to
862 * @param port to connect to
863 * @param timeout in MILLISECONDS
864 * @param pfd file descriptor returned
866 * @return NTSTATUS code
868 NTSTATUS
open_socket_out(const struct sockaddr_storage
*pss
, uint16_t port
,
869 int timeout
, int *pfd
)
871 TALLOC_CTX
*frame
= talloc_stackframe();
872 struct event_context
*ev
;
873 struct tevent_req
*req
;
874 NTSTATUS status
= NT_STATUS_NO_MEMORY
;
876 ev
= event_context_init(frame
);
881 req
= open_socket_out_send(frame
, ev
, pss
, port
, timeout
);
885 if (!tevent_req_poll(req
, ev
)) {
886 status
= NT_STATUS_INTERNAL_ERROR
;
889 status
= open_socket_out_recv(req
, pfd
);
895 struct open_socket_out_defer_state
{
896 struct event_context
*ev
;
897 struct sockaddr_storage ss
;
903 static void open_socket_out_defer_waited(struct tevent_req
*subreq
);
904 static void open_socket_out_defer_connected(struct tevent_req
*subreq
);
906 struct tevent_req
*open_socket_out_defer_send(TALLOC_CTX
*mem_ctx
,
907 struct event_context
*ev
,
908 struct timeval wait_time
,
909 const struct sockaddr_storage
*pss
,
913 struct tevent_req
*req
, *subreq
;
914 struct open_socket_out_defer_state
*state
;
916 req
= tevent_req_create(mem_ctx
, &state
,
917 struct open_socket_out_defer_state
);
924 state
->timeout
= timeout
;
926 subreq
= tevent_wakeup_send(
928 timeval_current_ofs(wait_time
.tv_sec
, wait_time
.tv_usec
));
929 if (subreq
== NULL
) {
932 tevent_req_set_callback(subreq
, open_socket_out_defer_waited
, req
);
939 static void open_socket_out_defer_waited(struct tevent_req
*subreq
)
941 struct tevent_req
*req
= tevent_req_callback_data(
942 subreq
, struct tevent_req
);
943 struct open_socket_out_defer_state
*state
= tevent_req_data(
944 req
, struct open_socket_out_defer_state
);
947 ret
= tevent_wakeup_recv(subreq
);
950 tevent_req_nterror(req
, NT_STATUS_INTERNAL_ERROR
);
954 subreq
= open_socket_out_send(state
, state
->ev
, &state
->ss
,
955 state
->port
, state
->timeout
);
956 if (tevent_req_nomem(subreq
, req
)) {
959 tevent_req_set_callback(subreq
, open_socket_out_defer_connected
, req
);
962 static void open_socket_out_defer_connected(struct tevent_req
*subreq
)
964 struct tevent_req
*req
= tevent_req_callback_data(
965 subreq
, struct tevent_req
);
966 struct open_socket_out_defer_state
*state
= tevent_req_data(
967 req
, struct open_socket_out_defer_state
);
970 status
= open_socket_out_recv(subreq
, &state
->fd
);
972 if (!NT_STATUS_IS_OK(status
)) {
973 tevent_req_nterror(req
, status
);
976 tevent_req_done(req
);
979 NTSTATUS
open_socket_out_defer_recv(struct tevent_req
*req
, int *pfd
)
981 struct open_socket_out_defer_state
*state
= tevent_req_data(
982 req
, struct open_socket_out_defer_state
);
985 if (tevent_req_is_nterror(req
, &status
)) {
993 /****************************************************************************
994 Open a connected UDP socket to host on port
995 **************************************************************************/
997 int open_udp_socket(const char *host
, int port
)
999 struct sockaddr_storage ss
;
1002 if (!interpret_string_addr(&ss
, host
, 0)) {
1003 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1008 res
= socket(ss
.ss_family
, SOCK_DGRAM
, 0);
1013 #if defined(HAVE_IPV6)
1014 if (ss
.ss_family
== AF_INET6
) {
1015 struct sockaddr_in6
*psa6
;
1016 psa6
= (struct sockaddr_in6
*)&ss
;
1017 psa6
->sin6_port
= htons(port
);
1018 if (psa6
->sin6_scope_id
== 0
1019 && IN6_IS_ADDR_LINKLOCAL(&psa6
->sin6_addr
)) {
1020 setup_linklocal_scope_id(
1021 (struct sockaddr
*)&ss
);
1025 if (ss
.ss_family
== AF_INET
) {
1026 struct sockaddr_in
*psa
;
1027 psa
= (struct sockaddr_in
*)&ss
;
1028 psa
->sin_port
= htons(port
);
1031 if (sys_connect(res
,(struct sockaddr
*)&ss
)) {
1039 /*******************************************************************
1040 Return the IP addr of the remote end of a socket as a string.
1041 Optionally return the struct sockaddr_storage.
1042 ******************************************************************/
1044 static const char *get_peer_addr_internal(int fd
,
1046 size_t addr_buf_len
,
1047 struct sockaddr
*pss
,
1050 struct sockaddr_storage ss
;
1051 socklen_t length
= sizeof(ss
);
1053 strlcpy(addr_buf
,"0.0.0.0",addr_buf_len
);
1060 pss
= (struct sockaddr
*)&ss
;
1064 if (getpeername(fd
, (struct sockaddr
*)pss
, plength
) < 0) {
1065 int level
= (errno
== ENOTCONN
) ? 2 : 0;
1066 DEBUG(level
, ("getpeername failed. Error was %s\n",
1071 print_sockaddr_len(addr_buf
,
1078 /*******************************************************************
1079 Matchname - determine if host name matches IP address. Used to
1080 confirm a hostname lookup to prevent spoof attacks.
1081 ******************************************************************/
1083 static bool matchname(const char *remotehost
,
1084 const struct sockaddr
*pss
,
1087 struct addrinfo
*res
= NULL
;
1088 struct addrinfo
*ailist
= NULL
;
1089 char addr_buf
[INET6_ADDRSTRLEN
];
1090 bool ret
= interpret_string_addr_internal(&ailist
,
1092 AI_ADDRCONFIG
|AI_CANONNAME
);
1094 if (!ret
|| ailist
== NULL
) {
1095 DEBUG(3,("matchname: getaddrinfo failed for "
1098 gai_strerror(ret
) ));
1103 * Make sure that getaddrinfo() returns the "correct" host name.
1106 if (ailist
->ai_canonname
== NULL
||
1107 (!strequal(remotehost
, ailist
->ai_canonname
) &&
1108 !strequal(remotehost
, "localhost"))) {
1109 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1111 ailist
->ai_canonname
?
1112 ailist
->ai_canonname
: "(NULL)"));
1113 freeaddrinfo(ailist
);
1117 /* Look up the host address in the address list we just got. */
1118 for (res
= ailist
; res
; res
= res
->ai_next
) {
1119 if (!res
->ai_addr
) {
1122 if (sockaddr_equal((const struct sockaddr
*)res
->ai_addr
,
1123 (struct sockaddr
*)pss
)) {
1124 freeaddrinfo(ailist
);
1130 * The host name does not map to the original host address. Perhaps
1131 * someone has compromised a name server. More likely someone botched
1132 * it, but that could be dangerous, too.
1135 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1136 print_sockaddr_len(addr_buf
,
1140 ailist
->ai_canonname
? ailist
->ai_canonname
: "(NULL)"));
1143 freeaddrinfo(ailist
);
1148 /*******************************************************************
1149 Deal with the singleton cache.
1150 ******************************************************************/
1152 struct name_addr_pair
{
1153 struct sockaddr_storage ss
;
1157 /*******************************************************************
1158 Lookup a name/addr pair. Returns memory allocated from memcache.
1159 ******************************************************************/
1161 static bool lookup_nc(struct name_addr_pair
*nc
)
1167 if (!memcache_lookup(
1168 NULL
, SINGLETON_CACHE
,
1169 data_blob_string_const_null("get_peer_name"),
1174 memcpy(&nc
->ss
, tmp
.data
, sizeof(nc
->ss
));
1175 nc
->name
= (const char *)tmp
.data
+ sizeof(nc
->ss
);
1179 /*******************************************************************
1180 Save a name/addr pair.
1181 ******************************************************************/
1183 static void store_nc(const struct name_addr_pair
*nc
)
1186 size_t namelen
= strlen(nc
->name
);
1188 tmp
= data_blob(NULL
, sizeof(nc
->ss
) + namelen
+ 1);
1192 memcpy(tmp
.data
, &nc
->ss
, sizeof(nc
->ss
));
1193 memcpy(tmp
.data
+sizeof(nc
->ss
), nc
->name
, namelen
+1);
1195 memcache_add(NULL
, SINGLETON_CACHE
,
1196 data_blob_string_const_null("get_peer_name"),
1198 data_blob_free(&tmp
);
1201 /*******************************************************************
1202 Return the DNS name of the remote end of a socket.
1203 ******************************************************************/
1205 const char *get_peer_name(int fd
, bool force_lookup
)
1207 struct name_addr_pair nc
;
1208 char addr_buf
[INET6_ADDRSTRLEN
];
1209 struct sockaddr_storage ss
;
1210 socklen_t length
= sizeof(ss
);
1213 char name_buf
[MAX_DNS_NAME_LENGTH
];
1214 char tmp_name
[MAX_DNS_NAME_LENGTH
];
1216 /* reverse lookups can be *very* expensive, and in many
1217 situations won't work because many networks don't link dhcp
1218 with dns. To avoid the delay we avoid the lookup if
1220 if (!lp_hostname_lookups() && (force_lookup
== false)) {
1221 length
= sizeof(nc
.ss
);
1222 nc
.name
= get_peer_addr_internal(fd
, addr_buf
, sizeof(addr_buf
),
1223 (struct sockaddr
*)&nc
.ss
, &length
);
1226 return nc
.name
? nc
.name
: "UNKNOWN";
1231 memset(&ss
, '\0', sizeof(ss
));
1232 p
= get_peer_addr_internal(fd
, addr_buf
, sizeof(addr_buf
), (struct sockaddr
*)&ss
, &length
);
1234 /* it might be the same as the last one - save some DNS work */
1235 if (sockaddr_equal((struct sockaddr
*)&ss
, (struct sockaddr
*)&nc
.ss
)) {
1236 return nc
.name
? nc
.name
: "UNKNOWN";
1239 /* Not the same. We need to lookup. */
1244 /* Look up the remote host name. */
1245 ret
= sys_getnameinfo((struct sockaddr
*)&ss
,
1254 DEBUG(1,("get_peer_name: getnameinfo failed "
1255 "for %s with error %s\n",
1257 gai_strerror(ret
)));
1258 strlcpy(name_buf
, p
, sizeof(name_buf
));
1260 if (!matchname(name_buf
, (struct sockaddr
*)&ss
, length
)) {
1261 DEBUG(0,("Matchname failed on %s %s\n",name_buf
,p
));
1262 strlcpy(name_buf
,"UNKNOWN",sizeof(name_buf
));
1266 /* can't pass the same source and dest strings in when you
1267 use --enable-developer or the clobber_region() call will
1270 strlcpy(tmp_name
, name_buf
, sizeof(tmp_name
));
1271 alpha_strcpy(name_buf
, tmp_name
, "_-.", sizeof(name_buf
));
1272 if (strstr(name_buf
,"..")) {
1273 strlcpy(name_buf
, "UNKNOWN", sizeof(name_buf
));
1281 return nc
.name
? nc
.name
: "UNKNOWN";
1284 /*******************************************************************
1285 Return the IP addr of the remote end of a socket as a string.
1286 ******************************************************************/
1288 const char *get_peer_addr(int fd
, char *addr
, size_t addr_len
)
1290 return get_peer_addr_internal(fd
, addr
, addr_len
, NULL
, NULL
);
1293 /*******************************************************************
1294 Create protected unix domain socket.
1296 Some unixes cannot set permissions on a ux-dom-sock, so we
1297 have to make sure that the directory contains the protection
1298 permissions instead.
1299 ******************************************************************/
1301 int create_pipe_sock(const char *socket_dir
,
1302 const char *socket_name
,
1305 #ifdef HAVE_UNIXSOCKET
1306 struct sockaddr_un sunaddr
;
1312 old_umask
= umask(0);
1314 /* Create the socket directory or reuse the existing one */
1316 if (lstat(socket_dir
, &st
) == -1) {
1317 if (errno
== ENOENT
) {
1318 /* Create directory */
1319 if (mkdir(socket_dir
, dir_perms
) == -1) {
1320 DEBUG(0, ("error creating socket directory "
1321 "%s: %s\n", socket_dir
,
1326 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1327 socket_dir
, strerror(errno
)));
1331 /* Check ownership and permission on existing directory */
1332 if (!S_ISDIR(st
.st_mode
)) {
1333 DEBUG(0, ("socket directory %s isn't a directory\n",
1337 if ((st
.st_uid
!= sec_initial_uid()) ||
1338 ((st
.st_mode
& 0777) != dir_perms
)) {
1339 DEBUG(0, ("invalid permissions on socket directory "
1340 "%s\n", socket_dir
));
1345 /* Create the socket file */
1347 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
1350 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1355 if (asprintf(&path
, "%s/%s", socket_dir
, socket_name
) == -1) {
1360 memset(&sunaddr
, 0, sizeof(sunaddr
));
1361 sunaddr
.sun_family
= AF_UNIX
;
1362 strlcpy(sunaddr
.sun_path
, path
, sizeof(sunaddr
.sun_path
));
1364 if (bind(sock
, (struct sockaddr
*)&sunaddr
, sizeof(sunaddr
)) == -1) {
1365 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path
,
1370 if (listen(sock
, 5) == -1) {
1371 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path
,
1391 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1393 #endif /* HAVE_UNIXSOCKET */
1396 /****************************************************************************
1397 Get my own canonical name, including domain.
1398 ****************************************************************************/
1400 const char *get_mydnsfullname(void)
1402 struct addrinfo
*res
= NULL
;
1403 char my_hostname
[HOST_NAME_MAX
];
1407 if (memcache_lookup(NULL
, SINGLETON_CACHE
,
1408 data_blob_string_const_null("get_mydnsfullname"),
1410 SMB_ASSERT(tmp
.length
> 0);
1411 return (const char *)tmp
.data
;
1414 /* get my host name */
1415 if (gethostname(my_hostname
, sizeof(my_hostname
)) == -1) {
1416 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1420 /* Ensure null termination. */
1421 my_hostname
[sizeof(my_hostname
)-1] = '\0';
1423 ret
= interpret_string_addr_internal(&res
,
1425 AI_ADDRCONFIG
|AI_CANONNAME
);
1427 if (!ret
|| res
== NULL
) {
1428 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1431 gai_strerror(ret
) ));
1436 * Make sure that getaddrinfo() returns the "correct" host name.
1439 if (res
->ai_canonname
== NULL
) {
1440 DEBUG(3,("get_mydnsfullname: failed to get "
1441 "canonical name for %s\n",
1447 /* This copies the data, so we must do a lookup
1448 * afterwards to find the value to return.
1451 memcache_add(NULL
, SINGLETON_CACHE
,
1452 data_blob_string_const_null("get_mydnsfullname"),
1453 data_blob_string_const_null(res
->ai_canonname
));
1455 if (!memcache_lookup(NULL
, SINGLETON_CACHE
,
1456 data_blob_string_const_null("get_mydnsfullname"),
1458 tmp
= data_blob_talloc(talloc_tos(), res
->ai_canonname
,
1459 strlen(res
->ai_canonname
) + 1);
1464 return (const char *)tmp
.data
;
1467 /************************************************************
1468 Is this my ip address ?
1469 ************************************************************/
1471 static bool is_my_ipaddr(const char *ipaddr_str
)
1473 struct sockaddr_storage ss
;
1474 struct iface_struct
*nics
;
1477 if (!interpret_string_addr(&ss
, ipaddr_str
, AI_NUMERICHOST
)) {
1481 if (ismyaddr((struct sockaddr
*)&ss
)) {
1485 if (is_zero_addr(&ss
) ||
1486 is_loopback_addr((struct sockaddr
*)&ss
)) {
1490 n
= get_interfaces(talloc_tos(), &nics
);
1491 for (i
=0; i
<n
; i
++) {
1492 if (sockaddr_equal((struct sockaddr
*)&nics
[i
].ip
, (struct sockaddr
*)&ss
)) {
1501 /************************************************************
1503 ************************************************************/
1505 bool is_myname_or_ipaddr(const char *s
)
1507 TALLOC_CTX
*ctx
= talloc_tos();
1509 const char *dnsname
;
1510 char *servername
= NULL
;
1516 /* Santize the string from '\\name' */
1517 name
= talloc_strdup(ctx
, s
);
1522 servername
= strrchr_m(name
, '\\' );
1529 /* Optimize for the common case */
1530 if (strequal(servername
, global_myname())) {
1534 /* Check for an alias */
1535 if (is_myname(servername
)) {
1539 /* Check for loopback */
1540 if (strequal(servername
, "127.0.0.1") ||
1541 strequal(servername
, "::1")) {
1545 if (strequal(servername
, "localhost")) {
1549 /* Maybe it's my dns name */
1550 dnsname
= get_mydnsfullname();
1551 if (dnsname
&& strequal(servername
, dnsname
)) {
1555 /* Maybe its an IP address? */
1556 if (is_ipaddress(servername
)) {
1557 return is_my_ipaddr(servername
);
1560 /* Handle possible CNAME records - convert to an IP addr. list. */
1562 /* Use DNS to resolve the name, check all addresses. */
1563 struct addrinfo
*p
= NULL
;
1564 struct addrinfo
*res
= NULL
;
1566 if (!interpret_string_addr_internal(&res
,
1572 for (p
= res
; p
; p
= p
->ai_next
) {
1573 char addr
[INET6_ADDRSTRLEN
];
1574 struct sockaddr_storage ss
;
1577 memcpy(&ss
, p
->ai_addr
, p
->ai_addrlen
);
1578 print_sockaddr(addr
,
1581 if (is_my_ipaddr(addr
)) {
1593 struct getaddrinfo_state
{
1595 const char *service
;
1596 const struct addrinfo
*hints
;
1597 struct addrinfo
*res
;
1601 static void getaddrinfo_do(void *private_data
);
1602 static void getaddrinfo_done(struct tevent_req
*subreq
);
1604 struct tevent_req
*getaddrinfo_send(TALLOC_CTX
*mem_ctx
,
1605 struct tevent_context
*ev
,
1606 struct fncall_context
*ctx
,
1608 const char *service
,
1609 const struct addrinfo
*hints
)
1611 struct tevent_req
*req
, *subreq
;
1612 struct getaddrinfo_state
*state
;
1614 req
= tevent_req_create(mem_ctx
, &state
, struct getaddrinfo_state
);
1620 state
->service
= service
;
1621 state
->hints
= hints
;
1623 subreq
= fncall_send(state
, ev
, ctx
, getaddrinfo_do
, state
);
1624 if (tevent_req_nomem(subreq
, req
)) {
1625 return tevent_req_post(req
, ev
);
1627 tevent_req_set_callback(subreq
, getaddrinfo_done
, req
);
1631 static void getaddrinfo_do(void *private_data
)
1633 struct getaddrinfo_state
*state
=
1634 (struct getaddrinfo_state
*)private_data
;
1636 state
->ret
= getaddrinfo(state
->node
, state
->service
, state
->hints
,
1640 static void getaddrinfo_done(struct tevent_req
*subreq
)
1642 struct tevent_req
*req
= tevent_req_callback_data(
1643 subreq
, struct tevent_req
);
1646 ret
= fncall_recv(subreq
, &err
);
1647 TALLOC_FREE(subreq
);
1649 tevent_req_error(req
, err
);
1652 tevent_req_done(req
);
1655 int getaddrinfo_recv(struct tevent_req
*req
, struct addrinfo
**res
)
1657 struct getaddrinfo_state
*state
= tevent_req_data(
1658 req
, struct getaddrinfo_state
);
1661 if (tevent_req_is_unix_error(req
, &err
)) {
1669 if (state
->ret
== 0) {
1675 int poll_one_fd(int fd
, int events
, int timeout
, int *revents
)
1681 fds
= TALLOC_ZERO_ARRAY(talloc_tos(), struct pollfd
, 2);
1687 fds
[0].events
= events
;
1689 ret
= sys_poll(fds
, 1, timeout
);
1692 * Assign whatever poll did, even in the ret<=0 case.
1694 *revents
= fds
[0].revents
;
1695 saved_errno
= errno
;
1697 errno
= saved_errno
;
1702 int poll_intr_one_fd(int fd
, int events
, int timeout
, int *revents
)
1708 pfd
.events
= events
;
1710 ret
= sys_poll_intr(&pfd
, 1, timeout
);
1715 *revents
= pfd
.revents
;