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, ("getsockname 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},
292 #ifdef TCP_KEEPALIVE_THRESHOLD
293 {"TCP_KEEPALIVE_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, 0, OPT_INT},
295 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
296 {"TCP_KEEPALIVE_ABORT_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, 0, OPT_INT},
300 /****************************************************************************
301 Print socket options.
302 ****************************************************************************/
304 static void print_socket_options(int s)
308 const smb_socket_option *p = &socket_options[0];
310 /* wrapped in if statement to prevent streams
311 * leak in SCO Openserver 5.0 */
312 /* reported on samba-technical --jerry */
313 if ( DEBUGLEVEL >= 5 ) {
314 DEBUG(5,("Socket options:\n"));
315 for (; p->name != NULL; p++) {
316 if (getsockopt(s, p->level, p->option,
317 (void *)&value, &vlen) == -1) {
318 DEBUGADD(5,("\tCould not test socket option %s.\n",
321 DEBUGADD(5,("\t%s = %d\n",
328 /****************************************************************************
329 Set user socket options.
330 ****************************************************************************/
332 void set_socket_options(int fd, const char *options)
334 TALLOC_CTX *ctx = talloc_stackframe();
337 while (next_token_talloc(ctx, &options, &tok," \t,")) {
341 bool got_value = false;
343 if ((p = strchr_m(tok,'='))) {
349 for (i=0;socket_options[i].name;i++)
350 if (strequal(socket_options[i].name,tok))
353 if (!socket_options[i].name) {
354 DEBUG(0,("Unknown socket option %s\n",tok));
358 switch (socket_options[i].opttype) {
361 ret = setsockopt(fd,socket_options[i].level,
362 socket_options[i].option,
363 (char *)&value,sizeof(int));
368 DEBUG(0,("syntax error - %s "
369 "does not take a value\n",tok));
372 int on = socket_options[i].value;
373 ret = setsockopt(fd,socket_options[i].level,
374 socket_options[i].option,
375 (char *)&on,sizeof(int));
381 /* be aware that some systems like Solaris return
382 * EINVAL to a setsockopt() call when the client
383 * sent a RST previously - no need to worry */
384 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
385 tok, strerror(errno) ));
390 print_socket_options(fd);
393 /****************************************************************************
395 ****************************************************************************/
397 ssize_t read_udp_v4_socket(int fd,
400 struct sockaddr_storage *psa)
403 socklen_t socklen = sizeof(*psa);
404 struct sockaddr_in *si = (struct sockaddr_in *)psa;
406 memset((char *)psa,'\0',socklen);
408 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
409 (struct sockaddr *)psa,&socklen);
411 /* Don't print a low debug error for a non-blocking socket. */
412 if (errno == EAGAIN) {
413 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
415 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
421 if (psa->ss_family != AF_INET) {
422 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
423 "(not IPv4)\n", (int)psa->ss_family));
427 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
428 inet_ntoa(si->sin_addr),
430 (unsigned long)ret));
435 /****************************************************************************
436 Read data from a file descriptor with a timout in msec.
437 mincount = if timeout, minimum to read before returning
438 maxcount = number to be read.
439 time_out = timeout in milliseconds
440 NB. This can be called with a non-socket fd, don't change
441 sys_read() to sys_recv() or other socket call.
442 ****************************************************************************/
444 NTSTATUS read_fd_with_timeout(int fd, char *buf,
445 size_t mincnt, size_t maxcnt,
446 unsigned int time_out,
453 struct timeval timeout;
455 /* just checking .... */
465 while (nread < mincnt) {
466 readret = sys_read(fd, buf + nread, maxcnt - nread);
469 DEBUG(5,("read_fd_with_timeout: "
470 "blocking read. EOF from client.\n"));
471 return NT_STATUS_END_OF_FILE;
475 return map_nt_error_from_unix(errno);
482 /* Most difficult - timeout read */
483 /* If this is ever called on a disk file and
484 mincnt is greater then the filesize then
485 system performance will suffer severely as
486 select always returns true on disk files */
488 /* Set initial timeout */
489 timeout.tv_sec = (time_t)(time_out / 1000);
490 timeout.tv_usec = (long)(1000 * (time_out % 1000));
492 for (nread=0; nread < mincnt; ) {
496 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
500 return map_nt_error_from_unix(errno);
503 /* Did we timeout ? */
505 DEBUG(10,("read_fd_with_timeout: timeout read. "
506 "select timed out.\n"));
507 return NT_STATUS_IO_TIMEOUT;
510 readret = sys_read(fd, buf+nread, maxcnt-nread);
513 /* we got EOF on the file descriptor */
514 DEBUG(5,("read_fd_with_timeout: timeout read. "
515 "EOF from client.\n"));
516 return NT_STATUS_END_OF_FILE;
520 return map_nt_error_from_unix(errno);
527 /* Return the number we got */
534 /****************************************************************************
535 Read data from an fd, reading exactly N bytes.
536 NB. This can be called with a non-socket fd, don't add dependencies
538 ****************************************************************************/
540 NTSTATUS read_data(int fd, char *buffer, size_t N)
542 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
545 /****************************************************************************
546 Write all data from an iov array
547 NB. This can be called with a non-socket fd, don't add dependencies
549 ****************************************************************************/
551 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
557 struct iovec *iov_copy, *iov;
560 for (i=0; i<iovcnt; i++) {
561 to_send += orig_iov[i].iov_len;
564 thistime = sys_writev(fd, orig_iov, iovcnt);
565 if ((thistime <= 0) || (thistime == to_send)) {
571 * We could not send everything in one call. Make a copy of iov that
572 * we can mess with. We keep a copy of the array start in iov_copy for
573 * the TALLOC_FREE, because we're going to modify iov later on,
574 * discarding elements.
577 iov_copy = (struct iovec *)TALLOC_MEMDUP(
578 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
580 if (iov_copy == NULL) {
586 while (sent < to_send) {
588 * We have to discard "thistime" bytes from the beginning
589 * iov array, "thistime" contains the number of bytes sent
592 while (thistime > 0) {
593 if (thistime < iov[0].iov_len) {
595 (char *)iov[0].iov_base + thistime;
596 iov[0].iov_base = (void *)new_base;
597 iov[0].iov_len -= thistime;
600 thistime -= iov[0].iov_len;
605 thistime = sys_writev(fd, iov, iovcnt);
612 TALLOC_FREE(iov_copy);
616 /****************************************************************************
618 NB. This can be called with a non-socket fd, don't add dependencies
620 ****************************************************************************/
622 ssize_t write_data(int fd, const char *buffer, size_t N)
626 iov.iov_base = CONST_DISCARD(void *, buffer);
628 return write_data_iov(fd, &iov, 1);
631 /****************************************************************************
632 Send a keepalive packet (rfc1002).
633 ****************************************************************************/
635 bool send_keepalive(int client)
637 unsigned char buf[4];
639 buf[0] = SMBkeepalive;
640 buf[1] = buf[2] = buf[3] = 0;
642 return(write_data(client,(char *)buf,4) == 4);
645 /****************************************************************************
646 Read 4 bytes of a smb packet and return the smb length of the packet.
647 Store the result in the buffer.
648 This version of the function will return a length of zero on receiving
650 Timeout is in milliseconds.
651 ****************************************************************************/
653 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
654 unsigned int timeout,
660 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
662 if (!NT_STATUS_IS_OK(status)) {
666 *len = smb_len(inbuf);
667 msg_type = CVAL(inbuf,0);
669 if (msg_type == SMBkeepalive) {
670 DEBUG(5,("Got keepalive packet\n"));
673 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
678 /****************************************************************************
679 Read an smb from a fd.
680 The timeout is in milliseconds.
681 This function will return on receipt of a session keepalive packet.
682 maxlen is the max number of bytes to return, not including the 4 byte
683 length. If zero it means buflen limit.
684 Doesn't check the MAC on signed packets.
685 ****************************************************************************/
687 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
688 size_t maxlen, size_t *p_len)
693 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
695 if (!NT_STATUS_IS_OK(status)) {
696 DEBUG(0, ("read_fd_with_timeout failed, read "
697 "error = %s.\n", nt_errstr(status)));
702 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
703 (unsigned long)len));
704 return NT_STATUS_INVALID_PARAMETER;
709 len = MIN(len,maxlen);
712 status = read_fd_with_timeout(
713 fd, buffer+4, len, len, timeout, &len);
715 if (!NT_STATUS_IS_OK(status)) {
716 DEBUG(0, ("read_fd_with_timeout failed, read error = "
717 "%s.\n", nt_errstr(status)));
721 /* not all of samba3 properly checks for packet-termination
722 * of strings. This ensures that we don't run off into
724 SSVAL(buffer+4,len, 0);
731 /****************************************************************************
732 Open a socket of the specified type, port, and address for incoming data.
733 ****************************************************************************/
735 int open_socket_in(int type,
738 const struct sockaddr_storage *psock,
741 struct sockaddr_storage sock;
743 socklen_t slen = sizeof(struct sockaddr_in);
747 #if defined(HAVE_IPV6)
748 if (sock.ss_family == AF_INET6) {
749 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
750 slen = sizeof(struct sockaddr_in6);
753 if (sock.ss_family == AF_INET) {
754 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
757 res = socket(sock.ss_family, type, 0 );
760 dbgtext( "open_socket_in(): socket() call failed: " );
761 dbgtext( "%s\n", strerror( errno ) );
766 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
768 int val = rebind ? 1 : 0;
769 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
770 (char *)&val,sizeof(val)) == -1 ) {
771 if( DEBUGLVL( dlevel ) ) {
772 dbgtext( "open_socket_in(): setsockopt: " );
773 dbgtext( "SO_REUSEADDR = %s ",
774 val?"true":"false" );
775 dbgtext( "on port %d failed ", port );
776 dbgtext( "with error = %s\n", strerror(errno) );
780 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
781 (char *)&val,sizeof(val)) == -1 ) {
782 if( DEBUGLVL( dlevel ) ) {
783 dbgtext( "open_socket_in(): setsockopt: ");
784 dbgtext( "SO_REUSEPORT = %s ",
786 dbgtext( "on port %d failed ", port);
787 dbgtext( "with error = %s\n", strerror(errno));
790 #endif /* SO_REUSEPORT */
793 /* now we've got a socket - we need to bind it */
794 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
795 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
796 port == SMB_PORT2 || port == NMB_PORT) ) {
797 char addr[INET6_ADDRSTRLEN];
798 print_sockaddr(addr, sizeof(addr),
800 dbgtext( "bind failed on port %d ", port);
801 dbgtext( "socket_addr = %s.\n", addr);
802 dbgtext( "Error = %s\n", strerror(errno));
808 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
812 struct open_socket_out_state {
814 struct event_context *ev;
815 struct sockaddr_storage ss;
821 static void open_socket_out_connected(struct tevent_req *subreq);
823 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
831 /****************************************************************************
832 Create an outgoing socket. timeout is in milliseconds.
833 **************************************************************************/
835 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
836 struct event_context *ev,
837 const struct sockaddr_storage *pss,
841 char addr[INET6_ADDRSTRLEN];
842 struct tevent_req *result, *subreq;
843 struct open_socket_out_state *state;
846 result = tevent_req_create(mem_ctx, &state,
847 struct open_socket_out_state);
848 if (result == NULL) {
854 state->wait_nsec = 10000;
857 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
858 if (state->fd == -1) {
859 status = map_nt_error_from_unix(errno);
862 talloc_set_destructor(state, open_socket_out_state_destructor);
864 if (!tevent_req_set_endtime(
865 result, ev, timeval_current_ofs(0, timeout*1000))) {
869 #if defined(HAVE_IPV6)
870 if (pss->ss_family == AF_INET6) {
871 struct sockaddr_in6 *psa6;
872 psa6 = (struct sockaddr_in6 *)&state->ss;
873 psa6->sin6_port = htons(port);
874 if (psa6->sin6_scope_id == 0
875 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
876 setup_linklocal_scope_id(
877 (struct sockaddr *)&(state->ss));
879 state->salen = sizeof(struct sockaddr_in6);
882 if (pss->ss_family == AF_INET) {
883 struct sockaddr_in *psa;
884 psa = (struct sockaddr_in *)&state->ss;
885 psa->sin_port = htons(port);
886 state->salen = sizeof(struct sockaddr_in);
889 if (pss->ss_family == AF_UNIX) {
890 state->salen = sizeof(struct sockaddr_un);
893 print_sockaddr(addr, sizeof(addr), &state->ss);
894 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
896 subreq = async_connect_send(state, state->ev, state->fd,
897 (struct sockaddr *)&state->ss,
900 || !tevent_req_set_endtime(
902 timeval_current_ofs(0, state->wait_nsec))) {
905 tevent_req_set_callback(subreq, open_socket_out_connected, result);
909 tevent_req_nterror(result, status);
910 return tevent_req_post(result, ev);
916 static void open_socket_out_connected(struct tevent_req *subreq)
918 struct tevent_req *req =
919 tevent_req_callback_data(subreq, struct tevent_req);
920 struct open_socket_out_state *state =
921 tevent_req_data(req, struct open_socket_out_state);
925 ret = async_connect_recv(subreq, &sys_errno);
928 tevent_req_done(req);
934 (sys_errno == ETIMEDOUT) ||
936 (sys_errno == EINPROGRESS) ||
937 (sys_errno == EALREADY) ||
938 (sys_errno == EAGAIN)) {
944 if (state->wait_nsec < 250000) {
945 state->wait_nsec *= 1.5;
948 subreq = async_connect_send(state, state->ev, state->fd,
949 (struct sockaddr *)&state->ss,
951 if (tevent_req_nomem(subreq, req)) {
954 if (!tevent_req_set_endtime(
956 timeval_current_ofs(0, state->wait_nsec))) {
957 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
960 tevent_req_set_callback(subreq, open_socket_out_connected, req);
965 if (sys_errno == EISCONN) {
966 tevent_req_done(req);
972 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
975 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
977 struct open_socket_out_state *state =
978 tevent_req_data(req, struct open_socket_out_state);
981 if (tevent_req_is_nterror(req, &status)) {
989 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
990 int timeout, int *pfd)
992 TALLOC_CTX *frame = talloc_stackframe();
993 struct event_context *ev;
994 struct tevent_req *req;
995 NTSTATUS status = NT_STATUS_NO_MEMORY;
997 ev = event_context_init(frame);
1002 req = open_socket_out_send(frame, ev, pss, port, timeout);
1006 if (!tevent_req_poll(req, ev)) {
1007 status = NT_STATUS_INTERNAL_ERROR;
1010 status = open_socket_out_recv(req, pfd);
1016 struct open_socket_out_defer_state {
1017 struct event_context *ev;
1018 struct sockaddr_storage ss;
1024 static void open_socket_out_defer_waited(struct tevent_req *subreq);
1025 static void open_socket_out_defer_connected(struct tevent_req *subreq);
1027 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
1028 struct event_context *ev,
1029 struct timeval wait_time,
1030 const struct sockaddr_storage *pss,
1034 struct tevent_req *req, *subreq;
1035 struct open_socket_out_defer_state *state;
1037 req = tevent_req_create(mem_ctx, &state,
1038 struct open_socket_out_defer_state);
1045 state->timeout = timeout;
1047 subreq = tevent_wakeup_send(
1049 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
1050 if (subreq == NULL) {
1053 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
1060 static void open_socket_out_defer_waited(struct tevent_req *subreq)
1062 struct tevent_req *req = tevent_req_callback_data(
1063 subreq, struct tevent_req);
1064 struct open_socket_out_defer_state *state = tevent_req_data(
1065 req, struct open_socket_out_defer_state);
1068 ret = tevent_wakeup_recv(subreq);
1069 TALLOC_FREE(subreq);
1071 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1075 subreq = open_socket_out_send(state, state->ev, &state->ss,
1076 state->port, state->timeout);
1077 if (tevent_req_nomem(subreq, req)) {
1080 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
1083 static void open_socket_out_defer_connected(struct tevent_req *subreq)
1085 struct tevent_req *req = tevent_req_callback_data(
1086 subreq, struct tevent_req);
1087 struct open_socket_out_defer_state *state = tevent_req_data(
1088 req, struct open_socket_out_defer_state);
1091 status = open_socket_out_recv(subreq, &state->fd);
1092 TALLOC_FREE(subreq);
1093 if (!NT_STATUS_IS_OK(status)) {
1094 tevent_req_nterror(req, status);
1097 tevent_req_done(req);
1100 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
1102 struct open_socket_out_defer_state *state = tevent_req_data(
1103 req, struct open_socket_out_defer_state);
1106 if (tevent_req_is_nterror(req, &status)) {
1111 return NT_STATUS_OK;
1114 /****************************************************************************
1115 Open a connected UDP socket to host on port
1116 **************************************************************************/
1118 int open_udp_socket(const char *host, int port)
1120 struct sockaddr_storage ss;
1123 if (!interpret_string_addr(&ss, host, 0)) {
1124 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1129 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1134 #if defined(HAVE_IPV6)
1135 if (ss.ss_family == AF_INET6) {
1136 struct sockaddr_in6 *psa6;
1137 psa6 = (struct sockaddr_in6 *)&ss;
1138 psa6->sin6_port = htons(port);
1139 if (psa6->sin6_scope_id == 0
1140 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1141 setup_linklocal_scope_id(
1142 (struct sockaddr *)&ss);
1146 if (ss.ss_family == AF_INET) {
1147 struct sockaddr_in *psa;
1148 psa = (struct sockaddr_in *)&ss;
1149 psa->sin_port = htons(port);
1152 if (sys_connect(res,(struct sockaddr *)&ss)) {
1160 /*******************************************************************
1161 Return the IP addr of the remote end of a socket as a string.
1162 Optionally return the struct sockaddr_storage.
1163 ******************************************************************/
1165 static const char *get_peer_addr_internal(int fd,
1167 size_t addr_buf_len,
1168 struct sockaddr *pss,
1171 struct sockaddr_storage ss;
1172 socklen_t length = sizeof(ss);
1174 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1181 pss = (struct sockaddr *)&ss;
1185 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1186 int level = (errno == ENOTCONN) ? 2 : 0;
1187 DEBUG(level, ("getpeername failed. Error was %s\n",
1192 print_sockaddr_len(addr_buf,
1199 /*******************************************************************
1200 Matchname - determine if host name matches IP address. Used to
1201 confirm a hostname lookup to prevent spoof attacks.
1202 ******************************************************************/
1204 static bool matchname(const char *remotehost,
1205 const struct sockaddr *pss,
1208 struct addrinfo *res = NULL;
1209 struct addrinfo *ailist = NULL;
1210 char addr_buf[INET6_ADDRSTRLEN];
1211 bool ret = interpret_string_addr_internal(&ailist,
1213 AI_ADDRCONFIG|AI_CANONNAME);
1215 if (!ret || ailist == NULL) {
1216 DEBUG(3,("matchname: getaddrinfo failed for "
1219 gai_strerror(ret) ));
1224 * Make sure that getaddrinfo() returns the "correct" host name.
1227 if (ailist->ai_canonname == NULL ||
1228 (!strequal(remotehost, ailist->ai_canonname) &&
1229 !strequal(remotehost, "localhost"))) {
1230 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1232 ailist->ai_canonname ?
1233 ailist->ai_canonname : "(NULL)"));
1234 freeaddrinfo(ailist);
1238 /* Look up the host address in the address list we just got. */
1239 for (res = ailist; res; res = res->ai_next) {
1240 if (!res->ai_addr) {
1243 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1244 (struct sockaddr *)pss)) {
1245 freeaddrinfo(ailist);
1251 * The host name does not map to the original host address. Perhaps
1252 * someone has compromised a name server. More likely someone botched
1253 * it, but that could be dangerous, too.
1256 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1257 print_sockaddr_len(addr_buf,
1261 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1264 freeaddrinfo(ailist);
1269 /*******************************************************************
1270 Deal with the singleton cache.
1271 ******************************************************************/
1273 struct name_addr_pair {
1274 struct sockaddr_storage ss;
1278 /*******************************************************************
1279 Lookup a name/addr pair. Returns memory allocated from memcache.
1280 ******************************************************************/
1282 static bool lookup_nc(struct name_addr_pair *nc)
1288 if (!memcache_lookup(
1289 NULL, SINGLETON_CACHE,
1290 data_blob_string_const_null("get_peer_name"),
1295 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1296 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1300 /*******************************************************************
1301 Save a name/addr pair.
1302 ******************************************************************/
1304 static void store_nc(const struct name_addr_pair *nc)
1307 size_t namelen = strlen(nc->name);
1309 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1313 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1314 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1316 memcache_add(NULL, SINGLETON_CACHE,
1317 data_blob_string_const_null("get_peer_name"),
1319 data_blob_free(&tmp);
1322 /*******************************************************************
1323 Return the DNS name of the remote end of a socket.
1324 ******************************************************************/
1326 const char *get_peer_name(int fd, bool force_lookup)
1328 struct name_addr_pair nc;
1329 char addr_buf[INET6_ADDRSTRLEN];
1330 struct sockaddr_storage ss;
1331 socklen_t length = sizeof(ss);
1334 char name_buf[MAX_DNS_NAME_LENGTH];
1335 char tmp_name[MAX_DNS_NAME_LENGTH];
1337 /* reverse lookups can be *very* expensive, and in many
1338 situations won't work because many networks don't link dhcp
1339 with dns. To avoid the delay we avoid the lookup if
1341 if (!lp_hostname_lookups() && (force_lookup == false)) {
1342 length = sizeof(nc.ss);
1343 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1344 (struct sockaddr *)&nc.ss, &length);
1347 return nc.name ? nc.name : "UNKNOWN";
1352 memset(&ss, '\0', sizeof(ss));
1353 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1355 /* it might be the same as the last one - save some DNS work */
1356 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1357 return nc.name ? nc.name : "UNKNOWN";
1360 /* Not the same. We need to lookup. */
1365 /* Look up the remote host name. */
1366 ret = sys_getnameinfo((struct sockaddr *)&ss,
1375 DEBUG(1,("get_peer_name: getnameinfo failed "
1376 "for %s with error %s\n",
1378 gai_strerror(ret)));
1379 strlcpy(name_buf, p, sizeof(name_buf));
1381 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1382 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1383 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1387 /* can't pass the same source and dest strings in when you
1388 use --enable-developer or the clobber_region() call will
1391 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1392 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1393 if (strstr(name_buf,"..")) {
1394 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1402 return nc.name ? nc.name : "UNKNOWN";
1405 /*******************************************************************
1406 Return the IP addr of the remote end of a socket as a string.
1407 ******************************************************************/
1409 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1411 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1414 /*******************************************************************
1415 Create protected unix domain socket.
1417 Some unixes cannot set permissions on a ux-dom-sock, so we
1418 have to make sure that the directory contains the protection
1419 permissions instead.
1420 ******************************************************************/
1422 int create_pipe_sock(const char *socket_dir,
1423 const char *socket_name,
1426 #ifdef HAVE_UNIXSOCKET
1427 struct sockaddr_un sunaddr;
1433 old_umask = umask(0);
1435 /* Create the socket directory or reuse the existing one */
1437 if (lstat(socket_dir, &st) == -1) {
1438 if (errno == ENOENT) {
1439 /* Create directory */
1440 if (mkdir(socket_dir, dir_perms) == -1) {
1441 DEBUG(0, ("error creating socket directory "
1442 "%s: %s\n", socket_dir,
1447 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1448 socket_dir, strerror(errno)));
1452 /* Check ownership and permission on existing directory */
1453 if (!S_ISDIR(st.st_mode)) {
1454 DEBUG(0, ("socket directory %s isn't a directory\n",
1458 if ((st.st_uid != sec_initial_uid()) ||
1459 ((st.st_mode & 0777) != dir_perms)) {
1460 DEBUG(0, ("invalid permissions on socket directory "
1461 "%s\n", socket_dir));
1466 /* Create the socket file */
1468 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1471 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1476 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1481 memset(&sunaddr, 0, sizeof(sunaddr));
1482 sunaddr.sun_family = AF_UNIX;
1483 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1485 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1486 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1491 if (listen(sock, 5) == -1) {
1492 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1512 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1514 #endif /* HAVE_UNIXSOCKET */
1517 /****************************************************************************
1518 Get my own canonical name, including domain.
1519 ****************************************************************************/
1521 const char *get_mydnsfullname(void)
1523 struct addrinfo *res = NULL;
1524 char my_hostname[HOST_NAME_MAX];
1528 if (memcache_lookup(NULL, SINGLETON_CACHE,
1529 data_blob_string_const_null("get_mydnsfullname"),
1531 SMB_ASSERT(tmp.length > 0);
1532 return (const char *)tmp.data;
1535 /* get my host name */
1536 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1537 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1541 /* Ensure null termination. */
1542 my_hostname[sizeof(my_hostname)-1] = '\0';
1544 ret = interpret_string_addr_internal(&res,
1546 AI_ADDRCONFIG|AI_CANONNAME);
1548 if (!ret || res == NULL) {
1549 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1552 gai_strerror(ret) ));
1557 * Make sure that getaddrinfo() returns the "correct" host name.
1560 if (res->ai_canonname == NULL) {
1561 DEBUG(3,("get_mydnsfullname: failed to get "
1562 "canonical name for %s\n",
1568 /* This copies the data, so we must do a lookup
1569 * afterwards to find the value to return.
1572 memcache_add(NULL, SINGLETON_CACHE,
1573 data_blob_string_const_null("get_mydnsfullname"),
1574 data_blob_string_const_null(res->ai_canonname));
1576 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1577 data_blob_string_const_null("get_mydnsfullname"),
1579 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1580 strlen(res->ai_canonname) + 1);
1585 return (const char *)tmp.data;
1588 /************************************************************
1590 ************************************************************/
1592 bool is_myname_or_ipaddr(const char *s)
1594 TALLOC_CTX *ctx = talloc_tos();
1595 char addr[INET6_ADDRSTRLEN];
1597 const char *dnsname;
1598 char *servername = NULL;
1604 /* Santize the string from '\\name' */
1605 name = talloc_strdup(ctx, s);
1610 servername = strrchr_m(name, '\\' );
1617 /* Optimize for the common case */
1618 if (strequal(servername, global_myname())) {
1622 /* Check for an alias */
1623 if (is_myname(servername)) {
1627 /* Check for loopback */
1628 if (strequal(servername, "127.0.0.1") ||
1629 strequal(servername, "::1")) {
1633 if (strequal(servername, "localhost")) {
1637 /* Maybe it's my dns name */
1638 dnsname = get_mydnsfullname();
1639 if (dnsname && strequal(servername, dnsname)) {
1643 /* Handle possible CNAME records - convert to an IP addr. */
1644 if (!is_ipaddress(servername)) {
1645 /* Use DNS to resolve the name, but only the first address */
1646 struct sockaddr_storage ss;
1647 if (interpret_string_addr(&ss, servername, 0)) {
1648 print_sockaddr(addr,
1655 /* Maybe its an IP address? */
1656 if (is_ipaddress(servername)) {
1657 struct sockaddr_storage ss;
1658 struct iface_struct *nics;
1661 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
1665 if (ismyaddr((struct sockaddr *)&ss)) {
1669 if (is_zero_addr((struct sockaddr *)&ss) ||
1670 is_loopback_addr((struct sockaddr *)&ss)) {
1674 n = get_interfaces(talloc_tos(), &nics);
1675 for (i=0; i<n; i++) {
1676 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1688 struct getaddrinfo_state {
1690 const char *service;
1691 const struct addrinfo *hints;
1692 struct addrinfo *res;
1696 static void getaddrinfo_do(void *private_data);
1697 static void getaddrinfo_done(struct tevent_req *subreq);
1699 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1700 struct tevent_context *ev,
1701 struct fncall_context *ctx,
1703 const char *service,
1704 const struct addrinfo *hints)
1706 struct tevent_req *req, *subreq;
1707 struct getaddrinfo_state *state;
1709 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1715 state->service = service;
1716 state->hints = hints;
1718 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1719 if (tevent_req_nomem(subreq, req)) {
1720 return tevent_req_post(req, ev);
1722 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1726 static void getaddrinfo_do(void *private_data)
1728 struct getaddrinfo_state *state =
1729 (struct getaddrinfo_state *)private_data;
1731 state->ret = getaddrinfo(state->node, state->service, state->hints,
1735 static void getaddrinfo_done(struct tevent_req *subreq)
1737 struct tevent_req *req = tevent_req_callback_data(
1738 subreq, struct tevent_req);
1741 ret = fncall_recv(subreq, &err);
1742 TALLOC_FREE(subreq);
1744 tevent_req_error(req, err);
1747 tevent_req_done(req);
1750 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1752 struct getaddrinfo_state *state = tevent_req_data(
1753 req, struct getaddrinfo_state);
1756 if (tevent_req_is_unix_error(req, &err)) {
1764 if (state->ret == 0) {