2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Tim Potter 2000-2001
6 Copyright (C) Jeremy Allison 1992-2007
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "system/filesys.h"
25 #include "../lib/async_req/async_sock.h"
26 #include "../lib/util/select.h"
27 #include "lib/socket/interfaces.h"
28 #include "../lib/util/tevent_unix.h"
29 #include "../lib/util/tevent_ntstatus.h"
30 #include "../lib/tsocket/tsocket.h"
32 const char *client_name(int fd)
34 return get_peer_name(fd,false);
37 const char *client_addr(int fd, char *addr, size_t addrlen)
39 return get_peer_addr(fd,addr,addrlen);
43 /* Not currently used. JRA. */
44 int client_socket_port(int fd)
46 return get_socket_port(fd);
50 /****************************************************************************
51 Accessor functions to make thread-safe code easier later...
52 ****************************************************************************/
54 void set_smb_read_error(enum smb_read_errors *pre,
55 enum smb_read_errors newerr)
62 void cond_set_smb_read_error(enum smb_read_errors *pre,
63 enum smb_read_errors newerr)
65 if (pre && *pre == SMB_READ_OK) {
70 /****************************************************************************
71 Determine if a file descriptor is in fact a socket.
72 ****************************************************************************/
74 bool is_a_socket(int fd)
79 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
82 /****************************************************************************
84 ****************************************************************************/
86 ssize_t read_udp_v4_socket(int fd,
89 struct sockaddr_storage *psa)
92 socklen_t socklen = sizeof(*psa);
93 struct sockaddr_in *si = (struct sockaddr_in *)psa;
95 memset((char *)psa,'\0',socklen);
97 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
98 (struct sockaddr *)psa,&socklen);
100 /* Don't print a low debug error for a non-blocking socket. */
101 if (errno == EAGAIN) {
102 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
104 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
110 if (psa->ss_family != AF_INET) {
111 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
112 "(not IPv4)\n", (int)psa->ss_family));
116 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
117 inet_ntoa(si->sin_addr),
119 (unsigned long)ret));
124 /****************************************************************************
125 Read data from a file descriptor with a timout in msec.
126 mincount = if timeout, minimum to read before returning
127 maxcount = number to be read.
128 time_out = timeout in milliseconds
129 NB. This can be called with a non-socket fd, don't change
130 sys_read() to sys_recv() or other socket call.
131 ****************************************************************************/
133 NTSTATUS read_fd_with_timeout(int fd, char *buf,
134 size_t mincnt, size_t maxcnt,
135 unsigned int time_out,
142 /* just checking .... */
152 while (nread < mincnt) {
153 readret = sys_read(fd, buf + nread, maxcnt - nread);
156 DEBUG(5,("read_fd_with_timeout: "
157 "blocking read. EOF from client.\n"));
158 return NT_STATUS_END_OF_FILE;
162 return map_nt_error_from_unix(errno);
169 /* Most difficult - timeout read */
170 /* If this is ever called on a disk file and
171 mincnt is greater then the filesize then
172 system performance will suffer severely as
173 select always returns true on disk files */
175 for (nread=0; nread < mincnt; ) {
178 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
183 return map_nt_error_from_unix(errno);
186 /* Did we timeout ? */
187 if ((pollrtn == 0) ||
188 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
189 DEBUG(10,("read_fd_with_timeout: timeout read. "
190 "select timed out.\n"));
191 return NT_STATUS_IO_TIMEOUT;
194 readret = sys_read(fd, buf+nread, maxcnt-nread);
197 /* we got EOF on the file descriptor */
198 DEBUG(5,("read_fd_with_timeout: timeout read. "
199 "EOF from client.\n"));
200 return NT_STATUS_END_OF_FILE;
204 return map_nt_error_from_unix(errno);
211 /* Return the number we got */
218 /****************************************************************************
219 Read data from an fd, reading exactly N bytes.
220 NB. This can be called with a non-socket fd, don't add dependencies
222 ****************************************************************************/
224 NTSTATUS read_data(int fd, char *buffer, size_t N)
226 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
229 /****************************************************************************
230 Write all data from an iov array
231 NB. This can be called with a non-socket fd, don't add dependencies
233 ****************************************************************************/
235 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
241 struct iovec *iov_copy, *iov;
244 for (i=0; i<iovcnt; i++) {
245 to_send += orig_iov[i].iov_len;
248 thistime = sys_writev(fd, orig_iov, iovcnt);
249 if ((thistime <= 0) || (thistime == to_send)) {
255 * We could not send everything in one call. Make a copy of iov that
256 * we can mess with. We keep a copy of the array start in iov_copy for
257 * the TALLOC_FREE, because we're going to modify iov later on,
258 * discarding elements.
261 iov_copy = (struct iovec *)talloc_memdup(
262 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
264 if (iov_copy == NULL) {
270 while (sent < to_send) {
272 * We have to discard "thistime" bytes from the beginning
273 * iov array, "thistime" contains the number of bytes sent
276 while (thistime > 0) {
277 if (thistime < iov[0].iov_len) {
279 (char *)iov[0].iov_base + thistime;
280 iov[0].iov_base = (void *)new_base;
281 iov[0].iov_len -= thistime;
284 thistime -= iov[0].iov_len;
289 thistime = sys_writev(fd, iov, iovcnt);
296 TALLOC_FREE(iov_copy);
300 /****************************************************************************
302 NB. This can be called with a non-socket fd, don't add dependencies
304 ****************************************************************************/
306 ssize_t write_data(int fd, const char *buffer, size_t N)
310 iov.iov_base = discard_const_p(void, buffer);
312 return write_data_iov(fd, &iov, 1);
315 /****************************************************************************
316 Send a keepalive packet (rfc1002).
317 ****************************************************************************/
319 bool send_keepalive(int client)
321 unsigned char buf[4];
323 buf[0] = SMBkeepalive;
324 buf[1] = buf[2] = buf[3] = 0;
326 return(write_data(client,(char *)buf,4) == 4);
329 /****************************************************************************
330 Read 4 bytes of a smb packet and return the smb length of the packet.
331 Store the result in the buffer.
332 This version of the function will return a length of zero on receiving
334 Timeout is in milliseconds.
335 ****************************************************************************/
337 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
338 unsigned int timeout,
344 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
346 if (!NT_STATUS_IS_OK(status)) {
350 *len = smb_len(inbuf);
351 msg_type = CVAL(inbuf,0);
353 if (msg_type == SMBkeepalive) {
354 DEBUG(5,("Got keepalive packet\n"));
357 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
362 /****************************************************************************
363 Read an smb from a fd.
364 The timeout is in milliseconds.
365 This function will return on receipt of a session keepalive packet.
366 maxlen is the max number of bytes to return, not including the 4 byte
367 length. If zero it means buflen limit.
368 Doesn't check the MAC on signed packets.
369 ****************************************************************************/
371 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
372 size_t maxlen, size_t *p_len)
377 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
379 if (!NT_STATUS_IS_OK(status)) {
380 DEBUG(0, ("read_fd_with_timeout failed, read "
381 "error = %s.\n", nt_errstr(status)));
386 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
387 (unsigned long)len));
388 return NT_STATUS_INVALID_PARAMETER;
393 len = MIN(len,maxlen);
396 status = read_fd_with_timeout(
397 fd, buffer+4, len, len, timeout, &len);
399 if (!NT_STATUS_IS_OK(status)) {
400 DEBUG(0, ("read_fd_with_timeout failed, read error = "
401 "%s.\n", nt_errstr(status)));
405 /* not all of samba3 properly checks for packet-termination
406 * of strings. This ensures that we don't run off into
408 SSVAL(buffer+4,len, 0);
415 /****************************************************************************
416 Open a socket of the specified type, port, and address for incoming data.
417 ****************************************************************************/
419 int open_socket_in(int type,
422 const struct sockaddr_storage *psock,
425 struct sockaddr_storage sock;
427 socklen_t slen = sizeof(struct sockaddr_in);
431 #if defined(HAVE_IPV6)
432 if (sock.ss_family == AF_INET6) {
433 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
434 slen = sizeof(struct sockaddr_in6);
437 if (sock.ss_family == AF_INET) {
438 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
441 res = socket(sock.ss_family, type, 0 );
444 dbgtext( "open_socket_in(): socket() call failed: " );
445 dbgtext( "%s\n", strerror( errno ) );
450 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
452 int val = rebind ? 1 : 0;
453 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
454 (char *)&val,sizeof(val)) == -1 ) {
455 if( DEBUGLVL( dlevel ) ) {
456 dbgtext( "open_socket_in(): setsockopt: " );
457 dbgtext( "SO_REUSEADDR = %s ",
458 val?"true":"false" );
459 dbgtext( "on port %d failed ", port );
460 dbgtext( "with error = %s\n", strerror(errno) );
464 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
465 (char *)&val,sizeof(val)) == -1 ) {
466 if( DEBUGLVL( dlevel ) ) {
467 dbgtext( "open_socket_in(): setsockopt: ");
468 dbgtext( "SO_REUSEPORT = %s ",
470 dbgtext( "on port %d failed ", port);
471 dbgtext( "with error = %s\n", strerror(errno));
474 #endif /* SO_REUSEPORT */
479 * As IPV6_V6ONLY is the default on some systems,
480 * we better try to be consistent and always use it.
482 * This also avoids using IPv4 via AF_INET6 sockets
483 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
486 if (sock.ss_family == AF_INET6) {
490 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
491 (const void *)&val, sizeof(val));
494 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
495 dbgtext("%s\n", strerror(errno));
503 /* now we've got a socket - we need to bind it */
504 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
505 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
506 port == SMB_PORT2 || port == NMB_PORT) ) {
507 char addr[INET6_ADDRSTRLEN];
508 print_sockaddr(addr, sizeof(addr),
510 dbgtext( "bind failed on port %d ", port);
511 dbgtext( "socket_addr = %s.\n", addr);
512 dbgtext( "Error = %s\n", strerror(errno));
518 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
522 struct open_socket_out_state {
524 struct event_context *ev;
525 struct sockaddr_storage ss;
531 static void open_socket_out_connected(struct tevent_req *subreq);
533 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
541 /****************************************************************************
542 Create an outgoing socket. timeout is in milliseconds.
543 **************************************************************************/
545 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
546 struct event_context *ev,
547 const struct sockaddr_storage *pss,
551 char addr[INET6_ADDRSTRLEN];
552 struct tevent_req *result, *subreq;
553 struct open_socket_out_state *state;
556 result = tevent_req_create(mem_ctx, &state,
557 struct open_socket_out_state);
558 if (result == NULL) {
564 state->wait_usec = 10000;
567 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
568 if (state->fd == -1) {
569 status = map_nt_error_from_unix(errno);
572 talloc_set_destructor(state, open_socket_out_state_destructor);
574 if (!tevent_req_set_endtime(
575 result, ev, timeval_current_ofs_msec(timeout))) {
579 #if defined(HAVE_IPV6)
580 if (pss->ss_family == AF_INET6) {
581 struct sockaddr_in6 *psa6;
582 psa6 = (struct sockaddr_in6 *)&state->ss;
583 psa6->sin6_port = htons(port);
584 if (psa6->sin6_scope_id == 0
585 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
586 setup_linklocal_scope_id(
587 (struct sockaddr *)&(state->ss));
589 state->salen = sizeof(struct sockaddr_in6);
592 if (pss->ss_family == AF_INET) {
593 struct sockaddr_in *psa;
594 psa = (struct sockaddr_in *)&state->ss;
595 psa->sin_port = htons(port);
596 state->salen = sizeof(struct sockaddr_in);
599 if (pss->ss_family == AF_UNIX) {
600 state->salen = sizeof(struct sockaddr_un);
603 print_sockaddr(addr, sizeof(addr), &state->ss);
604 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
606 subreq = async_connect_send(state, state->ev, state->fd,
607 (struct sockaddr *)&state->ss,
610 || !tevent_req_set_endtime(
612 timeval_current_ofs(0, state->wait_usec))) {
615 tevent_req_set_callback(subreq, open_socket_out_connected, result);
619 tevent_req_nterror(result, status);
620 return tevent_req_post(result, ev);
626 static void open_socket_out_connected(struct tevent_req *subreq)
628 struct tevent_req *req =
629 tevent_req_callback_data(subreq, struct tevent_req);
630 struct open_socket_out_state *state =
631 tevent_req_data(req, struct open_socket_out_state);
635 ret = async_connect_recv(subreq, &sys_errno);
638 tevent_req_done(req);
644 (sys_errno == ETIMEDOUT) ||
646 (sys_errno == EINPROGRESS) ||
647 (sys_errno == EALREADY) ||
648 (sys_errno == EAGAIN)) {
654 if (state->wait_usec < 250000) {
655 state->wait_usec *= 1.5;
658 subreq = async_connect_send(state, state->ev, state->fd,
659 (struct sockaddr *)&state->ss,
661 if (tevent_req_nomem(subreq, req)) {
664 if (!tevent_req_set_endtime(
666 timeval_current_ofs_usec(state->wait_usec))) {
667 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
670 tevent_req_set_callback(subreq, open_socket_out_connected, req);
675 if (sys_errno == EISCONN) {
676 tevent_req_done(req);
682 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
685 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
687 struct open_socket_out_state *state =
688 tevent_req_data(req, struct open_socket_out_state);
691 if (tevent_req_is_nterror(req, &status)) {
700 * @brief open a socket
702 * @param pss a struct sockaddr_storage defining the address to connect to
703 * @param port to connect to
704 * @param timeout in MILLISECONDS
705 * @param pfd file descriptor returned
707 * @return NTSTATUS code
709 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
710 int timeout, int *pfd)
712 TALLOC_CTX *frame = talloc_stackframe();
713 struct event_context *ev;
714 struct tevent_req *req;
715 NTSTATUS status = NT_STATUS_NO_MEMORY;
717 ev = event_context_init(frame);
722 req = open_socket_out_send(frame, ev, pss, port, timeout);
726 if (!tevent_req_poll(req, ev)) {
727 status = NT_STATUS_INTERNAL_ERROR;
730 status = open_socket_out_recv(req, pfd);
736 struct open_socket_out_defer_state {
737 struct event_context *ev;
738 struct sockaddr_storage ss;
744 static void open_socket_out_defer_waited(struct tevent_req *subreq);
745 static void open_socket_out_defer_connected(struct tevent_req *subreq);
747 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
748 struct event_context *ev,
749 struct timeval wait_time,
750 const struct sockaddr_storage *pss,
754 struct tevent_req *req, *subreq;
755 struct open_socket_out_defer_state *state;
757 req = tevent_req_create(mem_ctx, &state,
758 struct open_socket_out_defer_state);
765 state->timeout = timeout;
767 subreq = tevent_wakeup_send(
769 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
770 if (subreq == NULL) {
773 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
780 static void open_socket_out_defer_waited(struct tevent_req *subreq)
782 struct tevent_req *req = tevent_req_callback_data(
783 subreq, struct tevent_req);
784 struct open_socket_out_defer_state *state = tevent_req_data(
785 req, struct open_socket_out_defer_state);
788 ret = tevent_wakeup_recv(subreq);
791 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
795 subreq = open_socket_out_send(state, state->ev, &state->ss,
796 state->port, state->timeout);
797 if (tevent_req_nomem(subreq, req)) {
800 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
803 static void open_socket_out_defer_connected(struct tevent_req *subreq)
805 struct tevent_req *req = tevent_req_callback_data(
806 subreq, struct tevent_req);
807 struct open_socket_out_defer_state *state = tevent_req_data(
808 req, struct open_socket_out_defer_state);
811 status = open_socket_out_recv(subreq, &state->fd);
813 if (!NT_STATUS_IS_OK(status)) {
814 tevent_req_nterror(req, status);
817 tevent_req_done(req);
820 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
822 struct open_socket_out_defer_state *state = tevent_req_data(
823 req, struct open_socket_out_defer_state);
826 if (tevent_req_is_nterror(req, &status)) {
834 /****************************************************************************
835 Open a connected UDP socket to host on port
836 **************************************************************************/
838 int open_udp_socket(const char *host, int port)
840 struct sockaddr_storage ss;
843 if (!interpret_string_addr(&ss, host, 0)) {
844 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
849 res = socket(ss.ss_family, SOCK_DGRAM, 0);
854 #if defined(HAVE_IPV6)
855 if (ss.ss_family == AF_INET6) {
856 struct sockaddr_in6 *psa6;
857 psa6 = (struct sockaddr_in6 *)&ss;
858 psa6->sin6_port = htons(port);
859 if (psa6->sin6_scope_id == 0
860 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
861 setup_linklocal_scope_id(
862 (struct sockaddr *)&ss);
866 if (ss.ss_family == AF_INET) {
867 struct sockaddr_in *psa;
868 psa = (struct sockaddr_in *)&ss;
869 psa->sin_port = htons(port);
872 if (sys_connect(res,(struct sockaddr *)&ss)) {
880 /*******************************************************************
881 Return the IP addr of the remote end of a socket as a string.
882 Optionally return the struct sockaddr_storage.
883 ******************************************************************/
885 static const char *get_peer_addr_internal(int fd,
888 struct sockaddr *pss,
891 struct sockaddr_storage ss;
892 socklen_t length = sizeof(ss);
894 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
901 pss = (struct sockaddr *)&ss;
905 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
906 int level = (errno == ENOTCONN) ? 2 : 0;
907 DEBUG(level, ("getpeername failed. Error was %s\n",
912 print_sockaddr_len(addr_buf,
919 /*******************************************************************
920 Matchname - determine if host name matches IP address. Used to
921 confirm a hostname lookup to prevent spoof attacks.
922 ******************************************************************/
924 static bool matchname(const char *remotehost,
925 const struct sockaddr *pss,
928 struct addrinfo *res = NULL;
929 struct addrinfo *ailist = NULL;
930 char addr_buf[INET6_ADDRSTRLEN];
931 bool ret = interpret_string_addr_internal(&ailist,
933 AI_ADDRCONFIG|AI_CANONNAME);
935 if (!ret || ailist == NULL) {
936 DEBUG(3,("matchname: getaddrinfo failed for "
939 gai_strerror(ret) ));
944 * Make sure that getaddrinfo() returns the "correct" host name.
947 if (ailist->ai_canonname == NULL ||
948 (!strequal(remotehost, ailist->ai_canonname) &&
949 !strequal(remotehost, "localhost"))) {
950 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
952 ailist->ai_canonname ?
953 ailist->ai_canonname : "(NULL)"));
954 freeaddrinfo(ailist);
958 /* Look up the host address in the address list we just got. */
959 for (res = ailist; res; res = res->ai_next) {
963 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
964 (const struct sockaddr *)pss)) {
965 freeaddrinfo(ailist);
971 * The host name does not map to the original host address. Perhaps
972 * someone has compromised a name server. More likely someone botched
973 * it, but that could be dangerous, too.
976 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
977 print_sockaddr_len(addr_buf,
981 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
984 freeaddrinfo(ailist);
989 /*******************************************************************
990 Deal with the singleton cache.
991 ******************************************************************/
993 struct name_addr_pair {
994 struct sockaddr_storage ss;
998 /*******************************************************************
999 Lookup a name/addr pair. Returns memory allocated from memcache.
1000 ******************************************************************/
1002 static bool lookup_nc(struct name_addr_pair *nc)
1008 if (!memcache_lookup(
1009 NULL, SINGLETON_CACHE,
1010 data_blob_string_const_null("get_peer_name"),
1015 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1016 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1020 /*******************************************************************
1021 Save a name/addr pair.
1022 ******************************************************************/
1024 static void store_nc(const struct name_addr_pair *nc)
1027 size_t namelen = strlen(nc->name);
1029 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1033 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1034 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1036 memcache_add(NULL, SINGLETON_CACHE,
1037 data_blob_string_const_null("get_peer_name"),
1039 data_blob_free(&tmp);
1042 /*******************************************************************
1043 Return the DNS name of the remote end of a socket.
1044 ******************************************************************/
1046 const char *get_peer_name(int fd, bool force_lookup)
1048 struct name_addr_pair nc;
1049 char addr_buf[INET6_ADDRSTRLEN];
1050 struct sockaddr_storage ss;
1051 socklen_t length = sizeof(ss);
1054 char name_buf[MAX_DNS_NAME_LENGTH];
1055 char tmp_name[MAX_DNS_NAME_LENGTH];
1057 /* reverse lookups can be *very* expensive, and in many
1058 situations won't work because many networks don't link dhcp
1059 with dns. To avoid the delay we avoid the lookup if
1061 if (!lp_hostname_lookups() && (force_lookup == false)) {
1062 length = sizeof(nc.ss);
1063 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1064 (struct sockaddr *)&nc.ss, &length);
1067 return nc.name ? nc.name : "UNKNOWN";
1072 memset(&ss, '\0', sizeof(ss));
1073 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1075 /* it might be the same as the last one - save some DNS work */
1076 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1077 return nc.name ? nc.name : "UNKNOWN";
1080 /* Not the same. We need to lookup. */
1085 /* Look up the remote host name. */
1086 ret = sys_getnameinfo((struct sockaddr *)&ss,
1095 DEBUG(1,("get_peer_name: getnameinfo failed "
1096 "for %s with error %s\n",
1098 gai_strerror(ret)));
1099 strlcpy(name_buf, p, sizeof(name_buf));
1101 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1102 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1103 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1107 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1108 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1109 if (strstr(name_buf,"..")) {
1110 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1118 return nc.name ? nc.name : "UNKNOWN";
1121 /*******************************************************************
1122 Return the IP addr of the remote end of a socket as a string.
1123 ******************************************************************/
1125 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1127 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1130 int get_remote_hostname(const struct tsocket_address *remote_address,
1132 TALLOC_CTX *mem_ctx)
1134 char name_buf[MAX_DNS_NAME_LENGTH];
1135 char tmp_name[MAX_DNS_NAME_LENGTH];
1136 struct name_addr_pair nc;
1137 struct sockaddr_storage ss;
1141 if (!lp_hostname_lookups()) {
1142 nc.name = tsocket_address_inet_addr_string(remote_address,
1144 if (nc.name == NULL) {
1148 len = tsocket_address_bsd_sockaddr(remote_address,
1149 (struct sockaddr *) &nc.ss,
1150 sizeof(struct sockaddr_storage));
1158 if (nc.name == NULL) {
1159 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1161 *name = talloc_strdup(mem_ctx, nc.name);
1170 len = tsocket_address_bsd_sockaddr(remote_address,
1171 (struct sockaddr *) &ss,
1172 sizeof(struct sockaddr_storage));
1177 /* it might be the same as the last one - save some DNS work */
1178 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1179 if (nc.name == NULL) {
1180 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1182 *name = talloc_strdup(mem_ctx, nc.name);
1187 /* Look up the remote host name. */
1188 rc = sys_getnameinfo((struct sockaddr *) &ss,
1198 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1203 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1206 strlcpy(name_buf, p, sizeof(name_buf));
1210 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1211 DEBUG(0,("matchname failed on %s\n", name_buf));
1212 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1216 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1217 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1218 if (strstr(name_buf,"..")) {
1219 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1228 if (nc.name == NULL) {
1229 *name = talloc_strdup(mem_ctx, "UNKOWN");
1231 *name = talloc_strdup(mem_ctx, nc.name);
1237 /*******************************************************************
1238 Create protected unix domain socket.
1240 Some unixes cannot set permissions on a ux-dom-sock, so we
1241 have to make sure that the directory contains the protection
1242 permissions instead.
1243 ******************************************************************/
1245 int create_pipe_sock(const char *socket_dir,
1246 const char *socket_name,
1249 #ifdef HAVE_UNIXSOCKET
1250 struct sockaddr_un sunaddr;
1256 old_umask = umask(0);
1258 /* Create the socket directory or reuse the existing one */
1260 if (lstat(socket_dir, &st) == -1) {
1261 if (errno == ENOENT) {
1262 /* Create directory */
1263 if (mkdir(socket_dir, dir_perms) == -1) {
1264 DEBUG(0, ("error creating socket directory "
1265 "%s: %s\n", socket_dir,
1270 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1271 socket_dir, strerror(errno)));
1275 /* Check ownership and permission on existing directory */
1276 if (!S_ISDIR(st.st_mode)) {
1277 DEBUG(0, ("socket directory '%s' isn't a directory\n",
1281 if (st.st_uid != sec_initial_uid()) {
1282 DEBUG(0, ("invalid ownership on directory "
1283 "'%s'\n", socket_dir));
1287 if ((st.st_mode & 0777) != dir_perms) {
1288 DEBUG(0, ("invalid permissions on directory "
1289 "'%s': has 0%o should be 0%o\n", socket_dir,
1290 (st.st_mode & 0777), dir_perms));
1296 /* Create the socket file */
1298 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1301 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1306 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1311 memset(&sunaddr, 0, sizeof(sunaddr));
1312 sunaddr.sun_family = AF_UNIX;
1313 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1315 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1316 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1321 if (listen(sock, 5) == -1) {
1322 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1342 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1344 #endif /* HAVE_UNIXSOCKET */
1347 /****************************************************************************
1348 Get my own canonical name, including domain.
1349 ****************************************************************************/
1351 const char *get_mydnsfullname(void)
1353 struct addrinfo *res = NULL;
1354 char my_hostname[HOST_NAME_MAX];
1358 if (memcache_lookup(NULL, SINGLETON_CACHE,
1359 data_blob_string_const_null("get_mydnsfullname"),
1361 SMB_ASSERT(tmp.length > 0);
1362 return (const char *)tmp.data;
1365 /* get my host name */
1366 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1367 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1371 /* Ensure null termination. */
1372 my_hostname[sizeof(my_hostname)-1] = '\0';
1374 ret = interpret_string_addr_internal(&res,
1376 AI_ADDRCONFIG|AI_CANONNAME);
1378 if (!ret || res == NULL) {
1379 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1382 gai_strerror(ret) ));
1387 * Make sure that getaddrinfo() returns the "correct" host name.
1390 if (res->ai_canonname == NULL) {
1391 DEBUG(3,("get_mydnsfullname: failed to get "
1392 "canonical name for %s\n",
1398 /* This copies the data, so we must do a lookup
1399 * afterwards to find the value to return.
1402 memcache_add(NULL, SINGLETON_CACHE,
1403 data_blob_string_const_null("get_mydnsfullname"),
1404 data_blob_string_const_null(res->ai_canonname));
1406 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1407 data_blob_string_const_null("get_mydnsfullname"),
1409 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1410 strlen(res->ai_canonname) + 1);
1415 return (const char *)tmp.data;
1418 /************************************************************
1419 Is this my ip address ?
1420 ************************************************************/
1422 static bool is_my_ipaddr(const char *ipaddr_str)
1424 struct sockaddr_storage ss;
1425 struct iface_struct *nics;
1428 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1432 if (is_zero_addr(&ss)) {
1436 if (ismyaddr((struct sockaddr *)&ss) ||
1437 is_loopback_addr((struct sockaddr *)&ss)) {
1441 n = get_interfaces(talloc_tos(), &nics);
1442 for (i=0; i<n; i++) {
1443 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1452 /************************************************************
1454 ************************************************************/
1456 bool is_myname_or_ipaddr(const char *s)
1458 TALLOC_CTX *ctx = talloc_tos();
1460 const char *dnsname;
1461 char *servername = NULL;
1467 /* Santize the string from '\\name' */
1468 name = talloc_strdup(ctx, s);
1473 servername = strrchr_m(name, '\\' );
1480 /* Optimize for the common case */
1481 if (strequal(servername, lp_netbios_name())) {
1485 /* Check for an alias */
1486 if (is_myname(servername)) {
1490 /* Check for loopback */
1491 if (strequal(servername, "127.0.0.1") ||
1492 strequal(servername, "::1")) {
1496 if (strequal(servername, "localhost")) {
1500 /* Maybe it's my dns name */
1501 dnsname = get_mydnsfullname();
1502 if (dnsname && strequal(servername, dnsname)) {
1506 /* Maybe its an IP address? */
1507 if (is_ipaddress(servername)) {
1508 return is_my_ipaddr(servername);
1511 /* Handle possible CNAME records - convert to an IP addr. list. */
1513 /* Use DNS to resolve the name, check all addresses. */
1514 struct addrinfo *p = NULL;
1515 struct addrinfo *res = NULL;
1517 if (!interpret_string_addr_internal(&res,
1523 for (p = res; p; p = p->ai_next) {
1524 char addr[INET6_ADDRSTRLEN];
1525 struct sockaddr_storage ss;
1528 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1529 print_sockaddr(addr,
1532 if (is_my_ipaddr(addr)) {
1544 struct getaddrinfo_state {
1546 const char *service;
1547 const struct addrinfo *hints;
1548 struct addrinfo *res;
1552 static void getaddrinfo_do(void *private_data);
1553 static void getaddrinfo_done(struct tevent_req *subreq);
1555 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1556 struct tevent_context *ev,
1557 struct fncall_context *ctx,
1559 const char *service,
1560 const struct addrinfo *hints)
1562 struct tevent_req *req, *subreq;
1563 struct getaddrinfo_state *state;
1565 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1571 state->service = service;
1572 state->hints = hints;
1574 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1575 if (tevent_req_nomem(subreq, req)) {
1576 return tevent_req_post(req, ev);
1578 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1582 static void getaddrinfo_do(void *private_data)
1584 struct getaddrinfo_state *state =
1585 (struct getaddrinfo_state *)private_data;
1587 state->ret = getaddrinfo(state->node, state->service, state->hints,
1591 static void getaddrinfo_done(struct tevent_req *subreq)
1593 struct tevent_req *req = tevent_req_callback_data(
1594 subreq, struct tevent_req);
1597 ret = fncall_recv(subreq, &err);
1598 TALLOC_FREE(subreq);
1600 tevent_req_error(req, err);
1603 tevent_req_done(req);
1606 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1608 struct getaddrinfo_state *state = tevent_req_data(
1609 req, struct getaddrinfo_state);
1612 if (tevent_req_is_unix_error(req, &err)) {
1620 if (state->ret == 0) {
1626 int poll_one_fd(int fd, int events, int timeout, int *revents)
1632 fds = talloc_zero_array(talloc_tos(), struct pollfd, 2);
1638 fds[0].events = events;
1640 ret = sys_poll(fds, 1, timeout);
1643 * Assign whatever poll did, even in the ret<=0 case.
1645 *revents = fds[0].revents;
1646 saved_errno = errno;
1648 errno = saved_errno;
1653 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1659 pfd.events = events;
1661 ret = sys_poll_intr(&pfd, 1, timeout);
1666 *revents = pfd.revents;