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"
24 #include "../lib/util/memcache.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"
31 #include "lib/sys_rw.h"
33 const char *client_addr(int fd, char *addr, size_t addrlen)
35 return get_peer_addr(fd,addr,addrlen);
39 /* Not currently used. JRA. */
40 int client_socket_port(int fd)
42 return get_socket_port(fd);
46 /****************************************************************************
47 Determine if a file descriptor is in fact a socket.
48 ****************************************************************************/
50 bool is_a_socket(int fd)
55 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
58 /****************************************************************************
60 ****************************************************************************/
62 ssize_t read_udp_v4_socket(int fd,
65 struct sockaddr_storage *psa)
68 socklen_t socklen = sizeof(*psa);
69 struct sockaddr_in *si = (struct sockaddr_in *)psa;
71 memset((char *)psa,'\0',socklen);
73 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
74 (struct sockaddr *)psa,&socklen);
76 /* Don't print a low debug error for a non-blocking socket. */
77 if (errno == EAGAIN) {
78 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
80 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
86 if (psa->ss_family != AF_INET) {
87 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
88 "(not IPv4)\n", (int)psa->ss_family));
92 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
93 inet_ntoa(si->sin_addr),
100 /****************************************************************************
101 Read data from a file descriptor with a timout in msec.
102 mincount = if timeout, minimum to read before returning
103 maxcount = number to be read.
104 time_out = timeout in milliseconds
105 NB. This can be called with a non-socket fd, don't change
106 sys_read() to sys_recv() or other socket call.
107 ****************************************************************************/
109 NTSTATUS read_fd_with_timeout(int fd, char *buf,
110 size_t mincnt, size_t maxcnt,
111 unsigned int time_out,
118 /* just checking .... */
128 while (nread < mincnt) {
129 readret = sys_read(fd, buf + nread, maxcnt - nread);
132 DEBUG(5,("read_fd_with_timeout: "
133 "blocking read. EOF from client.\n"));
134 return NT_STATUS_END_OF_FILE;
138 return map_nt_error_from_unix(errno);
145 /* Most difficult - timeout read */
146 /* If this is ever called on a disk file and
147 mincnt is greater then the filesize then
148 system performance will suffer severely as
149 select always returns true on disk files */
151 for (nread=0; nread < mincnt; ) {
154 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
159 return map_nt_error_from_unix(errno);
162 /* Did we timeout ? */
163 if ((pollrtn == 0) ||
164 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
165 DEBUG(10,("read_fd_with_timeout: timeout read. "
166 "select timed out.\n"));
167 return NT_STATUS_IO_TIMEOUT;
170 readret = sys_read(fd, buf+nread, maxcnt-nread);
173 /* we got EOF on the file descriptor */
174 DEBUG(5,("read_fd_with_timeout: timeout read. "
175 "EOF from client.\n"));
176 return NT_STATUS_END_OF_FILE;
180 return map_nt_error_from_unix(errno);
187 /* Return the number we got */
194 /****************************************************************************
195 Read data from an fd, reading exactly N bytes.
196 NB. This can be called with a non-socket fd, don't add dependencies
198 ****************************************************************************/
200 NTSTATUS read_data(int fd, char *buffer, size_t N)
202 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
205 ssize_t iov_buflen(const struct iovec *iov, int iovcnt)
210 for (i=0; i<iovcnt; i++) {
211 size_t thislen = iov[i].iov_len;
212 size_t tmp = buflen + thislen;
214 if ((tmp < buflen) || (tmp < thislen)) {
223 uint8_t *iov_buf(TALLOC_CTX *mem_ctx, const struct iovec *iov, int iovcnt)
229 buflen = iov_buflen(iov, iovcnt);
233 buf = talloc_array(mem_ctx, uint8_t, buflen);
239 for (i=0; i<iovcnt; i++) {
240 size_t len = iov[i].iov_len;
242 memcpy(p, iov[i].iov_base, len);
248 /****************************************************************************
249 Write all data from an iov array
250 NB. This can be called with a non-socket fd, don't add dependencies
252 ****************************************************************************/
254 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
259 struct iovec iov_copy[iovcnt];
262 to_send = iov_buflen(orig_iov, iovcnt);
268 thistime = sys_writev(fd, orig_iov, iovcnt);
269 if ((thistime <= 0) || (thistime == to_send)) {
275 * We could not send everything in one call. Make a copy of iov that
276 * we can mess with. We keep a copy of the array start in iov_copy for
277 * the TALLOC_FREE, because we're going to modify iov later on,
278 * discarding elements.
281 memcpy(iov_copy, orig_iov, sizeof(struct iovec) * iovcnt);
284 while (sent < to_send) {
286 * We have to discard "thistime" bytes from the beginning
287 * iov array, "thistime" contains the number of bytes sent
290 while (thistime > 0) {
291 if (thistime < iov[0].iov_len) {
293 (char *)iov[0].iov_base + thistime;
294 iov[0].iov_base = (void *)new_base;
295 iov[0].iov_len -= thistime;
298 thistime -= iov[0].iov_len;
303 thistime = sys_writev(fd, iov, iovcnt);
313 /****************************************************************************
315 NB. This can be called with a non-socket fd, don't add dependencies
317 ****************************************************************************/
319 ssize_t write_data(int fd, const char *buffer, size_t N)
323 iov.iov_base = discard_const_p(void, buffer);
325 return write_data_iov(fd, &iov, 1);
328 /****************************************************************************
329 Send a keepalive packet (rfc1002).
330 ****************************************************************************/
332 bool send_keepalive(int client)
334 unsigned char buf[4];
336 buf[0] = NBSSkeepalive;
337 buf[1] = buf[2] = buf[3] = 0;
339 return(write_data(client,(char *)buf,4) == 4);
342 /****************************************************************************
343 Read 4 bytes of a smb packet and return the smb length of the packet.
344 Store the result in the buffer.
345 This version of the function will return a length of zero on receiving
347 Timeout is in milliseconds.
348 ****************************************************************************/
350 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
351 unsigned int timeout,
357 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
359 if (!NT_STATUS_IS_OK(status)) {
363 *len = smb_len(inbuf);
364 msg_type = CVAL(inbuf,0);
366 if (msg_type == NBSSkeepalive) {
367 DEBUG(5,("Got keepalive packet\n"));
370 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
375 /****************************************************************************
376 Read an smb from a fd.
377 The timeout is in milliseconds.
378 This function will return on receipt of a session keepalive packet.
379 maxlen is the max number of bytes to return, not including the 4 byte
380 length. If zero it means buflen limit.
381 Doesn't check the MAC on signed packets.
382 ****************************************************************************/
384 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
385 size_t maxlen, size_t *p_len)
390 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
392 if (!NT_STATUS_IS_OK(status)) {
393 DEBUG(0, ("read_fd_with_timeout failed, read "
394 "error = %s.\n", nt_errstr(status)));
399 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
400 (unsigned long)len));
401 return NT_STATUS_INVALID_PARAMETER;
406 len = MIN(len,maxlen);
409 status = read_fd_with_timeout(
410 fd, buffer+4, len, len, timeout, &len);
412 if (!NT_STATUS_IS_OK(status)) {
413 DEBUG(0, ("read_fd_with_timeout failed, read error = "
414 "%s.\n", nt_errstr(status)));
418 /* not all of samba3 properly checks for packet-termination
419 * of strings. This ensures that we don't run off into
421 SSVAL(buffer+4,len, 0);
428 /****************************************************************************
429 Open a socket of the specified type, port, and address for incoming data.
430 ****************************************************************************/
432 int open_socket_in(int type,
435 const struct sockaddr_storage *psock,
438 struct sockaddr_storage sock;
440 socklen_t slen = sizeof(struct sockaddr_in);
444 #if defined(HAVE_IPV6)
445 if (sock.ss_family == AF_INET6) {
446 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
447 slen = sizeof(struct sockaddr_in6);
450 if (sock.ss_family == AF_INET) {
451 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
454 res = socket(sock.ss_family, type, 0 );
457 dbgtext( "open_socket_in(): socket() call failed: " );
458 dbgtext( "%s\n", strerror( errno ) );
463 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
465 int val = rebind ? 1 : 0;
466 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
467 (char *)&val,sizeof(val)) == -1 ) {
468 if( DEBUGLVL( dlevel ) ) {
469 dbgtext( "open_socket_in(): setsockopt: " );
470 dbgtext( "SO_REUSEADDR = %s ",
471 val?"true":"false" );
472 dbgtext( "on port %d failed ", port );
473 dbgtext( "with error = %s\n", strerror(errno) );
477 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
478 (char *)&val,sizeof(val)) == -1 ) {
479 if( DEBUGLVL( dlevel ) ) {
480 dbgtext( "open_socket_in(): setsockopt: ");
481 dbgtext( "SO_REUSEPORT = %s ",
483 dbgtext( "on port %d failed ", port);
484 dbgtext( "with error = %s\n", strerror(errno));
487 #endif /* SO_REUSEPORT */
492 * As IPV6_V6ONLY is the default on some systems,
493 * we better try to be consistent and always use it.
495 * This also avoids using IPv4 via AF_INET6 sockets
496 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
499 if (sock.ss_family == AF_INET6) {
503 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
504 (const void *)&val, sizeof(val));
507 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
508 dbgtext("%s\n", strerror(errno));
516 /* now we've got a socket - we need to bind it */
517 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
518 if( DEBUGLVL(dlevel) && (port == NMB_PORT ||
519 port == NBT_SMB_PORT ||
520 port == TCP_SMB_PORT) ) {
521 char addr[INET6_ADDRSTRLEN];
522 print_sockaddr(addr, sizeof(addr),
524 dbgtext( "bind failed on port %d ", port);
525 dbgtext( "socket_addr = %s.\n", addr);
526 dbgtext( "Error = %s\n", strerror(errno));
532 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
536 struct open_socket_out_state {
538 struct tevent_context *ev;
539 struct sockaddr_storage ss;
545 static void open_socket_out_connected(struct tevent_req *subreq);
547 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
555 /****************************************************************************
556 Create an outgoing socket. timeout is in milliseconds.
557 **************************************************************************/
559 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
560 struct tevent_context *ev,
561 const struct sockaddr_storage *pss,
565 char addr[INET6_ADDRSTRLEN];
566 struct tevent_req *result, *subreq;
567 struct open_socket_out_state *state;
570 result = tevent_req_create(mem_ctx, &state,
571 struct open_socket_out_state);
572 if (result == NULL) {
578 state->wait_usec = 10000;
581 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
582 if (state->fd == -1) {
583 status = map_nt_error_from_unix(errno);
586 talloc_set_destructor(state, open_socket_out_state_destructor);
588 if (!tevent_req_set_endtime(
589 result, ev, timeval_current_ofs_msec(timeout))) {
593 #if defined(HAVE_IPV6)
594 if (pss->ss_family == AF_INET6) {
595 struct sockaddr_in6 *psa6;
596 psa6 = (struct sockaddr_in6 *)&state->ss;
597 psa6->sin6_port = htons(port);
598 if (psa6->sin6_scope_id == 0
599 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
600 setup_linklocal_scope_id(
601 (struct sockaddr *)&(state->ss));
603 state->salen = sizeof(struct sockaddr_in6);
606 if (pss->ss_family == AF_INET) {
607 struct sockaddr_in *psa;
608 psa = (struct sockaddr_in *)&state->ss;
609 psa->sin_port = htons(port);
610 state->salen = sizeof(struct sockaddr_in);
613 if (pss->ss_family == AF_UNIX) {
614 state->salen = sizeof(struct sockaddr_un);
617 print_sockaddr(addr, sizeof(addr), &state->ss);
618 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
620 subreq = async_connect_send(state, state->ev, state->fd,
621 (struct sockaddr *)&state->ss,
622 state->salen, NULL, NULL, NULL);
624 || !tevent_req_set_endtime(
626 timeval_current_ofs(0, state->wait_usec))) {
629 tevent_req_set_callback(subreq, open_socket_out_connected, result);
633 tevent_req_nterror(result, status);
634 return tevent_req_post(result, ev);
640 static void open_socket_out_connected(struct tevent_req *subreq)
642 struct tevent_req *req =
643 tevent_req_callback_data(subreq, struct tevent_req);
644 struct open_socket_out_state *state =
645 tevent_req_data(req, struct open_socket_out_state);
649 ret = async_connect_recv(subreq, &sys_errno);
652 tevent_req_done(req);
658 (sys_errno == ETIMEDOUT) ||
660 (sys_errno == EINPROGRESS) ||
661 (sys_errno == EALREADY) ||
662 (sys_errno == EAGAIN)) {
668 if (state->wait_usec < 250000) {
669 state->wait_usec *= 1.5;
672 subreq = async_connect_send(state, state->ev, state->fd,
673 (struct sockaddr *)&state->ss,
674 state->salen, NULL, NULL, NULL);
675 if (tevent_req_nomem(subreq, req)) {
678 if (!tevent_req_set_endtime(
680 timeval_current_ofs_usec(state->wait_usec))) {
681 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
684 tevent_req_set_callback(subreq, open_socket_out_connected, req);
689 if (sys_errno == EISCONN) {
690 tevent_req_done(req);
696 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
699 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
701 struct open_socket_out_state *state =
702 tevent_req_data(req, struct open_socket_out_state);
705 if (tevent_req_is_nterror(req, &status)) {
714 * @brief open a socket
716 * @param pss a struct sockaddr_storage defining the address to connect to
717 * @param port to connect to
718 * @param timeout in MILLISECONDS
719 * @param pfd file descriptor returned
721 * @return NTSTATUS code
723 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
724 int timeout, int *pfd)
726 TALLOC_CTX *frame = talloc_stackframe();
727 struct tevent_context *ev;
728 struct tevent_req *req;
729 NTSTATUS status = NT_STATUS_NO_MEMORY;
731 ev = samba_tevent_context_init(frame);
736 req = open_socket_out_send(frame, ev, pss, port, timeout);
740 if (!tevent_req_poll(req, ev)) {
741 status = NT_STATUS_INTERNAL_ERROR;
744 status = open_socket_out_recv(req, pfd);
750 struct open_socket_out_defer_state {
751 struct tevent_context *ev;
752 struct sockaddr_storage ss;
758 static void open_socket_out_defer_waited(struct tevent_req *subreq);
759 static void open_socket_out_defer_connected(struct tevent_req *subreq);
761 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
762 struct tevent_context *ev,
763 struct timeval wait_time,
764 const struct sockaddr_storage *pss,
768 struct tevent_req *req, *subreq;
769 struct open_socket_out_defer_state *state;
771 req = tevent_req_create(mem_ctx, &state,
772 struct open_socket_out_defer_state);
779 state->timeout = timeout;
781 subreq = tevent_wakeup_send(
783 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
784 if (subreq == NULL) {
787 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
794 static void open_socket_out_defer_waited(struct tevent_req *subreq)
796 struct tevent_req *req = tevent_req_callback_data(
797 subreq, struct tevent_req);
798 struct open_socket_out_defer_state *state = tevent_req_data(
799 req, struct open_socket_out_defer_state);
802 ret = tevent_wakeup_recv(subreq);
805 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
809 subreq = open_socket_out_send(state, state->ev, &state->ss,
810 state->port, state->timeout);
811 if (tevent_req_nomem(subreq, req)) {
814 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
817 static void open_socket_out_defer_connected(struct tevent_req *subreq)
819 struct tevent_req *req = tevent_req_callback_data(
820 subreq, struct tevent_req);
821 struct open_socket_out_defer_state *state = tevent_req_data(
822 req, struct open_socket_out_defer_state);
825 status = open_socket_out_recv(subreq, &state->fd);
827 if (!NT_STATUS_IS_OK(status)) {
828 tevent_req_nterror(req, status);
831 tevent_req_done(req);
834 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
836 struct open_socket_out_defer_state *state = tevent_req_data(
837 req, struct open_socket_out_defer_state);
840 if (tevent_req_is_nterror(req, &status)) {
848 /****************************************************************************
849 Open a connected UDP socket to host on port
850 **************************************************************************/
852 int open_udp_socket(const char *host, int port)
854 struct sockaddr_storage ss;
858 if (!interpret_string_addr(&ss, host, 0)) {
859 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
864 res = socket(ss.ss_family, SOCK_DGRAM, 0);
869 #if defined(HAVE_IPV6)
870 if (ss.ss_family == AF_INET6) {
871 struct sockaddr_in6 *psa6;
872 psa6 = (struct sockaddr_in6 *)&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 *)&ss);
879 salen = sizeof(struct sockaddr_in6);
882 if (ss.ss_family == AF_INET) {
883 struct sockaddr_in *psa;
884 psa = (struct sockaddr_in *)&ss;
885 psa->sin_port = htons(port);
886 salen = sizeof(struct sockaddr_in);
888 DEBUG(1, ("unknown socket family %d", ss.ss_family));
893 if (connect(res, (struct sockaddr *)&ss, salen)) {
901 /*******************************************************************
902 Return the IP addr of the remote end of a socket as a string.
903 Optionally return the struct sockaddr_storage.
904 ******************************************************************/
906 static const char *get_peer_addr_internal(int fd,
909 struct sockaddr *pss,
912 struct sockaddr_storage ss;
913 socklen_t length = sizeof(ss);
915 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
922 pss = (struct sockaddr *)&ss;
926 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
927 int level = (errno == ENOTCONN) ? 2 : 0;
928 DEBUG(level, ("getpeername failed. Error was %s\n",
933 print_sockaddr_len(addr_buf,
940 /*******************************************************************
941 Matchname - determine if host name matches IP address. Used to
942 confirm a hostname lookup to prevent spoof attacks.
943 ******************************************************************/
945 static bool matchname(const char *remotehost,
946 const struct sockaddr *pss,
949 struct addrinfo *res = NULL;
950 struct addrinfo *ailist = NULL;
951 char addr_buf[INET6_ADDRSTRLEN];
952 bool ret = interpret_string_addr_internal(&ailist,
954 AI_ADDRCONFIG|AI_CANONNAME);
956 if (!ret || ailist == NULL) {
957 DEBUG(3,("matchname: getaddrinfo failed for "
960 gai_strerror(ret) ));
965 * Make sure that getaddrinfo() returns the "correct" host name.
968 if (ailist->ai_canonname == NULL ||
969 (!strequal(remotehost, ailist->ai_canonname) &&
970 !strequal(remotehost, "localhost"))) {
971 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
973 ailist->ai_canonname ?
974 ailist->ai_canonname : "(NULL)"));
975 freeaddrinfo(ailist);
979 /* Look up the host address in the address list we just got. */
980 for (res = ailist; res; res = res->ai_next) {
984 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
985 (const struct sockaddr *)pss)) {
986 freeaddrinfo(ailist);
992 * The host name does not map to the original host address. Perhaps
993 * someone has compromised a name server. More likely someone botched
994 * it, but that could be dangerous, too.
997 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
998 print_sockaddr_len(addr_buf,
1002 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1005 freeaddrinfo(ailist);
1010 /*******************************************************************
1011 Deal with the singleton cache.
1012 ******************************************************************/
1014 struct name_addr_pair {
1015 struct sockaddr_storage ss;
1019 /*******************************************************************
1020 Lookup a name/addr pair. Returns memory allocated from memcache.
1021 ******************************************************************/
1023 static bool lookup_nc(struct name_addr_pair *nc)
1029 if (!memcache_lookup(
1030 NULL, SINGLETON_CACHE,
1031 data_blob_string_const_null("get_peer_name"),
1036 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1037 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1041 /*******************************************************************
1042 Save a name/addr pair.
1043 ******************************************************************/
1045 static void store_nc(const struct name_addr_pair *nc)
1048 size_t namelen = strlen(nc->name);
1050 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1054 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1055 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1057 memcache_add(NULL, SINGLETON_CACHE,
1058 data_blob_string_const_null("get_peer_name"),
1060 data_blob_free(&tmp);
1063 /*******************************************************************
1064 Return the IP addr of the remote end of a socket as a string.
1065 ******************************************************************/
1067 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1069 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1072 int get_remote_hostname(const struct tsocket_address *remote_address,
1074 TALLOC_CTX *mem_ctx)
1076 char name_buf[MAX_DNS_NAME_LENGTH];
1077 char tmp_name[MAX_DNS_NAME_LENGTH];
1078 struct name_addr_pair nc;
1079 struct sockaddr_storage ss;
1083 if (!lp_hostname_lookups()) {
1084 nc.name = tsocket_address_inet_addr_string(remote_address,
1086 if (nc.name == NULL) {
1090 len = tsocket_address_bsd_sockaddr(remote_address,
1091 (struct sockaddr *) &nc.ss,
1092 sizeof(struct sockaddr_storage));
1100 if (nc.name == NULL) {
1101 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1103 *name = talloc_strdup(mem_ctx, nc.name);
1112 len = tsocket_address_bsd_sockaddr(remote_address,
1113 (struct sockaddr *) &ss,
1114 sizeof(struct sockaddr_storage));
1119 /* it might be the same as the last one - save some DNS work */
1120 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1121 if (nc.name == NULL) {
1122 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1124 *name = talloc_strdup(mem_ctx, nc.name);
1129 /* Look up the remote host name. */
1130 rc = sys_getnameinfo((struct sockaddr *) &ss,
1140 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1145 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1148 strlcpy(name_buf, p, sizeof(name_buf));
1152 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1153 DEBUG(0,("matchname failed on %s\n", name_buf));
1154 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1158 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1159 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1160 if (strstr(name_buf,"..")) {
1161 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1170 if (nc.name == NULL) {
1171 *name = talloc_strdup(mem_ctx, "UNKOWN");
1173 *name = talloc_strdup(mem_ctx, nc.name);
1179 /*******************************************************************
1180 Create protected unix domain socket.
1182 Some unixes cannot set permissions on a ux-dom-sock, so we
1183 have to make sure that the directory contains the protection
1184 permissions instead.
1185 ******************************************************************/
1187 int create_pipe_sock(const char *socket_dir,
1188 const char *socket_name,
1191 #ifdef HAVE_UNIXSOCKET
1192 struct sockaddr_un sunaddr;
1198 old_umask = umask(0);
1200 ok = directory_create_or_exist_strict(socket_dir,
1207 /* Create the socket file */
1208 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1211 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1216 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1221 memset(&sunaddr, 0, sizeof(sunaddr));
1222 sunaddr.sun_family = AF_UNIX;
1223 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1225 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1226 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1245 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1247 #endif /* HAVE_UNIXSOCKET */
1250 /****************************************************************************
1251 Get my own canonical name, including domain.
1252 ****************************************************************************/
1254 const char *get_mydnsfullname(void)
1256 struct addrinfo *res = NULL;
1257 char my_hostname[HOST_NAME_MAX];
1261 if (memcache_lookup(NULL, SINGLETON_CACHE,
1262 data_blob_string_const_null("get_mydnsfullname"),
1264 SMB_ASSERT(tmp.length > 0);
1265 return (const char *)tmp.data;
1268 /* get my host name */
1269 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1270 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1274 /* Ensure null termination. */
1275 my_hostname[sizeof(my_hostname)-1] = '\0';
1277 ret = interpret_string_addr_internal(&res,
1279 AI_ADDRCONFIG|AI_CANONNAME);
1281 if (!ret || res == NULL) {
1282 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1285 gai_strerror(ret) ));
1290 * Make sure that getaddrinfo() returns the "correct" host name.
1293 if (res->ai_canonname == NULL) {
1294 DEBUG(3,("get_mydnsfullname: failed to get "
1295 "canonical name for %s\n",
1301 /* This copies the data, so we must do a lookup
1302 * afterwards to find the value to return.
1305 memcache_add(NULL, SINGLETON_CACHE,
1306 data_blob_string_const_null("get_mydnsfullname"),
1307 data_blob_string_const_null(res->ai_canonname));
1309 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1310 data_blob_string_const_null("get_mydnsfullname"),
1312 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1313 strlen(res->ai_canonname) + 1);
1318 return (const char *)tmp.data;
1321 /************************************************************
1322 Is this my ip address ?
1323 ************************************************************/
1325 static bool is_my_ipaddr(const char *ipaddr_str)
1327 struct sockaddr_storage ss;
1328 struct iface_struct *nics;
1331 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1335 if (is_zero_addr(&ss)) {
1339 if (ismyaddr((struct sockaddr *)&ss) ||
1340 is_loopback_addr((struct sockaddr *)&ss)) {
1344 n = get_interfaces(talloc_tos(), &nics);
1345 for (i=0; i<n; i++) {
1346 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1355 /************************************************************
1357 ************************************************************/
1359 bool is_myname_or_ipaddr(const char *s)
1361 TALLOC_CTX *ctx = talloc_tos();
1363 const char *dnsname;
1364 char *servername = NULL;
1370 /* Santize the string from '\\name' */
1371 name = talloc_strdup(ctx, s);
1376 servername = strrchr_m(name, '\\' );
1383 /* Optimize for the common case */
1384 if (strequal(servername, lp_netbios_name())) {
1388 /* Check for an alias */
1389 if (is_myname(servername)) {
1393 /* Check for loopback */
1394 if (strequal(servername, "127.0.0.1") ||
1395 strequal(servername, "::1")) {
1399 if (strequal(servername, "localhost")) {
1403 /* Maybe it's my dns name */
1404 dnsname = get_mydnsfullname();
1405 if (dnsname && strequal(servername, dnsname)) {
1409 /* Maybe its an IP address? */
1410 if (is_ipaddress(servername)) {
1411 return is_my_ipaddr(servername);
1414 /* Handle possible CNAME records - convert to an IP addr. list. */
1416 /* Use DNS to resolve the name, check all addresses. */
1417 struct addrinfo *p = NULL;
1418 struct addrinfo *res = NULL;
1420 if (!interpret_string_addr_internal(&res,
1426 for (p = res; p; p = p->ai_next) {
1427 char addr[INET6_ADDRSTRLEN];
1428 struct sockaddr_storage ss;
1431 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1432 print_sockaddr(addr,
1435 if (is_my_ipaddr(addr)) {
1447 struct getaddrinfo_state {
1449 const char *service;
1450 const struct addrinfo *hints;
1451 struct addrinfo *res;
1455 static void getaddrinfo_do(void *private_data);
1456 static void getaddrinfo_done(struct tevent_req *subreq);
1458 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1459 struct tevent_context *ev,
1460 struct fncall_context *ctx,
1462 const char *service,
1463 const struct addrinfo *hints)
1465 struct tevent_req *req, *subreq;
1466 struct getaddrinfo_state *state;
1468 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1474 state->service = service;
1475 state->hints = hints;
1477 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1478 if (tevent_req_nomem(subreq, req)) {
1479 return tevent_req_post(req, ev);
1481 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1485 static void getaddrinfo_do(void *private_data)
1487 struct getaddrinfo_state *state =
1488 (struct getaddrinfo_state *)private_data;
1490 state->ret = getaddrinfo(state->node, state->service, state->hints,
1494 static void getaddrinfo_done(struct tevent_req *subreq)
1496 struct tevent_req *req = tevent_req_callback_data(
1497 subreq, struct tevent_req);
1500 ret = fncall_recv(subreq, &err);
1501 TALLOC_FREE(subreq);
1503 tevent_req_error(req, err);
1506 tevent_req_done(req);
1509 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1511 struct getaddrinfo_state *state = tevent_req_data(
1512 req, struct getaddrinfo_state);
1515 if (tevent_req_is_unix_error(req, &err)) {
1523 if (state->ret == 0) {
1529 int poll_one_fd(int fd, int events, int timeout, int *revents)
1535 pfd.events = events;
1537 ret = poll(&pfd, 1, timeout);
1540 * Assign whatever poll did, even in the ret<=0 case.
1542 *revents = pfd.revents;
1547 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1553 pfd.events = events;
1555 ret = sys_poll_intr(&pfd, 1, timeout);
1560 *revents = pfd.revents;