srv_srvsvc_nt: remove unneeded get_share_params() call
[Samba.git] / source3 / lib / util_sock.c
blobd865ffba7c6d5ad91afa2877ce90956d50e9bb61
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"
32 const char *client_addr(int fd, char *addr, size_t addrlen)
34 return get_peer_addr(fd,addr,addrlen);
37 #if 0
38 /* Not currently used. JRA. */
39 int client_socket_port(int fd)
41 return get_socket_port(fd);
43 #endif
45 /****************************************************************************
46 Determine if a file descriptor is in fact a socket.
47 ****************************************************************************/
49 bool is_a_socket(int fd)
51 int v;
52 socklen_t l;
53 l = sizeof(int);
54 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
57 /****************************************************************************
58 Read from a socket.
59 ****************************************************************************/
61 ssize_t read_udp_v4_socket(int fd,
62 char *buf,
63 size_t len,
64 struct sockaddr_storage *psa)
66 ssize_t ret;
67 socklen_t socklen = sizeof(*psa);
68 struct sockaddr_in *si = (struct sockaddr_in *)psa;
70 memset((char *)psa,'\0',socklen);
72 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
73 (struct sockaddr *)psa,&socklen);
74 if (ret <= 0) {
75 /* Don't print a low debug error for a non-blocking socket. */
76 if (errno == EAGAIN) {
77 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
78 } else {
79 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
80 strerror(errno)));
82 return 0;
85 if (psa->ss_family != AF_INET) {
86 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
87 "(not IPv4)\n", (int)psa->ss_family));
88 return 0;
91 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
92 inet_ntoa(si->sin_addr),
93 si->sin_port,
94 (unsigned long)ret));
96 return ret;
99 /****************************************************************************
100 Read data from a file descriptor with a timout in msec.
101 mincount = if timeout, minimum to read before returning
102 maxcount = number to be read.
103 time_out = timeout in milliseconds
104 NB. This can be called with a non-socket fd, don't change
105 sys_read() to sys_recv() or other socket call.
106 ****************************************************************************/
108 NTSTATUS read_fd_with_timeout(int fd, char *buf,
109 size_t mincnt, size_t maxcnt,
110 unsigned int time_out,
111 size_t *size_ret)
113 int pollrtn;
114 ssize_t readret;
115 size_t nread = 0;
117 /* just checking .... */
118 if (maxcnt <= 0)
119 return NT_STATUS_OK;
121 /* Blocking read */
122 if (time_out == 0) {
123 if (mincnt == 0) {
124 mincnt = maxcnt;
127 while (nread < mincnt) {
128 readret = sys_read(fd, buf + nread, maxcnt - nread);
130 if (readret == 0) {
131 DEBUG(5,("read_fd_with_timeout: "
132 "blocking read. EOF from client.\n"));
133 return NT_STATUS_END_OF_FILE;
136 if (readret == -1) {
137 return map_nt_error_from_unix(errno);
139 nread += readret;
141 goto done;
144 /* Most difficult - timeout read */
145 /* If this is ever called on a disk file and
146 mincnt is greater then the filesize then
147 system performance will suffer severely as
148 select always returns true on disk files */
150 for (nread=0; nread < mincnt; ) {
151 int revents;
153 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
154 &revents);
156 /* Check if error */
157 if (pollrtn == -1) {
158 return map_nt_error_from_unix(errno);
161 /* Did we timeout ? */
162 if ((pollrtn == 0) ||
163 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
164 DEBUG(10,("read_fd_with_timeout: timeout read. "
165 "select timed out.\n"));
166 return NT_STATUS_IO_TIMEOUT;
169 readret = sys_read(fd, buf+nread, maxcnt-nread);
171 if (readret == 0) {
172 /* we got EOF on the file descriptor */
173 DEBUG(5,("read_fd_with_timeout: timeout read. "
174 "EOF from client.\n"));
175 return NT_STATUS_END_OF_FILE;
178 if (readret == -1) {
179 return map_nt_error_from_unix(errno);
182 nread += readret;
185 done:
186 /* Return the number we got */
187 if (size_ret) {
188 *size_ret = nread;
190 return NT_STATUS_OK;
193 /****************************************************************************
194 Read data from an fd, reading exactly N bytes.
195 NB. This can be called with a non-socket fd, don't add dependencies
196 on socket calls.
197 ****************************************************************************/
199 NTSTATUS read_data(int fd, char *buffer, size_t N)
201 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
204 ssize_t iov_buflen(const struct iovec *iov, int iovcnt)
206 size_t buflen = 0;
207 int i;
209 for (i=0; i<iovcnt; i++) {
210 size_t thislen = iov[i].iov_len;
211 size_t tmp = buflen + thislen;
213 if ((tmp < buflen) || (tmp < thislen)) {
214 /* overflow */
215 return -1;
217 buflen = tmp;
219 return buflen;
222 uint8_t *iov_buf(TALLOC_CTX *mem_ctx, const struct iovec *iov, int iovcnt)
224 int i;
225 ssize_t buflen;
226 uint8_t *buf, *p;
228 buflen = iov_buflen(iov, iovcnt);
229 if (buflen == -1) {
230 return NULL;
232 buf = talloc_array(mem_ctx, uint8_t, buflen);
233 if (buf == NULL) {
234 return NULL;
237 p = buf;
238 for (i=0; i<iovcnt; i++) {
239 size_t len = iov[i].iov_len;
241 memcpy(p, iov[i].iov_base, len);
242 p += len;
244 return buf;
247 /****************************************************************************
248 Write all data from an iov array
249 NB. This can be called with a non-socket fd, don't add dependencies
250 on socket calls.
251 ****************************************************************************/
253 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
255 ssize_t to_send;
256 ssize_t thistime;
257 size_t sent;
258 struct iovec iov_copy[iovcnt];
259 struct iovec *iov;
261 to_send = iov_buflen(orig_iov, iovcnt);
262 if (to_send == -1) {
263 errno = EINVAL;
264 return -1;
267 thistime = sys_writev(fd, orig_iov, iovcnt);
268 if ((thistime <= 0) || (thistime == to_send)) {
269 return thistime;
271 sent = thistime;
274 * We could not send everything in one call. Make a copy of iov that
275 * we can mess with. We keep a copy of the array start in iov_copy for
276 * the TALLOC_FREE, because we're going to modify iov later on,
277 * discarding elements.
280 memcpy(iov_copy, orig_iov, sizeof(struct iovec) * iovcnt);
281 iov = iov_copy;
283 while (sent < to_send) {
285 * We have to discard "thistime" bytes from the beginning
286 * iov array, "thistime" contains the number of bytes sent
287 * via writev last.
289 while (thistime > 0) {
290 if (thistime < iov[0].iov_len) {
291 char *new_base =
292 (char *)iov[0].iov_base + thistime;
293 iov[0].iov_base = (void *)new_base;
294 iov[0].iov_len -= thistime;
295 break;
297 thistime -= iov[0].iov_len;
298 iov += 1;
299 iovcnt -= 1;
302 thistime = sys_writev(fd, iov, iovcnt);
303 if (thistime <= 0) {
304 break;
306 sent += thistime;
309 return sent;
312 /****************************************************************************
313 Write data to a fd.
314 NB. This can be called with a non-socket fd, don't add dependencies
315 on socket calls.
316 ****************************************************************************/
318 ssize_t write_data(int fd, const char *buffer, size_t N)
320 struct iovec iov;
322 iov.iov_base = discard_const_p(void, buffer);
323 iov.iov_len = N;
324 return write_data_iov(fd, &iov, 1);
327 /****************************************************************************
328 Send a keepalive packet (rfc1002).
329 ****************************************************************************/
331 bool send_keepalive(int client)
333 unsigned char buf[4];
335 buf[0] = NBSSkeepalive;
336 buf[1] = buf[2] = buf[3] = 0;
338 return(write_data(client,(char *)buf,4) == 4);
341 /****************************************************************************
342 Read 4 bytes of a smb packet and return the smb length of the packet.
343 Store the result in the buffer.
344 This version of the function will return a length of zero on receiving
345 a keepalive packet.
346 Timeout is in milliseconds.
347 ****************************************************************************/
349 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
350 unsigned int timeout,
351 size_t *len)
353 int msg_type;
354 NTSTATUS status;
356 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
358 if (!NT_STATUS_IS_OK(status)) {
359 return status;
362 *len = smb_len(inbuf);
363 msg_type = CVAL(inbuf,0);
365 if (msg_type == NBSSkeepalive) {
366 DEBUG(5,("Got keepalive packet\n"));
369 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
371 return NT_STATUS_OK;
374 /****************************************************************************
375 Read an smb from a fd.
376 The timeout is in milliseconds.
377 This function will return on receipt of a session keepalive packet.
378 maxlen is the max number of bytes to return, not including the 4 byte
379 length. If zero it means buflen limit.
380 Doesn't check the MAC on signed packets.
381 ****************************************************************************/
383 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
384 size_t maxlen, size_t *p_len)
386 size_t len;
387 NTSTATUS status;
389 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
391 if (!NT_STATUS_IS_OK(status)) {
392 DEBUG(0, ("read_fd_with_timeout failed, read "
393 "error = %s.\n", nt_errstr(status)));
394 return status;
397 if (len > buflen) {
398 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
399 (unsigned long)len));
400 return NT_STATUS_INVALID_PARAMETER;
403 if(len > 0) {
404 if (maxlen) {
405 len = MIN(len,maxlen);
408 status = read_fd_with_timeout(
409 fd, buffer+4, len, len, timeout, &len);
411 if (!NT_STATUS_IS_OK(status)) {
412 DEBUG(0, ("read_fd_with_timeout failed, read error = "
413 "%s.\n", nt_errstr(status)));
414 return status;
417 /* not all of samba3 properly checks for packet-termination
418 * of strings. This ensures that we don't run off into
419 * empty space. */
420 SSVAL(buffer+4,len, 0);
423 *p_len = len;
424 return NT_STATUS_OK;
427 /****************************************************************************
428 Open a socket of the specified type, port, and address for incoming data.
429 ****************************************************************************/
431 int open_socket_in(int type,
432 uint16_t port,
433 int dlevel,
434 const struct sockaddr_storage *psock,
435 bool rebind)
437 struct sockaddr_storage sock;
438 int res;
439 socklen_t slen = sizeof(struct sockaddr_in);
441 sock = *psock;
443 #if defined(HAVE_IPV6)
444 if (sock.ss_family == AF_INET6) {
445 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
446 slen = sizeof(struct sockaddr_in6);
448 #endif
449 if (sock.ss_family == AF_INET) {
450 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
453 res = socket(sock.ss_family, type, 0 );
454 if( res == -1 ) {
455 if( DEBUGLVL(0) ) {
456 dbgtext( "open_socket_in(): socket() call failed: " );
457 dbgtext( "%s\n", strerror( errno ) );
459 return -1;
462 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
464 int val = rebind ? 1 : 0;
465 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
466 (char *)&val,sizeof(val)) == -1 ) {
467 if( DEBUGLVL( dlevel ) ) {
468 dbgtext( "open_socket_in(): setsockopt: " );
469 dbgtext( "SO_REUSEADDR = %s ",
470 val?"true":"false" );
471 dbgtext( "on port %d failed ", port );
472 dbgtext( "with error = %s\n", strerror(errno) );
475 #ifdef SO_REUSEPORT
476 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
477 (char *)&val,sizeof(val)) == -1 ) {
478 if( DEBUGLVL( dlevel ) ) {
479 dbgtext( "open_socket_in(): setsockopt: ");
480 dbgtext( "SO_REUSEPORT = %s ",
481 val?"true":"false");
482 dbgtext( "on port %d failed ", port);
483 dbgtext( "with error = %s\n", strerror(errno));
486 #endif /* SO_REUSEPORT */
489 #ifdef HAVE_IPV6
491 * As IPV6_V6ONLY is the default on some systems,
492 * we better try to be consistent and always use it.
494 * This also avoids using IPv4 via AF_INET6 sockets
495 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
496 * string.
498 if (sock.ss_family == AF_INET6) {
499 int val = 1;
500 int ret;
502 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
503 (const void *)&val, sizeof(val));
504 if (ret == -1) {
505 if(DEBUGLVL(0)) {
506 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
507 dbgtext("%s\n", strerror(errno));
509 close(res);
510 return -1;
513 #endif
515 /* now we've got a socket - we need to bind it */
516 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
517 if( DEBUGLVL(dlevel) && (port == NMB_PORT ||
518 port == NBT_SMB_PORT ||
519 port == TCP_SMB_PORT) ) {
520 char addr[INET6_ADDRSTRLEN];
521 print_sockaddr(addr, sizeof(addr),
522 &sock);
523 dbgtext( "bind failed on port %d ", port);
524 dbgtext( "socket_addr = %s.\n", addr);
525 dbgtext( "Error = %s\n", strerror(errno));
527 close(res);
528 return -1;
531 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
532 return( res );
535 struct open_socket_out_state {
536 int fd;
537 struct tevent_context *ev;
538 struct sockaddr_storage ss;
539 socklen_t salen;
540 uint16_t port;
541 int wait_usec;
544 static void open_socket_out_connected(struct tevent_req *subreq);
546 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
548 if (s->fd != -1) {
549 close(s->fd);
551 return 0;
554 /****************************************************************************
555 Create an outgoing socket. timeout is in milliseconds.
556 **************************************************************************/
558 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
559 struct tevent_context *ev,
560 const struct sockaddr_storage *pss,
561 uint16_t port,
562 int timeout)
564 char addr[INET6_ADDRSTRLEN];
565 struct tevent_req *result, *subreq;
566 struct open_socket_out_state *state;
567 NTSTATUS status;
569 result = tevent_req_create(mem_ctx, &state,
570 struct open_socket_out_state);
571 if (result == NULL) {
572 return NULL;
574 state->ev = ev;
575 state->ss = *pss;
576 state->port = port;
577 state->wait_usec = 10000;
578 state->salen = -1;
580 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
581 if (state->fd == -1) {
582 status = map_nt_error_from_unix(errno);
583 goto post_status;
585 talloc_set_destructor(state, open_socket_out_state_destructor);
587 if (!tevent_req_set_endtime(
588 result, ev, timeval_current_ofs_msec(timeout))) {
589 goto fail;
592 #if defined(HAVE_IPV6)
593 if (pss->ss_family == AF_INET6) {
594 struct sockaddr_in6 *psa6;
595 psa6 = (struct sockaddr_in6 *)&state->ss;
596 psa6->sin6_port = htons(port);
597 if (psa6->sin6_scope_id == 0
598 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
599 setup_linklocal_scope_id(
600 (struct sockaddr *)&(state->ss));
602 state->salen = sizeof(struct sockaddr_in6);
604 #endif
605 if (pss->ss_family == AF_INET) {
606 struct sockaddr_in *psa;
607 psa = (struct sockaddr_in *)&state->ss;
608 psa->sin_port = htons(port);
609 state->salen = sizeof(struct sockaddr_in);
612 if (pss->ss_family == AF_UNIX) {
613 state->salen = sizeof(struct sockaddr_un);
616 print_sockaddr(addr, sizeof(addr), &state->ss);
617 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
619 subreq = async_connect_send(state, state->ev, state->fd,
620 (struct sockaddr *)&state->ss,
621 state->salen, NULL, NULL, NULL);
622 if ((subreq == NULL)
623 || !tevent_req_set_endtime(
624 subreq, state->ev,
625 timeval_current_ofs(0, state->wait_usec))) {
626 goto fail;
628 tevent_req_set_callback(subreq, open_socket_out_connected, result);
629 return result;
631 post_status:
632 tevent_req_nterror(result, status);
633 return tevent_req_post(result, ev);
634 fail:
635 TALLOC_FREE(result);
636 return NULL;
639 static void open_socket_out_connected(struct tevent_req *subreq)
641 struct tevent_req *req =
642 tevent_req_callback_data(subreq, struct tevent_req);
643 struct open_socket_out_state *state =
644 tevent_req_data(req, struct open_socket_out_state);
645 int ret;
646 int sys_errno;
648 ret = async_connect_recv(subreq, &sys_errno);
649 TALLOC_FREE(subreq);
650 if (ret == 0) {
651 tevent_req_done(req);
652 return;
655 if (
656 #ifdef ETIMEDOUT
657 (sys_errno == ETIMEDOUT) ||
658 #endif
659 (sys_errno == EINPROGRESS) ||
660 (sys_errno == EALREADY) ||
661 (sys_errno == EAGAIN)) {
664 * retry
667 if (state->wait_usec < 250000) {
668 state->wait_usec *= 1.5;
671 subreq = async_connect_send(state, state->ev, state->fd,
672 (struct sockaddr *)&state->ss,
673 state->salen, NULL, NULL, NULL);
674 if (tevent_req_nomem(subreq, req)) {
675 return;
677 if (!tevent_req_set_endtime(
678 subreq, state->ev,
679 timeval_current_ofs_usec(state->wait_usec))) {
680 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
681 return;
683 tevent_req_set_callback(subreq, open_socket_out_connected, req);
684 return;
687 #ifdef EISCONN
688 if (sys_errno == EISCONN) {
689 tevent_req_done(req);
690 return;
692 #endif
694 /* real error */
695 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
698 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
700 struct open_socket_out_state *state =
701 tevent_req_data(req, struct open_socket_out_state);
702 NTSTATUS status;
704 if (tevent_req_is_nterror(req, &status)) {
705 return status;
707 *pfd = state->fd;
708 state->fd = -1;
709 return NT_STATUS_OK;
713 * @brief open a socket
715 * @param pss a struct sockaddr_storage defining the address to connect to
716 * @param port to connect to
717 * @param timeout in MILLISECONDS
718 * @param pfd file descriptor returned
720 * @return NTSTATUS code
722 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
723 int timeout, int *pfd)
725 TALLOC_CTX *frame = talloc_stackframe();
726 struct tevent_context *ev;
727 struct tevent_req *req;
728 NTSTATUS status = NT_STATUS_NO_MEMORY;
730 ev = samba_tevent_context_init(frame);
731 if (ev == NULL) {
732 goto fail;
735 req = open_socket_out_send(frame, ev, pss, port, timeout);
736 if (req == NULL) {
737 goto fail;
739 if (!tevent_req_poll(req, ev)) {
740 status = NT_STATUS_INTERNAL_ERROR;
741 goto fail;
743 status = open_socket_out_recv(req, pfd);
744 fail:
745 TALLOC_FREE(frame);
746 return status;
749 struct open_socket_out_defer_state {
750 struct tevent_context *ev;
751 struct sockaddr_storage ss;
752 uint16_t port;
753 int timeout;
754 int fd;
757 static void open_socket_out_defer_waited(struct tevent_req *subreq);
758 static void open_socket_out_defer_connected(struct tevent_req *subreq);
760 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
761 struct tevent_context *ev,
762 struct timeval wait_time,
763 const struct sockaddr_storage *pss,
764 uint16_t port,
765 int timeout)
767 struct tevent_req *req, *subreq;
768 struct open_socket_out_defer_state *state;
770 req = tevent_req_create(mem_ctx, &state,
771 struct open_socket_out_defer_state);
772 if (req == NULL) {
773 return NULL;
775 state->ev = ev;
776 state->ss = *pss;
777 state->port = port;
778 state->timeout = timeout;
780 subreq = tevent_wakeup_send(
781 state, ev,
782 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
783 if (subreq == NULL) {
784 goto fail;
786 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
787 return req;
788 fail:
789 TALLOC_FREE(req);
790 return NULL;
793 static void open_socket_out_defer_waited(struct tevent_req *subreq)
795 struct tevent_req *req = tevent_req_callback_data(
796 subreq, struct tevent_req);
797 struct open_socket_out_defer_state *state = tevent_req_data(
798 req, struct open_socket_out_defer_state);
799 bool ret;
801 ret = tevent_wakeup_recv(subreq);
802 TALLOC_FREE(subreq);
803 if (!ret) {
804 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
805 return;
808 subreq = open_socket_out_send(state, state->ev, &state->ss,
809 state->port, state->timeout);
810 if (tevent_req_nomem(subreq, req)) {
811 return;
813 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
816 static void open_socket_out_defer_connected(struct tevent_req *subreq)
818 struct tevent_req *req = tevent_req_callback_data(
819 subreq, struct tevent_req);
820 struct open_socket_out_defer_state *state = tevent_req_data(
821 req, struct open_socket_out_defer_state);
822 NTSTATUS status;
824 status = open_socket_out_recv(subreq, &state->fd);
825 TALLOC_FREE(subreq);
826 if (!NT_STATUS_IS_OK(status)) {
827 tevent_req_nterror(req, status);
828 return;
830 tevent_req_done(req);
833 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
835 struct open_socket_out_defer_state *state = tevent_req_data(
836 req, struct open_socket_out_defer_state);
837 NTSTATUS status;
839 if (tevent_req_is_nterror(req, &status)) {
840 return status;
842 *pfd = state->fd;
843 state->fd = -1;
844 return NT_STATUS_OK;
847 /****************************************************************************
848 Open a connected UDP socket to host on port
849 **************************************************************************/
851 int open_udp_socket(const char *host, int port)
853 struct sockaddr_storage ss;
854 int res;
855 socklen_t salen;
857 if (!interpret_string_addr(&ss, host, 0)) {
858 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
859 host));
860 return -1;
863 res = socket(ss.ss_family, SOCK_DGRAM, 0);
864 if (res == -1) {
865 return -1;
868 #if defined(HAVE_IPV6)
869 if (ss.ss_family == AF_INET6) {
870 struct sockaddr_in6 *psa6;
871 psa6 = (struct sockaddr_in6 *)&ss;
872 psa6->sin6_port = htons(port);
873 if (psa6->sin6_scope_id == 0
874 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
875 setup_linklocal_scope_id(
876 (struct sockaddr *)&ss);
878 salen = sizeof(struct sockaddr_in6);
879 } else
880 #endif
881 if (ss.ss_family == AF_INET) {
882 struct sockaddr_in *psa;
883 psa = (struct sockaddr_in *)&ss;
884 psa->sin_port = htons(port);
885 salen = sizeof(struct sockaddr_in);
886 } else {
887 DEBUG(1, ("unknown socket family %d", ss.ss_family));
888 close(res);
889 return -1;
892 if (connect(res, (struct sockaddr *)&ss, salen)) {
893 close(res);
894 return -1;
897 return res;
900 /*******************************************************************
901 Return the IP addr of the remote end of a socket as a string.
902 Optionally return the struct sockaddr_storage.
903 ******************************************************************/
905 static const char *get_peer_addr_internal(int fd,
906 char *addr_buf,
907 size_t addr_buf_len,
908 struct sockaddr *pss,
909 socklen_t *plength)
911 struct sockaddr_storage ss;
912 socklen_t length = sizeof(ss);
914 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
916 if (fd == -1) {
917 return addr_buf;
920 if (pss == NULL) {
921 pss = (struct sockaddr *)&ss;
922 plength = &length;
925 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
926 int level = (errno == ENOTCONN) ? 2 : 0;
927 DEBUG(level, ("getpeername failed. Error was %s\n",
928 strerror(errno)));
929 return addr_buf;
932 print_sockaddr_len(addr_buf,
933 addr_buf_len,
934 pss,
935 *plength);
936 return addr_buf;
939 /*******************************************************************
940 Matchname - determine if host name matches IP address. Used to
941 confirm a hostname lookup to prevent spoof attacks.
942 ******************************************************************/
944 static bool matchname(const char *remotehost,
945 const struct sockaddr *pss,
946 socklen_t len)
948 struct addrinfo *res = NULL;
949 struct addrinfo *ailist = NULL;
950 char addr_buf[INET6_ADDRSTRLEN];
951 bool ret = interpret_string_addr_internal(&ailist,
952 remotehost,
953 AI_ADDRCONFIG|AI_CANONNAME);
955 if (!ret || ailist == NULL) {
956 DEBUG(3,("matchname: getaddrinfo failed for "
957 "name %s [%s]\n",
958 remotehost,
959 gai_strerror(ret) ));
960 return false;
964 * Make sure that getaddrinfo() returns the "correct" host name.
967 if (ailist->ai_canonname == NULL ||
968 (!strequal(remotehost, ailist->ai_canonname) &&
969 !strequal(remotehost, "localhost"))) {
970 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
971 remotehost,
972 ailist->ai_canonname ?
973 ailist->ai_canonname : "(NULL)"));
974 freeaddrinfo(ailist);
975 return false;
978 /* Look up the host address in the address list we just got. */
979 for (res = ailist; res; res = res->ai_next) {
980 if (!res->ai_addr) {
981 continue;
983 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
984 (const struct sockaddr *)pss)) {
985 freeaddrinfo(ailist);
986 return true;
991 * The host name does not map to the original host address. Perhaps
992 * someone has compromised a name server. More likely someone botched
993 * it, but that could be dangerous, too.
996 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
997 print_sockaddr_len(addr_buf,
998 sizeof(addr_buf),
999 pss,
1000 len),
1001 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1003 if (ailist) {
1004 freeaddrinfo(ailist);
1006 return false;
1009 /*******************************************************************
1010 Deal with the singleton cache.
1011 ******************************************************************/
1013 struct name_addr_pair {
1014 struct sockaddr_storage ss;
1015 const char *name;
1018 /*******************************************************************
1019 Lookup a name/addr pair. Returns memory allocated from memcache.
1020 ******************************************************************/
1022 static bool lookup_nc(struct name_addr_pair *nc)
1024 DATA_BLOB tmp;
1026 ZERO_STRUCTP(nc);
1028 if (!memcache_lookup(
1029 NULL, SINGLETON_CACHE,
1030 data_blob_string_const_null("get_peer_name"),
1031 &tmp)) {
1032 return false;
1035 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1036 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1037 return true;
1040 /*******************************************************************
1041 Save a name/addr pair.
1042 ******************************************************************/
1044 static void store_nc(const struct name_addr_pair *nc)
1046 DATA_BLOB tmp;
1047 size_t namelen = strlen(nc->name);
1049 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1050 if (!tmp.data) {
1051 return;
1053 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1054 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1056 memcache_add(NULL, SINGLETON_CACHE,
1057 data_blob_string_const_null("get_peer_name"),
1058 tmp);
1059 data_blob_free(&tmp);
1062 /*******************************************************************
1063 Return the IP addr of the remote end of a socket as a string.
1064 ******************************************************************/
1066 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1068 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1071 int get_remote_hostname(const struct tsocket_address *remote_address,
1072 char **name,
1073 TALLOC_CTX *mem_ctx)
1075 char name_buf[MAX_DNS_NAME_LENGTH];
1076 char tmp_name[MAX_DNS_NAME_LENGTH];
1077 struct name_addr_pair nc;
1078 struct sockaddr_storage ss;
1079 ssize_t len;
1080 int rc;
1082 if (!lp_hostname_lookups()) {
1083 nc.name = tsocket_address_inet_addr_string(remote_address,
1084 mem_ctx);
1085 if (nc.name == NULL) {
1086 return -1;
1089 len = tsocket_address_bsd_sockaddr(remote_address,
1090 (struct sockaddr *) &nc.ss,
1091 sizeof(struct sockaddr_storage));
1092 if (len < 0) {
1093 return -1;
1096 store_nc(&nc);
1097 lookup_nc(&nc);
1099 if (nc.name == NULL) {
1100 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1101 } else {
1102 *name = talloc_strdup(mem_ctx, nc.name);
1104 return 0;
1107 lookup_nc(&nc);
1109 ZERO_STRUCT(ss);
1111 len = tsocket_address_bsd_sockaddr(remote_address,
1112 (struct sockaddr *) &ss,
1113 sizeof(struct sockaddr_storage));
1114 if (len < 0) {
1115 return -1;
1118 /* it might be the same as the last one - save some DNS work */
1119 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1120 if (nc.name == NULL) {
1121 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1122 } else {
1123 *name = talloc_strdup(mem_ctx, nc.name);
1125 return 0;
1128 /* Look up the remote host name. */
1129 rc = sys_getnameinfo((struct sockaddr *) &ss,
1130 len,
1131 name_buf,
1132 sizeof(name_buf),
1133 NULL,
1136 if (rc < 0) {
1137 char *p;
1139 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1140 if (p == NULL) {
1141 return -1;
1144 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1146 gai_strerror(rc)));
1147 strlcpy(name_buf, p, sizeof(name_buf));
1149 TALLOC_FREE(p);
1150 } else {
1151 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1152 DEBUG(0,("matchname failed on %s\n", name_buf));
1153 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1157 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1158 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1159 if (strstr(name_buf,"..")) {
1160 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1163 nc.name = name_buf;
1164 nc.ss = ss;
1166 store_nc(&nc);
1167 lookup_nc(&nc);
1169 if (nc.name == NULL) {
1170 *name = talloc_strdup(mem_ctx, "UNKOWN");
1171 } else {
1172 *name = talloc_strdup(mem_ctx, nc.name);
1175 return 0;
1178 /*******************************************************************
1179 Create protected unix domain socket.
1181 Some unixes cannot set permissions on a ux-dom-sock, so we
1182 have to make sure that the directory contains the protection
1183 permissions instead.
1184 ******************************************************************/
1186 int create_pipe_sock(const char *socket_dir,
1187 const char *socket_name,
1188 mode_t dir_perms)
1190 #ifdef HAVE_UNIXSOCKET
1191 struct sockaddr_un sunaddr;
1192 bool ok;
1193 int sock = -1;
1194 mode_t old_umask;
1195 char *path = NULL;
1197 old_umask = umask(0);
1199 ok = directory_create_or_exist_strict(socket_dir,
1200 sec_initial_uid(),
1201 dir_perms);
1202 if (!ok) {
1203 goto out_close;
1206 /* Create the socket file */
1207 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1209 if (sock == -1) {
1210 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1211 strerror(errno) ));
1212 goto out_close;
1215 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1216 goto out_close;
1219 unlink(path);
1220 memset(&sunaddr, 0, sizeof(sunaddr));
1221 sunaddr.sun_family = AF_UNIX;
1222 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1224 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1225 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1226 strerror(errno)));
1227 goto out_close;
1230 SAFE_FREE(path);
1232 umask(old_umask);
1233 return sock;
1235 out_close:
1236 SAFE_FREE(path);
1237 if (sock != -1)
1238 close(sock);
1240 umask(old_umask);
1241 return -1;
1243 #else
1244 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1245 return -1;
1246 #endif /* HAVE_UNIXSOCKET */
1249 /****************************************************************************
1250 Get my own canonical name, including domain.
1251 ****************************************************************************/
1253 const char *get_mydnsfullname(void)
1255 struct addrinfo *res = NULL;
1256 char my_hostname[HOST_NAME_MAX];
1257 bool ret;
1258 DATA_BLOB tmp;
1260 if (memcache_lookup(NULL, SINGLETON_CACHE,
1261 data_blob_string_const_null("get_mydnsfullname"),
1262 &tmp)) {
1263 SMB_ASSERT(tmp.length > 0);
1264 return (const char *)tmp.data;
1267 /* get my host name */
1268 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1269 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1270 return NULL;
1273 /* Ensure null termination. */
1274 my_hostname[sizeof(my_hostname)-1] = '\0';
1276 ret = interpret_string_addr_internal(&res,
1277 my_hostname,
1278 AI_ADDRCONFIG|AI_CANONNAME);
1280 if (!ret || res == NULL) {
1281 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1282 "name %s [%s]\n",
1283 my_hostname,
1284 gai_strerror(ret) ));
1285 return NULL;
1289 * Make sure that getaddrinfo() returns the "correct" host name.
1292 if (res->ai_canonname == NULL) {
1293 DEBUG(3,("get_mydnsfullname: failed to get "
1294 "canonical name for %s\n",
1295 my_hostname));
1296 freeaddrinfo(res);
1297 return NULL;
1300 /* This copies the data, so we must do a lookup
1301 * afterwards to find the value to return.
1304 memcache_add(NULL, SINGLETON_CACHE,
1305 data_blob_string_const_null("get_mydnsfullname"),
1306 data_blob_string_const_null(res->ai_canonname));
1308 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1309 data_blob_string_const_null("get_mydnsfullname"),
1310 &tmp)) {
1311 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1312 strlen(res->ai_canonname) + 1);
1315 freeaddrinfo(res);
1317 return (const char *)tmp.data;
1320 /************************************************************
1321 Is this my ip address ?
1322 ************************************************************/
1324 static bool is_my_ipaddr(const char *ipaddr_str)
1326 struct sockaddr_storage ss;
1327 struct iface_struct *nics;
1328 int i, n;
1330 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1331 return false;
1334 if (is_zero_addr(&ss)) {
1335 return false;
1338 if (ismyaddr((struct sockaddr *)&ss) ||
1339 is_loopback_addr((struct sockaddr *)&ss)) {
1340 return true;
1343 n = get_interfaces(talloc_tos(), &nics);
1344 for (i=0; i<n; i++) {
1345 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1346 TALLOC_FREE(nics);
1347 return true;
1350 TALLOC_FREE(nics);
1351 return false;
1354 /************************************************************
1355 Is this my name ?
1356 ************************************************************/
1358 bool is_myname_or_ipaddr(const char *s)
1360 TALLOC_CTX *ctx = talloc_tos();
1361 char *name = NULL;
1362 const char *dnsname;
1363 char *servername = NULL;
1365 if (!s) {
1366 return false;
1369 /* Santize the string from '\\name' */
1370 name = talloc_strdup(ctx, s);
1371 if (!name) {
1372 return false;
1375 servername = strrchr_m(name, '\\' );
1376 if (!servername) {
1377 servername = name;
1378 } else {
1379 servername++;
1382 /* Optimize for the common case */
1383 if (strequal(servername, lp_netbios_name())) {
1384 return true;
1387 /* Check for an alias */
1388 if (is_myname(servername)) {
1389 return true;
1392 /* Check for loopback */
1393 if (strequal(servername, "127.0.0.1") ||
1394 strequal(servername, "::1")) {
1395 return true;
1398 if (strequal(servername, "localhost")) {
1399 return true;
1402 /* Maybe it's my dns name */
1403 dnsname = get_mydnsfullname();
1404 if (dnsname && strequal(servername, dnsname)) {
1405 return true;
1408 /* Maybe its an IP address? */
1409 if (is_ipaddress(servername)) {
1410 return is_my_ipaddr(servername);
1413 /* Handle possible CNAME records - convert to an IP addr. list. */
1415 /* Use DNS to resolve the name, check all addresses. */
1416 struct addrinfo *p = NULL;
1417 struct addrinfo *res = NULL;
1419 if (!interpret_string_addr_internal(&res,
1420 servername,
1421 AI_ADDRCONFIG)) {
1422 return false;
1425 for (p = res; p; p = p->ai_next) {
1426 char addr[INET6_ADDRSTRLEN];
1427 struct sockaddr_storage ss;
1429 ZERO_STRUCT(ss);
1430 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1431 print_sockaddr(addr,
1432 sizeof(addr),
1433 &ss);
1434 if (is_my_ipaddr(addr)) {
1435 freeaddrinfo(res);
1436 return true;
1439 freeaddrinfo(res);
1442 /* No match */
1443 return false;
1446 struct getaddrinfo_state {
1447 const char *node;
1448 const char *service;
1449 const struct addrinfo *hints;
1450 struct addrinfo *res;
1451 int ret;
1454 static void getaddrinfo_do(void *private_data);
1455 static void getaddrinfo_done(struct tevent_req *subreq);
1457 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1458 struct tevent_context *ev,
1459 struct fncall_context *ctx,
1460 const char *node,
1461 const char *service,
1462 const struct addrinfo *hints)
1464 struct tevent_req *req, *subreq;
1465 struct getaddrinfo_state *state;
1467 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1468 if (req == NULL) {
1469 return NULL;
1472 state->node = node;
1473 state->service = service;
1474 state->hints = hints;
1476 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1477 if (tevent_req_nomem(subreq, req)) {
1478 return tevent_req_post(req, ev);
1480 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1481 return req;
1484 static void getaddrinfo_do(void *private_data)
1486 struct getaddrinfo_state *state =
1487 (struct getaddrinfo_state *)private_data;
1489 state->ret = getaddrinfo(state->node, state->service, state->hints,
1490 &state->res);
1493 static void getaddrinfo_done(struct tevent_req *subreq)
1495 struct tevent_req *req = tevent_req_callback_data(
1496 subreq, struct tevent_req);
1497 int ret, err;
1499 ret = fncall_recv(subreq, &err);
1500 TALLOC_FREE(subreq);
1501 if (ret == -1) {
1502 tevent_req_error(req, err);
1503 return;
1505 tevent_req_done(req);
1508 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1510 struct getaddrinfo_state *state = tevent_req_data(
1511 req, struct getaddrinfo_state);
1512 int err;
1514 if (tevent_req_is_unix_error(req, &err)) {
1515 switch(err) {
1516 case ENOMEM:
1517 return EAI_MEMORY;
1518 default:
1519 return EAI_FAIL;
1522 if (state->ret == 0) {
1523 *res = state->res;
1525 return state->ret;
1528 int poll_one_fd(int fd, int events, int timeout, int *revents)
1530 struct pollfd pfd;
1531 int ret;
1533 pfd.fd = fd;
1534 pfd.events = events;
1536 ret = poll(&pfd, 1, timeout);
1539 * Assign whatever poll did, even in the ret<=0 case.
1541 *revents = pfd.revents;
1543 return ret;
1546 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1548 struct pollfd pfd;
1549 int ret;
1551 pfd.fd = fd;
1552 pfd.events = events;
1554 ret = sys_poll_intr(&pfd, 1, timeout);
1555 if (ret <= 0) {
1556 *revents = 0;
1557 return ret;
1559 *revents = pfd.revents;
1560 return 1;