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"
25 #include "../lib/util/select.h"
27 /****************************************************************************
28 Get a port number in host byte order from a sockaddr_storage.
29 ****************************************************************************/
31 uint16_t get_sockaddr_port(const struct sockaddr_storage *pss)
35 if (pss->ss_family != AF_INET) {
36 #if defined(HAVE_IPV6)
38 const struct sockaddr_in6 *sa6 =
39 (const struct sockaddr_in6 *)pss;
40 port = ntohs(sa6->sin6_port);
43 const struct sockaddr_in *sa =
44 (const struct sockaddr_in *)pss;
45 port = ntohs(sa->sin_port);
50 /****************************************************************************
51 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
52 ****************************************************************************/
54 static char *print_sockaddr_len(char *dest,
56 const struct sockaddr *psa,
62 (void)sys_getnameinfo(psa,
70 /****************************************************************************
71 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
72 ****************************************************************************/
74 char *print_sockaddr(char *dest,
76 const struct sockaddr_storage *psa)
78 return print_sockaddr_len(dest, destlen, (struct sockaddr *)psa,
79 sizeof(struct sockaddr_storage));
82 /****************************************************************************
83 Print out a canonical IPv4 or IPv6 address from a struct sockaddr_storage.
84 ****************************************************************************/
86 char *print_canonical_sockaddr(TALLOC_CTX *ctx,
87 const struct sockaddr_storage *pss)
89 char addr[INET6_ADDRSTRLEN];
93 /* Linux getnameinfo() man pages says port is unitialized if
94 service name is NULL. */
96 ret = sys_getnameinfo((const struct sockaddr *)pss,
97 sizeof(struct sockaddr_storage),
105 if (pss->ss_family != AF_INET) {
106 #if defined(HAVE_IPV6)
107 dest = talloc_asprintf(ctx, "[%s]", addr);
112 dest = talloc_asprintf(ctx, "%s", addr);
118 /****************************************************************************
119 Return the string of an IP address (IPv4 or IPv6).
120 ****************************************************************************/
122 static const char *get_socket_addr(int fd, char *addr_buf, size_t addr_len)
124 struct sockaddr_storage sa;
125 socklen_t length = sizeof(sa);
127 /* Ok, returning a hard coded IPv4 address
128 * is bogus, but it's just as bogus as a
129 * zero IPv6 address. No good choice here.
132 strlcpy(addr_buf, "0.0.0.0", addr_len);
138 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
139 DEBUG(0,("getsockname failed. Error was %s\n",
144 return print_sockaddr_len(addr_buf, addr_len, (struct sockaddr *)&sa, length);
147 /****************************************************************************
148 Return the port number we've bound to on a socket.
149 ****************************************************************************/
151 int get_socket_port(int fd)
153 struct sockaddr_storage sa;
154 socklen_t length = sizeof(sa);
160 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
161 int level = (errno == ENOTCONN) ? 2 : 0;
162 DEBUG(level, ("getpeername failed. Error was %s\n",
167 #if defined(HAVE_IPV6)
168 if (sa.ss_family == AF_INET6) {
169 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
172 if (sa.ss_family == AF_INET) {
173 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
178 const char *client_name(int fd)
180 return get_peer_name(fd,false);
183 const char *client_addr(int fd, char *addr, size_t addrlen)
185 return get_peer_addr(fd,addr,addrlen);
188 const char *client_socket_addr(int fd, char *addr, size_t addr_len)
190 return get_socket_addr(fd, addr, addr_len);
194 /* Not currently used. JRA. */
195 int client_socket_port(int fd)
197 return get_socket_port(fd);
201 /****************************************************************************
202 Accessor functions to make thread-safe code easier later...
203 ****************************************************************************/
205 void set_smb_read_error(enum smb_read_errors *pre,
206 enum smb_read_errors newerr)
213 void cond_set_smb_read_error(enum smb_read_errors *pre,
214 enum smb_read_errors newerr)
216 if (pre && *pre == SMB_READ_OK) {
221 /****************************************************************************
222 Determine if a file descriptor is in fact a socket.
223 ****************************************************************************/
225 bool is_a_socket(int fd)
230 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
233 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
235 typedef struct smb_socket_option {
243 static const smb_socket_option socket_options[] = {
244 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
245 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
246 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
248 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
251 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
254 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
257 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
259 #ifdef IPTOS_LOWDELAY
260 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
262 #ifdef IPTOS_THROUGHPUT
263 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
266 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
269 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
272 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
275 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
278 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
281 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
284 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
287 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
290 {"TCP_QUICKACK", IPPROTO_TCP, TCP_QUICKACK, 0, OPT_BOOL},
294 /****************************************************************************
295 Print socket options.
296 ****************************************************************************/
298 static void print_socket_options(int s)
302 const smb_socket_option *p = &socket_options[0];
304 /* wrapped in if statement to prevent streams
305 * leak in SCO Openserver 5.0 */
306 /* reported on samba-technical --jerry */
307 if ( DEBUGLEVEL >= 5 ) {
308 DEBUG(5,("Socket options:\n"));
309 for (; p->name != NULL; p++) {
310 if (getsockopt(s, p->level, p->option,
311 (void *)&value, &vlen) == -1) {
312 DEBUGADD(5,("\tCould not test socket option %s.\n",
315 DEBUGADD(5,("\t%s = %d\n",
322 /****************************************************************************
323 Set user socket options.
324 ****************************************************************************/
326 void set_socket_options(int fd, const char *options)
328 TALLOC_CTX *ctx = talloc_stackframe();
331 while (next_token_talloc(ctx, &options, &tok," \t,")) {
335 bool got_value = false;
337 if ((p = strchr_m(tok,'='))) {
343 for (i=0;socket_options[i].name;i++)
344 if (strequal(socket_options[i].name,tok))
347 if (!socket_options[i].name) {
348 DEBUG(0,("Unknown socket option %s\n",tok));
352 switch (socket_options[i].opttype) {
355 ret = setsockopt(fd,socket_options[i].level,
356 socket_options[i].option,
357 (char *)&value,sizeof(int));
362 DEBUG(0,("syntax error - %s "
363 "does not take a value\n",tok));
366 int on = socket_options[i].value;
367 ret = setsockopt(fd,socket_options[i].level,
368 socket_options[i].option,
369 (char *)&on,sizeof(int));
375 /* be aware that some systems like Solaris return
376 * EINVAL to a setsockopt() call when the client
377 * sent a RST previously - no need to worry */
378 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
379 tok, strerror(errno) ));
384 print_socket_options(fd);
387 /****************************************************************************
389 ****************************************************************************/
391 ssize_t read_udp_v4_socket(int fd,
394 struct sockaddr_storage *psa)
397 socklen_t socklen = sizeof(*psa);
398 struct sockaddr_in *si = (struct sockaddr_in *)psa;
400 memset((char *)psa,'\0',socklen);
402 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
403 (struct sockaddr *)psa,&socklen);
405 /* Don't print a low debug error for a non-blocking socket. */
406 if (errno == EAGAIN) {
407 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
409 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
415 if (psa->ss_family != AF_INET) {
416 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
417 "(not IPv4)\n", (int)psa->ss_family));
421 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
422 inet_ntoa(si->sin_addr),
424 (unsigned long)ret));
429 /****************************************************************************
430 Read data from a file descriptor with a timout in msec.
431 mincount = if timeout, minimum to read before returning
432 maxcount = number to be read.
433 time_out = timeout in milliseconds
434 NB. This can be called with a non-socket fd, don't change
435 sys_read() to sys_recv() or other socket call.
436 ****************************************************************************/
438 NTSTATUS read_fd_with_timeout(int fd, char *buf,
439 size_t mincnt, size_t maxcnt,
440 unsigned int time_out,
447 struct timeval timeout;
449 /* just checking .... */
459 while (nread < mincnt) {
460 readret = sys_read(fd, buf + nread, maxcnt - nread);
463 DEBUG(5,("read_fd_with_timeout: "
464 "blocking read. EOF from client.\n"));
465 return NT_STATUS_END_OF_FILE;
469 return map_nt_error_from_unix(errno);
476 /* Most difficult - timeout read */
477 /* If this is ever called on a disk file and
478 mincnt is greater then the filesize then
479 system performance will suffer severely as
480 select always returns true on disk files */
482 /* Set initial timeout */
483 timeout.tv_sec = (time_t)(time_out / 1000);
484 timeout.tv_usec = (long)(1000 * (time_out % 1000));
486 for (nread=0; nread < mincnt; ) {
490 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
494 return map_nt_error_from_unix(errno);
497 /* Did we timeout ? */
499 DEBUG(10,("read_fd_with_timeout: timeout read. "
500 "select timed out.\n"));
501 return NT_STATUS_IO_TIMEOUT;
504 readret = sys_read(fd, buf+nread, maxcnt-nread);
507 /* we got EOF on the file descriptor */
508 DEBUG(5,("read_fd_with_timeout: timeout read. "
509 "EOF from client.\n"));
510 return NT_STATUS_END_OF_FILE;
514 return map_nt_error_from_unix(errno);
521 /* Return the number we got */
528 /****************************************************************************
529 Read data from an fd, reading exactly N bytes.
530 NB. This can be called with a non-socket fd, don't add dependencies
532 ****************************************************************************/
534 NTSTATUS read_data(int fd, char *buffer, size_t N)
536 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
539 /****************************************************************************
540 Write all data from an iov array
541 NB. This can be called with a non-socket fd, don't add dependencies
543 ****************************************************************************/
545 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
551 struct iovec *iov_copy, *iov;
554 for (i=0; i<iovcnt; i++) {
555 to_send += orig_iov[i].iov_len;
558 thistime = sys_writev(fd, orig_iov, iovcnt);
559 if ((thistime <= 0) || (thistime == to_send)) {
565 * We could not send everything in one call. Make a copy of iov that
566 * we can mess with. We keep a copy of the array start in iov_copy for
567 * the TALLOC_FREE, because we're going to modify iov later on,
568 * discarding elements.
571 iov_copy = (struct iovec *)TALLOC_MEMDUP(
572 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
574 if (iov_copy == NULL) {
580 while (sent < to_send) {
582 * We have to discard "thistime" bytes from the beginning
583 * iov array, "thistime" contains the number of bytes sent
586 while (thistime > 0) {
587 if (thistime < iov[0].iov_len) {
589 (char *)iov[0].iov_base + thistime;
590 iov[0].iov_base = (void *)new_base;
591 iov[0].iov_len -= thistime;
594 thistime -= iov[0].iov_len;
599 thistime = sys_writev(fd, iov, iovcnt);
606 TALLOC_FREE(iov_copy);
610 /****************************************************************************
612 NB. This can be called with a non-socket fd, don't add dependencies
614 ****************************************************************************/
616 ssize_t write_data(int fd, const char *buffer, size_t N)
620 iov.iov_base = CONST_DISCARD(void *, buffer);
622 return write_data_iov(fd, &iov, 1);
625 /****************************************************************************
626 Send a keepalive packet (rfc1002).
627 ****************************************************************************/
629 bool send_keepalive(int client)
631 unsigned char buf[4];
633 buf[0] = SMBkeepalive;
634 buf[1] = buf[2] = buf[3] = 0;
636 return(write_data(client,(char *)buf,4) == 4);
639 /****************************************************************************
640 Read 4 bytes of a smb packet and return the smb length of the packet.
641 Store the result in the buffer.
642 This version of the function will return a length of zero on receiving
644 Timeout is in milliseconds.
645 ****************************************************************************/
647 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
648 unsigned int timeout,
654 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
656 if (!NT_STATUS_IS_OK(status)) {
660 *len = smb_len(inbuf);
661 msg_type = CVAL(inbuf,0);
663 if (msg_type == SMBkeepalive) {
664 DEBUG(5,("Got keepalive packet\n"));
667 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
672 /****************************************************************************
673 Read an smb from a fd.
674 The timeout is in milliseconds.
675 This function will return on receipt of a session keepalive packet.
676 maxlen is the max number of bytes to return, not including the 4 byte
677 length. If zero it means buflen limit.
678 Doesn't check the MAC on signed packets.
679 ****************************************************************************/
681 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
682 size_t maxlen, size_t *p_len)
687 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
689 if (!NT_STATUS_IS_OK(status)) {
690 DEBUG(0, ("read_fd_with_timeout failed, read "
691 "error = %s.\n", nt_errstr(status)));
696 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
697 (unsigned long)len));
698 return NT_STATUS_INVALID_PARAMETER;
703 len = MIN(len,maxlen);
706 status = read_fd_with_timeout(
707 fd, buffer+4, len, len, timeout, &len);
709 if (!NT_STATUS_IS_OK(status)) {
710 DEBUG(0, ("read_fd_with_timeout failed, read error = "
711 "%s.\n", nt_errstr(status)));
715 /* not all of samba3 properly checks for packet-termination
716 * of strings. This ensures that we don't run off into
718 SSVAL(buffer+4,len, 0);
725 /****************************************************************************
726 Open a socket of the specified type, port, and address for incoming data.
727 ****************************************************************************/
729 int open_socket_in(int type,
732 const struct sockaddr_storage *psock,
735 struct sockaddr_storage sock;
737 socklen_t slen = sizeof(struct sockaddr_in);
741 #if defined(HAVE_IPV6)
742 if (sock.ss_family == AF_INET6) {
743 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
744 slen = sizeof(struct sockaddr_in6);
747 if (sock.ss_family == AF_INET) {
748 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
751 res = socket(sock.ss_family, type, 0 );
754 dbgtext( "open_socket_in(): socket() call failed: " );
755 dbgtext( "%s\n", strerror( errno ) );
760 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
762 int val = rebind ? 1 : 0;
763 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
764 (char *)&val,sizeof(val)) == -1 ) {
765 if( DEBUGLVL( dlevel ) ) {
766 dbgtext( "open_socket_in(): setsockopt: " );
767 dbgtext( "SO_REUSEADDR = %s ",
768 val?"true":"false" );
769 dbgtext( "on port %d failed ", port );
770 dbgtext( "with error = %s\n", strerror(errno) );
774 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
775 (char *)&val,sizeof(val)) == -1 ) {
776 if( DEBUGLVL( dlevel ) ) {
777 dbgtext( "open_socket_in(): setsockopt: ");
778 dbgtext( "SO_REUSEPORT = %s ",
780 dbgtext( "on port %d failed ", port);
781 dbgtext( "with error = %s\n", strerror(errno));
784 #endif /* SO_REUSEPORT */
787 /* now we've got a socket - we need to bind it */
788 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
789 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
790 port == SMB_PORT2 || port == NMB_PORT) ) {
791 char addr[INET6_ADDRSTRLEN];
792 print_sockaddr(addr, sizeof(addr),
794 dbgtext( "bind failed on port %d ", port);
795 dbgtext( "socket_addr = %s.\n", addr);
796 dbgtext( "Error = %s\n", strerror(errno));
802 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
806 struct open_socket_out_state {
808 struct event_context *ev;
809 struct sockaddr_storage ss;
815 static void open_socket_out_connected(struct tevent_req *subreq);
817 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
825 /****************************************************************************
826 Create an outgoing socket. timeout is in milliseconds.
827 **************************************************************************/
829 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
830 struct event_context *ev,
831 const struct sockaddr_storage *pss,
835 char addr[INET6_ADDRSTRLEN];
836 struct tevent_req *result, *subreq;
837 struct open_socket_out_state *state;
840 result = tevent_req_create(mem_ctx, &state,
841 struct open_socket_out_state);
842 if (result == NULL) {
848 state->wait_nsec = 10000;
851 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
852 if (state->fd == -1) {
853 status = map_nt_error_from_unix(errno);
856 talloc_set_destructor(state, open_socket_out_state_destructor);
858 if (!tevent_req_set_endtime(
859 result, ev, timeval_current_ofs(0, timeout*1000))) {
863 #if defined(HAVE_IPV6)
864 if (pss->ss_family == AF_INET6) {
865 struct sockaddr_in6 *psa6;
866 psa6 = (struct sockaddr_in6 *)&state->ss;
867 psa6->sin6_port = htons(port);
868 if (psa6->sin6_scope_id == 0
869 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
870 setup_linklocal_scope_id(
871 (struct sockaddr *)&(state->ss));
873 state->salen = sizeof(struct sockaddr_in6);
876 if (pss->ss_family == AF_INET) {
877 struct sockaddr_in *psa;
878 psa = (struct sockaddr_in *)&state->ss;
879 psa->sin_port = htons(port);
880 state->salen = sizeof(struct sockaddr_in);
883 if (pss->ss_family == AF_UNIX) {
884 state->salen = sizeof(struct sockaddr_un);
887 print_sockaddr(addr, sizeof(addr), &state->ss);
888 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
890 subreq = async_connect_send(state, state->ev, state->fd,
891 (struct sockaddr *)&state->ss,
894 || !tevent_req_set_endtime(
896 timeval_current_ofs(0, state->wait_nsec))) {
899 tevent_req_set_callback(subreq, open_socket_out_connected, result);
903 tevent_req_nterror(result, status);
904 return tevent_req_post(result, ev);
910 static void open_socket_out_connected(struct tevent_req *subreq)
912 struct tevent_req *req =
913 tevent_req_callback_data(subreq, struct tevent_req);
914 struct open_socket_out_state *state =
915 tevent_req_data(req, struct open_socket_out_state);
919 ret = async_connect_recv(subreq, &sys_errno);
922 tevent_req_done(req);
928 (sys_errno == ETIMEDOUT) ||
930 (sys_errno == EINPROGRESS) ||
931 (sys_errno == EALREADY) ||
932 (sys_errno == EAGAIN)) {
938 if (state->wait_nsec < 250000) {
939 state->wait_nsec *= 1.5;
942 subreq = async_connect_send(state, state->ev, state->fd,
943 (struct sockaddr *)&state->ss,
945 if (tevent_req_nomem(subreq, req)) {
948 if (!tevent_req_set_endtime(
950 timeval_current_ofs(0, state->wait_nsec))) {
951 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
954 tevent_req_set_callback(subreq, open_socket_out_connected, req);
959 if (sys_errno == EISCONN) {
960 tevent_req_done(req);
966 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
969 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
971 struct open_socket_out_state *state =
972 tevent_req_data(req, struct open_socket_out_state);
975 if (tevent_req_is_nterror(req, &status)) {
983 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
984 int timeout, int *pfd)
986 TALLOC_CTX *frame = talloc_stackframe();
987 struct event_context *ev;
988 struct tevent_req *req;
989 NTSTATUS status = NT_STATUS_NO_MEMORY;
991 ev = event_context_init(frame);
996 req = open_socket_out_send(frame, ev, pss, port, timeout);
1000 if (!tevent_req_poll(req, ev)) {
1001 status = NT_STATUS_INTERNAL_ERROR;
1004 status = open_socket_out_recv(req, pfd);
1010 struct open_socket_out_defer_state {
1011 struct event_context *ev;
1012 struct sockaddr_storage ss;
1018 static void open_socket_out_defer_waited(struct tevent_req *subreq);
1019 static void open_socket_out_defer_connected(struct tevent_req *subreq);
1021 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
1022 struct event_context *ev,
1023 struct timeval wait_time,
1024 const struct sockaddr_storage *pss,
1028 struct tevent_req *req, *subreq;
1029 struct open_socket_out_defer_state *state;
1031 req = tevent_req_create(mem_ctx, &state,
1032 struct open_socket_out_defer_state);
1039 state->timeout = timeout;
1041 subreq = tevent_wakeup_send(
1043 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
1044 if (subreq == NULL) {
1047 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
1054 static void open_socket_out_defer_waited(struct tevent_req *subreq)
1056 struct tevent_req *req = tevent_req_callback_data(
1057 subreq, struct tevent_req);
1058 struct open_socket_out_defer_state *state = tevent_req_data(
1059 req, struct open_socket_out_defer_state);
1062 ret = tevent_wakeup_recv(subreq);
1063 TALLOC_FREE(subreq);
1065 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1069 subreq = open_socket_out_send(state, state->ev, &state->ss,
1070 state->port, state->timeout);
1071 if (tevent_req_nomem(subreq, req)) {
1074 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
1077 static void open_socket_out_defer_connected(struct tevent_req *subreq)
1079 struct tevent_req *req = tevent_req_callback_data(
1080 subreq, struct tevent_req);
1081 struct open_socket_out_defer_state *state = tevent_req_data(
1082 req, struct open_socket_out_defer_state);
1085 status = open_socket_out_recv(subreq, &state->fd);
1086 TALLOC_FREE(subreq);
1087 if (!NT_STATUS_IS_OK(status)) {
1088 tevent_req_nterror(req, status);
1091 tevent_req_done(req);
1094 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
1096 struct open_socket_out_defer_state *state = tevent_req_data(
1097 req, struct open_socket_out_defer_state);
1100 if (tevent_req_is_nterror(req, &status)) {
1105 return NT_STATUS_OK;
1108 /*******************************************************************
1109 Create an outgoing TCP socket to the first addr that connects.
1111 This is for simultaneous connection attempts to port 445 and 139 of a host
1112 or for simultatneous connection attempts to multiple DCs at once. We return
1113 a socket fd of the first successful connection.
1115 @param[in] addrs list of Internet addresses and ports to connect to
1116 @param[in] num_addrs number of address/port pairs in the addrs list
1117 @param[in] timeout time after which we stop waiting for a socket connection
1118 to succeed, given in milliseconds
1119 @param[out] fd_index the entry in addrs which we successfully connected to
1120 @param[out] fd fd of the open and connected socket
1121 @return true on a successful connection, false if all connection attempts
1122 failed or we timed out
1123 *******************************************************************/
1125 bool open_any_socket_out(struct sockaddr_storage *addrs, int num_addrs,
1126 int timeout, int *fd_index, int *fd)
1128 int i, resulting_index, res;
1132 fd_set r_fds, wr_fds;
1136 int connect_loop = 10000; /* 10 milliseconds */
1138 timeout *= 1000; /* convert to microseconds */
1140 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1142 if (sockets == NULL)
1145 resulting_index = -1;
1147 for (i=0; i<num_addrs; i++)
1150 for (i=0; i<num_addrs; i++) {
1151 sockets[i] = socket(addrs[i].ss_family, SOCK_STREAM, 0);
1154 set_blocking(sockets[i], false);
1158 good_connect = false;
1160 for (i=0; i<num_addrs; i++) {
1161 const struct sockaddr * a =
1162 (const struct sockaddr *)&(addrs[i]);
1164 if (sockets[i] == -1)
1167 if (sys_connect(sockets[i], a) == 0) {
1168 /* Rather unlikely as we are non-blocking, but it
1169 * might actually happen. */
1170 resulting_index = i;
1174 if (errno == EINPROGRESS || errno == EALREADY ||
1178 errno == EAGAIN || errno == EINTR) {
1179 /* These are the error messages that something is
1181 good_connect = true;
1182 } else if (errno != 0) {
1183 /* There was a direct error */
1189 if (!good_connect) {
1190 /* All of the connect's resulted in real error conditions */
1194 /* Lets see if any of the connect attempts succeeded */
1200 for (i=0; i<num_addrs; i++) {
1201 if (sockets[i] == -1)
1203 FD_SET(sockets[i], &wr_fds);
1204 FD_SET(sockets[i], &r_fds);
1205 if (sockets[i]>maxfd)
1210 tv.tv_usec = connect_loop;
1212 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1220 for (i=0; i<num_addrs; i++) {
1222 if (sockets[i] == -1)
1225 /* Stevens, Network Programming says that if there's a
1226 * successful connect, the socket is only writable. Upon an
1227 * error, it's both readable and writable. */
1229 if (FD_ISSET(sockets[i], &r_fds) &&
1230 FD_ISSET(sockets[i], &wr_fds)) {
1231 /* readable and writable, so it's an error */
1237 if (!FD_ISSET(sockets[i], &r_fds) &&
1238 FD_ISSET(sockets[i], &wr_fds)) {
1239 /* Only writable, so it's connected */
1240 resulting_index = i;
1247 timeout -= connect_loop;
1250 connect_loop *= 1.5;
1251 if (connect_loop > timeout)
1252 connect_loop = timeout;
1256 for (i=0; i<num_addrs; i++) {
1257 if (i == resulting_index)
1259 if (sockets[i] >= 0)
1263 if (resulting_index >= 0) {
1264 *fd_index = resulting_index;
1265 *fd = sockets[*fd_index];
1266 set_blocking(*fd, true);
1271 return (resulting_index >= 0);
1273 /****************************************************************************
1274 Open a connected UDP socket to host on port
1275 **************************************************************************/
1277 int open_udp_socket(const char *host, int port)
1279 struct sockaddr_storage ss;
1282 if (!interpret_string_addr(&ss, host, 0)) {
1283 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1288 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1293 #if defined(HAVE_IPV6)
1294 if (ss.ss_family == AF_INET6) {
1295 struct sockaddr_in6 *psa6;
1296 psa6 = (struct sockaddr_in6 *)&ss;
1297 psa6->sin6_port = htons(port);
1298 if (psa6->sin6_scope_id == 0
1299 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1300 setup_linklocal_scope_id(
1301 (struct sockaddr *)&ss);
1305 if (ss.ss_family == AF_INET) {
1306 struct sockaddr_in *psa;
1307 psa = (struct sockaddr_in *)&ss;
1308 psa->sin_port = htons(port);
1311 if (sys_connect(res,(struct sockaddr *)&ss)) {
1319 /*******************************************************************
1320 Return the IP addr of the remote end of a socket as a string.
1321 Optionally return the struct sockaddr_storage.
1322 ******************************************************************/
1324 static const char *get_peer_addr_internal(int fd,
1326 size_t addr_buf_len,
1327 struct sockaddr *pss,
1330 struct sockaddr_storage ss;
1331 socklen_t length = sizeof(ss);
1333 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1340 pss = (struct sockaddr *)&ss;
1344 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1345 int level = (errno == ENOTCONN) ? 2 : 0;
1346 DEBUG(level, ("getpeername failed. Error was %s\n",
1351 print_sockaddr_len(addr_buf,
1358 /*******************************************************************
1359 Matchname - determine if host name matches IP address. Used to
1360 confirm a hostname lookup to prevent spoof attacks.
1361 ******************************************************************/
1363 static bool matchname(const char *remotehost,
1364 const struct sockaddr *pss,
1367 struct addrinfo *res = NULL;
1368 struct addrinfo *ailist = NULL;
1369 char addr_buf[INET6_ADDRSTRLEN];
1370 bool ret = interpret_string_addr_internal(&ailist,
1372 AI_ADDRCONFIG|AI_CANONNAME);
1374 if (!ret || ailist == NULL) {
1375 DEBUG(3,("matchname: getaddrinfo failed for "
1378 gai_strerror(ret) ));
1383 * Make sure that getaddrinfo() returns the "correct" host name.
1386 if (ailist->ai_canonname == NULL ||
1387 (!strequal(remotehost, ailist->ai_canonname) &&
1388 !strequal(remotehost, "localhost"))) {
1389 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1391 ailist->ai_canonname ?
1392 ailist->ai_canonname : "(NULL)"));
1393 freeaddrinfo(ailist);
1397 /* Look up the host address in the address list we just got. */
1398 for (res = ailist; res; res = res->ai_next) {
1399 if (!res->ai_addr) {
1402 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1403 (struct sockaddr *)pss)) {
1404 freeaddrinfo(ailist);
1410 * The host name does not map to the original host address. Perhaps
1411 * someone has compromised a name server. More likely someone botched
1412 * it, but that could be dangerous, too.
1415 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1416 print_sockaddr_len(addr_buf,
1420 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1423 freeaddrinfo(ailist);
1428 /*******************************************************************
1429 Deal with the singleton cache.
1430 ******************************************************************/
1432 struct name_addr_pair {
1433 struct sockaddr_storage ss;
1437 /*******************************************************************
1438 Lookup a name/addr pair. Returns memory allocated from memcache.
1439 ******************************************************************/
1441 static bool lookup_nc(struct name_addr_pair *nc)
1447 if (!memcache_lookup(
1448 NULL, SINGLETON_CACHE,
1449 data_blob_string_const_null("get_peer_name"),
1454 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1455 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1459 /*******************************************************************
1460 Save a name/addr pair.
1461 ******************************************************************/
1463 static void store_nc(const struct name_addr_pair *nc)
1466 size_t namelen = strlen(nc->name);
1468 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1472 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1473 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1475 memcache_add(NULL, SINGLETON_CACHE,
1476 data_blob_string_const_null("get_peer_name"),
1478 data_blob_free(&tmp);
1481 /*******************************************************************
1482 Return the DNS name of the remote end of a socket.
1483 ******************************************************************/
1485 const char *get_peer_name(int fd, bool force_lookup)
1487 struct name_addr_pair nc;
1488 char addr_buf[INET6_ADDRSTRLEN];
1489 struct sockaddr_storage ss;
1490 socklen_t length = sizeof(ss);
1493 char name_buf[MAX_DNS_NAME_LENGTH];
1494 char tmp_name[MAX_DNS_NAME_LENGTH];
1496 /* reverse lookups can be *very* expensive, and in many
1497 situations won't work because many networks don't link dhcp
1498 with dns. To avoid the delay we avoid the lookup if
1500 if (!lp_hostname_lookups() && (force_lookup == false)) {
1501 length = sizeof(nc.ss);
1502 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1503 (struct sockaddr *)&nc.ss, &length);
1506 return nc.name ? nc.name : "UNKNOWN";
1511 memset(&ss, '\0', sizeof(ss));
1512 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1514 /* it might be the same as the last one - save some DNS work */
1515 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1516 return nc.name ? nc.name : "UNKNOWN";
1519 /* Not the same. We need to lookup. */
1524 /* Look up the remote host name. */
1525 ret = sys_getnameinfo((struct sockaddr *)&ss,
1534 DEBUG(1,("get_peer_name: getnameinfo failed "
1535 "for %s with error %s\n",
1537 gai_strerror(ret)));
1538 strlcpy(name_buf, p, sizeof(name_buf));
1540 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1541 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1542 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1546 /* can't pass the same source and dest strings in when you
1547 use --enable-developer or the clobber_region() call will
1550 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1551 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1552 if (strstr(name_buf,"..")) {
1553 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1561 return nc.name ? nc.name : "UNKNOWN";
1564 /*******************************************************************
1565 Return the IP addr of the remote end of a socket as a string.
1566 ******************************************************************/
1568 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1570 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1573 /*******************************************************************
1574 Create protected unix domain socket.
1576 Some unixes cannot set permissions on a ux-dom-sock, so we
1577 have to make sure that the directory contains the protection
1578 permissions instead.
1579 ******************************************************************/
1581 int create_pipe_sock(const char *socket_dir,
1582 const char *socket_name,
1585 #ifdef HAVE_UNIXSOCKET
1586 struct sockaddr_un sunaddr;
1592 old_umask = umask(0);
1594 /* Create the socket directory or reuse the existing one */
1596 if (lstat(socket_dir, &st) == -1) {
1597 if (errno == ENOENT) {
1598 /* Create directory */
1599 if (mkdir(socket_dir, dir_perms) == -1) {
1600 DEBUG(0, ("error creating socket directory "
1601 "%s: %s\n", socket_dir,
1606 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1607 socket_dir, strerror(errno)));
1611 /* Check ownership and permission on existing directory */
1612 if (!S_ISDIR(st.st_mode)) {
1613 DEBUG(0, ("socket directory %s isn't a directory\n",
1617 if ((st.st_uid != sec_initial_uid()) ||
1618 ((st.st_mode & 0777) != dir_perms)) {
1619 DEBUG(0, ("invalid permissions on socket directory "
1620 "%s\n", socket_dir));
1625 /* Create the socket file */
1627 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1630 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1635 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1640 memset(&sunaddr, 0, sizeof(sunaddr));
1641 sunaddr.sun_family = AF_UNIX;
1642 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1644 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1645 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1650 if (listen(sock, 5) == -1) {
1651 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1671 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1673 #endif /* HAVE_UNIXSOCKET */
1676 /****************************************************************************
1677 Get my own canonical name, including domain.
1678 ****************************************************************************/
1680 const char *get_mydnsfullname(void)
1682 struct addrinfo *res = NULL;
1683 char my_hostname[HOST_NAME_MAX];
1687 if (memcache_lookup(NULL, SINGLETON_CACHE,
1688 data_blob_string_const_null("get_mydnsfullname"),
1690 SMB_ASSERT(tmp.length > 0);
1691 return (const char *)tmp.data;
1694 /* get my host name */
1695 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1696 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1700 /* Ensure null termination. */
1701 my_hostname[sizeof(my_hostname)-1] = '\0';
1703 ret = interpret_string_addr_internal(&res,
1705 AI_ADDRCONFIG|AI_CANONNAME);
1707 if (!ret || res == NULL) {
1708 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1711 gai_strerror(ret) ));
1716 * Make sure that getaddrinfo() returns the "correct" host name.
1719 if (res->ai_canonname == NULL) {
1720 DEBUG(3,("get_mydnsfullname: failed to get "
1721 "canonical name for %s\n",
1727 /* This copies the data, so we must do a lookup
1728 * afterwards to find the value to return.
1731 memcache_add(NULL, SINGLETON_CACHE,
1732 data_blob_string_const_null("get_mydnsfullname"),
1733 data_blob_string_const_null(res->ai_canonname));
1735 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1736 data_blob_string_const_null("get_mydnsfullname"),
1738 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1739 strlen(res->ai_canonname) + 1);
1744 return (const char *)tmp.data;
1747 /************************************************************
1749 ************************************************************/
1751 bool is_myname_or_ipaddr(const char *s)
1753 TALLOC_CTX *ctx = talloc_tos();
1754 char addr[INET6_ADDRSTRLEN];
1756 const char *dnsname;
1757 char *servername = NULL;
1763 /* Santize the string from '\\name' */
1764 name = talloc_strdup(ctx, s);
1769 servername = strrchr_m(name, '\\' );
1776 /* Optimize for the common case */
1777 if (strequal(servername, global_myname())) {
1781 /* Check for an alias */
1782 if (is_myname(servername)) {
1786 /* Check for loopback */
1787 if (strequal(servername, "127.0.0.1") ||
1788 strequal(servername, "::1")) {
1792 if (strequal(servername, "localhost")) {
1796 /* Maybe it's my dns name */
1797 dnsname = get_mydnsfullname();
1798 if (dnsname && strequal(servername, dnsname)) {
1802 /* Handle possible CNAME records - convert to an IP addr. */
1803 if (!is_ipaddress(servername)) {
1804 /* Use DNS to resolve the name, but only the first address */
1805 struct sockaddr_storage ss;
1806 if (interpret_string_addr(&ss, servername, 0)) {
1807 print_sockaddr(addr,
1814 /* Maybe its an IP address? */
1815 if (is_ipaddress(servername)) {
1816 struct sockaddr_storage ss;
1817 struct iface_struct *nics;
1820 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
1824 if (ismyaddr((struct sockaddr *)&ss)) {
1828 if (is_zero_addr((struct sockaddr *)&ss) ||
1829 is_loopback_addr((struct sockaddr *)&ss)) {
1833 n = get_interfaces(talloc_tos(), &nics);
1834 for (i=0; i<n; i++) {
1835 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1847 struct getaddrinfo_state {
1849 const char *service;
1850 const struct addrinfo *hints;
1851 struct addrinfo *res;
1855 static void getaddrinfo_do(void *private_data);
1856 static void getaddrinfo_done(struct tevent_req *subreq);
1858 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1859 struct tevent_context *ev,
1860 struct fncall_context *ctx,
1862 const char *service,
1863 const struct addrinfo *hints)
1865 struct tevent_req *req, *subreq;
1866 struct getaddrinfo_state *state;
1868 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1874 state->service = service;
1875 state->hints = hints;
1877 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1878 if (tevent_req_nomem(subreq, req)) {
1879 return tevent_req_post(req, ev);
1881 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1885 static void getaddrinfo_do(void *private_data)
1887 struct getaddrinfo_state *state =
1888 (struct getaddrinfo_state *)private_data;
1890 state->ret = getaddrinfo(state->node, state->service, state->hints,
1894 static void getaddrinfo_done(struct tevent_req *subreq)
1896 struct tevent_req *req = tevent_req_callback_data(
1897 subreq, struct tevent_req);
1900 ret = fncall_recv(subreq, &err);
1901 TALLOC_FREE(subreq);
1903 tevent_req_error(req, err);
1906 tevent_req_done(req);
1909 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1911 struct getaddrinfo_state *state = tevent_req_data(
1912 req, struct getaddrinfo_state);
1915 if (tevent_req_is_unix_error(req, &err)) {
1923 if (state->ret == 0) {