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 /****************************************************************************
25 Get a port number in host byte order from a sockaddr_storage.
26 ****************************************************************************/
28 uint16_t get_sockaddr_port(const struct sockaddr_storage *pss)
32 if (pss->ss_family != AF_INET) {
33 #if defined(HAVE_IPV6)
35 const struct sockaddr_in6 *sa6 =
36 (const struct sockaddr_in6 *)pss;
37 port = ntohs(sa6->sin6_port);
40 const struct sockaddr_in *sa =
41 (const struct sockaddr_in *)pss;
42 port = ntohs(sa->sin_port);
47 /****************************************************************************
48 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
49 ****************************************************************************/
51 static char *print_sockaddr_len(char *dest,
53 const struct sockaddr *psa,
59 (void)sys_getnameinfo(psa,
67 /****************************************************************************
68 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
69 ****************************************************************************/
71 char *print_sockaddr(char *dest,
73 const struct sockaddr_storage *psa)
75 return print_sockaddr_len(dest, destlen, (struct sockaddr *)psa,
76 sizeof(struct sockaddr_storage));
79 /****************************************************************************
80 Print out a canonical IPv4 or IPv6 address from a struct sockaddr_storage.
81 ****************************************************************************/
83 char *print_canonical_sockaddr(TALLOC_CTX *ctx,
84 const struct sockaddr_storage *pss)
86 char addr[INET6_ADDRSTRLEN];
90 /* Linux getnameinfo() man pages says port is unitialized if
91 service name is NULL. */
93 ret = sys_getnameinfo((const struct sockaddr *)pss,
94 sizeof(struct sockaddr_storage),
102 if (pss->ss_family != AF_INET) {
103 #if defined(HAVE_IPV6)
104 dest = talloc_asprintf(ctx, "[%s]", addr);
109 dest = talloc_asprintf(ctx, "%s", addr);
115 /****************************************************************************
116 Return the string of an IP address (IPv4 or IPv6).
117 ****************************************************************************/
119 static const char *get_socket_addr(int fd, char *addr_buf, size_t addr_len)
121 struct sockaddr_storage sa;
122 socklen_t length = sizeof(sa);
124 /* Ok, returning a hard coded IPv4 address
125 * is bogus, but it's just as bogus as a
126 * zero IPv6 address. No good choice here.
129 strlcpy(addr_buf, "0.0.0.0", addr_len);
135 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
136 DEBUG(0,("getsockname failed. Error was %s\n",
141 return print_sockaddr_len(addr_buf, addr_len, (struct sockaddr *)&sa, length);
144 /****************************************************************************
145 Return the port number we've bound to on a socket.
146 ****************************************************************************/
148 int get_socket_port(int fd)
150 struct sockaddr_storage sa;
151 socklen_t length = sizeof(sa);
157 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
158 int level = (errno == ENOTCONN) ? 2 : 0;
159 DEBUG(level, ("getpeername failed. Error was %s\n",
164 #if defined(HAVE_IPV6)
165 if (sa.ss_family == AF_INET6) {
166 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
169 if (sa.ss_family == AF_INET) {
170 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
175 const char *client_name(int fd)
177 return get_peer_name(fd,false);
180 const char *client_addr(int fd, char *addr, size_t addrlen)
182 return get_peer_addr(fd,addr,addrlen);
185 const char *client_socket_addr(int fd, char *addr, size_t addr_len)
187 return get_socket_addr(fd, addr, addr_len);
191 /* Not currently used. JRA. */
192 int client_socket_port(int fd)
194 return get_socket_port(fd);
198 /****************************************************************************
199 Accessor functions to make thread-safe code easier later...
200 ****************************************************************************/
202 void set_smb_read_error(enum smb_read_errors *pre,
203 enum smb_read_errors newerr)
210 void cond_set_smb_read_error(enum smb_read_errors *pre,
211 enum smb_read_errors newerr)
213 if (pre && *pre == SMB_READ_OK) {
218 /****************************************************************************
219 Determine if a file descriptor is in fact a socket.
220 ****************************************************************************/
222 bool is_a_socket(int fd)
227 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
230 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
232 typedef struct smb_socket_option {
240 static const smb_socket_option socket_options[] = {
241 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
242 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
243 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
245 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
248 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
251 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
254 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
256 #ifdef IPTOS_LOWDELAY
257 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
259 #ifdef IPTOS_THROUGHPUT
260 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
263 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
266 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
269 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
272 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
275 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
278 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
281 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
284 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
287 {"TCP_QUICKACK", IPPROTO_TCP, TCP_QUICKACK, 0, OPT_BOOL},
291 /****************************************************************************
292 Print socket options.
293 ****************************************************************************/
295 static void print_socket_options(int s)
299 const smb_socket_option *p = &socket_options[0];
301 /* wrapped in if statement to prevent streams
302 * leak in SCO Openserver 5.0 */
303 /* reported on samba-technical --jerry */
304 if ( DEBUGLEVEL >= 5 ) {
305 DEBUG(5,("Socket options:\n"));
306 for (; p->name != NULL; p++) {
307 if (getsockopt(s, p->level, p->option,
308 (void *)&value, &vlen) == -1) {
309 DEBUGADD(5,("\tCould not test socket option %s.\n",
312 DEBUGADD(5,("\t%s = %d\n",
319 /****************************************************************************
320 Set user socket options.
321 ****************************************************************************/
323 void set_socket_options(int fd, const char *options)
325 TALLOC_CTX *ctx = talloc_stackframe();
328 while (next_token_talloc(ctx, &options, &tok," \t,")) {
332 bool got_value = false;
334 if ((p = strchr_m(tok,'='))) {
340 for (i=0;socket_options[i].name;i++)
341 if (strequal(socket_options[i].name,tok))
344 if (!socket_options[i].name) {
345 DEBUG(0,("Unknown socket option %s\n",tok));
349 switch (socket_options[i].opttype) {
352 ret = setsockopt(fd,socket_options[i].level,
353 socket_options[i].option,
354 (char *)&value,sizeof(int));
359 DEBUG(0,("syntax error - %s "
360 "does not take a value\n",tok));
363 int on = socket_options[i].value;
364 ret = setsockopt(fd,socket_options[i].level,
365 socket_options[i].option,
366 (char *)&on,sizeof(int));
372 /* be aware that some systems like Solaris return
373 * EINVAL to a setsockopt() call when the client
374 * sent a RST previously - no need to worry */
375 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
376 tok, strerror(errno) ));
381 print_socket_options(fd);
384 /****************************************************************************
386 ****************************************************************************/
388 ssize_t read_udp_v4_socket(int fd,
391 struct sockaddr_storage *psa)
394 socklen_t socklen = sizeof(*psa);
395 struct sockaddr_in *si = (struct sockaddr_in *)psa;
397 memset((char *)psa,'\0',socklen);
399 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
400 (struct sockaddr *)psa,&socklen);
402 /* Don't print a low debug error for a non-blocking socket. */
403 if (errno == EAGAIN) {
404 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
406 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
412 if (psa->ss_family != AF_INET) {
413 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
414 "(not IPv4)\n", (int)psa->ss_family));
418 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
419 inet_ntoa(si->sin_addr),
421 (unsigned long)ret));
426 /****************************************************************************
427 Read data from a file descriptor with a timout in msec.
428 mincount = if timeout, minimum to read before returning
429 maxcount = number to be read.
430 time_out = timeout in milliseconds
431 NB. This can be called with a non-socket fd, don't change
432 sys_read() to sys_recv() or other socket call.
433 ****************************************************************************/
435 NTSTATUS read_fd_with_timeout(int fd, char *buf,
436 size_t mincnt, size_t maxcnt,
437 unsigned int time_out,
444 struct timeval timeout;
447 /* just checking .... */
457 while (nread < mincnt) {
458 readret = sys_read(fd, buf + nread, maxcnt - nread);
461 DEBUG(5,("read_fd_with_timeout: "
462 "blocking read. EOF from client.\n"));
463 return NT_STATUS_END_OF_FILE;
467 return map_nt_error_from_unix(save_errno);
474 /* Most difficult - timeout read */
475 /* If this is ever called on a disk file and
476 mincnt is greater then the filesize then
477 system performance will suffer severely as
478 select always returns true on disk files */
480 /* Set initial timeout */
481 timeout.tv_sec = (time_t)(time_out / 1000);
482 timeout.tv_usec = (long)(1000 * (time_out % 1000));
484 for (nread=0; nread < mincnt; ) {
488 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
492 return map_nt_error_from_unix(save_errno);
495 /* Did we timeout ? */
497 DEBUG(10,("read_fd_with_timeout: timeout read. "
498 "select timed out.\n"));
499 return NT_STATUS_IO_TIMEOUT;
502 readret = sys_read(fd, buf+nread, maxcnt-nread);
505 /* we got EOF on the file descriptor */
506 DEBUG(5,("read_fd_with_timeout: timeout read. "
507 "EOF from client.\n"));
508 return NT_STATUS_END_OF_FILE;
512 return map_nt_error_from_unix(errno);
519 /* Return the number we got */
526 /****************************************************************************
527 Read data from an fd, reading exactly N bytes.
528 NB. This can be called with a non-socket fd, don't add dependencies
530 ****************************************************************************/
532 NTSTATUS read_data(int fd, char *buffer, size_t N)
536 status = read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
537 if (NT_STATUS_IS_OK(status)) {
540 if (fd == smbd_server_fd()) {
541 char addr[INET6_ADDRSTRLEN];
542 /* Try and give an error message
543 * saying what client failed. */
544 DEBUG(0, ("read_fd_with_timeout failed for "
545 "client %s read error = %s.\n",
546 get_peer_addr(fd,addr,sizeof(addr)),
549 DEBUG(0, ("read_fd_with_timeout failed, read error = %s.\n",
555 /****************************************************************************
556 Write all data from an iov array
557 NB. This can be called with a non-socket fd, don't add dependencies
559 ****************************************************************************/
561 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
567 struct iovec *iov_copy, *iov;
570 for (i=0; i<iovcnt; i++) {
571 to_send += orig_iov[i].iov_len;
574 thistime = sys_writev(fd, orig_iov, iovcnt);
575 if ((thistime <= 0) || (thistime == to_send)) {
581 * We could not send everything in one call. Make a copy of iov that
582 * we can mess with. We keep a copy of the array start in iov_copy for
583 * the TALLOC_FREE, because we're going to modify iov later on,
584 * discarding elements.
587 iov_copy = (struct iovec *)TALLOC_MEMDUP(
588 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
590 if (iov_copy == NULL) {
596 while (sent < to_send) {
598 * We have to discard "thistime" bytes from the beginning
599 * iov array, "thistime" contains the number of bytes sent
602 while (thistime > 0) {
603 if (thistime < iov[0].iov_len) {
605 (char *)iov[0].iov_base + thistime;
606 iov[0].iov_base = (void *)new_base;
607 iov[0].iov_len -= thistime;
610 thistime -= iov[0].iov_len;
615 thistime = sys_writev(fd, iov, iovcnt);
622 TALLOC_FREE(iov_copy);
626 /****************************************************************************
628 NB. This can be called with a non-socket fd, don't add dependencies
630 ****************************************************************************/
632 ssize_t write_data(int fd, const char *buffer, size_t N)
636 iov.iov_base = CONST_DISCARD(void *, buffer);
638 return write_data_iov(fd, &iov, 1);
641 /****************************************************************************
642 Send a keepalive packet (rfc1002).
643 ****************************************************************************/
645 bool send_keepalive(int client)
647 unsigned char buf[4];
649 buf[0] = SMBkeepalive;
650 buf[1] = buf[2] = buf[3] = 0;
652 return(write_data(client,(char *)buf,4) == 4);
655 /****************************************************************************
656 Read 4 bytes of a smb packet and return the smb length of the packet.
657 Store the result in the buffer.
658 This version of the function will return a length of zero on receiving
660 Timeout is in milliseconds.
661 ****************************************************************************/
663 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
664 unsigned int timeout,
670 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
672 if (!NT_STATUS_IS_OK(status)) {
673 if (fd == smbd_server_fd()) {
674 char addr[INET6_ADDRSTRLEN];
675 /* Try and give an error message
676 * saying what client failed. */
677 DEBUG(0, ("read_fd_with_timeout failed for "
678 "client %s read error = %s.\n",
679 get_peer_addr(fd,addr,sizeof(addr)),
682 DEBUG(0, ("read_fd_with_timeout failed, read error = "
683 "%s.\n", nt_errstr(status)));
688 *len = smb_len(inbuf);
689 msg_type = CVAL(inbuf,0);
691 if (msg_type == SMBkeepalive) {
692 DEBUG(5,("Got keepalive packet\n"));
695 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
700 /****************************************************************************
701 Read 4 bytes of a smb packet and return the smb length of the packet.
702 Store the result in the buffer. This version of the function will
703 never return a session keepalive (length of zero).
704 Timeout is in milliseconds.
705 ****************************************************************************/
707 NTSTATUS read_smb_length(int fd, char *inbuf, unsigned int timeout,
710 uint8_t msgtype = SMBkeepalive;
712 while (msgtype == SMBkeepalive) {
715 status = read_smb_length_return_keepalive(fd, inbuf, timeout,
717 if (!NT_STATUS_IS_OK(status)) {
721 msgtype = CVAL(inbuf, 0);
724 DEBUG(10,("read_smb_length: got smb length of %lu\n",
725 (unsigned long)len));
730 /****************************************************************************
731 Read an smb from a fd.
732 The timeout is in milliseconds.
733 This function will return on receipt of a session keepalive packet.
734 maxlen is the max number of bytes to return, not including the 4 byte
735 length. If zero it means buflen limit.
736 Doesn't check the MAC on signed packets.
737 ****************************************************************************/
739 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
740 size_t maxlen, size_t *p_len)
745 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
747 if (!NT_STATUS_IS_OK(status)) {
748 DEBUG(10, ("receive_smb_raw: %s!\n", nt_errstr(status)));
753 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
754 (unsigned long)len));
755 return NT_STATUS_INVALID_PARAMETER;
760 len = MIN(len,maxlen);
763 status = read_fd_with_timeout(
764 fd, buffer+4, len, len, timeout, &len);
766 if (!NT_STATUS_IS_OK(status)) {
767 if (fd == smbd_server_fd()) {
768 char addr[INET6_ADDRSTRLEN];
769 /* Try and give an error message
770 * saying what client failed. */
771 DEBUG(0, ("read_fd_with_timeout failed for "
772 "client %s read error = %s.\n",
773 get_peer_addr(fd,addr,sizeof(addr)),
776 DEBUG(0, ("read_fd_with_timeout failed, "
777 "read error = %s.\n",
783 /* not all of samba3 properly checks for packet-termination
784 * of strings. This ensures that we don't run off into
786 SSVAL(buffer+4,len, 0);
793 /****************************************************************************
794 Open a socket of the specified type, port, and address for incoming data.
795 ****************************************************************************/
797 int open_socket_in(int type,
800 const struct sockaddr_storage *psock,
803 struct sockaddr_storage sock;
805 socklen_t slen = sizeof(struct sockaddr_in);
809 #if defined(HAVE_IPV6)
810 if (sock.ss_family == AF_INET6) {
811 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
812 slen = sizeof(struct sockaddr_in6);
815 if (sock.ss_family == AF_INET) {
816 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
819 res = socket(sock.ss_family, type, 0 );
822 dbgtext( "open_socket_in(): socket() call failed: " );
823 dbgtext( "%s\n", strerror( errno ) );
828 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
830 int val = rebind ? 1 : 0;
831 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
832 (char *)&val,sizeof(val)) == -1 ) {
833 if( DEBUGLVL( dlevel ) ) {
834 dbgtext( "open_socket_in(): setsockopt: " );
835 dbgtext( "SO_REUSEADDR = %s ",
836 val?"true":"false" );
837 dbgtext( "on port %d failed ", port );
838 dbgtext( "with error = %s\n", strerror(errno) );
842 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
843 (char *)&val,sizeof(val)) == -1 ) {
844 if( DEBUGLVL( dlevel ) ) {
845 dbgtext( "open_socket_in(): setsockopt: ");
846 dbgtext( "SO_REUSEPORT = %s ",
848 dbgtext( "on port %d failed ", port);
849 dbgtext( "with error = %s\n", strerror(errno));
852 #endif /* SO_REUSEPORT */
855 /* now we've got a socket - we need to bind it */
856 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
857 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
858 port == SMB_PORT2 || port == NMB_PORT) ) {
859 char addr[INET6_ADDRSTRLEN];
860 print_sockaddr(addr, sizeof(addr),
862 dbgtext( "bind failed on port %d ", port);
863 dbgtext( "socket_addr = %s.\n", addr);
864 dbgtext( "Error = %s\n", strerror(errno));
870 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
874 struct open_socket_out_state {
876 struct event_context *ev;
877 struct sockaddr_storage ss;
883 static void open_socket_out_connected(struct tevent_req *subreq);
885 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
893 /****************************************************************************
894 Create an outgoing socket. timeout is in milliseconds.
895 **************************************************************************/
897 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
898 struct event_context *ev,
899 const struct sockaddr_storage *pss,
903 char addr[INET6_ADDRSTRLEN];
904 struct tevent_req *result, *subreq;
905 struct open_socket_out_state *state;
908 result = tevent_req_create(mem_ctx, &state,
909 struct open_socket_out_state);
910 if (result == NULL) {
916 state->wait_nsec = 10000;
919 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
920 if (state->fd == -1) {
921 status = map_nt_error_from_unix(errno);
924 talloc_set_destructor(state, open_socket_out_state_destructor);
926 if (!tevent_req_set_endtime(
927 result, ev, timeval_current_ofs(0, timeout*1000))) {
931 #if defined(HAVE_IPV6)
932 if (pss->ss_family == AF_INET6) {
933 struct sockaddr_in6 *psa6;
934 psa6 = (struct sockaddr_in6 *)&state->ss;
935 psa6->sin6_port = htons(port);
936 if (psa6->sin6_scope_id == 0
937 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
938 setup_linklocal_scope_id(
939 (struct sockaddr *)&(state->ss));
941 state->salen = sizeof(struct sockaddr_in6);
944 if (pss->ss_family == AF_INET) {
945 struct sockaddr_in *psa;
946 psa = (struct sockaddr_in *)&state->ss;
947 psa->sin_port = htons(port);
948 state->salen = sizeof(struct sockaddr_in);
951 if (pss->ss_family == AF_UNIX) {
952 state->salen = sizeof(struct sockaddr_un);
955 print_sockaddr(addr, sizeof(addr), &state->ss);
956 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
958 subreq = async_connect_send(state, state->ev, state->fd,
959 (struct sockaddr *)&state->ss,
962 || !tevent_req_set_endtime(
964 timeval_current_ofs(0, state->wait_nsec))) {
967 tevent_req_set_callback(subreq, open_socket_out_connected, result);
971 tevent_req_nterror(result, status);
972 return tevent_req_post(result, ev);
978 static void open_socket_out_connected(struct tevent_req *subreq)
980 struct tevent_req *req =
981 tevent_req_callback_data(subreq, struct tevent_req);
982 struct open_socket_out_state *state =
983 tevent_req_data(req, struct open_socket_out_state);
987 ret = async_connect_recv(subreq, &sys_errno);
990 tevent_req_done(req);
996 (sys_errno == ETIMEDOUT) ||
998 (sys_errno == EINPROGRESS) ||
999 (sys_errno == EALREADY) ||
1000 (sys_errno == EAGAIN)) {
1006 if (state->wait_nsec < 250000) {
1007 state->wait_nsec *= 1.5;
1010 subreq = async_connect_send(state, state->ev, state->fd,
1011 (struct sockaddr *)&state->ss,
1013 if (tevent_req_nomem(subreq, req)) {
1016 if (!tevent_req_set_endtime(
1018 timeval_current_ofs(0, state->wait_nsec))) {
1019 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
1022 tevent_req_set_callback(subreq, open_socket_out_connected, req);
1027 if (sys_errno == EISCONN) {
1028 tevent_req_done(req);
1034 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
1037 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
1039 struct open_socket_out_state *state =
1040 tevent_req_data(req, struct open_socket_out_state);
1043 if (tevent_req_is_nterror(req, &status)) {
1048 return NT_STATUS_OK;
1051 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
1052 int timeout, int *pfd)
1054 TALLOC_CTX *frame = talloc_stackframe();
1055 struct event_context *ev;
1056 struct tevent_req *req;
1057 NTSTATUS status = NT_STATUS_NO_MEMORY;
1059 ev = event_context_init(frame);
1064 req = open_socket_out_send(frame, ev, pss, port, timeout);
1068 if (!tevent_req_poll(req, ev)) {
1069 status = NT_STATUS_INTERNAL_ERROR;
1072 status = open_socket_out_recv(req, pfd);
1078 struct open_socket_out_defer_state {
1079 struct event_context *ev;
1080 struct sockaddr_storage ss;
1086 static void open_socket_out_defer_waited(struct tevent_req *subreq);
1087 static void open_socket_out_defer_connected(struct tevent_req *subreq);
1089 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
1090 struct event_context *ev,
1091 struct timeval wait_time,
1092 const struct sockaddr_storage *pss,
1096 struct tevent_req *req, *subreq;
1097 struct open_socket_out_defer_state *state;
1099 req = tevent_req_create(mem_ctx, &state,
1100 struct open_socket_out_defer_state);
1107 state->timeout = timeout;
1109 subreq = tevent_wakeup_send(
1111 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
1112 if (subreq == NULL) {
1115 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
1122 static void open_socket_out_defer_waited(struct tevent_req *subreq)
1124 struct tevent_req *req = tevent_req_callback_data(
1125 subreq, struct tevent_req);
1126 struct open_socket_out_defer_state *state = tevent_req_data(
1127 req, struct open_socket_out_defer_state);
1130 ret = tevent_wakeup_recv(subreq);
1131 TALLOC_FREE(subreq);
1133 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1137 subreq = open_socket_out_send(state, state->ev, &state->ss,
1138 state->port, state->timeout);
1139 if (tevent_req_nomem(subreq, req)) {
1142 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
1145 static void open_socket_out_defer_connected(struct tevent_req *subreq)
1147 struct tevent_req *req = tevent_req_callback_data(
1148 subreq, struct tevent_req);
1149 struct open_socket_out_defer_state *state = tevent_req_data(
1150 req, struct open_socket_out_defer_state);
1153 status = open_socket_out_recv(subreq, &state->fd);
1154 TALLOC_FREE(subreq);
1155 if (!NT_STATUS_IS_OK(status)) {
1156 tevent_req_nterror(req, status);
1159 tevent_req_done(req);
1162 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
1164 struct open_socket_out_defer_state *state = tevent_req_data(
1165 req, struct open_socket_out_defer_state);
1168 if (tevent_req_is_nterror(req, &status)) {
1173 return NT_STATUS_OK;
1176 /*******************************************************************
1177 Create an outgoing TCP socket to the first addr that connects.
1179 This is for simultaneous connection attempts to port 445 and 139 of a host
1180 or for simultatneous connection attempts to multiple DCs at once. We return
1181 a socket fd of the first successful connection.
1183 @param[in] addrs list of Internet addresses and ports to connect to
1184 @param[in] num_addrs number of address/port pairs in the addrs list
1185 @param[in] timeout time after which we stop waiting for a socket connection
1186 to succeed, given in milliseconds
1187 @param[out] fd_index the entry in addrs which we successfully connected to
1188 @param[out] fd fd of the open and connected socket
1189 @return true on a successful connection, false if all connection attempts
1190 failed or we timed out
1191 *******************************************************************/
1193 bool open_any_socket_out(struct sockaddr_storage *addrs, int num_addrs,
1194 int timeout, int *fd_index, int *fd)
1196 int i, resulting_index, res;
1200 fd_set r_fds, wr_fds;
1204 int connect_loop = 10000; /* 10 milliseconds */
1206 timeout *= 1000; /* convert to microseconds */
1208 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1210 if (sockets == NULL)
1213 resulting_index = -1;
1215 for (i=0; i<num_addrs; i++)
1218 for (i=0; i<num_addrs; i++) {
1219 sockets[i] = socket(addrs[i].ss_family, SOCK_STREAM, 0);
1222 set_blocking(sockets[i], false);
1226 good_connect = false;
1228 for (i=0; i<num_addrs; i++) {
1229 const struct sockaddr * a =
1230 (const struct sockaddr *)&(addrs[i]);
1232 if (sockets[i] == -1)
1235 if (sys_connect(sockets[i], a) == 0) {
1236 /* Rather unlikely as we are non-blocking, but it
1237 * might actually happen. */
1238 resulting_index = i;
1242 if (errno == EINPROGRESS || errno == EALREADY ||
1246 errno == EAGAIN || errno == EINTR) {
1247 /* These are the error messages that something is
1249 good_connect = true;
1250 } else if (errno != 0) {
1251 /* There was a direct error */
1257 if (!good_connect) {
1258 /* All of the connect's resulted in real error conditions */
1262 /* Lets see if any of the connect attempts succeeded */
1268 for (i=0; i<num_addrs; i++) {
1269 if (sockets[i] == -1)
1271 FD_SET(sockets[i], &wr_fds);
1272 FD_SET(sockets[i], &r_fds);
1273 if (sockets[i]>maxfd)
1278 tv.tv_usec = connect_loop;
1280 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1288 for (i=0; i<num_addrs; i++) {
1290 if (sockets[i] == -1)
1293 /* Stevens, Network Programming says that if there's a
1294 * successful connect, the socket is only writable. Upon an
1295 * error, it's both readable and writable. */
1297 if (FD_ISSET(sockets[i], &r_fds) &&
1298 FD_ISSET(sockets[i], &wr_fds)) {
1299 /* readable and writable, so it's an error */
1305 if (!FD_ISSET(sockets[i], &r_fds) &&
1306 FD_ISSET(sockets[i], &wr_fds)) {
1307 /* Only writable, so it's connected */
1308 resulting_index = i;
1315 timeout -= connect_loop;
1318 connect_loop *= 1.5;
1319 if (connect_loop > timeout)
1320 connect_loop = timeout;
1324 for (i=0; i<num_addrs; i++) {
1325 if (i == resulting_index)
1327 if (sockets[i] >= 0)
1331 if (resulting_index >= 0) {
1332 *fd_index = resulting_index;
1333 *fd = sockets[*fd_index];
1334 set_blocking(*fd, true);
1339 return (resulting_index >= 0);
1341 /****************************************************************************
1342 Open a connected UDP socket to host on port
1343 **************************************************************************/
1345 int open_udp_socket(const char *host, int port)
1347 struct sockaddr_storage ss;
1350 if (!interpret_string_addr(&ss, host, 0)) {
1351 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1356 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1361 #if defined(HAVE_IPV6)
1362 if (ss.ss_family == AF_INET6) {
1363 struct sockaddr_in6 *psa6;
1364 psa6 = (struct sockaddr_in6 *)&ss;
1365 psa6->sin6_port = htons(port);
1366 if (psa6->sin6_scope_id == 0
1367 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1368 setup_linklocal_scope_id(
1369 (struct sockaddr *)&ss);
1373 if (ss.ss_family == AF_INET) {
1374 struct sockaddr_in *psa;
1375 psa = (struct sockaddr_in *)&ss;
1376 psa->sin_port = htons(port);
1379 if (sys_connect(res,(struct sockaddr *)&ss)) {
1387 /*******************************************************************
1388 Return the IP addr of the remote end of a socket as a string.
1389 Optionally return the struct sockaddr_storage.
1390 ******************************************************************/
1392 static const char *get_peer_addr_internal(int fd,
1394 size_t addr_buf_len,
1395 struct sockaddr *pss,
1398 struct sockaddr_storage ss;
1399 socklen_t length = sizeof(ss);
1401 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1408 pss = (struct sockaddr *)&ss;
1412 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1413 int level = (errno == ENOTCONN) ? 2 : 0;
1414 DEBUG(level, ("getpeername failed. Error was %s\n",
1419 print_sockaddr_len(addr_buf,
1426 /*******************************************************************
1427 Matchname - determine if host name matches IP address. Used to
1428 confirm a hostname lookup to prevent spoof attacks.
1429 ******************************************************************/
1431 static bool matchname(const char *remotehost,
1432 const struct sockaddr *pss,
1435 struct addrinfo *res = NULL;
1436 struct addrinfo *ailist = NULL;
1437 char addr_buf[INET6_ADDRSTRLEN];
1438 bool ret = interpret_string_addr_internal(&ailist,
1440 AI_ADDRCONFIG|AI_CANONNAME);
1442 if (!ret || ailist == NULL) {
1443 DEBUG(3,("matchname: getaddrinfo failed for "
1446 gai_strerror(ret) ));
1451 * Make sure that getaddrinfo() returns the "correct" host name.
1454 if (ailist->ai_canonname == NULL ||
1455 (!strequal(remotehost, ailist->ai_canonname) &&
1456 !strequal(remotehost, "localhost"))) {
1457 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1459 ailist->ai_canonname ?
1460 ailist->ai_canonname : "(NULL)"));
1461 freeaddrinfo(ailist);
1465 /* Look up the host address in the address list we just got. */
1466 for (res = ailist; res; res = res->ai_next) {
1467 if (!res->ai_addr) {
1470 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1471 (struct sockaddr *)pss)) {
1472 freeaddrinfo(ailist);
1478 * The host name does not map to the original host address. Perhaps
1479 * someone has compromised a name server. More likely someone botched
1480 * it, but that could be dangerous, too.
1483 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1484 print_sockaddr_len(addr_buf,
1488 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1491 freeaddrinfo(ailist);
1496 /*******************************************************************
1497 Deal with the singleton cache.
1498 ******************************************************************/
1500 struct name_addr_pair {
1501 struct sockaddr_storage ss;
1505 /*******************************************************************
1506 Lookup a name/addr pair. Returns memory allocated from memcache.
1507 ******************************************************************/
1509 static bool lookup_nc(struct name_addr_pair *nc)
1515 if (!memcache_lookup(
1516 NULL, SINGLETON_CACHE,
1517 data_blob_string_const_null("get_peer_name"),
1522 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1523 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1527 /*******************************************************************
1528 Save a name/addr pair.
1529 ******************************************************************/
1531 static void store_nc(const struct name_addr_pair *nc)
1534 size_t namelen = strlen(nc->name);
1536 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1540 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1541 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1543 memcache_add(NULL, SINGLETON_CACHE,
1544 data_blob_string_const_null("get_peer_name"),
1546 data_blob_free(&tmp);
1549 /*******************************************************************
1550 Return the DNS name of the remote end of a socket.
1551 ******************************************************************/
1553 const char *get_peer_name(int fd, bool force_lookup)
1555 struct name_addr_pair nc;
1556 char addr_buf[INET6_ADDRSTRLEN];
1557 struct sockaddr_storage ss;
1558 socklen_t length = sizeof(ss);
1561 char name_buf[MAX_DNS_NAME_LENGTH];
1562 char tmp_name[MAX_DNS_NAME_LENGTH];
1564 /* reverse lookups can be *very* expensive, and in many
1565 situations won't work because many networks don't link dhcp
1566 with dns. To avoid the delay we avoid the lookup if
1568 if (!lp_hostname_lookups() && (force_lookup == false)) {
1569 length = sizeof(nc.ss);
1570 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1571 (struct sockaddr *)&nc.ss, &length);
1574 return nc.name ? nc.name : "UNKNOWN";
1579 memset(&ss, '\0', sizeof(ss));
1580 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1582 /* it might be the same as the last one - save some DNS work */
1583 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1584 return nc.name ? nc.name : "UNKNOWN";
1587 /* Not the same. We need to lookup. */
1592 /* Look up the remote host name. */
1593 ret = sys_getnameinfo((struct sockaddr *)&ss,
1602 DEBUG(1,("get_peer_name: getnameinfo failed "
1603 "for %s with error %s\n",
1605 gai_strerror(ret)));
1606 strlcpy(name_buf, p, sizeof(name_buf));
1608 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1609 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1610 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1614 /* can't pass the same source and dest strings in when you
1615 use --enable-developer or the clobber_region() call will
1618 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1619 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1620 if (strstr(name_buf,"..")) {
1621 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1629 return nc.name ? nc.name : "UNKNOWN";
1632 /*******************************************************************
1633 Return the IP addr of the remote end of a socket as a string.
1634 ******************************************************************/
1636 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1638 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1641 /*******************************************************************
1642 Create protected unix domain socket.
1644 Some unixes cannot set permissions on a ux-dom-sock, so we
1645 have to make sure that the directory contains the protection
1646 permissions instead.
1647 ******************************************************************/
1649 int create_pipe_sock(const char *socket_dir,
1650 const char *socket_name,
1653 #ifdef HAVE_UNIXSOCKET
1654 struct sockaddr_un sunaddr;
1660 old_umask = umask(0);
1662 /* Create the socket directory or reuse the existing one */
1664 if (lstat(socket_dir, &st) == -1) {
1665 if (errno == ENOENT) {
1666 /* Create directory */
1667 if (mkdir(socket_dir, dir_perms) == -1) {
1668 DEBUG(0, ("error creating socket directory "
1669 "%s: %s\n", socket_dir,
1674 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1675 socket_dir, strerror(errno)));
1679 /* Check ownership and permission on existing directory */
1680 if (!S_ISDIR(st.st_mode)) {
1681 DEBUG(0, ("socket directory %s isn't a directory\n",
1685 if ((st.st_uid != sec_initial_uid()) ||
1686 ((st.st_mode & 0777) != dir_perms)) {
1687 DEBUG(0, ("invalid permissions on socket directory "
1688 "%s\n", socket_dir));
1693 /* Create the socket file */
1695 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1698 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1703 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1708 memset(&sunaddr, 0, sizeof(sunaddr));
1709 sunaddr.sun_family = AF_UNIX;
1710 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1712 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1713 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1718 if (listen(sock, 5) == -1) {
1719 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1739 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1741 #endif /* HAVE_UNIXSOCKET */
1744 /****************************************************************************
1745 Get my own canonical name, including domain.
1746 ****************************************************************************/
1748 const char *get_mydnsfullname(void)
1750 struct addrinfo *res = NULL;
1751 char my_hostname[HOST_NAME_MAX];
1755 if (memcache_lookup(NULL, SINGLETON_CACHE,
1756 data_blob_string_const_null("get_mydnsfullname"),
1758 SMB_ASSERT(tmp.length > 0);
1759 return (const char *)tmp.data;
1762 /* get my host name */
1763 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1764 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1768 /* Ensure null termination. */
1769 my_hostname[sizeof(my_hostname)-1] = '\0';
1771 ret = interpret_string_addr_internal(&res,
1773 AI_ADDRCONFIG|AI_CANONNAME);
1775 if (!ret || res == NULL) {
1776 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1779 gai_strerror(ret) ));
1784 * Make sure that getaddrinfo() returns the "correct" host name.
1787 if (res->ai_canonname == NULL) {
1788 DEBUG(3,("get_mydnsfullname: failed to get "
1789 "canonical name for %s\n",
1795 /* This copies the data, so we must do a lookup
1796 * afterwards to find the value to return.
1799 memcache_add(NULL, SINGLETON_CACHE,
1800 data_blob_string_const_null("get_mydnsfullname"),
1801 data_blob_string_const_null(res->ai_canonname));
1803 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1804 data_blob_string_const_null("get_mydnsfullname"),
1806 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1807 strlen(res->ai_canonname) + 1);
1812 return (const char *)tmp.data;
1815 /************************************************************
1817 ************************************************************/
1819 bool is_myname_or_ipaddr(const char *s)
1821 TALLOC_CTX *ctx = talloc_tos();
1822 char addr[INET6_ADDRSTRLEN];
1824 const char *dnsname;
1825 char *servername = NULL;
1831 /* Santize the string from '\\name' */
1832 name = talloc_strdup(ctx, s);
1837 servername = strrchr_m(name, '\\' );
1844 /* Optimize for the common case */
1845 if (strequal(servername, global_myname())) {
1849 /* Check for an alias */
1850 if (is_myname(servername)) {
1854 /* Check for loopback */
1855 if (strequal(servername, "127.0.0.1") ||
1856 strequal(servername, "::1")) {
1860 if (strequal(servername, "localhost")) {
1864 /* Maybe it's my dns name */
1865 dnsname = get_mydnsfullname();
1866 if (dnsname && strequal(servername, dnsname)) {
1870 /* Handle possible CNAME records - convert to an IP addr. */
1871 if (!is_ipaddress(servername)) {
1872 /* Use DNS to resolve the name, but only the first address */
1873 struct sockaddr_storage ss;
1874 if (interpret_string_addr(&ss, servername, 0)) {
1875 print_sockaddr(addr,
1882 /* Maybe its an IP address? */
1883 if (is_ipaddress(servername)) {
1884 struct sockaddr_storage ss;
1885 struct iface_struct *nics;
1888 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
1892 if (ismyaddr((struct sockaddr *)&ss)) {
1896 if (is_zero_addr((struct sockaddr *)&ss) ||
1897 is_loopback_addr((struct sockaddr *)&ss)) {
1901 n = get_interfaces(talloc_tos(), &nics);
1902 for (i=0; i<n; i++) {
1903 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1915 struct getaddrinfo_state {
1917 const char *service;
1918 const struct addrinfo *hints;
1919 struct addrinfo *res;
1923 static void getaddrinfo_do(void *private_data);
1924 static void getaddrinfo_done(struct tevent_req *subreq);
1926 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1927 struct tevent_context *ev,
1928 struct fncall_context *ctx,
1930 const char *service,
1931 const struct addrinfo *hints)
1933 struct tevent_req *req, *subreq;
1934 struct getaddrinfo_state *state;
1936 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1942 state->service = service;
1943 state->hints = hints;
1945 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1946 if (tevent_req_nomem(subreq, req)) {
1947 return tevent_req_post(req, ev);
1949 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1953 static void getaddrinfo_do(void *private_data)
1955 struct getaddrinfo_state *state =
1956 (struct getaddrinfo_state *)private_data;
1958 state->ret = getaddrinfo(state->node, state->service, state->hints,
1962 static void getaddrinfo_done(struct tevent_req *subreq)
1964 struct tevent_req *req = tevent_req_callback_data(
1965 subreq, struct tevent_req);
1968 ret = fncall_recv(subreq, &err);
1969 TALLOC_FREE(subreq);
1971 tevent_req_error(req, err);
1974 tevent_req_done(req);
1977 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1979 struct getaddrinfo_state *state = tevent_req_data(
1980 req, struct getaddrinfo_state);
1983 if (tevent_req_is_unix_error(req, &err)) {
1991 if (state->ret == 0) {