selftest: rename env s3member_rfc2307 to ad_member_rfc2307
[Samba.git] / source3 / lib / util_sock.c
blob682d964b30c8eee95fa7c9d467ed3ad0076625b7
1 /*
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/>.
22 #include "includes.h"
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"
32 #include "lib/sys_rw_data.h"
34 const char *client_addr(int fd, char *addr, size_t addrlen)
36 return get_peer_addr(fd,addr,addrlen);
39 #if 0
40 /* Not currently used. JRA. */
41 int client_socket_port(int fd)
43 return get_socket_port(fd);
45 #endif
47 /****************************************************************************
48 Determine if a file descriptor is in fact a socket.
49 ****************************************************************************/
51 bool is_a_socket(int fd)
53 int v;
54 socklen_t l;
55 l = sizeof(int);
56 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
59 /****************************************************************************
60 Read from a socket.
61 ****************************************************************************/
63 ssize_t read_udp_v4_socket(int fd,
64 char *buf,
65 size_t len,
66 struct sockaddr_storage *psa)
68 ssize_t ret;
69 socklen_t socklen = sizeof(*psa);
70 struct sockaddr_in *si = (struct sockaddr_in *)psa;
72 memset((char *)psa,'\0',socklen);
74 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
75 (struct sockaddr *)psa,&socklen);
76 if (ret <= 0) {
77 /* Don't print a low debug error for a non-blocking socket. */
78 if (errno == EAGAIN) {
79 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
80 } else {
81 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
82 strerror(errno)));
84 return 0;
87 if (psa->ss_family != AF_INET) {
88 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
89 "(not IPv4)\n", (int)psa->ss_family));
90 return 0;
93 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
94 inet_ntoa(si->sin_addr),
95 si->sin_port,
96 (unsigned long)ret));
98 return ret;
101 /****************************************************************************
102 Read data from a file descriptor with a timout in msec.
103 mincount = if timeout, minimum to read before returning
104 maxcount = number to be read.
105 time_out = timeout in milliseconds
106 NB. This can be called with a non-socket fd, don't change
107 sys_read() to sys_recv() or other socket call.
108 ****************************************************************************/
110 NTSTATUS read_fd_with_timeout(int fd, char *buf,
111 size_t mincnt, size_t maxcnt,
112 unsigned int time_out,
113 size_t *size_ret)
115 int pollrtn;
116 ssize_t readret;
117 size_t nread = 0;
119 /* just checking .... */
120 if (maxcnt <= 0)
121 return NT_STATUS_OK;
123 /* Blocking read */
124 if (time_out == 0) {
125 if (mincnt == 0) {
126 mincnt = maxcnt;
129 while (nread < mincnt) {
130 readret = sys_read(fd, buf + nread, maxcnt - nread);
132 if (readret == 0) {
133 DEBUG(5,("read_fd_with_timeout: "
134 "blocking read. EOF from client.\n"));
135 return NT_STATUS_END_OF_FILE;
138 if (readret == -1) {
139 return map_nt_error_from_unix(errno);
141 nread += readret;
143 goto done;
146 /* Most difficult - timeout read */
147 /* If this is ever called on a disk file and
148 mincnt is greater then the filesize then
149 system performance will suffer severely as
150 select always returns true on disk files */
152 for (nread=0; nread < mincnt; ) {
153 int revents;
155 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
156 &revents);
158 /* Check if error */
159 if (pollrtn == -1) {
160 return map_nt_error_from_unix(errno);
163 /* Did we timeout ? */
164 if ((pollrtn == 0) ||
165 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
166 DEBUG(10,("read_fd_with_timeout: timeout read. "
167 "select timed out.\n"));
168 return NT_STATUS_IO_TIMEOUT;
171 readret = sys_read(fd, buf+nread, maxcnt-nread);
173 if (readret == 0) {
174 /* we got EOF on the file descriptor */
175 DEBUG(5,("read_fd_with_timeout: timeout read. "
176 "EOF from client.\n"));
177 return NT_STATUS_END_OF_FILE;
180 if (readret == -1) {
181 return map_nt_error_from_unix(errno);
184 nread += readret;
187 done:
188 /* Return the number we got */
189 if (size_ret) {
190 *size_ret = nread;
192 return NT_STATUS_OK;
195 /****************************************************************************
196 Read data from an fd, reading exactly N bytes.
197 NB. This can be called with a non-socket fd, don't add dependencies
198 on socket calls.
199 ****************************************************************************/
201 NTSTATUS read_data_ntstatus(int fd, char *buffer, size_t N)
203 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
206 /****************************************************************************
207 Send a keepalive packet (rfc1002).
208 ****************************************************************************/
210 bool send_keepalive(int client)
212 unsigned char buf[4];
214 buf[0] = NBSSkeepalive;
215 buf[1] = buf[2] = buf[3] = 0;
217 return(write_data(client,(char *)buf,4) == 4);
220 /****************************************************************************
221 Read 4 bytes of a smb packet and return the smb length of the packet.
222 Store the result in the buffer.
223 This version of the function will return a length of zero on receiving
224 a keepalive packet.
225 Timeout is in milliseconds.
226 ****************************************************************************/
228 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
229 unsigned int timeout,
230 size_t *len)
232 int msg_type;
233 NTSTATUS status;
235 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
237 if (!NT_STATUS_IS_OK(status)) {
238 return status;
241 *len = smb_len(inbuf);
242 msg_type = CVAL(inbuf,0);
244 if (msg_type == NBSSkeepalive) {
245 DEBUG(5,("Got keepalive packet\n"));
248 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
250 return NT_STATUS_OK;
253 /****************************************************************************
254 Read an smb from a fd.
255 The timeout is in milliseconds.
256 This function will return on receipt of a session keepalive packet.
257 maxlen is the max number of bytes to return, not including the 4 byte
258 length. If zero it means buflen limit.
259 Doesn't check the MAC on signed packets.
260 ****************************************************************************/
262 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
263 size_t maxlen, size_t *p_len)
265 size_t len;
266 NTSTATUS status;
268 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
270 if (!NT_STATUS_IS_OK(status)) {
271 DEBUG(0, ("read_fd_with_timeout failed, read "
272 "error = %s.\n", nt_errstr(status)));
273 return status;
276 if (len > buflen) {
277 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
278 (unsigned long)len));
279 return NT_STATUS_INVALID_PARAMETER;
282 if(len > 0) {
283 if (maxlen) {
284 len = MIN(len,maxlen);
287 status = read_fd_with_timeout(
288 fd, buffer+4, len, len, timeout, &len);
290 if (!NT_STATUS_IS_OK(status)) {
291 DEBUG(0, ("read_fd_with_timeout failed, read error = "
292 "%s.\n", nt_errstr(status)));
293 return status;
296 /* not all of samba3 properly checks for packet-termination
297 * of strings. This ensures that we don't run off into
298 * empty space. */
299 SSVAL(buffer+4,len, 0);
302 *p_len = len;
303 return NT_STATUS_OK;
306 /****************************************************************************
307 Open a socket of the specified type, port, and address for incoming data.
308 ****************************************************************************/
310 int open_socket_in(int type,
311 uint16_t port,
312 int dlevel,
313 const struct sockaddr_storage *psock,
314 bool rebind)
316 struct sockaddr_storage sock;
317 int res;
318 socklen_t slen = sizeof(struct sockaddr_in);
320 sock = *psock;
322 #if defined(HAVE_IPV6)
323 if (sock.ss_family == AF_INET6) {
324 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
325 slen = sizeof(struct sockaddr_in6);
327 #endif
328 if (sock.ss_family == AF_INET) {
329 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
332 res = socket(sock.ss_family, type, 0 );
333 if( res == -1 ) {
334 if( DEBUGLVL(0) ) {
335 dbgtext( "open_socket_in(): socket() call failed: " );
336 dbgtext( "%s\n", strerror( errno ) );
338 return -1;
341 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
343 int val = rebind ? 1 : 0;
344 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
345 (char *)&val,sizeof(val)) == -1 ) {
346 if( DEBUGLVL( dlevel ) ) {
347 dbgtext( "open_socket_in(): setsockopt: " );
348 dbgtext( "SO_REUSEADDR = %s ",
349 val?"true":"false" );
350 dbgtext( "on port %d failed ", port );
351 dbgtext( "with error = %s\n", strerror(errno) );
354 #ifdef SO_REUSEPORT
355 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
356 (char *)&val,sizeof(val)) == -1 ) {
357 if( DEBUGLVL( dlevel ) ) {
358 dbgtext( "open_socket_in(): setsockopt: ");
359 dbgtext( "SO_REUSEPORT = %s ",
360 val?"true":"false");
361 dbgtext( "on port %d failed ", port);
362 dbgtext( "with error = %s\n", strerror(errno));
365 #endif /* SO_REUSEPORT */
368 #ifdef HAVE_IPV6
370 * As IPV6_V6ONLY is the default on some systems,
371 * we better try to be consistent and always use it.
373 * This also avoids using IPv4 via AF_INET6 sockets
374 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
375 * string.
377 if (sock.ss_family == AF_INET6) {
378 int val = 1;
379 int ret;
381 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
382 (const void *)&val, sizeof(val));
383 if (ret == -1) {
384 if(DEBUGLVL(0)) {
385 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
386 dbgtext("%s\n", strerror(errno));
388 close(res);
389 return -1;
392 #endif
394 /* now we've got a socket - we need to bind it */
395 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
396 if( DEBUGLVL(dlevel) && (port == NMB_PORT ||
397 port == NBT_SMB_PORT ||
398 port == TCP_SMB_PORT) ) {
399 char addr[INET6_ADDRSTRLEN];
400 print_sockaddr(addr, sizeof(addr),
401 &sock);
402 dbgtext( "bind failed on port %d ", port);
403 dbgtext( "socket_addr = %s.\n", addr);
404 dbgtext( "Error = %s\n", strerror(errno));
406 close(res);
407 return -1;
410 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
411 return( res );
414 struct open_socket_out_state {
415 int fd;
416 struct tevent_context *ev;
417 struct sockaddr_storage ss;
418 socklen_t salen;
419 uint16_t port;
420 int wait_usec;
423 static void open_socket_out_connected(struct tevent_req *subreq);
425 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
427 if (s->fd != -1) {
428 close(s->fd);
430 return 0;
433 /****************************************************************************
434 Create an outgoing socket. timeout is in milliseconds.
435 **************************************************************************/
437 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
438 struct tevent_context *ev,
439 const struct sockaddr_storage *pss,
440 uint16_t port,
441 int timeout)
443 char addr[INET6_ADDRSTRLEN];
444 struct tevent_req *result, *subreq;
445 struct open_socket_out_state *state;
446 NTSTATUS status;
448 result = tevent_req_create(mem_ctx, &state,
449 struct open_socket_out_state);
450 if (result == NULL) {
451 return NULL;
453 state->ev = ev;
454 state->ss = *pss;
455 state->port = port;
456 state->wait_usec = 10000;
457 state->salen = -1;
459 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
460 if (state->fd == -1) {
461 status = map_nt_error_from_unix(errno);
462 goto post_status;
464 talloc_set_destructor(state, open_socket_out_state_destructor);
466 if (!tevent_req_set_endtime(
467 result, ev, timeval_current_ofs_msec(timeout))) {
468 goto fail;
471 #if defined(HAVE_IPV6)
472 if (pss->ss_family == AF_INET6) {
473 struct sockaddr_in6 *psa6;
474 psa6 = (struct sockaddr_in6 *)&state->ss;
475 psa6->sin6_port = htons(port);
476 if (psa6->sin6_scope_id == 0
477 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
478 setup_linklocal_scope_id(
479 (struct sockaddr *)&(state->ss));
481 state->salen = sizeof(struct sockaddr_in6);
483 #endif
484 if (pss->ss_family == AF_INET) {
485 struct sockaddr_in *psa;
486 psa = (struct sockaddr_in *)&state->ss;
487 psa->sin_port = htons(port);
488 state->salen = sizeof(struct sockaddr_in);
491 if (pss->ss_family == AF_UNIX) {
492 state->salen = sizeof(struct sockaddr_un);
495 print_sockaddr(addr, sizeof(addr), &state->ss);
496 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
498 subreq = async_connect_send(state, state->ev, state->fd,
499 (struct sockaddr *)&state->ss,
500 state->salen, NULL, NULL, NULL);
501 if ((subreq == NULL)
502 || !tevent_req_set_endtime(
503 subreq, state->ev,
504 timeval_current_ofs(0, state->wait_usec))) {
505 goto fail;
507 tevent_req_set_callback(subreq, open_socket_out_connected, result);
508 return result;
510 post_status:
511 tevent_req_nterror(result, status);
512 return tevent_req_post(result, ev);
513 fail:
514 TALLOC_FREE(result);
515 return NULL;
518 static void open_socket_out_connected(struct tevent_req *subreq)
520 struct tevent_req *req =
521 tevent_req_callback_data(subreq, struct tevent_req);
522 struct open_socket_out_state *state =
523 tevent_req_data(req, struct open_socket_out_state);
524 int ret;
525 int sys_errno;
527 ret = async_connect_recv(subreq, &sys_errno);
528 TALLOC_FREE(subreq);
529 if (ret == 0) {
530 tevent_req_done(req);
531 return;
534 if (
535 #ifdef ETIMEDOUT
536 (sys_errno == ETIMEDOUT) ||
537 #endif
538 (sys_errno == EINPROGRESS) ||
539 (sys_errno == EALREADY) ||
540 (sys_errno == EAGAIN)) {
543 * retry
546 if (state->wait_usec < 250000) {
547 state->wait_usec *= 1.5;
550 subreq = async_connect_send(state, state->ev, state->fd,
551 (struct sockaddr *)&state->ss,
552 state->salen, NULL, NULL, NULL);
553 if (tevent_req_nomem(subreq, req)) {
554 return;
556 if (!tevent_req_set_endtime(
557 subreq, state->ev,
558 timeval_current_ofs_usec(state->wait_usec))) {
559 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
560 return;
562 tevent_req_set_callback(subreq, open_socket_out_connected, req);
563 return;
566 #ifdef EISCONN
567 if (sys_errno == EISCONN) {
568 tevent_req_done(req);
569 return;
571 #endif
573 /* real error */
574 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
577 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
579 struct open_socket_out_state *state =
580 tevent_req_data(req, struct open_socket_out_state);
581 NTSTATUS status;
583 if (tevent_req_is_nterror(req, &status)) {
584 return status;
586 *pfd = state->fd;
587 state->fd = -1;
588 return NT_STATUS_OK;
592 * @brief open a socket
594 * @param pss a struct sockaddr_storage defining the address to connect to
595 * @param port to connect to
596 * @param timeout in MILLISECONDS
597 * @param pfd file descriptor returned
599 * @return NTSTATUS code
601 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
602 int timeout, int *pfd)
604 TALLOC_CTX *frame = talloc_stackframe();
605 struct tevent_context *ev;
606 struct tevent_req *req;
607 NTSTATUS status = NT_STATUS_NO_MEMORY;
609 ev = samba_tevent_context_init(frame);
610 if (ev == NULL) {
611 goto fail;
614 req = open_socket_out_send(frame, ev, pss, port, timeout);
615 if (req == NULL) {
616 goto fail;
618 if (!tevent_req_poll(req, ev)) {
619 status = NT_STATUS_INTERNAL_ERROR;
620 goto fail;
622 status = open_socket_out_recv(req, pfd);
623 fail:
624 TALLOC_FREE(frame);
625 return status;
628 struct open_socket_out_defer_state {
629 struct tevent_context *ev;
630 struct sockaddr_storage ss;
631 uint16_t port;
632 int timeout;
633 int fd;
636 static void open_socket_out_defer_waited(struct tevent_req *subreq);
637 static void open_socket_out_defer_connected(struct tevent_req *subreq);
639 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
640 struct tevent_context *ev,
641 struct timeval wait_time,
642 const struct sockaddr_storage *pss,
643 uint16_t port,
644 int timeout)
646 struct tevent_req *req, *subreq;
647 struct open_socket_out_defer_state *state;
649 req = tevent_req_create(mem_ctx, &state,
650 struct open_socket_out_defer_state);
651 if (req == NULL) {
652 return NULL;
654 state->ev = ev;
655 state->ss = *pss;
656 state->port = port;
657 state->timeout = timeout;
659 subreq = tevent_wakeup_send(
660 state, ev,
661 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
662 if (subreq == NULL) {
663 goto fail;
665 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
666 return req;
667 fail:
668 TALLOC_FREE(req);
669 return NULL;
672 static void open_socket_out_defer_waited(struct tevent_req *subreq)
674 struct tevent_req *req = tevent_req_callback_data(
675 subreq, struct tevent_req);
676 struct open_socket_out_defer_state *state = tevent_req_data(
677 req, struct open_socket_out_defer_state);
678 bool ret;
680 ret = tevent_wakeup_recv(subreq);
681 TALLOC_FREE(subreq);
682 if (!ret) {
683 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
684 return;
687 subreq = open_socket_out_send(state, state->ev, &state->ss,
688 state->port, state->timeout);
689 if (tevent_req_nomem(subreq, req)) {
690 return;
692 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
695 static void open_socket_out_defer_connected(struct tevent_req *subreq)
697 struct tevent_req *req = tevent_req_callback_data(
698 subreq, struct tevent_req);
699 struct open_socket_out_defer_state *state = tevent_req_data(
700 req, struct open_socket_out_defer_state);
701 NTSTATUS status;
703 status = open_socket_out_recv(subreq, &state->fd);
704 TALLOC_FREE(subreq);
705 if (!NT_STATUS_IS_OK(status)) {
706 tevent_req_nterror(req, status);
707 return;
709 tevent_req_done(req);
712 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
714 struct open_socket_out_defer_state *state = tevent_req_data(
715 req, struct open_socket_out_defer_state);
716 NTSTATUS status;
718 if (tevent_req_is_nterror(req, &status)) {
719 return status;
721 *pfd = state->fd;
722 state->fd = -1;
723 return NT_STATUS_OK;
726 /****************************************************************************
727 Open a connected UDP socket to host on port
728 **************************************************************************/
730 int open_udp_socket(const char *host, int port)
732 struct sockaddr_storage ss;
733 int res;
734 socklen_t salen;
736 if (!interpret_string_addr(&ss, host, 0)) {
737 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
738 host));
739 return -1;
742 res = socket(ss.ss_family, SOCK_DGRAM, 0);
743 if (res == -1) {
744 return -1;
747 #if defined(HAVE_IPV6)
748 if (ss.ss_family == AF_INET6) {
749 struct sockaddr_in6 *psa6;
750 psa6 = (struct sockaddr_in6 *)&ss;
751 psa6->sin6_port = htons(port);
752 if (psa6->sin6_scope_id == 0
753 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
754 setup_linklocal_scope_id(
755 (struct sockaddr *)&ss);
757 salen = sizeof(struct sockaddr_in6);
758 } else
759 #endif
760 if (ss.ss_family == AF_INET) {
761 struct sockaddr_in *psa;
762 psa = (struct sockaddr_in *)&ss;
763 psa->sin_port = htons(port);
764 salen = sizeof(struct sockaddr_in);
765 } else {
766 DEBUG(1, ("unknown socket family %d", ss.ss_family));
767 close(res);
768 return -1;
771 if (connect(res, (struct sockaddr *)&ss, salen)) {
772 close(res);
773 return -1;
776 return res;
779 /*******************************************************************
780 Return the IP addr of the remote end of a socket as a string.
781 Optionally return the struct sockaddr_storage.
782 ******************************************************************/
784 static const char *get_peer_addr_internal(int fd,
785 char *addr_buf,
786 size_t addr_buf_len,
787 struct sockaddr *pss,
788 socklen_t *plength)
790 struct sockaddr_storage ss;
791 socklen_t length = sizeof(ss);
793 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
795 if (fd == -1) {
796 return addr_buf;
799 if (pss == NULL) {
800 pss = (struct sockaddr *)&ss;
801 plength = &length;
804 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
805 int level = (errno == ENOTCONN) ? 2 : 0;
806 DEBUG(level, ("getpeername failed. Error was %s\n",
807 strerror(errno)));
808 return addr_buf;
811 print_sockaddr_len(addr_buf,
812 addr_buf_len,
813 pss,
814 *plength);
815 return addr_buf;
818 /*******************************************************************
819 Matchname - determine if host name matches IP address. Used to
820 confirm a hostname lookup to prevent spoof attacks.
821 ******************************************************************/
823 static bool matchname(const char *remotehost,
824 const struct sockaddr *pss,
825 socklen_t len)
827 struct addrinfo *res = NULL;
828 struct addrinfo *ailist = NULL;
829 char addr_buf[INET6_ADDRSTRLEN];
830 bool ret = interpret_string_addr_internal(&ailist,
831 remotehost,
832 AI_ADDRCONFIG|AI_CANONNAME);
834 if (!ret || ailist == NULL) {
835 DEBUG(3,("matchname: getaddrinfo failed for "
836 "name %s [%s]\n",
837 remotehost,
838 gai_strerror(ret) ));
839 return false;
843 * Make sure that getaddrinfo() returns the "correct" host name.
846 if (ailist->ai_canonname == NULL ||
847 (!strequal(remotehost, ailist->ai_canonname) &&
848 !strequal(remotehost, "localhost"))) {
849 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
850 remotehost,
851 ailist->ai_canonname ?
852 ailist->ai_canonname : "(NULL)"));
853 freeaddrinfo(ailist);
854 return false;
857 /* Look up the host address in the address list we just got. */
858 for (res = ailist; res; res = res->ai_next) {
859 if (!res->ai_addr) {
860 continue;
862 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
863 (const struct sockaddr *)pss)) {
864 freeaddrinfo(ailist);
865 return true;
870 * The host name does not map to the original host address. Perhaps
871 * someone has compromised a name server. More likely someone botched
872 * it, but that could be dangerous, too.
875 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
876 print_sockaddr_len(addr_buf,
877 sizeof(addr_buf),
878 pss,
879 len),
880 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
882 if (ailist) {
883 freeaddrinfo(ailist);
885 return false;
888 /*******************************************************************
889 Deal with the singleton cache.
890 ******************************************************************/
892 struct name_addr_pair {
893 struct sockaddr_storage ss;
894 const char *name;
897 /*******************************************************************
898 Lookup a name/addr pair. Returns memory allocated from memcache.
899 ******************************************************************/
901 static bool lookup_nc(struct name_addr_pair *nc)
903 DATA_BLOB tmp;
905 ZERO_STRUCTP(nc);
907 if (!memcache_lookup(
908 NULL, SINGLETON_CACHE,
909 data_blob_string_const_null("get_peer_name"),
910 &tmp)) {
911 return false;
914 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
915 nc->name = (const char *)tmp.data + sizeof(nc->ss);
916 return true;
919 /*******************************************************************
920 Save a name/addr pair.
921 ******************************************************************/
923 static void store_nc(const struct name_addr_pair *nc)
925 DATA_BLOB tmp;
926 size_t namelen = strlen(nc->name);
928 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
929 if (!tmp.data) {
930 return;
932 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
933 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
935 memcache_add(NULL, SINGLETON_CACHE,
936 data_blob_string_const_null("get_peer_name"),
937 tmp);
938 data_blob_free(&tmp);
941 /*******************************************************************
942 Return the IP addr of the remote end of a socket as a string.
943 ******************************************************************/
945 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
947 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
950 int get_remote_hostname(const struct tsocket_address *remote_address,
951 char **name,
952 TALLOC_CTX *mem_ctx)
954 char name_buf[MAX_DNS_NAME_LENGTH];
955 char tmp_name[MAX_DNS_NAME_LENGTH];
956 struct name_addr_pair nc;
957 struct sockaddr_storage ss;
958 ssize_t len;
959 int rc;
961 if (!lp_hostname_lookups()) {
962 nc.name = tsocket_address_inet_addr_string(remote_address,
963 mem_ctx);
964 if (nc.name == NULL) {
965 return -1;
968 len = tsocket_address_bsd_sockaddr(remote_address,
969 (struct sockaddr *) &nc.ss,
970 sizeof(struct sockaddr_storage));
971 if (len < 0) {
972 return -1;
975 store_nc(&nc);
976 lookup_nc(&nc);
978 if (nc.name == NULL) {
979 *name = talloc_strdup(mem_ctx, "UNKNOWN");
980 } else {
981 *name = talloc_strdup(mem_ctx, nc.name);
983 return 0;
986 lookup_nc(&nc);
988 ZERO_STRUCT(ss);
990 len = tsocket_address_bsd_sockaddr(remote_address,
991 (struct sockaddr *) &ss,
992 sizeof(struct sockaddr_storage));
993 if (len < 0) {
994 return -1;
997 /* it might be the same as the last one - save some DNS work */
998 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
999 if (nc.name == NULL) {
1000 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1001 } else {
1002 *name = talloc_strdup(mem_ctx, nc.name);
1004 return 0;
1007 /* Look up the remote host name. */
1008 rc = sys_getnameinfo((struct sockaddr *) &ss,
1009 len,
1010 name_buf,
1011 sizeof(name_buf),
1012 NULL,
1015 if (rc < 0) {
1016 char *p;
1018 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1019 if (p == NULL) {
1020 return -1;
1023 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1025 gai_strerror(rc)));
1026 strlcpy(name_buf, p, sizeof(name_buf));
1028 TALLOC_FREE(p);
1029 } else {
1030 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1031 DEBUG(0,("matchname failed on %s\n", name_buf));
1032 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1036 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1037 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1038 if (strstr(name_buf,"..")) {
1039 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1042 nc.name = name_buf;
1043 nc.ss = ss;
1045 store_nc(&nc);
1046 lookup_nc(&nc);
1048 if (nc.name == NULL) {
1049 *name = talloc_strdup(mem_ctx, "UNKOWN");
1050 } else {
1051 *name = talloc_strdup(mem_ctx, nc.name);
1054 return 0;
1057 /*******************************************************************
1058 Create protected unix domain socket.
1060 Some unixes cannot set permissions on a ux-dom-sock, so we
1061 have to make sure that the directory contains the protection
1062 permissions instead.
1063 ******************************************************************/
1065 int create_pipe_sock(const char *socket_dir,
1066 const char *socket_name,
1067 mode_t dir_perms)
1069 #ifdef HAVE_UNIXSOCKET
1070 struct sockaddr_un sunaddr;
1071 bool ok;
1072 int sock = -1;
1073 mode_t old_umask;
1074 char *path = NULL;
1076 old_umask = umask(0);
1078 ok = directory_create_or_exist_strict(socket_dir,
1079 sec_initial_uid(),
1080 dir_perms);
1081 if (!ok) {
1082 goto out_close;
1085 /* Create the socket file */
1086 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1088 if (sock == -1) {
1089 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1090 strerror(errno) ));
1091 goto out_close;
1094 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1095 goto out_close;
1098 unlink(path);
1099 memset(&sunaddr, 0, sizeof(sunaddr));
1100 sunaddr.sun_family = AF_UNIX;
1101 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1103 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1104 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1105 strerror(errno)));
1106 goto out_close;
1109 SAFE_FREE(path);
1111 umask(old_umask);
1112 return sock;
1114 out_close:
1115 SAFE_FREE(path);
1116 if (sock != -1)
1117 close(sock);
1119 umask(old_umask);
1120 return -1;
1122 #else
1123 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1124 return -1;
1125 #endif /* HAVE_UNIXSOCKET */
1128 /****************************************************************************
1129 Get my own canonical name, including domain.
1130 ****************************************************************************/
1132 const char *get_mydnsfullname(void)
1134 struct addrinfo *res = NULL;
1135 char my_hostname[HOST_NAME_MAX];
1136 bool ret;
1137 DATA_BLOB tmp;
1139 if (memcache_lookup(NULL, SINGLETON_CACHE,
1140 data_blob_string_const_null("get_mydnsfullname"),
1141 &tmp)) {
1142 SMB_ASSERT(tmp.length > 0);
1143 return (const char *)tmp.data;
1146 /* get my host name */
1147 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1148 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1149 return NULL;
1152 /* Ensure null termination. */
1153 my_hostname[sizeof(my_hostname)-1] = '\0';
1155 ret = interpret_string_addr_internal(&res,
1156 my_hostname,
1157 AI_ADDRCONFIG|AI_CANONNAME);
1159 if (!ret || res == NULL) {
1160 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1161 "name %s [%s]\n",
1162 my_hostname,
1163 gai_strerror(ret) ));
1164 return NULL;
1168 * Make sure that getaddrinfo() returns the "correct" host name.
1171 if (res->ai_canonname == NULL) {
1172 DEBUG(3,("get_mydnsfullname: failed to get "
1173 "canonical name for %s\n",
1174 my_hostname));
1175 freeaddrinfo(res);
1176 return NULL;
1179 /* This copies the data, so we must do a lookup
1180 * afterwards to find the value to return.
1183 memcache_add(NULL, SINGLETON_CACHE,
1184 data_blob_string_const_null("get_mydnsfullname"),
1185 data_blob_string_const_null(res->ai_canonname));
1187 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1188 data_blob_string_const_null("get_mydnsfullname"),
1189 &tmp)) {
1190 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1191 strlen(res->ai_canonname) + 1);
1194 freeaddrinfo(res);
1196 return (const char *)tmp.data;
1199 /************************************************************
1200 Is this my ip address ?
1201 ************************************************************/
1203 static bool is_my_ipaddr(const char *ipaddr_str)
1205 struct sockaddr_storage ss;
1206 struct iface_struct *nics;
1207 int i, n;
1209 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1210 return false;
1213 if (is_zero_addr(&ss)) {
1214 return false;
1217 if (ismyaddr((struct sockaddr *)&ss) ||
1218 is_loopback_addr((struct sockaddr *)&ss)) {
1219 return true;
1222 n = get_interfaces(talloc_tos(), &nics);
1223 for (i=0; i<n; i++) {
1224 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1225 TALLOC_FREE(nics);
1226 return true;
1229 TALLOC_FREE(nics);
1230 return false;
1233 /************************************************************
1234 Is this my name ?
1235 ************************************************************/
1237 bool is_myname_or_ipaddr(const char *s)
1239 TALLOC_CTX *ctx = talloc_tos();
1240 char *name = NULL;
1241 const char *dnsname;
1242 char *servername = NULL;
1244 if (!s) {
1245 return false;
1248 /* Santize the string from '\\name' */
1249 name = talloc_strdup(ctx, s);
1250 if (!name) {
1251 return false;
1254 servername = strrchr_m(name, '\\' );
1255 if (!servername) {
1256 servername = name;
1257 } else {
1258 servername++;
1261 /* Optimize for the common case */
1262 if (strequal(servername, lp_netbios_name())) {
1263 return true;
1266 /* Check for an alias */
1267 if (is_myname(servername)) {
1268 return true;
1271 /* Check for loopback */
1272 if (strequal(servername, "127.0.0.1") ||
1273 strequal(servername, "::1")) {
1274 return true;
1277 if (strequal(servername, "localhost")) {
1278 return true;
1281 /* Maybe it's my dns name */
1282 dnsname = get_mydnsfullname();
1283 if (dnsname && strequal(servername, dnsname)) {
1284 return true;
1287 /* Maybe its an IP address? */
1288 if (is_ipaddress(servername)) {
1289 return is_my_ipaddr(servername);
1292 /* Handle possible CNAME records - convert to an IP addr. list. */
1294 /* Use DNS to resolve the name, check all addresses. */
1295 struct addrinfo *p = NULL;
1296 struct addrinfo *res = NULL;
1298 if (!interpret_string_addr_internal(&res,
1299 servername,
1300 AI_ADDRCONFIG)) {
1301 return false;
1304 for (p = res; p; p = p->ai_next) {
1305 char addr[INET6_ADDRSTRLEN];
1306 struct sockaddr_storage ss;
1308 ZERO_STRUCT(ss);
1309 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1310 print_sockaddr(addr,
1311 sizeof(addr),
1312 &ss);
1313 if (is_my_ipaddr(addr)) {
1314 freeaddrinfo(res);
1315 return true;
1318 freeaddrinfo(res);
1321 /* No match */
1322 return false;
1325 struct getaddrinfo_state {
1326 const char *node;
1327 const char *service;
1328 const struct addrinfo *hints;
1329 struct addrinfo *res;
1330 int ret;
1333 static void getaddrinfo_do(void *private_data);
1334 static void getaddrinfo_done(struct tevent_req *subreq);
1336 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1337 struct tevent_context *ev,
1338 struct fncall_context *ctx,
1339 const char *node,
1340 const char *service,
1341 const struct addrinfo *hints)
1343 struct tevent_req *req, *subreq;
1344 struct getaddrinfo_state *state;
1346 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1347 if (req == NULL) {
1348 return NULL;
1351 state->node = node;
1352 state->service = service;
1353 state->hints = hints;
1355 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1356 if (tevent_req_nomem(subreq, req)) {
1357 return tevent_req_post(req, ev);
1359 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1360 return req;
1363 static void getaddrinfo_do(void *private_data)
1365 struct getaddrinfo_state *state =
1366 (struct getaddrinfo_state *)private_data;
1368 state->ret = getaddrinfo(state->node, state->service, state->hints,
1369 &state->res);
1372 static void getaddrinfo_done(struct tevent_req *subreq)
1374 struct tevent_req *req = tevent_req_callback_data(
1375 subreq, struct tevent_req);
1376 int ret, err;
1378 ret = fncall_recv(subreq, &err);
1379 TALLOC_FREE(subreq);
1380 if (ret == -1) {
1381 tevent_req_error(req, err);
1382 return;
1384 tevent_req_done(req);
1387 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1389 struct getaddrinfo_state *state = tevent_req_data(
1390 req, struct getaddrinfo_state);
1391 int err;
1393 if (tevent_req_is_unix_error(req, &err)) {
1394 switch(err) {
1395 case ENOMEM:
1396 return EAI_MEMORY;
1397 default:
1398 return EAI_FAIL;
1401 if (state->ret == 0) {
1402 *res = state->res;
1404 return state->ret;
1407 int poll_one_fd(int fd, int events, int timeout, int *revents)
1409 struct pollfd pfd;
1410 int ret;
1412 pfd.fd = fd;
1413 pfd.events = events;
1415 ret = poll(&pfd, 1, timeout);
1418 * Assign whatever poll did, even in the ret<=0 case.
1420 *revents = pfd.revents;
1422 return ret;
1425 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1427 struct pollfd pfd;
1428 int ret;
1430 pfd.fd = fd;
1431 pfd.events = events;
1433 ret = sys_poll_intr(&pfd, 1, timeout);
1434 if (ret <= 0) {
1435 *revents = 0;
1436 return ret;
1438 *revents = pfd.revents;
1439 return 1;