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 #include "../lib/async_req/async_sock.h"
26 /****************************************************************************
27 Get a port number in host byte order from a sockaddr_storage.
28 ****************************************************************************/
30 uint16_t get_sockaddr_port(const struct sockaddr_storage *pss)
34 if (pss->ss_family != AF_INET) {
35 #if defined(HAVE_IPV6)
37 const struct sockaddr_in6 *sa6 =
38 (const struct sockaddr_in6 *)pss;
39 port = ntohs(sa6->sin6_port);
42 const struct sockaddr_in *sa =
43 (const struct sockaddr_in *)pss;
44 port = ntohs(sa->sin_port);
49 /****************************************************************************
50 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
51 ****************************************************************************/
53 static char *print_sockaddr_len(char *dest,
55 const struct sockaddr *psa,
61 (void)sys_getnameinfo(psa,
69 /****************************************************************************
70 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
71 ****************************************************************************/
73 char *print_sockaddr(char *dest,
75 const struct sockaddr_storage *psa)
77 return print_sockaddr_len(dest, destlen, (struct sockaddr *)psa,
78 sizeof(struct sockaddr_storage));
81 /****************************************************************************
82 Print out a canonical IPv4 or IPv6 address from a struct sockaddr_storage.
83 ****************************************************************************/
85 char *print_canonical_sockaddr(TALLOC_CTX *ctx,
86 const struct sockaddr_storage *pss)
88 char addr[INET6_ADDRSTRLEN];
92 /* Linux getnameinfo() man pages says port is unitialized if
93 service name is NULL. */
95 ret = sys_getnameinfo((const struct sockaddr *)pss,
96 sizeof(struct sockaddr_storage),
104 if (pss->ss_family != AF_INET) {
105 #if defined(HAVE_IPV6)
106 dest = talloc_asprintf(ctx, "[%s]", addr);
111 dest = talloc_asprintf(ctx, "%s", addr);
117 /****************************************************************************
118 Return the string of an IP address (IPv4 or IPv6).
119 ****************************************************************************/
121 static const char *get_socket_addr(int fd, char *addr_buf, size_t addr_len)
123 struct sockaddr_storage sa;
124 socklen_t length = sizeof(sa);
126 /* Ok, returning a hard coded IPv4 address
127 * is bogus, but it's just as bogus as a
128 * zero IPv6 address. No good choice here.
131 strlcpy(addr_buf, "0.0.0.0", addr_len);
137 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
138 DEBUG(0,("getsockname failed. Error was %s\n",
143 return print_sockaddr_len(addr_buf, addr_len, (struct sockaddr *)&sa, length);
146 /****************************************************************************
147 Return the port number we've bound to on a socket.
148 ****************************************************************************/
150 int get_socket_port(int fd)
152 struct sockaddr_storage sa;
153 socklen_t length = sizeof(sa);
159 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
160 int level = (errno == ENOTCONN) ? 2 : 0;
161 DEBUG(level, ("getpeername failed. Error was %s\n",
166 #if defined(HAVE_IPV6)
167 if (sa.ss_family == AF_INET6) {
168 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
171 if (sa.ss_family == AF_INET) {
172 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
177 const char *client_name(int fd)
179 return get_peer_name(fd,false);
182 const char *client_addr(int fd, char *addr, size_t addrlen)
184 return get_peer_addr(fd,addr,addrlen);
187 const char *client_socket_addr(int fd, char *addr, size_t addr_len)
189 return get_socket_addr(fd, addr, addr_len);
193 /* Not currently used. JRA. */
194 int client_socket_port(int fd)
196 return get_socket_port(fd);
200 /****************************************************************************
201 Accessor functions to make thread-safe code easier later...
202 ****************************************************************************/
204 void set_smb_read_error(enum smb_read_errors *pre,
205 enum smb_read_errors newerr)
212 void cond_set_smb_read_error(enum smb_read_errors *pre,
213 enum smb_read_errors newerr)
215 if (pre && *pre == SMB_READ_OK) {
220 /****************************************************************************
221 Determine if a file descriptor is in fact a socket.
222 ****************************************************************************/
224 bool is_a_socket(int fd)
229 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
232 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
234 typedef struct smb_socket_option {
242 static const smb_socket_option socket_options[] = {
243 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
244 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
245 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
247 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
250 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
253 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
256 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
258 #ifdef IPTOS_LOWDELAY
259 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
261 #ifdef IPTOS_THROUGHPUT
262 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
265 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
268 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
271 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
274 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
277 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
280 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
283 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
286 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
289 {"TCP_QUICKACK", IPPROTO_TCP, TCP_QUICKACK, 0, OPT_BOOL},
293 /****************************************************************************
294 Print socket options.
295 ****************************************************************************/
297 static void print_socket_options(int s)
301 const smb_socket_option *p = &socket_options[0];
303 /* wrapped in if statement to prevent streams
304 * leak in SCO Openserver 5.0 */
305 /* reported on samba-technical --jerry */
306 if ( DEBUGLEVEL >= 5 ) {
307 DEBUG(5,("Socket options:\n"));
308 for (; p->name != NULL; p++) {
309 if (getsockopt(s, p->level, p->option,
310 (void *)&value, &vlen) == -1) {
311 DEBUGADD(5,("\tCould not test socket option %s.\n",
314 DEBUGADD(5,("\t%s = %d\n",
321 /****************************************************************************
322 Set user socket options.
323 ****************************************************************************/
325 void set_socket_options(int fd, const char *options)
327 TALLOC_CTX *ctx = talloc_stackframe();
330 while (next_token_talloc(ctx, &options, &tok," \t,")) {
334 bool got_value = false;
336 if ((p = strchr_m(tok,'='))) {
342 for (i=0;socket_options[i].name;i++)
343 if (strequal(socket_options[i].name,tok))
346 if (!socket_options[i].name) {
347 DEBUG(0,("Unknown socket option %s\n",tok));
351 switch (socket_options[i].opttype) {
354 ret = setsockopt(fd,socket_options[i].level,
355 socket_options[i].option,
356 (char *)&value,sizeof(int));
361 DEBUG(0,("syntax error - %s "
362 "does not take a value\n",tok));
365 int on = socket_options[i].value;
366 ret = setsockopt(fd,socket_options[i].level,
367 socket_options[i].option,
368 (char *)&on,sizeof(int));
374 /* be aware that some systems like Solaris return
375 * EINVAL to a setsockopt() call when the client
376 * sent a RST previously - no need to worry */
377 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
378 tok, strerror(errno) ));
383 print_socket_options(fd);
386 /****************************************************************************
388 ****************************************************************************/
390 ssize_t read_udp_v4_socket(int fd,
393 struct sockaddr_storage *psa)
396 socklen_t socklen = sizeof(*psa);
397 struct sockaddr_in *si = (struct sockaddr_in *)psa;
399 memset((char *)psa,'\0',socklen);
401 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
402 (struct sockaddr *)psa,&socklen);
404 /* Don't print a low debug error for a non-blocking socket. */
405 if (errno == EAGAIN) {
406 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
408 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
414 if (psa->ss_family != AF_INET) {
415 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
416 "(not IPv4)\n", (int)psa->ss_family));
420 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
421 inet_ntoa(si->sin_addr),
423 (unsigned long)ret));
428 /****************************************************************************
429 Read data from a file descriptor with a timout in msec.
430 mincount = if timeout, minimum to read before returning
431 maxcount = number to be read.
432 time_out = timeout in milliseconds
433 NB. This can be called with a non-socket fd, don't change
434 sys_read() to sys_recv() or other socket call.
435 ****************************************************************************/
437 NTSTATUS read_fd_with_timeout(int fd, char *buf,
438 size_t mincnt, size_t maxcnt,
439 unsigned int time_out,
446 struct timeval timeout;
448 /* just checking .... */
458 while (nread < mincnt) {
459 readret = sys_read(fd, buf + nread, maxcnt - nread);
462 DEBUG(5,("read_fd_with_timeout: "
463 "blocking read. EOF from client.\n"));
464 return NT_STATUS_END_OF_FILE;
468 return map_nt_error_from_unix(errno);
475 /* Most difficult - timeout read */
476 /* If this is ever called on a disk file and
477 mincnt is greater then the filesize then
478 system performance will suffer severely as
479 select always returns true on disk files */
481 /* Set initial timeout */
482 timeout.tv_sec = (time_t)(time_out / 1000);
483 timeout.tv_usec = (long)(1000 * (time_out % 1000));
485 for (nread=0; nread < mincnt; ) {
489 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
493 return map_nt_error_from_unix(errno);
496 /* Did we timeout ? */
498 DEBUG(10,("read_fd_with_timeout: timeout read. "
499 "select timed out.\n"));
500 return NT_STATUS_IO_TIMEOUT;
503 readret = sys_read(fd, buf+nread, maxcnt-nread);
506 /* we got EOF on the file descriptor */
507 DEBUG(5,("read_fd_with_timeout: timeout read. "
508 "EOF from client.\n"));
509 return NT_STATUS_END_OF_FILE;
513 return map_nt_error_from_unix(errno);
520 /* Return the number we got */
527 /****************************************************************************
528 Read data from an fd, reading exactly N bytes.
529 NB. This can be called with a non-socket fd, don't add dependencies
531 ****************************************************************************/
533 NTSTATUS read_data(int fd, char *buffer, size_t N)
535 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
538 /****************************************************************************
539 Write all data from an iov array
540 NB. This can be called with a non-socket fd, don't add dependencies
542 ****************************************************************************/
544 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
550 struct iovec *iov_copy, *iov;
553 for (i=0; i<iovcnt; i++) {
554 to_send += orig_iov[i].iov_len;
557 thistime = sys_writev(fd, orig_iov, iovcnt);
558 if ((thistime <= 0) || (thistime == to_send)) {
564 * We could not send everything in one call. Make a copy of iov that
565 * we can mess with. We keep a copy of the array start in iov_copy for
566 * the TALLOC_FREE, because we're going to modify iov later on,
567 * discarding elements.
570 iov_copy = (struct iovec *)TALLOC_MEMDUP(
571 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
573 if (iov_copy == NULL) {
579 while (sent < to_send) {
581 * We have to discard "thistime" bytes from the beginning
582 * iov array, "thistime" contains the number of bytes sent
585 while (thistime > 0) {
586 if (thistime < iov[0].iov_len) {
588 (char *)iov[0].iov_base + thistime;
589 iov[0].iov_base = (void *)new_base;
590 iov[0].iov_len -= thistime;
593 thistime -= iov[0].iov_len;
598 thistime = sys_writev(fd, iov, iovcnt);
605 TALLOC_FREE(iov_copy);
609 /****************************************************************************
611 NB. This can be called with a non-socket fd, don't add dependencies
613 ****************************************************************************/
615 ssize_t write_data(int fd, const char *buffer, size_t N)
619 iov.iov_base = CONST_DISCARD(void *, buffer);
621 return write_data_iov(fd, &iov, 1);
624 /****************************************************************************
625 Send a keepalive packet (rfc1002).
626 ****************************************************************************/
628 bool send_keepalive(int client)
630 unsigned char buf[4];
632 buf[0] = SMBkeepalive;
633 buf[1] = buf[2] = buf[3] = 0;
635 return(write_data(client,(char *)buf,4) == 4);
638 /****************************************************************************
639 Read 4 bytes of a smb packet and return the smb length of the packet.
640 Store the result in the buffer.
641 This version of the function will return a length of zero on receiving
643 Timeout is in milliseconds.
644 ****************************************************************************/
646 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
647 unsigned int timeout,
653 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
655 if (!NT_STATUS_IS_OK(status)) {
659 *len = smb_len(inbuf);
660 msg_type = CVAL(inbuf,0);
662 if (msg_type == SMBkeepalive) {
663 DEBUG(5,("Got keepalive packet\n"));
666 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
671 /****************************************************************************
672 Read an smb from a fd.
673 The timeout is in milliseconds.
674 This function will return on receipt of a session keepalive packet.
675 maxlen is the max number of bytes to return, not including the 4 byte
676 length. If zero it means buflen limit.
677 Doesn't check the MAC on signed packets.
678 ****************************************************************************/
680 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
681 size_t maxlen, size_t *p_len)
686 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
688 if (!NT_STATUS_IS_OK(status)) {
689 DEBUG(0, ("read_fd_with_timeout failed, read "
690 "error = %s.\n", nt_errstr(status)));
695 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
696 (unsigned long)len));
697 return NT_STATUS_INVALID_PARAMETER;
702 len = MIN(len,maxlen);
705 status = read_fd_with_timeout(
706 fd, buffer+4, len, len, timeout, &len);
708 if (!NT_STATUS_IS_OK(status)) {
709 DEBUG(0, ("read_fd_with_timeout failed, read error = "
710 "%s.\n", nt_errstr(status)));
714 /* not all of samba3 properly checks for packet-termination
715 * of strings. This ensures that we don't run off into
717 SSVAL(buffer+4,len, 0);
724 /****************************************************************************
725 Open a socket of the specified type, port, and address for incoming data.
726 ****************************************************************************/
728 int open_socket_in(int type,
731 const struct sockaddr_storage *psock,
734 struct sockaddr_storage sock;
736 socklen_t slen = sizeof(struct sockaddr_in);
740 #if defined(HAVE_IPV6)
741 if (sock.ss_family == AF_INET6) {
742 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
743 slen = sizeof(struct sockaddr_in6);
746 if (sock.ss_family == AF_INET) {
747 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
750 res = socket(sock.ss_family, type, 0 );
753 dbgtext( "open_socket_in(): socket() call failed: " );
754 dbgtext( "%s\n", strerror( errno ) );
759 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
761 int val = rebind ? 1 : 0;
762 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
763 (char *)&val,sizeof(val)) == -1 ) {
764 if( DEBUGLVL( dlevel ) ) {
765 dbgtext( "open_socket_in(): setsockopt: " );
766 dbgtext( "SO_REUSEADDR = %s ",
767 val?"true":"false" );
768 dbgtext( "on port %d failed ", port );
769 dbgtext( "with error = %s\n", strerror(errno) );
773 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
774 (char *)&val,sizeof(val)) == -1 ) {
775 if( DEBUGLVL( dlevel ) ) {
776 dbgtext( "open_socket_in(): setsockopt: ");
777 dbgtext( "SO_REUSEPORT = %s ",
779 dbgtext( "on port %d failed ", port);
780 dbgtext( "with error = %s\n", strerror(errno));
783 #endif /* SO_REUSEPORT */
786 /* now we've got a socket - we need to bind it */
787 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
788 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
789 port == SMB_PORT2 || port == NMB_PORT) ) {
790 char addr[INET6_ADDRSTRLEN];
791 print_sockaddr(addr, sizeof(addr),
793 dbgtext( "bind failed on port %d ", port);
794 dbgtext( "socket_addr = %s.\n", addr);
795 dbgtext( "Error = %s\n", strerror(errno));
801 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
805 struct open_socket_out_state {
807 struct event_context *ev;
808 struct sockaddr_storage ss;
814 static void open_socket_out_connected(struct tevent_req *subreq);
816 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
824 /****************************************************************************
825 Create an outgoing socket. timeout is in milliseconds.
826 **************************************************************************/
828 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
829 struct event_context *ev,
830 const struct sockaddr_storage *pss,
834 char addr[INET6_ADDRSTRLEN];
835 struct tevent_req *result, *subreq;
836 struct open_socket_out_state *state;
839 result = tevent_req_create(mem_ctx, &state,
840 struct open_socket_out_state);
841 if (result == NULL) {
847 state->wait_nsec = 10000;
850 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
851 if (state->fd == -1) {
852 status = map_nt_error_from_unix(errno);
855 talloc_set_destructor(state, open_socket_out_state_destructor);
857 if (!tevent_req_set_endtime(
858 result, ev, timeval_current_ofs(0, timeout*1000))) {
862 #if defined(HAVE_IPV6)
863 if (pss->ss_family == AF_INET6) {
864 struct sockaddr_in6 *psa6;
865 psa6 = (struct sockaddr_in6 *)&state->ss;
866 psa6->sin6_port = htons(port);
867 if (psa6->sin6_scope_id == 0
868 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
869 setup_linklocal_scope_id(
870 (struct sockaddr *)&(state->ss));
872 state->salen = sizeof(struct sockaddr_in6);
875 if (pss->ss_family == AF_INET) {
876 struct sockaddr_in *psa;
877 psa = (struct sockaddr_in *)&state->ss;
878 psa->sin_port = htons(port);
879 state->salen = sizeof(struct sockaddr_in);
882 if (pss->ss_family == AF_UNIX) {
883 state->salen = sizeof(struct sockaddr_un);
886 print_sockaddr(addr, sizeof(addr), &state->ss);
887 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
889 subreq = async_connect_send(state, state->ev, state->fd,
890 (struct sockaddr *)&state->ss,
893 || !tevent_req_set_endtime(
895 timeval_current_ofs(0, state->wait_nsec))) {
898 tevent_req_set_callback(subreq, open_socket_out_connected, result);
902 tevent_req_nterror(result, status);
903 return tevent_req_post(result, ev);
909 static void open_socket_out_connected(struct tevent_req *subreq)
911 struct tevent_req *req =
912 tevent_req_callback_data(subreq, struct tevent_req);
913 struct open_socket_out_state *state =
914 tevent_req_data(req, struct open_socket_out_state);
918 ret = async_connect_recv(subreq, &sys_errno);
921 tevent_req_done(req);
927 (sys_errno == ETIMEDOUT) ||
929 (sys_errno == EINPROGRESS) ||
930 (sys_errno == EALREADY) ||
931 (sys_errno == EAGAIN)) {
937 if (state->wait_nsec < 250000) {
938 state->wait_nsec *= 1.5;
941 subreq = async_connect_send(state, state->ev, state->fd,
942 (struct sockaddr *)&state->ss,
944 if (tevent_req_nomem(subreq, req)) {
947 if (!tevent_req_set_endtime(
949 timeval_current_ofs(0, state->wait_nsec))) {
950 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
953 tevent_req_set_callback(subreq, open_socket_out_connected, req);
958 if (sys_errno == EISCONN) {
959 tevent_req_done(req);
965 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
968 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
970 struct open_socket_out_state *state =
971 tevent_req_data(req, struct open_socket_out_state);
974 if (tevent_req_is_nterror(req, &status)) {
982 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
983 int timeout, int *pfd)
985 TALLOC_CTX *frame = talloc_stackframe();
986 struct event_context *ev;
987 struct tevent_req *req;
988 NTSTATUS status = NT_STATUS_NO_MEMORY;
990 ev = event_context_init(frame);
995 req = open_socket_out_send(frame, ev, pss, port, timeout);
999 if (!tevent_req_poll(req, ev)) {
1000 status = NT_STATUS_INTERNAL_ERROR;
1003 status = open_socket_out_recv(req, pfd);
1009 struct open_socket_out_defer_state {
1010 struct event_context *ev;
1011 struct sockaddr_storage ss;
1017 static void open_socket_out_defer_waited(struct tevent_req *subreq);
1018 static void open_socket_out_defer_connected(struct tevent_req *subreq);
1020 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
1021 struct event_context *ev,
1022 struct timeval wait_time,
1023 const struct sockaddr_storage *pss,
1027 struct tevent_req *req, *subreq;
1028 struct open_socket_out_defer_state *state;
1030 req = tevent_req_create(mem_ctx, &state,
1031 struct open_socket_out_defer_state);
1038 state->timeout = timeout;
1040 subreq = tevent_wakeup_send(
1042 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
1043 if (subreq == NULL) {
1046 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
1053 static void open_socket_out_defer_waited(struct tevent_req *subreq)
1055 struct tevent_req *req = tevent_req_callback_data(
1056 subreq, struct tevent_req);
1057 struct open_socket_out_defer_state *state = tevent_req_data(
1058 req, struct open_socket_out_defer_state);
1061 ret = tevent_wakeup_recv(subreq);
1062 TALLOC_FREE(subreq);
1064 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1068 subreq = open_socket_out_send(state, state->ev, &state->ss,
1069 state->port, state->timeout);
1070 if (tevent_req_nomem(subreq, req)) {
1073 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
1076 static void open_socket_out_defer_connected(struct tevent_req *subreq)
1078 struct tevent_req *req = tevent_req_callback_data(
1079 subreq, struct tevent_req);
1080 struct open_socket_out_defer_state *state = tevent_req_data(
1081 req, struct open_socket_out_defer_state);
1084 status = open_socket_out_recv(subreq, &state->fd);
1085 TALLOC_FREE(subreq);
1086 if (!NT_STATUS_IS_OK(status)) {
1087 tevent_req_nterror(req, status);
1090 tevent_req_done(req);
1093 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
1095 struct open_socket_out_defer_state *state = tevent_req_data(
1096 req, struct open_socket_out_defer_state);
1099 if (tevent_req_is_nterror(req, &status)) {
1104 return NT_STATUS_OK;
1107 /*******************************************************************
1108 Create an outgoing TCP socket to the first addr that connects.
1110 This is for simultaneous connection attempts to port 445 and 139 of a host
1111 or for simultatneous connection attempts to multiple DCs at once. We return
1112 a socket fd of the first successful connection.
1114 @param[in] addrs list of Internet addresses and ports to connect to
1115 @param[in] num_addrs number of address/port pairs in the addrs list
1116 @param[in] timeout time after which we stop waiting for a socket connection
1117 to succeed, given in milliseconds
1118 @param[out] fd_index the entry in addrs which we successfully connected to
1119 @param[out] fd fd of the open and connected socket
1120 @return true on a successful connection, false if all connection attempts
1121 failed or we timed out
1122 *******************************************************************/
1124 bool open_any_socket_out(struct sockaddr_storage *addrs, int num_addrs,
1125 int timeout, int *fd_index, int *fd)
1127 int i, resulting_index, res;
1131 fd_set r_fds, wr_fds;
1135 int connect_loop = 10000; /* 10 milliseconds */
1137 timeout *= 1000; /* convert to microseconds */
1139 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1141 if (sockets == NULL)
1144 resulting_index = -1;
1146 for (i=0; i<num_addrs; i++)
1149 for (i=0; i<num_addrs; i++) {
1150 sockets[i] = socket(addrs[i].ss_family, SOCK_STREAM, 0);
1153 set_blocking(sockets[i], false);
1157 good_connect = false;
1159 for (i=0; i<num_addrs; i++) {
1160 const struct sockaddr * a =
1161 (const struct sockaddr *)&(addrs[i]);
1163 if (sockets[i] == -1)
1166 if (sys_connect(sockets[i], a) == 0) {
1167 /* Rather unlikely as we are non-blocking, but it
1168 * might actually happen. */
1169 resulting_index = i;
1173 if (errno == EINPROGRESS || errno == EALREADY ||
1177 errno == EAGAIN || errno == EINTR) {
1178 /* These are the error messages that something is
1180 good_connect = true;
1181 } else if (errno != 0) {
1182 /* There was a direct error */
1188 if (!good_connect) {
1189 /* All of the connect's resulted in real error conditions */
1193 /* Lets see if any of the connect attempts succeeded */
1199 for (i=0; i<num_addrs; i++) {
1200 if (sockets[i] == -1)
1202 FD_SET(sockets[i], &wr_fds);
1203 FD_SET(sockets[i], &r_fds);
1204 if (sockets[i]>maxfd)
1209 tv.tv_usec = connect_loop;
1211 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1219 for (i=0; i<num_addrs; i++) {
1221 if (sockets[i] == -1)
1224 /* Stevens, Network Programming says that if there's a
1225 * successful connect, the socket is only writable. Upon an
1226 * error, it's both readable and writable. */
1228 if (FD_ISSET(sockets[i], &r_fds) &&
1229 FD_ISSET(sockets[i], &wr_fds)) {
1230 /* readable and writable, so it's an error */
1236 if (!FD_ISSET(sockets[i], &r_fds) &&
1237 FD_ISSET(sockets[i], &wr_fds)) {
1238 /* Only writable, so it's connected */
1239 resulting_index = i;
1246 timeout -= connect_loop;
1249 connect_loop *= 1.5;
1250 if (connect_loop > timeout)
1251 connect_loop = timeout;
1255 for (i=0; i<num_addrs; i++) {
1256 if (i == resulting_index)
1258 if (sockets[i] >= 0)
1262 if (resulting_index >= 0) {
1263 *fd_index = resulting_index;
1264 *fd = sockets[*fd_index];
1265 set_blocking(*fd, true);
1270 return (resulting_index >= 0);
1272 /****************************************************************************
1273 Open a connected UDP socket to host on port
1274 **************************************************************************/
1276 int open_udp_socket(const char *host, int port)
1278 struct sockaddr_storage ss;
1281 if (!interpret_string_addr(&ss, host, 0)) {
1282 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1287 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1292 #if defined(HAVE_IPV6)
1293 if (ss.ss_family == AF_INET6) {
1294 struct sockaddr_in6 *psa6;
1295 psa6 = (struct sockaddr_in6 *)&ss;
1296 psa6->sin6_port = htons(port);
1297 if (psa6->sin6_scope_id == 0
1298 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1299 setup_linklocal_scope_id(
1300 (struct sockaddr *)&ss);
1304 if (ss.ss_family == AF_INET) {
1305 struct sockaddr_in *psa;
1306 psa = (struct sockaddr_in *)&ss;
1307 psa->sin_port = htons(port);
1310 if (sys_connect(res,(struct sockaddr *)&ss)) {
1318 /*******************************************************************
1319 Return the IP addr of the remote end of a socket as a string.
1320 Optionally return the struct sockaddr_storage.
1321 ******************************************************************/
1323 static const char *get_peer_addr_internal(int fd,
1325 size_t addr_buf_len,
1326 struct sockaddr *pss,
1329 struct sockaddr_storage ss;
1330 socklen_t length = sizeof(ss);
1332 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1339 pss = (struct sockaddr *)&ss;
1343 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1344 int level = (errno == ENOTCONN) ? 2 : 0;
1345 DEBUG(level, ("getpeername failed. Error was %s\n",
1350 print_sockaddr_len(addr_buf,
1357 /*******************************************************************
1358 Matchname - determine if host name matches IP address. Used to
1359 confirm a hostname lookup to prevent spoof attacks.
1360 ******************************************************************/
1362 static bool matchname(const char *remotehost,
1363 const struct sockaddr *pss,
1366 struct addrinfo *res = NULL;
1367 struct addrinfo *ailist = NULL;
1368 char addr_buf[INET6_ADDRSTRLEN];
1369 bool ret = interpret_string_addr_internal(&ailist,
1371 AI_ADDRCONFIG|AI_CANONNAME);
1373 if (!ret || ailist == NULL) {
1374 DEBUG(3,("matchname: getaddrinfo failed for "
1377 gai_strerror(ret) ));
1382 * Make sure that getaddrinfo() returns the "correct" host name.
1385 if (ailist->ai_canonname == NULL ||
1386 (!strequal(remotehost, ailist->ai_canonname) &&
1387 !strequal(remotehost, "localhost"))) {
1388 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1390 ailist->ai_canonname ?
1391 ailist->ai_canonname : "(NULL)"));
1392 freeaddrinfo(ailist);
1396 /* Look up the host address in the address list we just got. */
1397 for (res = ailist; res; res = res->ai_next) {
1398 if (!res->ai_addr) {
1401 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1402 (struct sockaddr *)pss)) {
1403 freeaddrinfo(ailist);
1409 * The host name does not map to the original host address. Perhaps
1410 * someone has compromised a name server. More likely someone botched
1411 * it, but that could be dangerous, too.
1414 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1415 print_sockaddr_len(addr_buf,
1419 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1422 freeaddrinfo(ailist);
1427 /*******************************************************************
1428 Deal with the singleton cache.
1429 ******************************************************************/
1431 struct name_addr_pair {
1432 struct sockaddr_storage ss;
1436 /*******************************************************************
1437 Lookup a name/addr pair. Returns memory allocated from memcache.
1438 ******************************************************************/
1440 static bool lookup_nc(struct name_addr_pair *nc)
1446 if (!memcache_lookup(
1447 NULL, SINGLETON_CACHE,
1448 data_blob_string_const_null("get_peer_name"),
1453 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1454 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1458 /*******************************************************************
1459 Save a name/addr pair.
1460 ******************************************************************/
1462 static void store_nc(const struct name_addr_pair *nc)
1465 size_t namelen = strlen(nc->name);
1467 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1471 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1472 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1474 memcache_add(NULL, SINGLETON_CACHE,
1475 data_blob_string_const_null("get_peer_name"),
1477 data_blob_free(&tmp);
1480 /*******************************************************************
1481 Return the DNS name of the remote end of a socket.
1482 ******************************************************************/
1484 const char *get_peer_name(int fd, bool force_lookup)
1486 struct name_addr_pair nc;
1487 char addr_buf[INET6_ADDRSTRLEN];
1488 struct sockaddr_storage ss;
1489 socklen_t length = sizeof(ss);
1492 char name_buf[MAX_DNS_NAME_LENGTH];
1493 char tmp_name[MAX_DNS_NAME_LENGTH];
1495 /* reverse lookups can be *very* expensive, and in many
1496 situations won't work because many networks don't link dhcp
1497 with dns. To avoid the delay we avoid the lookup if
1499 if (!lp_hostname_lookups() && (force_lookup == false)) {
1500 length = sizeof(nc.ss);
1501 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1502 (struct sockaddr *)&nc.ss, &length);
1505 return nc.name ? nc.name : "UNKNOWN";
1510 memset(&ss, '\0', sizeof(ss));
1511 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1513 /* it might be the same as the last one - save some DNS work */
1514 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1515 return nc.name ? nc.name : "UNKNOWN";
1518 /* Not the same. We need to lookup. */
1523 /* Look up the remote host name. */
1524 ret = sys_getnameinfo((struct sockaddr *)&ss,
1533 DEBUG(1,("get_peer_name: getnameinfo failed "
1534 "for %s with error %s\n",
1536 gai_strerror(ret)));
1537 strlcpy(name_buf, p, sizeof(name_buf));
1539 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1540 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1541 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1545 /* can't pass the same source and dest strings in when you
1546 use --enable-developer or the clobber_region() call will
1549 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1550 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1551 if (strstr(name_buf,"..")) {
1552 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1560 return nc.name ? nc.name : "UNKNOWN";
1563 /*******************************************************************
1564 Return the IP addr of the remote end of a socket as a string.
1565 ******************************************************************/
1567 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1569 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1572 /*******************************************************************
1573 Create protected unix domain socket.
1575 Some unixes cannot set permissions on a ux-dom-sock, so we
1576 have to make sure that the directory contains the protection
1577 permissions instead.
1578 ******************************************************************/
1580 int create_pipe_sock(const char *socket_dir,
1581 const char *socket_name,
1584 #ifdef HAVE_UNIXSOCKET
1585 struct sockaddr_un sunaddr;
1591 old_umask = umask(0);
1593 /* Create the socket directory or reuse the existing one */
1595 if (lstat(socket_dir, &st) == -1) {
1596 if (errno == ENOENT) {
1597 /* Create directory */
1598 if (mkdir(socket_dir, dir_perms) == -1) {
1599 DEBUG(0, ("error creating socket directory "
1600 "%s: %s\n", socket_dir,
1605 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1606 socket_dir, strerror(errno)));
1610 /* Check ownership and permission on existing directory */
1611 if (!S_ISDIR(st.st_mode)) {
1612 DEBUG(0, ("socket directory %s isn't a directory\n",
1616 if ((st.st_uid != sec_initial_uid()) ||
1617 ((st.st_mode & 0777) != dir_perms)) {
1618 DEBUG(0, ("invalid permissions on socket directory "
1619 "%s\n", socket_dir));
1624 /* Create the socket file */
1626 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1629 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1634 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1639 memset(&sunaddr, 0, sizeof(sunaddr));
1640 sunaddr.sun_family = AF_UNIX;
1641 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1643 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1644 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1649 if (listen(sock, 5) == -1) {
1650 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1670 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1672 #endif /* HAVE_UNIXSOCKET */
1675 /****************************************************************************
1676 Get my own canonical name, including domain.
1677 ****************************************************************************/
1679 const char *get_mydnsfullname(void)
1681 struct addrinfo *res = NULL;
1682 char my_hostname[HOST_NAME_MAX];
1686 if (memcache_lookup(NULL, SINGLETON_CACHE,
1687 data_blob_string_const_null("get_mydnsfullname"),
1689 SMB_ASSERT(tmp.length > 0);
1690 return (const char *)tmp.data;
1693 /* get my host name */
1694 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1695 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1699 /* Ensure null termination. */
1700 my_hostname[sizeof(my_hostname)-1] = '\0';
1702 ret = interpret_string_addr_internal(&res,
1704 AI_ADDRCONFIG|AI_CANONNAME);
1706 if (!ret || res == NULL) {
1707 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1710 gai_strerror(ret) ));
1715 * Make sure that getaddrinfo() returns the "correct" host name.
1718 if (res->ai_canonname == NULL) {
1719 DEBUG(3,("get_mydnsfullname: failed to get "
1720 "canonical name for %s\n",
1726 /* This copies the data, so we must do a lookup
1727 * afterwards to find the value to return.
1730 memcache_add(NULL, SINGLETON_CACHE,
1731 data_blob_string_const_null("get_mydnsfullname"),
1732 data_blob_string_const_null(res->ai_canonname));
1734 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1735 data_blob_string_const_null("get_mydnsfullname"),
1737 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1738 strlen(res->ai_canonname) + 1);
1743 return (const char *)tmp.data;
1746 /************************************************************
1748 ************************************************************/
1750 bool is_myname_or_ipaddr(const char *s)
1752 TALLOC_CTX *ctx = talloc_tos();
1753 char addr[INET6_ADDRSTRLEN];
1755 const char *dnsname;
1756 char *servername = NULL;
1762 /* Santize the string from '\\name' */
1763 name = talloc_strdup(ctx, s);
1768 servername = strrchr_m(name, '\\' );
1775 /* Optimize for the common case */
1776 if (strequal(servername, global_myname())) {
1780 /* Check for an alias */
1781 if (is_myname(servername)) {
1785 /* Check for loopback */
1786 if (strequal(servername, "127.0.0.1") ||
1787 strequal(servername, "::1")) {
1791 if (strequal(servername, "localhost")) {
1795 /* Maybe it's my dns name */
1796 dnsname = get_mydnsfullname();
1797 if (dnsname && strequal(servername, dnsname)) {
1801 /* Handle possible CNAME records - convert to an IP addr. */
1802 if (!is_ipaddress(servername)) {
1803 /* Use DNS to resolve the name, but only the first address */
1804 struct sockaddr_storage ss;
1805 if (interpret_string_addr(&ss, servername, 0)) {
1806 print_sockaddr(addr,
1813 /* Maybe its an IP address? */
1814 if (is_ipaddress(servername)) {
1815 struct sockaddr_storage ss;
1816 struct iface_struct *nics;
1819 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
1823 if (ismyaddr((struct sockaddr *)&ss)) {
1827 if (is_zero_addr((struct sockaddr *)&ss) ||
1828 is_loopback_addr((struct sockaddr *)&ss)) {
1832 n = get_interfaces(talloc_tos(), &nics);
1833 for (i=0; i<n; i++) {
1834 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1846 struct getaddrinfo_state {
1848 const char *service;
1849 const struct addrinfo *hints;
1850 struct addrinfo *res;
1854 static void getaddrinfo_do(void *private_data);
1855 static void getaddrinfo_done(struct tevent_req *subreq);
1857 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1858 struct tevent_context *ev,
1859 struct fncall_context *ctx,
1861 const char *service,
1862 const struct addrinfo *hints)
1864 struct tevent_req *req, *subreq;
1865 struct getaddrinfo_state *state;
1867 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1873 state->service = service;
1874 state->hints = hints;
1876 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1877 if (tevent_req_nomem(subreq, req)) {
1878 return tevent_req_post(req, ev);
1880 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1884 static void getaddrinfo_do(void *private_data)
1886 struct getaddrinfo_state *state =
1887 (struct getaddrinfo_state *)private_data;
1889 state->ret = getaddrinfo(state->node, state->service, state->hints,
1893 static void getaddrinfo_done(struct tevent_req *subreq)
1895 struct tevent_req *req = tevent_req_callback_data(
1896 subreq, struct tevent_req);
1899 ret = fncall_recv(subreq, &err);
1900 TALLOC_FREE(subreq);
1902 tevent_req_error(req, err);
1905 tevent_req_done(req);
1908 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1910 struct getaddrinfo_state *state = tevent_req_data(
1911 req, struct getaddrinfo_state);
1914 if (tevent_req_is_unix_error(req, &err)) {
1922 if (state->ret == 0) {