s3:smbd/server: create smbd_parent_context earlier
[Samba/id10ts.git] / source3 / lib / util_sock.c
blob9ade23c8bc7b68ebe2cba10122ac09d7758f1712
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 == SMB_PORT1 ||
486 port == SMB_PORT2 || port == NMB_PORT) ) {
487 char addr[INET6_ADDRSTRLEN];
488 print_sockaddr(addr, sizeof(addr),
489 &sock);
490 dbgtext( "bind failed on port %d ", port);
491 dbgtext( "socket_addr = %s.\n", addr);
492 dbgtext( "Error = %s\n", strerror(errno));
494 close(res);
495 return -1;
498 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
499 return( res );
502 struct open_socket_out_state {
503 int fd;
504 struct event_context *ev;
505 struct sockaddr_storage ss;
506 socklen_t salen;
507 uint16_t port;
508 int wait_usec;
511 static void open_socket_out_connected(struct tevent_req *subreq);
513 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
515 if (s->fd != -1) {
516 close(s->fd);
518 return 0;
521 /****************************************************************************
522 Create an outgoing socket. timeout is in milliseconds.
523 **************************************************************************/
525 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
526 struct event_context *ev,
527 const struct sockaddr_storage *pss,
528 uint16_t port,
529 int timeout)
531 char addr[INET6_ADDRSTRLEN];
532 struct tevent_req *result, *subreq;
533 struct open_socket_out_state *state;
534 NTSTATUS status;
536 result = tevent_req_create(mem_ctx, &state,
537 struct open_socket_out_state);
538 if (result == NULL) {
539 return NULL;
541 state->ev = ev;
542 state->ss = *pss;
543 state->port = port;
544 state->wait_usec = 10000;
545 state->salen = -1;
547 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
548 if (state->fd == -1) {
549 status = map_nt_error_from_unix(errno);
550 goto post_status;
552 talloc_set_destructor(state, open_socket_out_state_destructor);
554 if (!tevent_req_set_endtime(
555 result, ev, timeval_current_ofs_msec(timeout))) {
556 goto fail;
559 #if defined(HAVE_IPV6)
560 if (pss->ss_family == AF_INET6) {
561 struct sockaddr_in6 *psa6;
562 psa6 = (struct sockaddr_in6 *)&state->ss;
563 psa6->sin6_port = htons(port);
564 if (psa6->sin6_scope_id == 0
565 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
566 setup_linklocal_scope_id(
567 (struct sockaddr *)&(state->ss));
569 state->salen = sizeof(struct sockaddr_in6);
571 #endif
572 if (pss->ss_family == AF_INET) {
573 struct sockaddr_in *psa;
574 psa = (struct sockaddr_in *)&state->ss;
575 psa->sin_port = htons(port);
576 state->salen = sizeof(struct sockaddr_in);
579 if (pss->ss_family == AF_UNIX) {
580 state->salen = sizeof(struct sockaddr_un);
583 print_sockaddr(addr, sizeof(addr), &state->ss);
584 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
586 subreq = async_connect_send(state, state->ev, state->fd,
587 (struct sockaddr *)&state->ss,
588 state->salen);
589 if ((subreq == NULL)
590 || !tevent_req_set_endtime(
591 subreq, state->ev,
592 timeval_current_ofs(0, state->wait_usec))) {
593 goto fail;
595 tevent_req_set_callback(subreq, open_socket_out_connected, result);
596 return result;
598 post_status:
599 tevent_req_nterror(result, status);
600 return tevent_req_post(result, ev);
601 fail:
602 TALLOC_FREE(result);
603 return NULL;
606 static void open_socket_out_connected(struct tevent_req *subreq)
608 struct tevent_req *req =
609 tevent_req_callback_data(subreq, struct tevent_req);
610 struct open_socket_out_state *state =
611 tevent_req_data(req, struct open_socket_out_state);
612 int ret;
613 int sys_errno;
615 ret = async_connect_recv(subreq, &sys_errno);
616 TALLOC_FREE(subreq);
617 if (ret == 0) {
618 tevent_req_done(req);
619 return;
622 if (
623 #ifdef ETIMEDOUT
624 (sys_errno == ETIMEDOUT) ||
625 #endif
626 (sys_errno == EINPROGRESS) ||
627 (sys_errno == EALREADY) ||
628 (sys_errno == EAGAIN)) {
631 * retry
634 if (state->wait_usec < 250000) {
635 state->wait_usec *= 1.5;
638 subreq = async_connect_send(state, state->ev, state->fd,
639 (struct sockaddr *)&state->ss,
640 state->salen);
641 if (tevent_req_nomem(subreq, req)) {
642 return;
644 if (!tevent_req_set_endtime(
645 subreq, state->ev,
646 timeval_current_ofs_usec(state->wait_usec))) {
647 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
648 return;
650 tevent_req_set_callback(subreq, open_socket_out_connected, req);
651 return;
654 #ifdef EISCONN
655 if (sys_errno == EISCONN) {
656 tevent_req_done(req);
657 return;
659 #endif
661 /* real error */
662 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
665 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
667 struct open_socket_out_state *state =
668 tevent_req_data(req, struct open_socket_out_state);
669 NTSTATUS status;
671 if (tevent_req_is_nterror(req, &status)) {
672 return status;
674 *pfd = state->fd;
675 state->fd = -1;
676 return NT_STATUS_OK;
680 * @brief open a socket
682 * @param pss a struct sockaddr_storage defining the address to connect to
683 * @param port to connect to
684 * @param timeout in MILLISECONDS
685 * @param pfd file descriptor returned
687 * @return NTSTATUS code
689 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
690 int timeout, int *pfd)
692 TALLOC_CTX *frame = talloc_stackframe();
693 struct event_context *ev;
694 struct tevent_req *req;
695 NTSTATUS status = NT_STATUS_NO_MEMORY;
697 ev = event_context_init(frame);
698 if (ev == NULL) {
699 goto fail;
702 req = open_socket_out_send(frame, ev, pss, port, timeout);
703 if (req == NULL) {
704 goto fail;
706 if (!tevent_req_poll(req, ev)) {
707 status = NT_STATUS_INTERNAL_ERROR;
708 goto fail;
710 status = open_socket_out_recv(req, pfd);
711 fail:
712 TALLOC_FREE(frame);
713 return status;
716 struct open_socket_out_defer_state {
717 struct event_context *ev;
718 struct sockaddr_storage ss;
719 uint16_t port;
720 int timeout;
721 int fd;
724 static void open_socket_out_defer_waited(struct tevent_req *subreq);
725 static void open_socket_out_defer_connected(struct tevent_req *subreq);
727 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
728 struct event_context *ev,
729 struct timeval wait_time,
730 const struct sockaddr_storage *pss,
731 uint16_t port,
732 int timeout)
734 struct tevent_req *req, *subreq;
735 struct open_socket_out_defer_state *state;
737 req = tevent_req_create(mem_ctx, &state,
738 struct open_socket_out_defer_state);
739 if (req == NULL) {
740 return NULL;
742 state->ev = ev;
743 state->ss = *pss;
744 state->port = port;
745 state->timeout = timeout;
747 subreq = tevent_wakeup_send(
748 state, ev,
749 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
750 if (subreq == NULL) {
751 goto fail;
753 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
754 return req;
755 fail:
756 TALLOC_FREE(req);
757 return NULL;
760 static void open_socket_out_defer_waited(struct tevent_req *subreq)
762 struct tevent_req *req = tevent_req_callback_data(
763 subreq, struct tevent_req);
764 struct open_socket_out_defer_state *state = tevent_req_data(
765 req, struct open_socket_out_defer_state);
766 bool ret;
768 ret = tevent_wakeup_recv(subreq);
769 TALLOC_FREE(subreq);
770 if (!ret) {
771 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
772 return;
775 subreq = open_socket_out_send(state, state->ev, &state->ss,
776 state->port, state->timeout);
777 if (tevent_req_nomem(subreq, req)) {
778 return;
780 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
783 static void open_socket_out_defer_connected(struct tevent_req *subreq)
785 struct tevent_req *req = tevent_req_callback_data(
786 subreq, struct tevent_req);
787 struct open_socket_out_defer_state *state = tevent_req_data(
788 req, struct open_socket_out_defer_state);
789 NTSTATUS status;
791 status = open_socket_out_recv(subreq, &state->fd);
792 TALLOC_FREE(subreq);
793 if (!NT_STATUS_IS_OK(status)) {
794 tevent_req_nterror(req, status);
795 return;
797 tevent_req_done(req);
800 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
802 struct open_socket_out_defer_state *state = tevent_req_data(
803 req, struct open_socket_out_defer_state);
804 NTSTATUS status;
806 if (tevent_req_is_nterror(req, &status)) {
807 return status;
809 *pfd = state->fd;
810 state->fd = -1;
811 return NT_STATUS_OK;
814 /****************************************************************************
815 Open a connected UDP socket to host on port
816 **************************************************************************/
818 int open_udp_socket(const char *host, int port)
820 struct sockaddr_storage ss;
821 int res;
823 if (!interpret_string_addr(&ss, host, 0)) {
824 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
825 host));
826 return -1;
829 res = socket(ss.ss_family, SOCK_DGRAM, 0);
830 if (res == -1) {
831 return -1;
834 #if defined(HAVE_IPV6)
835 if (ss.ss_family == AF_INET6) {
836 struct sockaddr_in6 *psa6;
837 psa6 = (struct sockaddr_in6 *)&ss;
838 psa6->sin6_port = htons(port);
839 if (psa6->sin6_scope_id == 0
840 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
841 setup_linklocal_scope_id(
842 (struct sockaddr *)&ss);
845 #endif
846 if (ss.ss_family == AF_INET) {
847 struct sockaddr_in *psa;
848 psa = (struct sockaddr_in *)&ss;
849 psa->sin_port = htons(port);
852 if (sys_connect(res,(struct sockaddr *)&ss)) {
853 close(res);
854 return -1;
857 return res;
860 /*******************************************************************
861 Return the IP addr of the remote end of a socket as a string.
862 Optionally return the struct sockaddr_storage.
863 ******************************************************************/
865 static const char *get_peer_addr_internal(int fd,
866 char *addr_buf,
867 size_t addr_buf_len,
868 struct sockaddr *pss,
869 socklen_t *plength)
871 struct sockaddr_storage ss;
872 socklen_t length = sizeof(ss);
874 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
876 if (fd == -1) {
877 return addr_buf;
880 if (pss == NULL) {
881 pss = (struct sockaddr *)&ss;
882 plength = &length;
885 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
886 int level = (errno == ENOTCONN) ? 2 : 0;
887 DEBUG(level, ("getpeername failed. Error was %s\n",
888 strerror(errno)));
889 return addr_buf;
892 print_sockaddr_len(addr_buf,
893 addr_buf_len,
894 pss,
895 *plength);
896 return addr_buf;
899 /*******************************************************************
900 Matchname - determine if host name matches IP address. Used to
901 confirm a hostname lookup to prevent spoof attacks.
902 ******************************************************************/
904 static bool matchname(const char *remotehost,
905 const struct sockaddr *pss,
906 socklen_t len)
908 struct addrinfo *res = NULL;
909 struct addrinfo *ailist = NULL;
910 char addr_buf[INET6_ADDRSTRLEN];
911 bool ret = interpret_string_addr_internal(&ailist,
912 remotehost,
913 AI_ADDRCONFIG|AI_CANONNAME);
915 if (!ret || ailist == NULL) {
916 DEBUG(3,("matchname: getaddrinfo failed for "
917 "name %s [%s]\n",
918 remotehost,
919 gai_strerror(ret) ));
920 return false;
924 * Make sure that getaddrinfo() returns the "correct" host name.
927 if (ailist->ai_canonname == NULL ||
928 (!strequal(remotehost, ailist->ai_canonname) &&
929 !strequal(remotehost, "localhost"))) {
930 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
931 remotehost,
932 ailist->ai_canonname ?
933 ailist->ai_canonname : "(NULL)"));
934 freeaddrinfo(ailist);
935 return false;
938 /* Look up the host address in the address list we just got. */
939 for (res = ailist; res; res = res->ai_next) {
940 if (!res->ai_addr) {
941 continue;
943 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
944 (const struct sockaddr *)pss)) {
945 freeaddrinfo(ailist);
946 return true;
951 * The host name does not map to the original host address. Perhaps
952 * someone has compromised a name server. More likely someone botched
953 * it, but that could be dangerous, too.
956 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
957 print_sockaddr_len(addr_buf,
958 sizeof(addr_buf),
959 pss,
960 len),
961 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
963 if (ailist) {
964 freeaddrinfo(ailist);
966 return false;
969 /*******************************************************************
970 Deal with the singleton cache.
971 ******************************************************************/
973 struct name_addr_pair {
974 struct sockaddr_storage ss;
975 const char *name;
978 /*******************************************************************
979 Lookup a name/addr pair. Returns memory allocated from memcache.
980 ******************************************************************/
982 static bool lookup_nc(struct name_addr_pair *nc)
984 DATA_BLOB tmp;
986 ZERO_STRUCTP(nc);
988 if (!memcache_lookup(
989 NULL, SINGLETON_CACHE,
990 data_blob_string_const_null("get_peer_name"),
991 &tmp)) {
992 return false;
995 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
996 nc->name = (const char *)tmp.data + sizeof(nc->ss);
997 return true;
1000 /*******************************************************************
1001 Save a name/addr pair.
1002 ******************************************************************/
1004 static void store_nc(const struct name_addr_pair *nc)
1006 DATA_BLOB tmp;
1007 size_t namelen = strlen(nc->name);
1009 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1010 if (!tmp.data) {
1011 return;
1013 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1014 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1016 memcache_add(NULL, SINGLETON_CACHE,
1017 data_blob_string_const_null("get_peer_name"),
1018 tmp);
1019 data_blob_free(&tmp);
1022 /*******************************************************************
1023 Return the DNS name of the remote end of a socket.
1024 ******************************************************************/
1026 const char *get_peer_name(int fd, bool force_lookup)
1028 struct name_addr_pair nc;
1029 char addr_buf[INET6_ADDRSTRLEN];
1030 struct sockaddr_storage ss;
1031 socklen_t length = sizeof(ss);
1032 const char *p;
1033 int ret;
1034 char name_buf[MAX_DNS_NAME_LENGTH];
1035 char tmp_name[MAX_DNS_NAME_LENGTH];
1037 /* reverse lookups can be *very* expensive, and in many
1038 situations won't work because many networks don't link dhcp
1039 with dns. To avoid the delay we avoid the lookup if
1040 possible */
1041 if (!lp_hostname_lookups() && (force_lookup == false)) {
1042 length = sizeof(nc.ss);
1043 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1044 (struct sockaddr *)&nc.ss, &length);
1045 store_nc(&nc);
1046 lookup_nc(&nc);
1047 return nc.name ? nc.name : "UNKNOWN";
1050 lookup_nc(&nc);
1052 memset(&ss, '\0', sizeof(ss));
1053 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1055 /* it might be the same as the last one - save some DNS work */
1056 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1057 return nc.name ? nc.name : "UNKNOWN";
1060 /* Not the same. We need to lookup. */
1061 if (fd == -1) {
1062 return "UNKNOWN";
1065 /* Look up the remote host name. */
1066 ret = sys_getnameinfo((struct sockaddr *)&ss,
1067 length,
1068 name_buf,
1069 sizeof(name_buf),
1070 NULL,
1074 if (ret) {
1075 DEBUG(1,("get_peer_name: getnameinfo failed "
1076 "for %s with error %s\n",
1078 gai_strerror(ret)));
1079 strlcpy(name_buf, p, sizeof(name_buf));
1080 } else {
1081 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1082 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1083 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1087 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1088 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1089 if (strstr(name_buf,"..")) {
1090 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1093 nc.name = name_buf;
1094 nc.ss = ss;
1096 store_nc(&nc);
1097 lookup_nc(&nc);
1098 return nc.name ? nc.name : "UNKNOWN";
1101 /*******************************************************************
1102 Return the IP addr of the remote end of a socket as a string.
1103 ******************************************************************/
1105 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1107 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1110 int get_remote_hostname(const struct tsocket_address *remote_address,
1111 char **name,
1112 TALLOC_CTX *mem_ctx)
1114 char name_buf[MAX_DNS_NAME_LENGTH];
1115 char tmp_name[MAX_DNS_NAME_LENGTH];
1116 struct name_addr_pair nc;
1117 struct sockaddr_storage ss;
1118 ssize_t len;
1119 int rc;
1121 if (!lp_hostname_lookups()) {
1122 nc.name = tsocket_address_inet_addr_string(remote_address,
1123 mem_ctx);
1124 if (nc.name == NULL) {
1125 return -1;
1128 len = tsocket_address_bsd_sockaddr(remote_address,
1129 (struct sockaddr *) &nc.ss,
1130 sizeof(struct sockaddr_storage));
1131 if (len < 0) {
1132 return -1;
1135 store_nc(&nc);
1136 lookup_nc(&nc);
1138 if (nc.name == NULL) {
1139 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1140 } else {
1141 *name = talloc_strdup(mem_ctx, nc.name);
1143 return 0;
1146 lookup_nc(&nc);
1148 ZERO_STRUCT(ss);
1150 len = tsocket_address_bsd_sockaddr(remote_address,
1151 (struct sockaddr *) &ss,
1152 sizeof(struct sockaddr_storage));
1153 if (len < 0) {
1154 return -1;
1157 /* it might be the same as the last one - save some DNS work */
1158 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1159 if (nc.name == NULL) {
1160 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1161 } else {
1162 *name = talloc_strdup(mem_ctx, nc.name);
1164 return 0;
1167 /* Look up the remote host name. */
1168 rc = sys_getnameinfo((struct sockaddr *) &ss,
1169 len,
1170 name_buf,
1171 sizeof(name_buf),
1172 NULL,
1175 if (rc < 0) {
1176 char *p;
1178 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1179 if (p == NULL) {
1180 return -1;
1183 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1185 gai_strerror(rc)));
1186 strlcpy(name_buf, p, sizeof(name_buf));
1188 TALLOC_FREE(p);
1189 } else {
1190 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1191 DEBUG(0,("matchname failed on %s\n", name_buf));
1192 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1196 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1197 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1198 if (strstr(name_buf,"..")) {
1199 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1202 nc.name = name_buf;
1203 nc.ss = ss;
1205 store_nc(&nc);
1206 lookup_nc(&nc);
1208 if (nc.name == NULL) {
1209 *name = talloc_strdup(mem_ctx, "UNKOWN");
1210 } else {
1211 *name = talloc_strdup(mem_ctx, nc.name);
1214 return 0;
1217 /*******************************************************************
1218 Create protected unix domain socket.
1220 Some unixes cannot set permissions on a ux-dom-sock, so we
1221 have to make sure that the directory contains the protection
1222 permissions instead.
1223 ******************************************************************/
1225 int create_pipe_sock(const char *socket_dir,
1226 const char *socket_name,
1227 mode_t dir_perms)
1229 #ifdef HAVE_UNIXSOCKET
1230 struct sockaddr_un sunaddr;
1231 struct stat st;
1232 int sock;
1233 mode_t old_umask;
1234 char *path = NULL;
1236 old_umask = umask(0);
1238 /* Create the socket directory or reuse the existing one */
1240 if (lstat(socket_dir, &st) == -1) {
1241 if (errno == ENOENT) {
1242 /* Create directory */
1243 if (mkdir(socket_dir, dir_perms) == -1) {
1244 DEBUG(0, ("error creating socket directory "
1245 "%s: %s\n", socket_dir,
1246 strerror(errno)));
1247 goto out_umask;
1249 } else {
1250 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1251 socket_dir, strerror(errno)));
1252 goto out_umask;
1254 } else {
1255 /* Check ownership and permission on existing directory */
1256 if (!S_ISDIR(st.st_mode)) {
1257 DEBUG(0, ("socket directory '%s' isn't a directory\n",
1258 socket_dir));
1259 goto out_umask;
1261 if (st.st_uid != sec_initial_uid()) {
1262 DEBUG(0, ("invalid ownership on directory "
1263 "'%s'\n", socket_dir));
1264 umask(old_umask);
1265 goto out_umask;
1267 if ((st.st_mode & 0777) != dir_perms) {
1268 DEBUG(0, ("invalid permissions on directory "
1269 "'%s': has 0%o should be 0%o\n", socket_dir,
1270 (st.st_mode & 0777), dir_perms));
1271 umask(old_umask);
1272 goto out_umask;
1276 /* Create the socket file */
1278 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1280 if (sock == -1) {
1281 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1282 strerror(errno) ));
1283 goto out_close;
1286 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1287 goto out_close;
1290 unlink(path);
1291 memset(&sunaddr, 0, sizeof(sunaddr));
1292 sunaddr.sun_family = AF_UNIX;
1293 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1295 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1296 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1297 strerror(errno)));
1298 goto out_close;
1301 SAFE_FREE(path);
1303 umask(old_umask);
1304 return sock;
1306 out_close:
1307 SAFE_FREE(path);
1308 if (sock != -1)
1309 close(sock);
1311 out_umask:
1312 umask(old_umask);
1313 return -1;
1315 #else
1316 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1317 return -1;
1318 #endif /* HAVE_UNIXSOCKET */
1321 /****************************************************************************
1322 Get my own canonical name, including domain.
1323 ****************************************************************************/
1325 const char *get_mydnsfullname(void)
1327 struct addrinfo *res = NULL;
1328 char my_hostname[HOST_NAME_MAX];
1329 bool ret;
1330 DATA_BLOB tmp;
1332 if (memcache_lookup(NULL, SINGLETON_CACHE,
1333 data_blob_string_const_null("get_mydnsfullname"),
1334 &tmp)) {
1335 SMB_ASSERT(tmp.length > 0);
1336 return (const char *)tmp.data;
1339 /* get my host name */
1340 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1341 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1342 return NULL;
1345 /* Ensure null termination. */
1346 my_hostname[sizeof(my_hostname)-1] = '\0';
1348 ret = interpret_string_addr_internal(&res,
1349 my_hostname,
1350 AI_ADDRCONFIG|AI_CANONNAME);
1352 if (!ret || res == NULL) {
1353 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1354 "name %s [%s]\n",
1355 my_hostname,
1356 gai_strerror(ret) ));
1357 return NULL;
1361 * Make sure that getaddrinfo() returns the "correct" host name.
1364 if (res->ai_canonname == NULL) {
1365 DEBUG(3,("get_mydnsfullname: failed to get "
1366 "canonical name for %s\n",
1367 my_hostname));
1368 freeaddrinfo(res);
1369 return NULL;
1372 /* This copies the data, so we must do a lookup
1373 * afterwards to find the value to return.
1376 memcache_add(NULL, SINGLETON_CACHE,
1377 data_blob_string_const_null("get_mydnsfullname"),
1378 data_blob_string_const_null(res->ai_canonname));
1380 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1381 data_blob_string_const_null("get_mydnsfullname"),
1382 &tmp)) {
1383 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1384 strlen(res->ai_canonname) + 1);
1387 freeaddrinfo(res);
1389 return (const char *)tmp.data;
1392 /************************************************************
1393 Is this my ip address ?
1394 ************************************************************/
1396 static bool is_my_ipaddr(const char *ipaddr_str)
1398 struct sockaddr_storage ss;
1399 struct iface_struct *nics;
1400 int i, n;
1402 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1403 return false;
1406 if (is_zero_addr(&ss)) {
1407 return false;
1410 if (ismyaddr((struct sockaddr *)&ss) ||
1411 is_loopback_addr((struct sockaddr *)&ss)) {
1412 return true;
1415 n = get_interfaces(talloc_tos(), &nics);
1416 for (i=0; i<n; i++) {
1417 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1418 TALLOC_FREE(nics);
1419 return true;
1422 TALLOC_FREE(nics);
1423 return false;
1426 /************************************************************
1427 Is this my name ?
1428 ************************************************************/
1430 bool is_myname_or_ipaddr(const char *s)
1432 TALLOC_CTX *ctx = talloc_tos();
1433 char *name = NULL;
1434 const char *dnsname;
1435 char *servername = NULL;
1437 if (!s) {
1438 return false;
1441 /* Santize the string from '\\name' */
1442 name = talloc_strdup(ctx, s);
1443 if (!name) {
1444 return false;
1447 servername = strrchr_m(name, '\\' );
1448 if (!servername) {
1449 servername = name;
1450 } else {
1451 servername++;
1454 /* Optimize for the common case */
1455 if (strequal(servername, lp_netbios_name())) {
1456 return true;
1459 /* Check for an alias */
1460 if (is_myname(servername)) {
1461 return true;
1464 /* Check for loopback */
1465 if (strequal(servername, "127.0.0.1") ||
1466 strequal(servername, "::1")) {
1467 return true;
1470 if (strequal(servername, "localhost")) {
1471 return true;
1474 /* Maybe it's my dns name */
1475 dnsname = get_mydnsfullname();
1476 if (dnsname && strequal(servername, dnsname)) {
1477 return true;
1480 /* Maybe its an IP address? */
1481 if (is_ipaddress(servername)) {
1482 return is_my_ipaddr(servername);
1485 /* Handle possible CNAME records - convert to an IP addr. list. */
1487 /* Use DNS to resolve the name, check all addresses. */
1488 struct addrinfo *p = NULL;
1489 struct addrinfo *res = NULL;
1491 if (!interpret_string_addr_internal(&res,
1492 servername,
1493 AI_ADDRCONFIG)) {
1494 return false;
1497 for (p = res; p; p = p->ai_next) {
1498 char addr[INET6_ADDRSTRLEN];
1499 struct sockaddr_storage ss;
1501 ZERO_STRUCT(ss);
1502 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1503 print_sockaddr(addr,
1504 sizeof(addr),
1505 &ss);
1506 if (is_my_ipaddr(addr)) {
1507 freeaddrinfo(res);
1508 return true;
1511 freeaddrinfo(res);
1514 /* No match */
1515 return false;
1518 struct getaddrinfo_state {
1519 const char *node;
1520 const char *service;
1521 const struct addrinfo *hints;
1522 struct addrinfo *res;
1523 int ret;
1526 static void getaddrinfo_do(void *private_data);
1527 static void getaddrinfo_done(struct tevent_req *subreq);
1529 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1530 struct tevent_context *ev,
1531 struct fncall_context *ctx,
1532 const char *node,
1533 const char *service,
1534 const struct addrinfo *hints)
1536 struct tevent_req *req, *subreq;
1537 struct getaddrinfo_state *state;
1539 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1540 if (req == NULL) {
1541 return NULL;
1544 state->node = node;
1545 state->service = service;
1546 state->hints = hints;
1548 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1549 if (tevent_req_nomem(subreq, req)) {
1550 return tevent_req_post(req, ev);
1552 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1553 return req;
1556 static void getaddrinfo_do(void *private_data)
1558 struct getaddrinfo_state *state =
1559 (struct getaddrinfo_state *)private_data;
1561 state->ret = getaddrinfo(state->node, state->service, state->hints,
1562 &state->res);
1565 static void getaddrinfo_done(struct tevent_req *subreq)
1567 struct tevent_req *req = tevent_req_callback_data(
1568 subreq, struct tevent_req);
1569 int ret, err;
1571 ret = fncall_recv(subreq, &err);
1572 TALLOC_FREE(subreq);
1573 if (ret == -1) {
1574 tevent_req_error(req, err);
1575 return;
1577 tevent_req_done(req);
1580 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1582 struct getaddrinfo_state *state = tevent_req_data(
1583 req, struct getaddrinfo_state);
1584 int err;
1586 if (tevent_req_is_unix_error(req, &err)) {
1587 switch(err) {
1588 case ENOMEM:
1589 return EAI_MEMORY;
1590 default:
1591 return EAI_FAIL;
1594 if (state->ret == 0) {
1595 *res = state->res;
1597 return state->ret;
1600 int poll_one_fd(int fd, int events, int timeout, int *revents)
1602 struct pollfd *fds;
1603 int ret;
1604 int saved_errno;
1606 fds = talloc_zero_array(talloc_tos(), struct pollfd, 2);
1607 if (fds == NULL) {
1608 errno = ENOMEM;
1609 return -1;
1611 fds[0].fd = fd;
1612 fds[0].events = events;
1614 ret = sys_poll(fds, 1, timeout);
1617 * Assign whatever poll did, even in the ret<=0 case.
1619 *revents = fds[0].revents;
1620 saved_errno = errno;
1621 TALLOC_FREE(fds);
1622 errno = saved_errno;
1624 return ret;
1627 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1629 struct pollfd pfd;
1630 int ret;
1632 pfd.fd = fd;
1633 pfd.events = events;
1635 ret = sys_poll_intr(&pfd, 1, timeout);
1636 if (ret <= 0) {
1637 *revents = 0;
1638 return ret;
1640 *revents = pfd.revents;
1641 return 1;