lib: Introduce iov_buflen
[Samba.git] / source3 / lib / util_sock.c
blobb8149cad83845ae54590e98ecad0c21edf85ce3c
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_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 /****************************************************************************
223 Write all data from an iov array
224 NB. This can be called with a non-socket fd, don't add dependencies
225 on socket calls.
226 ****************************************************************************/
228 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
230 ssize_t to_send;
231 ssize_t thistime;
232 size_t sent;
233 struct iovec *iov_copy, *iov;
235 to_send = iov_buflen(orig_iov, iovcnt);
236 if (to_send == -1) {
237 errno = EINVAL;
238 return -1;
241 thistime = sys_writev(fd, orig_iov, iovcnt);
242 if ((thistime <= 0) || (thistime == to_send)) {
243 return thistime;
245 sent = thistime;
248 * We could not send everything in one call. Make a copy of iov that
249 * we can mess with. We keep a copy of the array start in iov_copy for
250 * the TALLOC_FREE, because we're going to modify iov later on,
251 * discarding elements.
254 iov_copy = (struct iovec *)talloc_memdup(
255 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
257 if (iov_copy == NULL) {
258 errno = ENOMEM;
259 return -1;
261 iov = iov_copy;
263 while (sent < to_send) {
265 * We have to discard "thistime" bytes from the beginning
266 * iov array, "thistime" contains the number of bytes sent
267 * via writev last.
269 while (thistime > 0) {
270 if (thistime < iov[0].iov_len) {
271 char *new_base =
272 (char *)iov[0].iov_base + thistime;
273 iov[0].iov_base = (void *)new_base;
274 iov[0].iov_len -= thistime;
275 break;
277 thistime -= iov[0].iov_len;
278 iov += 1;
279 iovcnt -= 1;
282 thistime = sys_writev(fd, iov, iovcnt);
283 if (thistime <= 0) {
284 break;
286 sent += thistime;
289 TALLOC_FREE(iov_copy);
290 return sent;
293 /****************************************************************************
294 Write data to a fd.
295 NB. This can be called with a non-socket fd, don't add dependencies
296 on socket calls.
297 ****************************************************************************/
299 ssize_t write_data(int fd, const char *buffer, size_t N)
301 struct iovec iov;
303 iov.iov_base = discard_const_p(void, buffer);
304 iov.iov_len = N;
305 return write_data_iov(fd, &iov, 1);
308 /****************************************************************************
309 Send a keepalive packet (rfc1002).
310 ****************************************************************************/
312 bool send_keepalive(int client)
314 unsigned char buf[4];
316 buf[0] = NBSSkeepalive;
317 buf[1] = buf[2] = buf[3] = 0;
319 return(write_data(client,(char *)buf,4) == 4);
322 /****************************************************************************
323 Read 4 bytes of a smb packet and return the smb length of the packet.
324 Store the result in the buffer.
325 This version of the function will return a length of zero on receiving
326 a keepalive packet.
327 Timeout is in milliseconds.
328 ****************************************************************************/
330 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
331 unsigned int timeout,
332 size_t *len)
334 int msg_type;
335 NTSTATUS status;
337 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
339 if (!NT_STATUS_IS_OK(status)) {
340 return status;
343 *len = smb_len(inbuf);
344 msg_type = CVAL(inbuf,0);
346 if (msg_type == NBSSkeepalive) {
347 DEBUG(5,("Got keepalive packet\n"));
350 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
352 return NT_STATUS_OK;
355 /****************************************************************************
356 Read an smb from a fd.
357 The timeout is in milliseconds.
358 This function will return on receipt of a session keepalive packet.
359 maxlen is the max number of bytes to return, not including the 4 byte
360 length. If zero it means buflen limit.
361 Doesn't check the MAC on signed packets.
362 ****************************************************************************/
364 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
365 size_t maxlen, size_t *p_len)
367 size_t len;
368 NTSTATUS status;
370 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
372 if (!NT_STATUS_IS_OK(status)) {
373 DEBUG(0, ("read_fd_with_timeout failed, read "
374 "error = %s.\n", nt_errstr(status)));
375 return status;
378 if (len > buflen) {
379 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
380 (unsigned long)len));
381 return NT_STATUS_INVALID_PARAMETER;
384 if(len > 0) {
385 if (maxlen) {
386 len = MIN(len,maxlen);
389 status = read_fd_with_timeout(
390 fd, buffer+4, len, len, timeout, &len);
392 if (!NT_STATUS_IS_OK(status)) {
393 DEBUG(0, ("read_fd_with_timeout failed, read error = "
394 "%s.\n", nt_errstr(status)));
395 return status;
398 /* not all of samba3 properly checks for packet-termination
399 * of strings. This ensures that we don't run off into
400 * empty space. */
401 SSVAL(buffer+4,len, 0);
404 *p_len = len;
405 return NT_STATUS_OK;
408 /****************************************************************************
409 Open a socket of the specified type, port, and address for incoming data.
410 ****************************************************************************/
412 int open_socket_in(int type,
413 uint16_t port,
414 int dlevel,
415 const struct sockaddr_storage *psock,
416 bool rebind)
418 struct sockaddr_storage sock;
419 int res;
420 socklen_t slen = sizeof(struct sockaddr_in);
422 sock = *psock;
424 #if defined(HAVE_IPV6)
425 if (sock.ss_family == AF_INET6) {
426 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
427 slen = sizeof(struct sockaddr_in6);
429 #endif
430 if (sock.ss_family == AF_INET) {
431 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
434 res = socket(sock.ss_family, type, 0 );
435 if( res == -1 ) {
436 if( DEBUGLVL(0) ) {
437 dbgtext( "open_socket_in(): socket() call failed: " );
438 dbgtext( "%s\n", strerror( errno ) );
440 return -1;
443 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
445 int val = rebind ? 1 : 0;
446 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
447 (char *)&val,sizeof(val)) == -1 ) {
448 if( DEBUGLVL( dlevel ) ) {
449 dbgtext( "open_socket_in(): setsockopt: " );
450 dbgtext( "SO_REUSEADDR = %s ",
451 val?"true":"false" );
452 dbgtext( "on port %d failed ", port );
453 dbgtext( "with error = %s\n", strerror(errno) );
456 #ifdef SO_REUSEPORT
457 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
458 (char *)&val,sizeof(val)) == -1 ) {
459 if( DEBUGLVL( dlevel ) ) {
460 dbgtext( "open_socket_in(): setsockopt: ");
461 dbgtext( "SO_REUSEPORT = %s ",
462 val?"true":"false");
463 dbgtext( "on port %d failed ", port);
464 dbgtext( "with error = %s\n", strerror(errno));
467 #endif /* SO_REUSEPORT */
470 #ifdef HAVE_IPV6
472 * As IPV6_V6ONLY is the default on some systems,
473 * we better try to be consistent and always use it.
475 * This also avoids using IPv4 via AF_INET6 sockets
476 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
477 * string.
479 if (sock.ss_family == AF_INET6) {
480 int val = 1;
481 int ret;
483 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
484 (const void *)&val, sizeof(val));
485 if (ret == -1) {
486 if(DEBUGLVL(0)) {
487 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
488 dbgtext("%s\n", strerror(errno));
490 close(res);
491 return -1;
494 #endif
496 /* now we've got a socket - we need to bind it */
497 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
498 if( DEBUGLVL(dlevel) && (port == NMB_PORT ||
499 port == NBT_SMB_PORT ||
500 port == TCP_SMB_PORT) ) {
501 char addr[INET6_ADDRSTRLEN];
502 print_sockaddr(addr, sizeof(addr),
503 &sock);
504 dbgtext( "bind failed on port %d ", port);
505 dbgtext( "socket_addr = %s.\n", addr);
506 dbgtext( "Error = %s\n", strerror(errno));
508 close(res);
509 return -1;
512 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
513 return( res );
516 struct open_socket_out_state {
517 int fd;
518 struct tevent_context *ev;
519 struct sockaddr_storage ss;
520 socklen_t salen;
521 uint16_t port;
522 int wait_usec;
525 static void open_socket_out_connected(struct tevent_req *subreq);
527 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
529 if (s->fd != -1) {
530 close(s->fd);
532 return 0;
535 /****************************************************************************
536 Create an outgoing socket. timeout is in milliseconds.
537 **************************************************************************/
539 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
540 struct tevent_context *ev,
541 const struct sockaddr_storage *pss,
542 uint16_t port,
543 int timeout)
545 char addr[INET6_ADDRSTRLEN];
546 struct tevent_req *result, *subreq;
547 struct open_socket_out_state *state;
548 NTSTATUS status;
550 result = tevent_req_create(mem_ctx, &state,
551 struct open_socket_out_state);
552 if (result == NULL) {
553 return NULL;
555 state->ev = ev;
556 state->ss = *pss;
557 state->port = port;
558 state->wait_usec = 10000;
559 state->salen = -1;
561 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
562 if (state->fd == -1) {
563 status = map_nt_error_from_unix(errno);
564 goto post_status;
566 talloc_set_destructor(state, open_socket_out_state_destructor);
568 if (!tevent_req_set_endtime(
569 result, ev, timeval_current_ofs_msec(timeout))) {
570 goto fail;
573 #if defined(HAVE_IPV6)
574 if (pss->ss_family == AF_INET6) {
575 struct sockaddr_in6 *psa6;
576 psa6 = (struct sockaddr_in6 *)&state->ss;
577 psa6->sin6_port = htons(port);
578 if (psa6->sin6_scope_id == 0
579 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
580 setup_linklocal_scope_id(
581 (struct sockaddr *)&(state->ss));
583 state->salen = sizeof(struct sockaddr_in6);
585 #endif
586 if (pss->ss_family == AF_INET) {
587 struct sockaddr_in *psa;
588 psa = (struct sockaddr_in *)&state->ss;
589 psa->sin_port = htons(port);
590 state->salen = sizeof(struct sockaddr_in);
593 if (pss->ss_family == AF_UNIX) {
594 state->salen = sizeof(struct sockaddr_un);
597 print_sockaddr(addr, sizeof(addr), &state->ss);
598 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
600 subreq = async_connect_send(state, state->ev, state->fd,
601 (struct sockaddr *)&state->ss,
602 state->salen, NULL, NULL, NULL);
603 if ((subreq == NULL)
604 || !tevent_req_set_endtime(
605 subreq, state->ev,
606 timeval_current_ofs(0, state->wait_usec))) {
607 goto fail;
609 tevent_req_set_callback(subreq, open_socket_out_connected, result);
610 return result;
612 post_status:
613 tevent_req_nterror(result, status);
614 return tevent_req_post(result, ev);
615 fail:
616 TALLOC_FREE(result);
617 return NULL;
620 static void open_socket_out_connected(struct tevent_req *subreq)
622 struct tevent_req *req =
623 tevent_req_callback_data(subreq, struct tevent_req);
624 struct open_socket_out_state *state =
625 tevent_req_data(req, struct open_socket_out_state);
626 int ret;
627 int sys_errno;
629 ret = async_connect_recv(subreq, &sys_errno);
630 TALLOC_FREE(subreq);
631 if (ret == 0) {
632 tevent_req_done(req);
633 return;
636 if (
637 #ifdef ETIMEDOUT
638 (sys_errno == ETIMEDOUT) ||
639 #endif
640 (sys_errno == EINPROGRESS) ||
641 (sys_errno == EALREADY) ||
642 (sys_errno == EAGAIN)) {
645 * retry
648 if (state->wait_usec < 250000) {
649 state->wait_usec *= 1.5;
652 subreq = async_connect_send(state, state->ev, state->fd,
653 (struct sockaddr *)&state->ss,
654 state->salen, NULL, NULL, NULL);
655 if (tevent_req_nomem(subreq, req)) {
656 return;
658 if (!tevent_req_set_endtime(
659 subreq, state->ev,
660 timeval_current_ofs_usec(state->wait_usec))) {
661 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
662 return;
664 tevent_req_set_callback(subreq, open_socket_out_connected, req);
665 return;
668 #ifdef EISCONN
669 if (sys_errno == EISCONN) {
670 tevent_req_done(req);
671 return;
673 #endif
675 /* real error */
676 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
679 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
681 struct open_socket_out_state *state =
682 tevent_req_data(req, struct open_socket_out_state);
683 NTSTATUS status;
685 if (tevent_req_is_nterror(req, &status)) {
686 return status;
688 *pfd = state->fd;
689 state->fd = -1;
690 return NT_STATUS_OK;
694 * @brief open a socket
696 * @param pss a struct sockaddr_storage defining the address to connect to
697 * @param port to connect to
698 * @param timeout in MILLISECONDS
699 * @param pfd file descriptor returned
701 * @return NTSTATUS code
703 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
704 int timeout, int *pfd)
706 TALLOC_CTX *frame = talloc_stackframe();
707 struct tevent_context *ev;
708 struct tevent_req *req;
709 NTSTATUS status = NT_STATUS_NO_MEMORY;
711 ev = samba_tevent_context_init(frame);
712 if (ev == NULL) {
713 goto fail;
716 req = open_socket_out_send(frame, ev, pss, port, timeout);
717 if (req == NULL) {
718 goto fail;
720 if (!tevent_req_poll(req, ev)) {
721 status = NT_STATUS_INTERNAL_ERROR;
722 goto fail;
724 status = open_socket_out_recv(req, pfd);
725 fail:
726 TALLOC_FREE(frame);
727 return status;
730 struct open_socket_out_defer_state {
731 struct tevent_context *ev;
732 struct sockaddr_storage ss;
733 uint16_t port;
734 int timeout;
735 int fd;
738 static void open_socket_out_defer_waited(struct tevent_req *subreq);
739 static void open_socket_out_defer_connected(struct tevent_req *subreq);
741 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
742 struct tevent_context *ev,
743 struct timeval wait_time,
744 const struct sockaddr_storage *pss,
745 uint16_t port,
746 int timeout)
748 struct tevent_req *req, *subreq;
749 struct open_socket_out_defer_state *state;
751 req = tevent_req_create(mem_ctx, &state,
752 struct open_socket_out_defer_state);
753 if (req == NULL) {
754 return NULL;
756 state->ev = ev;
757 state->ss = *pss;
758 state->port = port;
759 state->timeout = timeout;
761 subreq = tevent_wakeup_send(
762 state, ev,
763 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
764 if (subreq == NULL) {
765 goto fail;
767 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
768 return req;
769 fail:
770 TALLOC_FREE(req);
771 return NULL;
774 static void open_socket_out_defer_waited(struct tevent_req *subreq)
776 struct tevent_req *req = tevent_req_callback_data(
777 subreq, struct tevent_req);
778 struct open_socket_out_defer_state *state = tevent_req_data(
779 req, struct open_socket_out_defer_state);
780 bool ret;
782 ret = tevent_wakeup_recv(subreq);
783 TALLOC_FREE(subreq);
784 if (!ret) {
785 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
786 return;
789 subreq = open_socket_out_send(state, state->ev, &state->ss,
790 state->port, state->timeout);
791 if (tevent_req_nomem(subreq, req)) {
792 return;
794 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
797 static void open_socket_out_defer_connected(struct tevent_req *subreq)
799 struct tevent_req *req = tevent_req_callback_data(
800 subreq, struct tevent_req);
801 struct open_socket_out_defer_state *state = tevent_req_data(
802 req, struct open_socket_out_defer_state);
803 NTSTATUS status;
805 status = open_socket_out_recv(subreq, &state->fd);
806 TALLOC_FREE(subreq);
807 if (!NT_STATUS_IS_OK(status)) {
808 tevent_req_nterror(req, status);
809 return;
811 tevent_req_done(req);
814 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
816 struct open_socket_out_defer_state *state = tevent_req_data(
817 req, struct open_socket_out_defer_state);
818 NTSTATUS status;
820 if (tevent_req_is_nterror(req, &status)) {
821 return status;
823 *pfd = state->fd;
824 state->fd = -1;
825 return NT_STATUS_OK;
828 /****************************************************************************
829 Open a connected UDP socket to host on port
830 **************************************************************************/
832 int open_udp_socket(const char *host, int port)
834 struct sockaddr_storage ss;
835 int res;
836 socklen_t salen;
838 if (!interpret_string_addr(&ss, host, 0)) {
839 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
840 host));
841 return -1;
844 res = socket(ss.ss_family, SOCK_DGRAM, 0);
845 if (res == -1) {
846 return -1;
849 #if defined(HAVE_IPV6)
850 if (ss.ss_family == AF_INET6) {
851 struct sockaddr_in6 *psa6;
852 psa6 = (struct sockaddr_in6 *)&ss;
853 psa6->sin6_port = htons(port);
854 if (psa6->sin6_scope_id == 0
855 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
856 setup_linklocal_scope_id(
857 (struct sockaddr *)&ss);
859 salen = sizeof(struct sockaddr_in6);
860 } else
861 #endif
862 if (ss.ss_family == AF_INET) {
863 struct sockaddr_in *psa;
864 psa = (struct sockaddr_in *)&ss;
865 psa->sin_port = htons(port);
866 salen = sizeof(struct sockaddr_in);
867 } else {
868 DEBUG(1, ("unknown socket family %d", ss.ss_family));
869 close(res);
870 return -1;
873 if (connect(res, (struct sockaddr *)&ss, salen)) {
874 close(res);
875 return -1;
878 return res;
881 /*******************************************************************
882 Return the IP addr of the remote end of a socket as a string.
883 Optionally return the struct sockaddr_storage.
884 ******************************************************************/
886 static const char *get_peer_addr_internal(int fd,
887 char *addr_buf,
888 size_t addr_buf_len,
889 struct sockaddr *pss,
890 socklen_t *plength)
892 struct sockaddr_storage ss;
893 socklen_t length = sizeof(ss);
895 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
897 if (fd == -1) {
898 return addr_buf;
901 if (pss == NULL) {
902 pss = (struct sockaddr *)&ss;
903 plength = &length;
906 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
907 int level = (errno == ENOTCONN) ? 2 : 0;
908 DEBUG(level, ("getpeername failed. Error was %s\n",
909 strerror(errno)));
910 return addr_buf;
913 print_sockaddr_len(addr_buf,
914 addr_buf_len,
915 pss,
916 *plength);
917 return addr_buf;
920 /*******************************************************************
921 Matchname - determine if host name matches IP address. Used to
922 confirm a hostname lookup to prevent spoof attacks.
923 ******************************************************************/
925 static bool matchname(const char *remotehost,
926 const struct sockaddr *pss,
927 socklen_t len)
929 struct addrinfo *res = NULL;
930 struct addrinfo *ailist = NULL;
931 char addr_buf[INET6_ADDRSTRLEN];
932 bool ret = interpret_string_addr_internal(&ailist,
933 remotehost,
934 AI_ADDRCONFIG|AI_CANONNAME);
936 if (!ret || ailist == NULL) {
937 DEBUG(3,("matchname: getaddrinfo failed for "
938 "name %s [%s]\n",
939 remotehost,
940 gai_strerror(ret) ));
941 return false;
945 * Make sure that getaddrinfo() returns the "correct" host name.
948 if (ailist->ai_canonname == NULL ||
949 (!strequal(remotehost, ailist->ai_canonname) &&
950 !strequal(remotehost, "localhost"))) {
951 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
952 remotehost,
953 ailist->ai_canonname ?
954 ailist->ai_canonname : "(NULL)"));
955 freeaddrinfo(ailist);
956 return false;
959 /* Look up the host address in the address list we just got. */
960 for (res = ailist; res; res = res->ai_next) {
961 if (!res->ai_addr) {
962 continue;
964 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
965 (const struct sockaddr *)pss)) {
966 freeaddrinfo(ailist);
967 return true;
972 * The host name does not map to the original host address. Perhaps
973 * someone has compromised a name server. More likely someone botched
974 * it, but that could be dangerous, too.
977 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
978 print_sockaddr_len(addr_buf,
979 sizeof(addr_buf),
980 pss,
981 len),
982 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
984 if (ailist) {
985 freeaddrinfo(ailist);
987 return false;
990 /*******************************************************************
991 Deal with the singleton cache.
992 ******************************************************************/
994 struct name_addr_pair {
995 struct sockaddr_storage ss;
996 const char *name;
999 /*******************************************************************
1000 Lookup a name/addr pair. Returns memory allocated from memcache.
1001 ******************************************************************/
1003 static bool lookup_nc(struct name_addr_pair *nc)
1005 DATA_BLOB tmp;
1007 ZERO_STRUCTP(nc);
1009 if (!memcache_lookup(
1010 NULL, SINGLETON_CACHE,
1011 data_blob_string_const_null("get_peer_name"),
1012 &tmp)) {
1013 return false;
1016 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1017 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1018 return true;
1021 /*******************************************************************
1022 Save a name/addr pair.
1023 ******************************************************************/
1025 static void store_nc(const struct name_addr_pair *nc)
1027 DATA_BLOB tmp;
1028 size_t namelen = strlen(nc->name);
1030 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1031 if (!tmp.data) {
1032 return;
1034 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1035 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1037 memcache_add(NULL, SINGLETON_CACHE,
1038 data_blob_string_const_null("get_peer_name"),
1039 tmp);
1040 data_blob_free(&tmp);
1043 /*******************************************************************
1044 Return the IP addr of the remote end of a socket as a string.
1045 ******************************************************************/
1047 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1049 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1052 int get_remote_hostname(const struct tsocket_address *remote_address,
1053 char **name,
1054 TALLOC_CTX *mem_ctx)
1056 char name_buf[MAX_DNS_NAME_LENGTH];
1057 char tmp_name[MAX_DNS_NAME_LENGTH];
1058 struct name_addr_pair nc;
1059 struct sockaddr_storage ss;
1060 ssize_t len;
1061 int rc;
1063 if (!lp_hostname_lookups()) {
1064 nc.name = tsocket_address_inet_addr_string(remote_address,
1065 mem_ctx);
1066 if (nc.name == NULL) {
1067 return -1;
1070 len = tsocket_address_bsd_sockaddr(remote_address,
1071 (struct sockaddr *) &nc.ss,
1072 sizeof(struct sockaddr_storage));
1073 if (len < 0) {
1074 return -1;
1077 store_nc(&nc);
1078 lookup_nc(&nc);
1080 if (nc.name == NULL) {
1081 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1082 } else {
1083 *name = talloc_strdup(mem_ctx, nc.name);
1085 return 0;
1088 lookup_nc(&nc);
1090 ZERO_STRUCT(ss);
1092 len = tsocket_address_bsd_sockaddr(remote_address,
1093 (struct sockaddr *) &ss,
1094 sizeof(struct sockaddr_storage));
1095 if (len < 0) {
1096 return -1;
1099 /* it might be the same as the last one - save some DNS work */
1100 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1101 if (nc.name == NULL) {
1102 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1103 } else {
1104 *name = talloc_strdup(mem_ctx, nc.name);
1106 return 0;
1109 /* Look up the remote host name. */
1110 rc = sys_getnameinfo((struct sockaddr *) &ss,
1111 len,
1112 name_buf,
1113 sizeof(name_buf),
1114 NULL,
1117 if (rc < 0) {
1118 char *p;
1120 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1121 if (p == NULL) {
1122 return -1;
1125 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1127 gai_strerror(rc)));
1128 strlcpy(name_buf, p, sizeof(name_buf));
1130 TALLOC_FREE(p);
1131 } else {
1132 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1133 DEBUG(0,("matchname failed on %s\n", name_buf));
1134 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1138 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1139 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1140 if (strstr(name_buf,"..")) {
1141 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1144 nc.name = name_buf;
1145 nc.ss = ss;
1147 store_nc(&nc);
1148 lookup_nc(&nc);
1150 if (nc.name == NULL) {
1151 *name = talloc_strdup(mem_ctx, "UNKOWN");
1152 } else {
1153 *name = talloc_strdup(mem_ctx, nc.name);
1156 return 0;
1159 /*******************************************************************
1160 Create protected unix domain socket.
1162 Some unixes cannot set permissions on a ux-dom-sock, so we
1163 have to make sure that the directory contains the protection
1164 permissions instead.
1165 ******************************************************************/
1167 int create_pipe_sock(const char *socket_dir,
1168 const char *socket_name,
1169 mode_t dir_perms)
1171 #ifdef HAVE_UNIXSOCKET
1172 struct sockaddr_un sunaddr;
1173 bool ok;
1174 int sock = -1;
1175 mode_t old_umask;
1176 char *path = NULL;
1178 old_umask = umask(0);
1180 ok = directory_create_or_exist_strict(socket_dir,
1181 sec_initial_uid(),
1182 dir_perms);
1183 if (!ok) {
1184 goto out_close;
1187 /* Create the socket file */
1188 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1190 if (sock == -1) {
1191 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1192 strerror(errno) ));
1193 goto out_close;
1196 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1197 goto out_close;
1200 unlink(path);
1201 memset(&sunaddr, 0, sizeof(sunaddr));
1202 sunaddr.sun_family = AF_UNIX;
1203 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1205 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1206 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1207 strerror(errno)));
1208 goto out_close;
1211 SAFE_FREE(path);
1213 umask(old_umask);
1214 return sock;
1216 out_close:
1217 SAFE_FREE(path);
1218 if (sock != -1)
1219 close(sock);
1221 umask(old_umask);
1222 return -1;
1224 #else
1225 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1226 return -1;
1227 #endif /* HAVE_UNIXSOCKET */
1230 /****************************************************************************
1231 Get my own canonical name, including domain.
1232 ****************************************************************************/
1234 const char *get_mydnsfullname(void)
1236 struct addrinfo *res = NULL;
1237 char my_hostname[HOST_NAME_MAX];
1238 bool ret;
1239 DATA_BLOB tmp;
1241 if (memcache_lookup(NULL, SINGLETON_CACHE,
1242 data_blob_string_const_null("get_mydnsfullname"),
1243 &tmp)) {
1244 SMB_ASSERT(tmp.length > 0);
1245 return (const char *)tmp.data;
1248 /* get my host name */
1249 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1250 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1251 return NULL;
1254 /* Ensure null termination. */
1255 my_hostname[sizeof(my_hostname)-1] = '\0';
1257 ret = interpret_string_addr_internal(&res,
1258 my_hostname,
1259 AI_ADDRCONFIG|AI_CANONNAME);
1261 if (!ret || res == NULL) {
1262 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1263 "name %s [%s]\n",
1264 my_hostname,
1265 gai_strerror(ret) ));
1266 return NULL;
1270 * Make sure that getaddrinfo() returns the "correct" host name.
1273 if (res->ai_canonname == NULL) {
1274 DEBUG(3,("get_mydnsfullname: failed to get "
1275 "canonical name for %s\n",
1276 my_hostname));
1277 freeaddrinfo(res);
1278 return NULL;
1281 /* This copies the data, so we must do a lookup
1282 * afterwards to find the value to return.
1285 memcache_add(NULL, SINGLETON_CACHE,
1286 data_blob_string_const_null("get_mydnsfullname"),
1287 data_blob_string_const_null(res->ai_canonname));
1289 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1290 data_blob_string_const_null("get_mydnsfullname"),
1291 &tmp)) {
1292 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1293 strlen(res->ai_canonname) + 1);
1296 freeaddrinfo(res);
1298 return (const char *)tmp.data;
1301 /************************************************************
1302 Is this my ip address ?
1303 ************************************************************/
1305 static bool is_my_ipaddr(const char *ipaddr_str)
1307 struct sockaddr_storage ss;
1308 struct iface_struct *nics;
1309 int i, n;
1311 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1312 return false;
1315 if (is_zero_addr(&ss)) {
1316 return false;
1319 if (ismyaddr((struct sockaddr *)&ss) ||
1320 is_loopback_addr((struct sockaddr *)&ss)) {
1321 return true;
1324 n = get_interfaces(talloc_tos(), &nics);
1325 for (i=0; i<n; i++) {
1326 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1327 TALLOC_FREE(nics);
1328 return true;
1331 TALLOC_FREE(nics);
1332 return false;
1335 /************************************************************
1336 Is this my name ?
1337 ************************************************************/
1339 bool is_myname_or_ipaddr(const char *s)
1341 TALLOC_CTX *ctx = talloc_tos();
1342 char *name = NULL;
1343 const char *dnsname;
1344 char *servername = NULL;
1346 if (!s) {
1347 return false;
1350 /* Santize the string from '\\name' */
1351 name = talloc_strdup(ctx, s);
1352 if (!name) {
1353 return false;
1356 servername = strrchr_m(name, '\\' );
1357 if (!servername) {
1358 servername = name;
1359 } else {
1360 servername++;
1363 /* Optimize for the common case */
1364 if (strequal(servername, lp_netbios_name())) {
1365 return true;
1368 /* Check for an alias */
1369 if (is_myname(servername)) {
1370 return true;
1373 /* Check for loopback */
1374 if (strequal(servername, "127.0.0.1") ||
1375 strequal(servername, "::1")) {
1376 return true;
1379 if (strequal(servername, "localhost")) {
1380 return true;
1383 /* Maybe it's my dns name */
1384 dnsname = get_mydnsfullname();
1385 if (dnsname && strequal(servername, dnsname)) {
1386 return true;
1389 /* Maybe its an IP address? */
1390 if (is_ipaddress(servername)) {
1391 return is_my_ipaddr(servername);
1394 /* Handle possible CNAME records - convert to an IP addr. list. */
1396 /* Use DNS to resolve the name, check all addresses. */
1397 struct addrinfo *p = NULL;
1398 struct addrinfo *res = NULL;
1400 if (!interpret_string_addr_internal(&res,
1401 servername,
1402 AI_ADDRCONFIG)) {
1403 return false;
1406 for (p = res; p; p = p->ai_next) {
1407 char addr[INET6_ADDRSTRLEN];
1408 struct sockaddr_storage ss;
1410 ZERO_STRUCT(ss);
1411 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1412 print_sockaddr(addr,
1413 sizeof(addr),
1414 &ss);
1415 if (is_my_ipaddr(addr)) {
1416 freeaddrinfo(res);
1417 return true;
1420 freeaddrinfo(res);
1423 /* No match */
1424 return false;
1427 struct getaddrinfo_state {
1428 const char *node;
1429 const char *service;
1430 const struct addrinfo *hints;
1431 struct addrinfo *res;
1432 int ret;
1435 static void getaddrinfo_do(void *private_data);
1436 static void getaddrinfo_done(struct tevent_req *subreq);
1438 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1439 struct tevent_context *ev,
1440 struct fncall_context *ctx,
1441 const char *node,
1442 const char *service,
1443 const struct addrinfo *hints)
1445 struct tevent_req *req, *subreq;
1446 struct getaddrinfo_state *state;
1448 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1449 if (req == NULL) {
1450 return NULL;
1453 state->node = node;
1454 state->service = service;
1455 state->hints = hints;
1457 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1458 if (tevent_req_nomem(subreq, req)) {
1459 return tevent_req_post(req, ev);
1461 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1462 return req;
1465 static void getaddrinfo_do(void *private_data)
1467 struct getaddrinfo_state *state =
1468 (struct getaddrinfo_state *)private_data;
1470 state->ret = getaddrinfo(state->node, state->service, state->hints,
1471 &state->res);
1474 static void getaddrinfo_done(struct tevent_req *subreq)
1476 struct tevent_req *req = tevent_req_callback_data(
1477 subreq, struct tevent_req);
1478 int ret, err;
1480 ret = fncall_recv(subreq, &err);
1481 TALLOC_FREE(subreq);
1482 if (ret == -1) {
1483 tevent_req_error(req, err);
1484 return;
1486 tevent_req_done(req);
1489 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1491 struct getaddrinfo_state *state = tevent_req_data(
1492 req, struct getaddrinfo_state);
1493 int err;
1495 if (tevent_req_is_unix_error(req, &err)) {
1496 switch(err) {
1497 case ENOMEM:
1498 return EAI_MEMORY;
1499 default:
1500 return EAI_FAIL;
1503 if (state->ret == 0) {
1504 *res = state->res;
1506 return state->ret;
1509 int poll_one_fd(int fd, int events, int timeout, int *revents)
1511 struct pollfd pfd;
1512 int ret;
1514 pfd.fd = fd;
1515 pfd.events = events;
1517 ret = poll(&pfd, 1, timeout);
1520 * Assign whatever poll did, even in the ret<=0 case.
1522 *revents = pfd.revents;
1524 return ret;
1527 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1529 struct pollfd pfd;
1530 int ret;
1532 pfd.fd = fd;
1533 pfd.events = events;
1535 ret = sys_poll_intr(&pfd, 1, timeout);
1536 if (ret <= 0) {
1537 *revents = 0;
1538 return ret;
1540 *revents = pfd.revents;
1541 return 1;