s3:lib: s/struct event_context/struct tevent_context
[Samba/gebeck_regimport.git] / source3 / lib / util_sock.c
blob8f212e5d851efc7412f076d3d595626ff96b6292
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 "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"
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);
42 #if 0
43 /* Not currently used. JRA. */
44 int client_socket_port(int fd)
46 return get_socket_port(fd);
48 #endif
50 /****************************************************************************
51 Determine if a file descriptor is in fact a socket.
52 ****************************************************************************/
54 bool is_a_socket(int fd)
56 int v;
57 socklen_t l;
58 l = sizeof(int);
59 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
62 /****************************************************************************
63 Read from a socket.
64 ****************************************************************************/
66 ssize_t read_udp_v4_socket(int fd,
67 char *buf,
68 size_t len,
69 struct sockaddr_storage *psa)
71 ssize_t ret;
72 socklen_t socklen = sizeof(*psa);
73 struct sockaddr_in *si = (struct sockaddr_in *)psa;
75 memset((char *)psa,'\0',socklen);
77 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
78 (struct sockaddr *)psa,&socklen);
79 if (ret <= 0) {
80 /* Don't print a low debug error for a non-blocking socket. */
81 if (errno == EAGAIN) {
82 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
83 } else {
84 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
85 strerror(errno)));
87 return 0;
90 if (psa->ss_family != AF_INET) {
91 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
92 "(not IPv4)\n", (int)psa->ss_family));
93 return 0;
96 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
97 inet_ntoa(si->sin_addr),
98 si->sin_port,
99 (unsigned long)ret));
101 return ret;
104 /****************************************************************************
105 Read data from a file descriptor with a timout in msec.
106 mincount = if timeout, minimum to read before returning
107 maxcount = number to be read.
108 time_out = timeout in milliseconds
109 NB. This can be called with a non-socket fd, don't change
110 sys_read() to sys_recv() or other socket call.
111 ****************************************************************************/
113 NTSTATUS read_fd_with_timeout(int fd, char *buf,
114 size_t mincnt, size_t maxcnt,
115 unsigned int time_out,
116 size_t *size_ret)
118 int pollrtn;
119 ssize_t readret;
120 size_t nread = 0;
122 /* just checking .... */
123 if (maxcnt <= 0)
124 return NT_STATUS_OK;
126 /* Blocking read */
127 if (time_out == 0) {
128 if (mincnt == 0) {
129 mincnt = maxcnt;
132 while (nread < mincnt) {
133 readret = sys_read(fd, buf + nread, maxcnt - nread);
135 if (readret == 0) {
136 DEBUG(5,("read_fd_with_timeout: "
137 "blocking read. EOF from client.\n"));
138 return NT_STATUS_END_OF_FILE;
141 if (readret == -1) {
142 return map_nt_error_from_unix(errno);
144 nread += readret;
146 goto done;
149 /* Most difficult - timeout read */
150 /* If this is ever called on a disk file and
151 mincnt is greater then the filesize then
152 system performance will suffer severely as
153 select always returns true on disk files */
155 for (nread=0; nread < mincnt; ) {
156 int revents;
158 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
159 &revents);
161 /* Check if error */
162 if (pollrtn == -1) {
163 return map_nt_error_from_unix(errno);
166 /* Did we timeout ? */
167 if ((pollrtn == 0) ||
168 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
169 DEBUG(10,("read_fd_with_timeout: timeout read. "
170 "select timed out.\n"));
171 return NT_STATUS_IO_TIMEOUT;
174 readret = sys_read(fd, buf+nread, maxcnt-nread);
176 if (readret == 0) {
177 /* we got EOF on the file descriptor */
178 DEBUG(5,("read_fd_with_timeout: timeout read. "
179 "EOF from client.\n"));
180 return NT_STATUS_END_OF_FILE;
183 if (readret == -1) {
184 return map_nt_error_from_unix(errno);
187 nread += readret;
190 done:
191 /* Return the number we got */
192 if (size_ret) {
193 *size_ret = nread;
195 return NT_STATUS_OK;
198 /****************************************************************************
199 Read data from an fd, reading exactly N bytes.
200 NB. This can be called with a non-socket fd, don't add dependencies
201 on socket calls.
202 ****************************************************************************/
204 NTSTATUS read_data(int fd, char *buffer, size_t N)
206 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
209 /****************************************************************************
210 Write all data from an iov array
211 NB. This can be called with a non-socket fd, don't add dependencies
212 on socket calls.
213 ****************************************************************************/
215 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
217 int i;
218 size_t to_send;
219 ssize_t thistime;
220 size_t sent;
221 struct iovec *iov_copy, *iov;
223 to_send = 0;
224 for (i=0; i<iovcnt; i++) {
225 to_send += orig_iov[i].iov_len;
228 thistime = sys_writev(fd, orig_iov, iovcnt);
229 if ((thistime <= 0) || (thistime == to_send)) {
230 return thistime;
232 sent = thistime;
235 * We could not send everything in one call. Make a copy of iov that
236 * we can mess with. We keep a copy of the array start in iov_copy for
237 * the TALLOC_FREE, because we're going to modify iov later on,
238 * discarding elements.
241 iov_copy = (struct iovec *)talloc_memdup(
242 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
244 if (iov_copy == NULL) {
245 errno = ENOMEM;
246 return -1;
248 iov = iov_copy;
250 while (sent < to_send) {
252 * We have to discard "thistime" bytes from the beginning
253 * iov array, "thistime" contains the number of bytes sent
254 * via writev last.
256 while (thistime > 0) {
257 if (thistime < iov[0].iov_len) {
258 char *new_base =
259 (char *)iov[0].iov_base + thistime;
260 iov[0].iov_base = (void *)new_base;
261 iov[0].iov_len -= thistime;
262 break;
264 thistime -= iov[0].iov_len;
265 iov += 1;
266 iovcnt -= 1;
269 thistime = sys_writev(fd, iov, iovcnt);
270 if (thistime <= 0) {
271 break;
273 sent += thistime;
276 TALLOC_FREE(iov_copy);
277 return sent;
280 /****************************************************************************
281 Write data to a fd.
282 NB. This can be called with a non-socket fd, don't add dependencies
283 on socket calls.
284 ****************************************************************************/
286 ssize_t write_data(int fd, const char *buffer, size_t N)
288 struct iovec iov;
290 iov.iov_base = discard_const_p(void, buffer);
291 iov.iov_len = N;
292 return write_data_iov(fd, &iov, 1);
295 /****************************************************************************
296 Send a keepalive packet (rfc1002).
297 ****************************************************************************/
299 bool send_keepalive(int client)
301 unsigned char buf[4];
303 buf[0] = NBSSkeepalive;
304 buf[1] = buf[2] = buf[3] = 0;
306 return(write_data(client,(char *)buf,4) == 4);
309 /****************************************************************************
310 Read 4 bytes of a smb packet and return the smb length of the packet.
311 Store the result in the buffer.
312 This version of the function will return a length of zero on receiving
313 a keepalive packet.
314 Timeout is in milliseconds.
315 ****************************************************************************/
317 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
318 unsigned int timeout,
319 size_t *len)
321 int msg_type;
322 NTSTATUS status;
324 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
326 if (!NT_STATUS_IS_OK(status)) {
327 return status;
330 *len = smb_len(inbuf);
331 msg_type = CVAL(inbuf,0);
333 if (msg_type == NBSSkeepalive) {
334 DEBUG(5,("Got keepalive packet\n"));
337 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
339 return NT_STATUS_OK;
342 /****************************************************************************
343 Read an smb from a fd.
344 The timeout is in milliseconds.
345 This function will return on receipt of a session keepalive packet.
346 maxlen is the max number of bytes to return, not including the 4 byte
347 length. If zero it means buflen limit.
348 Doesn't check the MAC on signed packets.
349 ****************************************************************************/
351 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
352 size_t maxlen, size_t *p_len)
354 size_t len;
355 NTSTATUS status;
357 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
359 if (!NT_STATUS_IS_OK(status)) {
360 DEBUG(0, ("read_fd_with_timeout failed, read "
361 "error = %s.\n", nt_errstr(status)));
362 return status;
365 if (len > buflen) {
366 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
367 (unsigned long)len));
368 return NT_STATUS_INVALID_PARAMETER;
371 if(len > 0) {
372 if (maxlen) {
373 len = MIN(len,maxlen);
376 status = read_fd_with_timeout(
377 fd, buffer+4, len, len, timeout, &len);
379 if (!NT_STATUS_IS_OK(status)) {
380 DEBUG(0, ("read_fd_with_timeout failed, read error = "
381 "%s.\n", nt_errstr(status)));
382 return status;
385 /* not all of samba3 properly checks for packet-termination
386 * of strings. This ensures that we don't run off into
387 * empty space. */
388 SSVAL(buffer+4,len, 0);
391 *p_len = len;
392 return NT_STATUS_OK;
395 /****************************************************************************
396 Open a socket of the specified type, port, and address for incoming data.
397 ****************************************************************************/
399 int open_socket_in(int type,
400 uint16_t port,
401 int dlevel,
402 const struct sockaddr_storage *psock,
403 bool rebind)
405 struct sockaddr_storage sock;
406 int res;
407 socklen_t slen = sizeof(struct sockaddr_in);
409 sock = *psock;
411 #if defined(HAVE_IPV6)
412 if (sock.ss_family == AF_INET6) {
413 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
414 slen = sizeof(struct sockaddr_in6);
416 #endif
417 if (sock.ss_family == AF_INET) {
418 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
421 res = socket(sock.ss_family, type, 0 );
422 if( res == -1 ) {
423 if( DEBUGLVL(0) ) {
424 dbgtext( "open_socket_in(): socket() call failed: " );
425 dbgtext( "%s\n", strerror( errno ) );
427 return -1;
430 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
432 int val = rebind ? 1 : 0;
433 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
434 (char *)&val,sizeof(val)) == -1 ) {
435 if( DEBUGLVL( dlevel ) ) {
436 dbgtext( "open_socket_in(): setsockopt: " );
437 dbgtext( "SO_REUSEADDR = %s ",
438 val?"true":"false" );
439 dbgtext( "on port %d failed ", port );
440 dbgtext( "with error = %s\n", strerror(errno) );
443 #ifdef SO_REUSEPORT
444 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
445 (char *)&val,sizeof(val)) == -1 ) {
446 if( DEBUGLVL( dlevel ) ) {
447 dbgtext( "open_socket_in(): setsockopt: ");
448 dbgtext( "SO_REUSEPORT = %s ",
449 val?"true":"false");
450 dbgtext( "on port %d failed ", port);
451 dbgtext( "with error = %s\n", strerror(errno));
454 #endif /* SO_REUSEPORT */
457 #ifdef HAVE_IPV6
459 * As IPV6_V6ONLY is the default on some systems,
460 * we better try to be consistent and always use it.
462 * This also avoids using IPv4 via AF_INET6 sockets
463 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
464 * string.
466 if (sock.ss_family == AF_INET6) {
467 int val = 1;
468 int ret;
470 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
471 (const void *)&val, sizeof(val));
472 if (ret == -1) {
473 if(DEBUGLVL(0)) {
474 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
475 dbgtext("%s\n", strerror(errno));
477 close(res);
478 return -1;
481 #endif
483 /* now we've got a socket - we need to bind it */
484 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
485 if( DEBUGLVL(dlevel) && (port == NMB_PORT ||
486 port == NBT_SMB_PORT ||
487 port == TCP_SMB_PORT) ) {
488 char addr[INET6_ADDRSTRLEN];
489 print_sockaddr(addr, sizeof(addr),
490 &sock);
491 dbgtext( "bind failed on port %d ", port);
492 dbgtext( "socket_addr = %s.\n", addr);
493 dbgtext( "Error = %s\n", strerror(errno));
495 close(res);
496 return -1;
499 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
500 return( res );
503 struct open_socket_out_state {
504 int fd;
505 struct tevent_context *ev;
506 struct sockaddr_storage ss;
507 socklen_t salen;
508 uint16_t port;
509 int wait_usec;
512 static void open_socket_out_connected(struct tevent_req *subreq);
514 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
516 if (s->fd != -1) {
517 close(s->fd);
519 return 0;
522 /****************************************************************************
523 Create an outgoing socket. timeout is in milliseconds.
524 **************************************************************************/
526 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
527 struct tevent_context *ev,
528 const struct sockaddr_storage *pss,
529 uint16_t port,
530 int timeout)
532 char addr[INET6_ADDRSTRLEN];
533 struct tevent_req *result, *subreq;
534 struct open_socket_out_state *state;
535 NTSTATUS status;
537 result = tevent_req_create(mem_ctx, &state,
538 struct open_socket_out_state);
539 if (result == NULL) {
540 return NULL;
542 state->ev = ev;
543 state->ss = *pss;
544 state->port = port;
545 state->wait_usec = 10000;
546 state->salen = -1;
548 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
549 if (state->fd == -1) {
550 status = map_nt_error_from_unix(errno);
551 goto post_status;
553 talloc_set_destructor(state, open_socket_out_state_destructor);
555 if (!tevent_req_set_endtime(
556 result, ev, timeval_current_ofs_msec(timeout))) {
557 goto fail;
560 #if defined(HAVE_IPV6)
561 if (pss->ss_family == AF_INET6) {
562 struct sockaddr_in6 *psa6;
563 psa6 = (struct sockaddr_in6 *)&state->ss;
564 psa6->sin6_port = htons(port);
565 if (psa6->sin6_scope_id == 0
566 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
567 setup_linklocal_scope_id(
568 (struct sockaddr *)&(state->ss));
570 state->salen = sizeof(struct sockaddr_in6);
572 #endif
573 if (pss->ss_family == AF_INET) {
574 struct sockaddr_in *psa;
575 psa = (struct sockaddr_in *)&state->ss;
576 psa->sin_port = htons(port);
577 state->salen = sizeof(struct sockaddr_in);
580 if (pss->ss_family == AF_UNIX) {
581 state->salen = sizeof(struct sockaddr_un);
584 print_sockaddr(addr, sizeof(addr), &state->ss);
585 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
587 subreq = async_connect_send(state, state->ev, state->fd,
588 (struct sockaddr *)&state->ss,
589 state->salen);
590 if ((subreq == NULL)
591 || !tevent_req_set_endtime(
592 subreq, state->ev,
593 timeval_current_ofs(0, state->wait_usec))) {
594 goto fail;
596 tevent_req_set_callback(subreq, open_socket_out_connected, result);
597 return result;
599 post_status:
600 tevent_req_nterror(result, status);
601 return tevent_req_post(result, ev);
602 fail:
603 TALLOC_FREE(result);
604 return NULL;
607 static void open_socket_out_connected(struct tevent_req *subreq)
609 struct tevent_req *req =
610 tevent_req_callback_data(subreq, struct tevent_req);
611 struct open_socket_out_state *state =
612 tevent_req_data(req, struct open_socket_out_state);
613 int ret;
614 int sys_errno;
616 ret = async_connect_recv(subreq, &sys_errno);
617 TALLOC_FREE(subreq);
618 if (ret == 0) {
619 tevent_req_done(req);
620 return;
623 if (
624 #ifdef ETIMEDOUT
625 (sys_errno == ETIMEDOUT) ||
626 #endif
627 (sys_errno == EINPROGRESS) ||
628 (sys_errno == EALREADY) ||
629 (sys_errno == EAGAIN)) {
632 * retry
635 if (state->wait_usec < 250000) {
636 state->wait_usec *= 1.5;
639 subreq = async_connect_send(state, state->ev, state->fd,
640 (struct sockaddr *)&state->ss,
641 state->salen);
642 if (tevent_req_nomem(subreq, req)) {
643 return;
645 if (!tevent_req_set_endtime(
646 subreq, state->ev,
647 timeval_current_ofs_usec(state->wait_usec))) {
648 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
649 return;
651 tevent_req_set_callback(subreq, open_socket_out_connected, req);
652 return;
655 #ifdef EISCONN
656 if (sys_errno == EISCONN) {
657 tevent_req_done(req);
658 return;
660 #endif
662 /* real error */
663 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
666 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
668 struct open_socket_out_state *state =
669 tevent_req_data(req, struct open_socket_out_state);
670 NTSTATUS status;
672 if (tevent_req_is_nterror(req, &status)) {
673 return status;
675 *pfd = state->fd;
676 state->fd = -1;
677 return NT_STATUS_OK;
681 * @brief open a socket
683 * @param pss a struct sockaddr_storage defining the address to connect to
684 * @param port to connect to
685 * @param timeout in MILLISECONDS
686 * @param pfd file descriptor returned
688 * @return NTSTATUS code
690 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
691 int timeout, int *pfd)
693 TALLOC_CTX *frame = talloc_stackframe();
694 struct tevent_context *ev;
695 struct tevent_req *req;
696 NTSTATUS status = NT_STATUS_NO_MEMORY;
698 ev = samba_tevent_context_init(frame);
699 if (ev == NULL) {
700 goto fail;
703 req = open_socket_out_send(frame, ev, pss, port, timeout);
704 if (req == NULL) {
705 goto fail;
707 if (!tevent_req_poll(req, ev)) {
708 status = NT_STATUS_INTERNAL_ERROR;
709 goto fail;
711 status = open_socket_out_recv(req, pfd);
712 fail:
713 TALLOC_FREE(frame);
714 return status;
717 struct open_socket_out_defer_state {
718 struct tevent_context *ev;
719 struct sockaddr_storage ss;
720 uint16_t port;
721 int timeout;
722 int fd;
725 static void open_socket_out_defer_waited(struct tevent_req *subreq);
726 static void open_socket_out_defer_connected(struct tevent_req *subreq);
728 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
729 struct tevent_context *ev,
730 struct timeval wait_time,
731 const struct sockaddr_storage *pss,
732 uint16_t port,
733 int timeout)
735 struct tevent_req *req, *subreq;
736 struct open_socket_out_defer_state *state;
738 req = tevent_req_create(mem_ctx, &state,
739 struct open_socket_out_defer_state);
740 if (req == NULL) {
741 return NULL;
743 state->ev = ev;
744 state->ss = *pss;
745 state->port = port;
746 state->timeout = timeout;
748 subreq = tevent_wakeup_send(
749 state, ev,
750 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
751 if (subreq == NULL) {
752 goto fail;
754 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
755 return req;
756 fail:
757 TALLOC_FREE(req);
758 return NULL;
761 static void open_socket_out_defer_waited(struct tevent_req *subreq)
763 struct tevent_req *req = tevent_req_callback_data(
764 subreq, struct tevent_req);
765 struct open_socket_out_defer_state *state = tevent_req_data(
766 req, struct open_socket_out_defer_state);
767 bool ret;
769 ret = tevent_wakeup_recv(subreq);
770 TALLOC_FREE(subreq);
771 if (!ret) {
772 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
773 return;
776 subreq = open_socket_out_send(state, state->ev, &state->ss,
777 state->port, state->timeout);
778 if (tevent_req_nomem(subreq, req)) {
779 return;
781 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
784 static void open_socket_out_defer_connected(struct tevent_req *subreq)
786 struct tevent_req *req = tevent_req_callback_data(
787 subreq, struct tevent_req);
788 struct open_socket_out_defer_state *state = tevent_req_data(
789 req, struct open_socket_out_defer_state);
790 NTSTATUS status;
792 status = open_socket_out_recv(subreq, &state->fd);
793 TALLOC_FREE(subreq);
794 if (!NT_STATUS_IS_OK(status)) {
795 tevent_req_nterror(req, status);
796 return;
798 tevent_req_done(req);
801 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
803 struct open_socket_out_defer_state *state = tevent_req_data(
804 req, struct open_socket_out_defer_state);
805 NTSTATUS status;
807 if (tevent_req_is_nterror(req, &status)) {
808 return status;
810 *pfd = state->fd;
811 state->fd = -1;
812 return NT_STATUS_OK;
815 /****************************************************************************
816 Open a connected UDP socket to host on port
817 **************************************************************************/
819 int open_udp_socket(const char *host, int port)
821 struct sockaddr_storage ss;
822 int res;
823 socklen_t salen;
825 if (!interpret_string_addr(&ss, host, 0)) {
826 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
827 host));
828 return -1;
831 res = socket(ss.ss_family, SOCK_DGRAM, 0);
832 if (res == -1) {
833 return -1;
836 #if defined(HAVE_IPV6)
837 if (ss.ss_family == AF_INET6) {
838 struct sockaddr_in6 *psa6;
839 psa6 = (struct sockaddr_in6 *)&ss;
840 psa6->sin6_port = htons(port);
841 if (psa6->sin6_scope_id == 0
842 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
843 setup_linklocal_scope_id(
844 (struct sockaddr *)&ss);
846 salen = sizeof(struct sockaddr_in6);
847 } else
848 #endif
849 if (ss.ss_family == AF_INET) {
850 struct sockaddr_in *psa;
851 psa = (struct sockaddr_in *)&ss;
852 psa->sin_port = htons(port);
853 salen = sizeof(struct sockaddr_in);
854 } else {
855 DEBUG(1, ("unknown socket family %d", ss.ss_family));
856 close(res);
857 return -1;
860 if (connect(res, (struct sockaddr *)&ss, salen)) {
861 close(res);
862 return -1;
865 return res;
868 /*******************************************************************
869 Return the IP addr of the remote end of a socket as a string.
870 Optionally return the struct sockaddr_storage.
871 ******************************************************************/
873 static const char *get_peer_addr_internal(int fd,
874 char *addr_buf,
875 size_t addr_buf_len,
876 struct sockaddr *pss,
877 socklen_t *plength)
879 struct sockaddr_storage ss;
880 socklen_t length = sizeof(ss);
882 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
884 if (fd == -1) {
885 return addr_buf;
888 if (pss == NULL) {
889 pss = (struct sockaddr *)&ss;
890 plength = &length;
893 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
894 int level = (errno == ENOTCONN) ? 2 : 0;
895 DEBUG(level, ("getpeername failed. Error was %s\n",
896 strerror(errno)));
897 return addr_buf;
900 print_sockaddr_len(addr_buf,
901 addr_buf_len,
902 pss,
903 *plength);
904 return addr_buf;
907 /*******************************************************************
908 Matchname - determine if host name matches IP address. Used to
909 confirm a hostname lookup to prevent spoof attacks.
910 ******************************************************************/
912 static bool matchname(const char *remotehost,
913 const struct sockaddr *pss,
914 socklen_t len)
916 struct addrinfo *res = NULL;
917 struct addrinfo *ailist = NULL;
918 char addr_buf[INET6_ADDRSTRLEN];
919 bool ret = interpret_string_addr_internal(&ailist,
920 remotehost,
921 AI_ADDRCONFIG|AI_CANONNAME);
923 if (!ret || ailist == NULL) {
924 DEBUG(3,("matchname: getaddrinfo failed for "
925 "name %s [%s]\n",
926 remotehost,
927 gai_strerror(ret) ));
928 return false;
932 * Make sure that getaddrinfo() returns the "correct" host name.
935 if (ailist->ai_canonname == NULL ||
936 (!strequal(remotehost, ailist->ai_canonname) &&
937 !strequal(remotehost, "localhost"))) {
938 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
939 remotehost,
940 ailist->ai_canonname ?
941 ailist->ai_canonname : "(NULL)"));
942 freeaddrinfo(ailist);
943 return false;
946 /* Look up the host address in the address list we just got. */
947 for (res = ailist; res; res = res->ai_next) {
948 if (!res->ai_addr) {
949 continue;
951 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
952 (const struct sockaddr *)pss)) {
953 freeaddrinfo(ailist);
954 return true;
959 * The host name does not map to the original host address. Perhaps
960 * someone has compromised a name server. More likely someone botched
961 * it, but that could be dangerous, too.
964 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
965 print_sockaddr_len(addr_buf,
966 sizeof(addr_buf),
967 pss,
968 len),
969 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
971 if (ailist) {
972 freeaddrinfo(ailist);
974 return false;
977 /*******************************************************************
978 Deal with the singleton cache.
979 ******************************************************************/
981 struct name_addr_pair {
982 struct sockaddr_storage ss;
983 const char *name;
986 /*******************************************************************
987 Lookup a name/addr pair. Returns memory allocated from memcache.
988 ******************************************************************/
990 static bool lookup_nc(struct name_addr_pair *nc)
992 DATA_BLOB tmp;
994 ZERO_STRUCTP(nc);
996 if (!memcache_lookup(
997 NULL, SINGLETON_CACHE,
998 data_blob_string_const_null("get_peer_name"),
999 &tmp)) {
1000 return false;
1003 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1004 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1005 return true;
1008 /*******************************************************************
1009 Save a name/addr pair.
1010 ******************************************************************/
1012 static void store_nc(const struct name_addr_pair *nc)
1014 DATA_BLOB tmp;
1015 size_t namelen = strlen(nc->name);
1017 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1018 if (!tmp.data) {
1019 return;
1021 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1022 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1024 memcache_add(NULL, SINGLETON_CACHE,
1025 data_blob_string_const_null("get_peer_name"),
1026 tmp);
1027 data_blob_free(&tmp);
1030 /*******************************************************************
1031 Return the DNS name of the remote end of a socket.
1032 ******************************************************************/
1034 const char *get_peer_name(int fd, bool force_lookup)
1036 struct name_addr_pair nc;
1037 char addr_buf[INET6_ADDRSTRLEN];
1038 struct sockaddr_storage ss;
1039 socklen_t length = sizeof(ss);
1040 const char *p;
1041 int ret;
1042 char name_buf[MAX_DNS_NAME_LENGTH];
1043 char tmp_name[MAX_DNS_NAME_LENGTH];
1045 /* reverse lookups can be *very* expensive, and in many
1046 situations won't work because many networks don't link dhcp
1047 with dns. To avoid the delay we avoid the lookup if
1048 possible */
1049 if (!lp_hostname_lookups() && (force_lookup == false)) {
1050 length = sizeof(nc.ss);
1051 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1052 (struct sockaddr *)&nc.ss, &length);
1053 store_nc(&nc);
1054 lookup_nc(&nc);
1055 return nc.name ? nc.name : "UNKNOWN";
1058 lookup_nc(&nc);
1060 memset(&ss, '\0', sizeof(ss));
1061 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1063 /* it might be the same as the last one - save some DNS work */
1064 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1065 return nc.name ? nc.name : "UNKNOWN";
1068 /* Not the same. We need to lookup. */
1069 if (fd == -1) {
1070 return "UNKNOWN";
1073 /* Look up the remote host name. */
1074 ret = sys_getnameinfo((struct sockaddr *)&ss,
1075 length,
1076 name_buf,
1077 sizeof(name_buf),
1078 NULL,
1082 if (ret) {
1083 DEBUG(1,("get_peer_name: getnameinfo failed "
1084 "for %s with error %s\n",
1086 gai_strerror(ret)));
1087 strlcpy(name_buf, p, sizeof(name_buf));
1088 } else {
1089 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1090 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1091 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1095 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1096 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1097 if (strstr(name_buf,"..")) {
1098 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1101 nc.name = name_buf;
1102 nc.ss = ss;
1104 store_nc(&nc);
1105 lookup_nc(&nc);
1106 return nc.name ? nc.name : "UNKNOWN";
1109 /*******************************************************************
1110 Return the IP addr of the remote end of a socket as a string.
1111 ******************************************************************/
1113 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1115 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1118 int get_remote_hostname(const struct tsocket_address *remote_address,
1119 char **name,
1120 TALLOC_CTX *mem_ctx)
1122 char name_buf[MAX_DNS_NAME_LENGTH];
1123 char tmp_name[MAX_DNS_NAME_LENGTH];
1124 struct name_addr_pair nc;
1125 struct sockaddr_storage ss;
1126 ssize_t len;
1127 int rc;
1129 if (!lp_hostname_lookups()) {
1130 nc.name = tsocket_address_inet_addr_string(remote_address,
1131 mem_ctx);
1132 if (nc.name == NULL) {
1133 return -1;
1136 len = tsocket_address_bsd_sockaddr(remote_address,
1137 (struct sockaddr *) &nc.ss,
1138 sizeof(struct sockaddr_storage));
1139 if (len < 0) {
1140 return -1;
1143 store_nc(&nc);
1144 lookup_nc(&nc);
1146 if (nc.name == NULL) {
1147 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1148 } else {
1149 *name = talloc_strdup(mem_ctx, nc.name);
1151 return 0;
1154 lookup_nc(&nc);
1156 ZERO_STRUCT(ss);
1158 len = tsocket_address_bsd_sockaddr(remote_address,
1159 (struct sockaddr *) &ss,
1160 sizeof(struct sockaddr_storage));
1161 if (len < 0) {
1162 return -1;
1165 /* it might be the same as the last one - save some DNS work */
1166 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1167 if (nc.name == NULL) {
1168 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1169 } else {
1170 *name = talloc_strdup(mem_ctx, nc.name);
1172 return 0;
1175 /* Look up the remote host name. */
1176 rc = sys_getnameinfo((struct sockaddr *) &ss,
1177 len,
1178 name_buf,
1179 sizeof(name_buf),
1180 NULL,
1183 if (rc < 0) {
1184 char *p;
1186 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1187 if (p == NULL) {
1188 return -1;
1191 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1193 gai_strerror(rc)));
1194 strlcpy(name_buf, p, sizeof(name_buf));
1196 TALLOC_FREE(p);
1197 } else {
1198 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1199 DEBUG(0,("matchname failed on %s\n", name_buf));
1200 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1204 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1205 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1206 if (strstr(name_buf,"..")) {
1207 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1210 nc.name = name_buf;
1211 nc.ss = ss;
1213 store_nc(&nc);
1214 lookup_nc(&nc);
1216 if (nc.name == NULL) {
1217 *name = talloc_strdup(mem_ctx, "UNKOWN");
1218 } else {
1219 *name = talloc_strdup(mem_ctx, nc.name);
1222 return 0;
1225 /*******************************************************************
1226 Create protected unix domain socket.
1228 Some unixes cannot set permissions on a ux-dom-sock, so we
1229 have to make sure that the directory contains the protection
1230 permissions instead.
1231 ******************************************************************/
1233 int create_pipe_sock(const char *socket_dir,
1234 const char *socket_name,
1235 mode_t dir_perms)
1237 #ifdef HAVE_UNIXSOCKET
1238 struct sockaddr_un sunaddr;
1239 bool ok;
1240 int sock;
1241 char *path = NULL;
1243 ok = directory_create_or_exist_strict(socket_dir,
1244 sec_initial_uid(),
1245 dir_perms);
1246 if (!ok) {
1247 return -1;
1250 /* Create the socket file */
1251 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1253 if (sock == -1) {
1254 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1255 strerror(errno) ));
1256 goto out_close;
1259 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1260 goto out_close;
1263 unlink(path);
1264 memset(&sunaddr, 0, sizeof(sunaddr));
1265 sunaddr.sun_family = AF_UNIX;
1266 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1268 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1269 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1270 strerror(errno)));
1271 goto out_close;
1274 SAFE_FREE(path);
1276 return sock;
1278 out_close:
1279 SAFE_FREE(path);
1280 if (sock != -1)
1281 close(sock);
1283 return -1;
1285 #else
1286 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1287 return -1;
1288 #endif /* HAVE_UNIXSOCKET */
1291 /****************************************************************************
1292 Get my own canonical name, including domain.
1293 ****************************************************************************/
1295 const char *get_mydnsfullname(void)
1297 struct addrinfo *res = NULL;
1298 char my_hostname[HOST_NAME_MAX];
1299 bool ret;
1300 DATA_BLOB tmp;
1302 if (memcache_lookup(NULL, SINGLETON_CACHE,
1303 data_blob_string_const_null("get_mydnsfullname"),
1304 &tmp)) {
1305 SMB_ASSERT(tmp.length > 0);
1306 return (const char *)tmp.data;
1309 /* get my host name */
1310 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1311 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1312 return NULL;
1315 /* Ensure null termination. */
1316 my_hostname[sizeof(my_hostname)-1] = '\0';
1318 ret = interpret_string_addr_internal(&res,
1319 my_hostname,
1320 AI_ADDRCONFIG|AI_CANONNAME);
1322 if (!ret || res == NULL) {
1323 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1324 "name %s [%s]\n",
1325 my_hostname,
1326 gai_strerror(ret) ));
1327 return NULL;
1331 * Make sure that getaddrinfo() returns the "correct" host name.
1334 if (res->ai_canonname == NULL) {
1335 DEBUG(3,("get_mydnsfullname: failed to get "
1336 "canonical name for %s\n",
1337 my_hostname));
1338 freeaddrinfo(res);
1339 return NULL;
1342 /* This copies the data, so we must do a lookup
1343 * afterwards to find the value to return.
1346 memcache_add(NULL, SINGLETON_CACHE,
1347 data_blob_string_const_null("get_mydnsfullname"),
1348 data_blob_string_const_null(res->ai_canonname));
1350 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1351 data_blob_string_const_null("get_mydnsfullname"),
1352 &tmp)) {
1353 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1354 strlen(res->ai_canonname) + 1);
1357 freeaddrinfo(res);
1359 return (const char *)tmp.data;
1362 /************************************************************
1363 Is this my ip address ?
1364 ************************************************************/
1366 static bool is_my_ipaddr(const char *ipaddr_str)
1368 struct sockaddr_storage ss;
1369 struct iface_struct *nics;
1370 int i, n;
1372 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1373 return false;
1376 if (is_zero_addr(&ss)) {
1377 return false;
1380 if (ismyaddr((struct sockaddr *)&ss) ||
1381 is_loopback_addr((struct sockaddr *)&ss)) {
1382 return true;
1385 n = get_interfaces(talloc_tos(), &nics);
1386 for (i=0; i<n; i++) {
1387 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1388 TALLOC_FREE(nics);
1389 return true;
1392 TALLOC_FREE(nics);
1393 return false;
1396 /************************************************************
1397 Is this my name ?
1398 ************************************************************/
1400 bool is_myname_or_ipaddr(const char *s)
1402 TALLOC_CTX *ctx = talloc_tos();
1403 char *name = NULL;
1404 const char *dnsname;
1405 char *servername = NULL;
1407 if (!s) {
1408 return false;
1411 /* Santize the string from '\\name' */
1412 name = talloc_strdup(ctx, s);
1413 if (!name) {
1414 return false;
1417 servername = strrchr_m(name, '\\' );
1418 if (!servername) {
1419 servername = name;
1420 } else {
1421 servername++;
1424 /* Optimize for the common case */
1425 if (strequal(servername, lp_netbios_name())) {
1426 return true;
1429 /* Check for an alias */
1430 if (is_myname(servername)) {
1431 return true;
1434 /* Check for loopback */
1435 if (strequal(servername, "127.0.0.1") ||
1436 strequal(servername, "::1")) {
1437 return true;
1440 if (strequal(servername, "localhost")) {
1441 return true;
1444 /* Maybe it's my dns name */
1445 dnsname = get_mydnsfullname();
1446 if (dnsname && strequal(servername, dnsname)) {
1447 return true;
1450 /* Maybe its an IP address? */
1451 if (is_ipaddress(servername)) {
1452 return is_my_ipaddr(servername);
1455 /* Handle possible CNAME records - convert to an IP addr. list. */
1457 /* Use DNS to resolve the name, check all addresses. */
1458 struct addrinfo *p = NULL;
1459 struct addrinfo *res = NULL;
1461 if (!interpret_string_addr_internal(&res,
1462 servername,
1463 AI_ADDRCONFIG)) {
1464 return false;
1467 for (p = res; p; p = p->ai_next) {
1468 char addr[INET6_ADDRSTRLEN];
1469 struct sockaddr_storage ss;
1471 ZERO_STRUCT(ss);
1472 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1473 print_sockaddr(addr,
1474 sizeof(addr),
1475 &ss);
1476 if (is_my_ipaddr(addr)) {
1477 freeaddrinfo(res);
1478 return true;
1481 freeaddrinfo(res);
1484 /* No match */
1485 return false;
1488 struct getaddrinfo_state {
1489 const char *node;
1490 const char *service;
1491 const struct addrinfo *hints;
1492 struct addrinfo *res;
1493 int ret;
1496 static void getaddrinfo_do(void *private_data);
1497 static void getaddrinfo_done(struct tevent_req *subreq);
1499 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1500 struct tevent_context *ev,
1501 struct fncall_context *ctx,
1502 const char *node,
1503 const char *service,
1504 const struct addrinfo *hints)
1506 struct tevent_req *req, *subreq;
1507 struct getaddrinfo_state *state;
1509 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1510 if (req == NULL) {
1511 return NULL;
1514 state->node = node;
1515 state->service = service;
1516 state->hints = hints;
1518 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1519 if (tevent_req_nomem(subreq, req)) {
1520 return tevent_req_post(req, ev);
1522 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1523 return req;
1526 static void getaddrinfo_do(void *private_data)
1528 struct getaddrinfo_state *state =
1529 (struct getaddrinfo_state *)private_data;
1531 state->ret = getaddrinfo(state->node, state->service, state->hints,
1532 &state->res);
1535 static void getaddrinfo_done(struct tevent_req *subreq)
1537 struct tevent_req *req = tevent_req_callback_data(
1538 subreq, struct tevent_req);
1539 int ret, err;
1541 ret = fncall_recv(subreq, &err);
1542 TALLOC_FREE(subreq);
1543 if (ret == -1) {
1544 tevent_req_error(req, err);
1545 return;
1547 tevent_req_done(req);
1550 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1552 struct getaddrinfo_state *state = tevent_req_data(
1553 req, struct getaddrinfo_state);
1554 int err;
1556 if (tevent_req_is_unix_error(req, &err)) {
1557 switch(err) {
1558 case ENOMEM:
1559 return EAI_MEMORY;
1560 default:
1561 return EAI_FAIL;
1564 if (state->ret == 0) {
1565 *res = state->res;
1567 return state->ret;
1570 int poll_one_fd(int fd, int events, int timeout, int *revents)
1572 struct pollfd *fds;
1573 int ret;
1574 int saved_errno;
1576 fds = talloc_zero_array(talloc_tos(), struct pollfd, 1);
1577 if (fds == NULL) {
1578 errno = ENOMEM;
1579 return -1;
1581 fds[0].fd = fd;
1582 fds[0].events = events;
1584 ret = poll(fds, 1, timeout);
1587 * Assign whatever poll did, even in the ret<=0 case.
1589 *revents = fds[0].revents;
1590 saved_errno = errno;
1591 TALLOC_FREE(fds);
1592 errno = saved_errno;
1594 return ret;
1597 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1599 struct pollfd pfd;
1600 int ret;
1602 pfd.fd = fd;
1603 pfd.events = events;
1605 ret = sys_poll_intr(&pfd, 1, timeout);
1606 if (ret <= 0) {
1607 *revents = 0;
1608 return ret;
1610 *revents = pfd.revents;
1611 return 1;