Second part of fix for bug 8953 - winbind can hang as nbt_getdc() has no timeout.
[Samba.git] / source3 / lib / util_sock.c
blob40e6e048d7985253f0b1945150c340094be825b1
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 "interfaces.h"
28 #include "../lib/util/tevent_unix.h"
29 #include "../lib/util/tevent_ntstatus.h"
31 const char *client_name(int fd)
33 return get_peer_name(fd,false);
36 const char *client_addr(int fd, char *addr, size_t addrlen)
38 return get_peer_addr(fd,addr,addrlen);
41 #if 0
42 /* Not currently used. JRA. */
43 int client_socket_port(int fd)
45 return get_socket_port(fd);
47 #endif
49 /****************************************************************************
50 Accessor functions to make thread-safe code easier later...
51 ****************************************************************************/
53 void set_smb_read_error(enum smb_read_errors *pre,
54 enum smb_read_errors newerr)
56 if (pre) {
57 *pre = newerr;
61 void cond_set_smb_read_error(enum smb_read_errors *pre,
62 enum smb_read_errors newerr)
64 if (pre && *pre == SMB_READ_OK) {
65 *pre = newerr;
69 /****************************************************************************
70 Determine if a file descriptor is in fact a socket.
71 ****************************************************************************/
73 bool is_a_socket(int fd)
75 int v;
76 socklen_t l;
77 l = sizeof(int);
78 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
81 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
83 typedef struct smb_socket_option {
84 const char *name;
85 int level;
86 int option;
87 int value;
88 int opttype;
89 } smb_socket_option;
91 static const smb_socket_option socket_options[] = {
92 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
93 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
94 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
95 #ifdef TCP_NODELAY
96 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
97 #endif
98 #ifdef TCP_KEEPCNT
99 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
100 #endif
101 #ifdef TCP_KEEPIDLE
102 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
103 #endif
104 #ifdef TCP_KEEPINTVL
105 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
106 #endif
107 #ifdef IPTOS_LOWDELAY
108 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
109 #endif
110 #ifdef IPTOS_THROUGHPUT
111 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
112 #endif
113 #ifdef SO_REUSEPORT
114 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
115 #endif
116 #ifdef SO_SNDBUF
117 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
118 #endif
119 #ifdef SO_RCVBUF
120 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
121 #endif
122 #ifdef SO_SNDLOWAT
123 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
124 #endif
125 #ifdef SO_RCVLOWAT
126 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
127 #endif
128 #ifdef SO_SNDTIMEO
129 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
130 #endif
131 #ifdef SO_RCVTIMEO
132 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
133 #endif
134 #ifdef TCP_FASTACK
135 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
136 #endif
137 #ifdef TCP_QUICKACK
138 {"TCP_QUICKACK", IPPROTO_TCP, TCP_QUICKACK, 0, OPT_BOOL},
139 #endif
140 #ifdef TCP_NODELAYACK
141 {"TCP_NODELAYACK", IPPROTO_TCP, TCP_NODELAYACK, 0, OPT_BOOL},
142 #endif
143 #ifdef TCP_KEEPALIVE_THRESHOLD
144 {"TCP_KEEPALIVE_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, 0, OPT_INT},
145 #endif
146 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
147 {"TCP_KEEPALIVE_ABORT_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, 0, OPT_INT},
148 #endif
149 {NULL,0,0,0,0}};
151 /****************************************************************************
152 Print socket options.
153 ****************************************************************************/
155 static void print_socket_options(int s)
157 int value;
158 socklen_t vlen = 4;
159 const smb_socket_option *p = &socket_options[0];
161 /* wrapped in if statement to prevent streams
162 * leak in SCO Openserver 5.0 */
163 /* reported on samba-technical --jerry */
164 if ( DEBUGLEVEL >= 5 ) {
165 DEBUG(5,("Socket options:\n"));
166 for (; p->name != NULL; p++) {
167 if (getsockopt(s, p->level, p->option,
168 (void *)&value, &vlen) == -1) {
169 DEBUGADD(5,("\tCould not test socket option %s.\n",
170 p->name));
171 } else {
172 DEBUGADD(5,("\t%s = %d\n",
173 p->name,value));
179 /****************************************************************************
180 Set user socket options.
181 ****************************************************************************/
183 void set_socket_options(int fd, const char *options)
185 TALLOC_CTX *ctx = talloc_stackframe();
186 char *tok;
188 while (next_token_talloc(ctx, &options, &tok," \t,")) {
189 int ret=0,i;
190 int value = 1;
191 char *p;
192 bool got_value = false;
194 if ((p = strchr_m(tok,'='))) {
195 *p = 0;
196 value = atoi(p+1);
197 got_value = true;
200 for (i=0;socket_options[i].name;i++)
201 if (strequal(socket_options[i].name,tok))
202 break;
204 if (!socket_options[i].name) {
205 DEBUG(0,("Unknown socket option %s\n",tok));
206 continue;
209 switch (socket_options[i].opttype) {
210 case OPT_BOOL:
211 case OPT_INT:
212 ret = setsockopt(fd,socket_options[i].level,
213 socket_options[i].option,
214 (char *)&value,sizeof(int));
215 break;
217 case OPT_ON:
218 if (got_value)
219 DEBUG(0,("syntax error - %s "
220 "does not take a value\n",tok));
223 int on = socket_options[i].value;
224 ret = setsockopt(fd,socket_options[i].level,
225 socket_options[i].option,
226 (char *)&on,sizeof(int));
228 break;
231 if (ret != 0) {
232 /* be aware that some systems like Solaris return
233 * EINVAL to a setsockopt() call when the client
234 * sent a RST previously - no need to worry */
235 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
236 tok, strerror(errno) ));
240 TALLOC_FREE(ctx);
241 print_socket_options(fd);
244 /****************************************************************************
245 Read from a socket.
246 ****************************************************************************/
248 ssize_t read_udp_v4_socket(int fd,
249 char *buf,
250 size_t len,
251 struct sockaddr_storage *psa)
253 ssize_t ret;
254 socklen_t socklen = sizeof(*psa);
255 struct sockaddr_in *si = (struct sockaddr_in *)psa;
257 memset((char *)psa,'\0',socklen);
259 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
260 (struct sockaddr *)psa,&socklen);
261 if (ret <= 0) {
262 /* Don't print a low debug error for a non-blocking socket. */
263 if (errno == EAGAIN) {
264 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
265 } else {
266 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
267 strerror(errno)));
269 return 0;
272 if (psa->ss_family != AF_INET) {
273 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
274 "(not IPv4)\n", (int)psa->ss_family));
275 return 0;
278 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
279 inet_ntoa(si->sin_addr),
280 si->sin_port,
281 (unsigned long)ret));
283 return ret;
286 /****************************************************************************
287 Read data from a file descriptor with a timout in msec.
288 mincount = if timeout, minimum to read before returning
289 maxcount = number to be read.
290 time_out = timeout in milliseconds
291 NB. This can be called with a non-socket fd, don't change
292 sys_read() to sys_recv() or other socket call.
293 ****************************************************************************/
295 NTSTATUS read_fd_with_timeout(int fd, char *buf,
296 size_t mincnt, size_t maxcnt,
297 unsigned int time_out,
298 size_t *size_ret)
300 int pollrtn;
301 ssize_t readret;
302 size_t nread = 0;
304 /* just checking .... */
305 if (maxcnt <= 0)
306 return NT_STATUS_OK;
308 /* Blocking read */
309 if (time_out == 0) {
310 if (mincnt == 0) {
311 mincnt = maxcnt;
314 while (nread < mincnt) {
315 readret = sys_read(fd, buf + nread, maxcnt - nread);
317 if (readret == 0) {
318 DEBUG(5,("read_fd_with_timeout: "
319 "blocking read. EOF from client.\n"));
320 return NT_STATUS_END_OF_FILE;
323 if (readret == -1) {
324 return map_nt_error_from_unix(errno);
326 nread += readret;
328 goto done;
331 /* Most difficult - timeout read */
332 /* If this is ever called on a disk file and
333 mincnt is greater then the filesize then
334 system performance will suffer severely as
335 select always returns true on disk files */
337 for (nread=0; nread < mincnt; ) {
338 int revents;
340 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
341 &revents);
343 /* Check if error */
344 if (pollrtn == -1) {
345 return map_nt_error_from_unix(errno);
348 /* Did we timeout ? */
349 if ((pollrtn == 0) ||
350 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
351 DEBUG(10,("read_fd_with_timeout: timeout read. "
352 "select timed out.\n"));
353 return NT_STATUS_IO_TIMEOUT;
356 readret = sys_read(fd, buf+nread, maxcnt-nread);
358 if (readret == 0) {
359 /* we got EOF on the file descriptor */
360 DEBUG(5,("read_fd_with_timeout: timeout read. "
361 "EOF from client.\n"));
362 return NT_STATUS_END_OF_FILE;
365 if (readret == -1) {
366 return map_nt_error_from_unix(errno);
369 nread += readret;
372 done:
373 /* Return the number we got */
374 if (size_ret) {
375 *size_ret = nread;
377 return NT_STATUS_OK;
380 /****************************************************************************
381 Read data from an fd, reading exactly N bytes.
382 NB. This can be called with a non-socket fd, don't add dependencies
383 on socket calls.
384 ****************************************************************************/
386 NTSTATUS read_data(int fd, char *buffer, size_t N)
388 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
391 /****************************************************************************
392 Write all data from an iov array
393 NB. This can be called with a non-socket fd, don't add dependencies
394 on socket calls.
395 ****************************************************************************/
397 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
399 int i;
400 size_t to_send;
401 ssize_t thistime;
402 size_t sent;
403 struct iovec *iov_copy, *iov;
405 to_send = 0;
406 for (i=0; i<iovcnt; i++) {
407 to_send += orig_iov[i].iov_len;
410 thistime = sys_writev(fd, orig_iov, iovcnt);
411 if ((thistime <= 0) || (thistime == to_send)) {
412 return thistime;
414 sent = thistime;
417 * We could not send everything in one call. Make a copy of iov that
418 * we can mess with. We keep a copy of the array start in iov_copy for
419 * the TALLOC_FREE, because we're going to modify iov later on,
420 * discarding elements.
423 iov_copy = (struct iovec *)TALLOC_MEMDUP(
424 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
426 if (iov_copy == NULL) {
427 errno = ENOMEM;
428 return -1;
430 iov = iov_copy;
432 while (sent < to_send) {
434 * We have to discard "thistime" bytes from the beginning
435 * iov array, "thistime" contains the number of bytes sent
436 * via writev last.
438 while (thistime > 0) {
439 if (thistime < iov[0].iov_len) {
440 char *new_base =
441 (char *)iov[0].iov_base + thistime;
442 iov[0].iov_base = (void *)new_base;
443 iov[0].iov_len -= thistime;
444 break;
446 thistime -= iov[0].iov_len;
447 iov += 1;
448 iovcnt -= 1;
451 thistime = sys_writev(fd, iov, iovcnt);
452 if (thistime <= 0) {
453 break;
455 sent += thistime;
458 TALLOC_FREE(iov_copy);
459 return sent;
462 /****************************************************************************
463 Write data to a fd.
464 NB. This can be called with a non-socket fd, don't add dependencies
465 on socket calls.
466 ****************************************************************************/
468 ssize_t write_data(int fd, const char *buffer, size_t N)
470 struct iovec iov;
472 iov.iov_base = CONST_DISCARD(void *, buffer);
473 iov.iov_len = N;
474 return write_data_iov(fd, &iov, 1);
477 /****************************************************************************
478 Send a keepalive packet (rfc1002).
479 ****************************************************************************/
481 bool send_keepalive(int client)
483 unsigned char buf[4];
485 buf[0] = SMBkeepalive;
486 buf[1] = buf[2] = buf[3] = 0;
488 return(write_data(client,(char *)buf,4) == 4);
491 /****************************************************************************
492 Read 4 bytes of a smb packet and return the smb length of the packet.
493 Store the result in the buffer.
494 This version of the function will return a length of zero on receiving
495 a keepalive packet.
496 Timeout is in milliseconds.
497 ****************************************************************************/
499 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
500 unsigned int timeout,
501 size_t *len)
503 int msg_type;
504 NTSTATUS status;
506 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
508 if (!NT_STATUS_IS_OK(status)) {
509 return status;
512 *len = smb_len(inbuf);
513 msg_type = CVAL(inbuf,0);
515 if (msg_type == SMBkeepalive) {
516 DEBUG(5,("Got keepalive packet\n"));
519 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
521 return NT_STATUS_OK;
524 /****************************************************************************
525 Read an smb from a fd.
526 The timeout is in milliseconds.
527 This function will return on receipt of a session keepalive packet.
528 maxlen is the max number of bytes to return, not including the 4 byte
529 length. If zero it means buflen limit.
530 Doesn't check the MAC on signed packets.
531 ****************************************************************************/
533 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
534 size_t maxlen, size_t *p_len)
536 size_t len;
537 NTSTATUS status;
539 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
541 if (!NT_STATUS_IS_OK(status)) {
542 DEBUG(0, ("read_fd_with_timeout failed, read "
543 "error = %s.\n", nt_errstr(status)));
544 return status;
547 if (len > buflen) {
548 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
549 (unsigned long)len));
550 return NT_STATUS_INVALID_PARAMETER;
553 if(len > 0) {
554 if (maxlen) {
555 len = MIN(len,maxlen);
558 status = read_fd_with_timeout(
559 fd, buffer+4, len, len, timeout, &len);
561 if (!NT_STATUS_IS_OK(status)) {
562 DEBUG(0, ("read_fd_with_timeout failed, read error = "
563 "%s.\n", nt_errstr(status)));
564 return status;
567 /* not all of samba3 properly checks for packet-termination
568 * of strings. This ensures that we don't run off into
569 * empty space. */
570 SSVAL(buffer+4,len, 0);
573 *p_len = len;
574 return NT_STATUS_OK;
577 /****************************************************************************
578 Open a socket of the specified type, port, and address for incoming data.
579 ****************************************************************************/
581 int open_socket_in(int type,
582 uint16_t port,
583 int dlevel,
584 const struct sockaddr_storage *psock,
585 bool rebind)
587 struct sockaddr_storage sock;
588 int res;
589 socklen_t slen = sizeof(struct sockaddr_in);
591 sock = *psock;
593 #if defined(HAVE_IPV6)
594 if (sock.ss_family == AF_INET6) {
595 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
596 slen = sizeof(struct sockaddr_in6);
598 #endif
599 if (sock.ss_family == AF_INET) {
600 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
603 res = socket(sock.ss_family, type, 0 );
604 if( res == -1 ) {
605 if( DEBUGLVL(0) ) {
606 dbgtext( "open_socket_in(): socket() call failed: " );
607 dbgtext( "%s\n", strerror( errno ) );
609 return -1;
612 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
614 int val = rebind ? 1 : 0;
615 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
616 (char *)&val,sizeof(val)) == -1 ) {
617 if( DEBUGLVL( dlevel ) ) {
618 dbgtext( "open_socket_in(): setsockopt: " );
619 dbgtext( "SO_REUSEADDR = %s ",
620 val?"true":"false" );
621 dbgtext( "on port %d failed ", port );
622 dbgtext( "with error = %s\n", strerror(errno) );
625 #ifdef SO_REUSEPORT
626 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
627 (char *)&val,sizeof(val)) == -1 ) {
628 if( DEBUGLVL( dlevel ) ) {
629 dbgtext( "open_socket_in(): setsockopt: ");
630 dbgtext( "SO_REUSEPORT = %s ",
631 val?"true":"false");
632 dbgtext( "on port %d failed ", port);
633 dbgtext( "with error = %s\n", strerror(errno));
636 #endif /* SO_REUSEPORT */
639 #ifdef HAVE_IPV6
641 * As IPV6_V6ONLY is the default on some systems,
642 * we better try to be consistent and always use it.
644 * This also avoids using IPv4 via AF_INET6 sockets
645 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
646 * string.
648 if (sock.ss_family == AF_INET6) {
649 int val = 1;
650 int ret;
652 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
653 (const void *)&val, sizeof(val));
654 if (ret == -1) {
655 if(DEBUGLVL(0)) {
656 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
657 dbgtext("%s\n", strerror(errno));
659 close(res);
660 return -1;
663 #endif
665 /* now we've got a socket - we need to bind it */
666 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
667 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
668 port == SMB_PORT2 || port == NMB_PORT) ) {
669 char addr[INET6_ADDRSTRLEN];
670 print_sockaddr(addr, sizeof(addr),
671 &sock);
672 dbgtext( "bind failed on port %d ", port);
673 dbgtext( "socket_addr = %s.\n", addr);
674 dbgtext( "Error = %s\n", strerror(errno));
676 close(res);
677 return -1;
680 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
681 return( res );
684 struct open_socket_out_state {
685 int fd;
686 struct event_context *ev;
687 struct sockaddr_storage ss;
688 socklen_t salen;
689 uint16_t port;
690 int wait_nsec;
693 static void open_socket_out_connected(struct tevent_req *subreq);
695 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
697 if (s->fd != -1) {
698 close(s->fd);
700 return 0;
703 /****************************************************************************
704 Create an outgoing socket. timeout is in milliseconds.
705 **************************************************************************/
707 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
708 struct event_context *ev,
709 const struct sockaddr_storage *pss,
710 uint16_t port,
711 int timeout)
713 char addr[INET6_ADDRSTRLEN];
714 struct tevent_req *result, *subreq;
715 struct open_socket_out_state *state;
716 NTSTATUS status;
718 result = tevent_req_create(mem_ctx, &state,
719 struct open_socket_out_state);
720 if (result == NULL) {
721 return NULL;
723 state->ev = ev;
724 state->ss = *pss;
725 state->port = port;
726 state->wait_nsec = 10000;
727 state->salen = -1;
729 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
730 if (state->fd == -1) {
731 status = map_nt_error_from_unix(errno);
732 goto post_status;
734 talloc_set_destructor(state, open_socket_out_state_destructor);
736 if (!tevent_req_set_endtime(
737 result, ev, timeval_current_ofs(0, timeout*1000))) {
738 goto fail;
741 #if defined(HAVE_IPV6)
742 if (pss->ss_family == AF_INET6) {
743 struct sockaddr_in6 *psa6;
744 psa6 = (struct sockaddr_in6 *)&state->ss;
745 psa6->sin6_port = htons(port);
746 if (psa6->sin6_scope_id == 0
747 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
748 setup_linklocal_scope_id(
749 (struct sockaddr *)&(state->ss));
751 state->salen = sizeof(struct sockaddr_in6);
753 #endif
754 if (pss->ss_family == AF_INET) {
755 struct sockaddr_in *psa;
756 psa = (struct sockaddr_in *)&state->ss;
757 psa->sin_port = htons(port);
758 state->salen = sizeof(struct sockaddr_in);
761 if (pss->ss_family == AF_UNIX) {
762 state->salen = sizeof(struct sockaddr_un);
765 print_sockaddr(addr, sizeof(addr), &state->ss);
766 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
768 subreq = async_connect_send(state, state->ev, state->fd,
769 (struct sockaddr *)&state->ss,
770 state->salen);
771 if ((subreq == NULL)
772 || !tevent_req_set_endtime(
773 subreq, state->ev,
774 timeval_current_ofs(0, state->wait_nsec))) {
775 goto fail;
777 tevent_req_set_callback(subreq, open_socket_out_connected, result);
778 return result;
780 post_status:
781 tevent_req_nterror(result, status);
782 return tevent_req_post(result, ev);
783 fail:
784 TALLOC_FREE(result);
785 return NULL;
788 static void open_socket_out_connected(struct tevent_req *subreq)
790 struct tevent_req *req =
791 tevent_req_callback_data(subreq, struct tevent_req);
792 struct open_socket_out_state *state =
793 tevent_req_data(req, struct open_socket_out_state);
794 int ret;
795 int sys_errno;
797 ret = async_connect_recv(subreq, &sys_errno);
798 TALLOC_FREE(subreq);
799 if (ret == 0) {
800 tevent_req_done(req);
801 return;
804 if (
805 #ifdef ETIMEDOUT
806 (sys_errno == ETIMEDOUT) ||
807 #endif
808 (sys_errno == EINPROGRESS) ||
809 (sys_errno == EALREADY) ||
810 (sys_errno == EAGAIN)) {
813 * retry
816 if (state->wait_nsec < 250000) {
817 state->wait_nsec *= 1.5;
820 subreq = async_connect_send(state, state->ev, state->fd,
821 (struct sockaddr *)&state->ss,
822 state->salen);
823 if (tevent_req_nomem(subreq, req)) {
824 return;
826 if (!tevent_req_set_endtime(
827 subreq, state->ev,
828 timeval_current_ofs(0, state->wait_nsec))) {
829 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
830 return;
832 tevent_req_set_callback(subreq, open_socket_out_connected, req);
833 return;
836 #ifdef EISCONN
837 if (sys_errno == EISCONN) {
838 tevent_req_done(req);
839 return;
841 #endif
843 /* real error */
844 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
847 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
849 struct open_socket_out_state *state =
850 tevent_req_data(req, struct open_socket_out_state);
851 NTSTATUS status;
853 if (tevent_req_is_nterror(req, &status)) {
854 return status;
856 *pfd = state->fd;
857 state->fd = -1;
858 return NT_STATUS_OK;
862 * @brief open a socket
864 * @param pss a struct sockaddr_storage defining the address to connect to
865 * @param port to connect to
866 * @param timeout in MILLISECONDS
867 * @param pfd file descriptor returned
869 * @return NTSTATUS code
871 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
872 int timeout, int *pfd)
874 TALLOC_CTX *frame = talloc_stackframe();
875 struct event_context *ev;
876 struct tevent_req *req;
877 NTSTATUS status = NT_STATUS_NO_MEMORY;
879 ev = event_context_init(frame);
880 if (ev == NULL) {
881 goto fail;
884 req = open_socket_out_send(frame, ev, pss, port, timeout);
885 if (req == NULL) {
886 goto fail;
888 if (!tevent_req_poll(req, ev)) {
889 status = NT_STATUS_INTERNAL_ERROR;
890 goto fail;
892 status = open_socket_out_recv(req, pfd);
893 fail:
894 TALLOC_FREE(frame);
895 return status;
898 struct open_socket_out_defer_state {
899 struct event_context *ev;
900 struct sockaddr_storage ss;
901 uint16_t port;
902 int timeout;
903 int fd;
906 static void open_socket_out_defer_waited(struct tevent_req *subreq);
907 static void open_socket_out_defer_connected(struct tevent_req *subreq);
909 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
910 struct event_context *ev,
911 struct timeval wait_time,
912 const struct sockaddr_storage *pss,
913 uint16_t port,
914 int timeout)
916 struct tevent_req *req, *subreq;
917 struct open_socket_out_defer_state *state;
919 req = tevent_req_create(mem_ctx, &state,
920 struct open_socket_out_defer_state);
921 if (req == NULL) {
922 return NULL;
924 state->ev = ev;
925 state->ss = *pss;
926 state->port = port;
927 state->timeout = timeout;
929 subreq = tevent_wakeup_send(
930 state, ev,
931 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
932 if (subreq == NULL) {
933 goto fail;
935 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
936 return req;
937 fail:
938 TALLOC_FREE(req);
939 return NULL;
942 static void open_socket_out_defer_waited(struct tevent_req *subreq)
944 struct tevent_req *req = tevent_req_callback_data(
945 subreq, struct tevent_req);
946 struct open_socket_out_defer_state *state = tevent_req_data(
947 req, struct open_socket_out_defer_state);
948 bool ret;
950 ret = tevent_wakeup_recv(subreq);
951 TALLOC_FREE(subreq);
952 if (!ret) {
953 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
954 return;
957 subreq = open_socket_out_send(state, state->ev, &state->ss,
958 state->port, state->timeout);
959 if (tevent_req_nomem(subreq, req)) {
960 return;
962 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
965 static void open_socket_out_defer_connected(struct tevent_req *subreq)
967 struct tevent_req *req = tevent_req_callback_data(
968 subreq, struct tevent_req);
969 struct open_socket_out_defer_state *state = tevent_req_data(
970 req, struct open_socket_out_defer_state);
971 NTSTATUS status;
973 status = open_socket_out_recv(subreq, &state->fd);
974 TALLOC_FREE(subreq);
975 if (!NT_STATUS_IS_OK(status)) {
976 tevent_req_nterror(req, status);
977 return;
979 tevent_req_done(req);
982 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
984 struct open_socket_out_defer_state *state = tevent_req_data(
985 req, struct open_socket_out_defer_state);
986 NTSTATUS status;
988 if (tevent_req_is_nterror(req, &status)) {
989 return status;
991 *pfd = state->fd;
992 state->fd = -1;
993 return NT_STATUS_OK;
996 /****************************************************************************
997 Open a connected UDP socket to host on port
998 **************************************************************************/
1000 int open_udp_socket(const char *host, int port)
1002 struct sockaddr_storage ss;
1003 int res;
1005 if (!interpret_string_addr(&ss, host, 0)) {
1006 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1007 host));
1008 return -1;
1011 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1012 if (res == -1) {
1013 return -1;
1016 #if defined(HAVE_IPV6)
1017 if (ss.ss_family == AF_INET6) {
1018 struct sockaddr_in6 *psa6;
1019 psa6 = (struct sockaddr_in6 *)&ss;
1020 psa6->sin6_port = htons(port);
1021 if (psa6->sin6_scope_id == 0
1022 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1023 setup_linklocal_scope_id(
1024 (struct sockaddr *)&ss);
1027 #endif
1028 if (ss.ss_family == AF_INET) {
1029 struct sockaddr_in *psa;
1030 psa = (struct sockaddr_in *)&ss;
1031 psa->sin_port = htons(port);
1034 if (sys_connect(res,(struct sockaddr *)&ss)) {
1035 close(res);
1036 return -1;
1039 return res;
1042 /*******************************************************************
1043 Return the IP addr of the remote end of a socket as a string.
1044 Optionally return the struct sockaddr_storage.
1045 ******************************************************************/
1047 static const char *get_peer_addr_internal(int fd,
1048 char *addr_buf,
1049 size_t addr_buf_len,
1050 struct sockaddr *pss,
1051 socklen_t *plength)
1053 struct sockaddr_storage ss;
1054 socklen_t length = sizeof(ss);
1056 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1058 if (fd == -1) {
1059 return addr_buf;
1062 if (pss == NULL) {
1063 pss = (struct sockaddr *)&ss;
1064 plength = &length;
1067 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1068 int level = (errno == ENOTCONN) ? 2 : 0;
1069 DEBUG(level, ("getpeername failed. Error was %s\n",
1070 strerror(errno)));
1071 return addr_buf;
1074 print_sockaddr_len(addr_buf,
1075 addr_buf_len,
1076 pss,
1077 *plength);
1078 return addr_buf;
1081 /*******************************************************************
1082 Matchname - determine if host name matches IP address. Used to
1083 confirm a hostname lookup to prevent spoof attacks.
1084 ******************************************************************/
1086 static bool matchname(const char *remotehost,
1087 const struct sockaddr *pss,
1088 socklen_t len)
1090 struct addrinfo *res = NULL;
1091 struct addrinfo *ailist = NULL;
1092 char addr_buf[INET6_ADDRSTRLEN];
1093 bool ret = interpret_string_addr_internal(&ailist,
1094 remotehost,
1095 AI_ADDRCONFIG|AI_CANONNAME);
1097 if (!ret || ailist == NULL) {
1098 DEBUG(3,("matchname: getaddrinfo failed for "
1099 "name %s [%s]\n",
1100 remotehost,
1101 gai_strerror(ret) ));
1102 return false;
1106 * Make sure that getaddrinfo() returns the "correct" host name.
1109 if (ailist->ai_canonname == NULL ||
1110 (!strequal(remotehost, ailist->ai_canonname) &&
1111 !strequal(remotehost, "localhost"))) {
1112 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1113 remotehost,
1114 ailist->ai_canonname ?
1115 ailist->ai_canonname : "(NULL)"));
1116 freeaddrinfo(ailist);
1117 return false;
1120 /* Look up the host address in the address list we just got. */
1121 for (res = ailist; res; res = res->ai_next) {
1122 if (!res->ai_addr) {
1123 continue;
1125 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1126 (struct sockaddr *)pss)) {
1127 freeaddrinfo(ailist);
1128 return true;
1133 * The host name does not map to the original host address. Perhaps
1134 * someone has compromised a name server. More likely someone botched
1135 * it, but that could be dangerous, too.
1138 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1139 print_sockaddr_len(addr_buf,
1140 sizeof(addr_buf),
1141 pss,
1142 len),
1143 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1145 if (ailist) {
1146 freeaddrinfo(ailist);
1148 return false;
1151 /*******************************************************************
1152 Deal with the singleton cache.
1153 ******************************************************************/
1155 struct name_addr_pair {
1156 struct sockaddr_storage ss;
1157 const char *name;
1160 /*******************************************************************
1161 Lookup a name/addr pair. Returns memory allocated from memcache.
1162 ******************************************************************/
1164 static bool lookup_nc(struct name_addr_pair *nc)
1166 DATA_BLOB tmp;
1168 ZERO_STRUCTP(nc);
1170 if (!memcache_lookup(
1171 NULL, SINGLETON_CACHE,
1172 data_blob_string_const_null("get_peer_name"),
1173 &tmp)) {
1174 return false;
1177 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1178 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1179 return true;
1182 /*******************************************************************
1183 Save a name/addr pair.
1184 ******************************************************************/
1186 static void store_nc(const struct name_addr_pair *nc)
1188 DATA_BLOB tmp;
1189 size_t namelen = strlen(nc->name);
1191 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1192 if (!tmp.data) {
1193 return;
1195 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1196 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1198 memcache_add(NULL, SINGLETON_CACHE,
1199 data_blob_string_const_null("get_peer_name"),
1200 tmp);
1201 data_blob_free(&tmp);
1204 /*******************************************************************
1205 Return the DNS name of the remote end of a socket.
1206 ******************************************************************/
1208 const char *get_peer_name(int fd, bool force_lookup)
1210 struct name_addr_pair nc;
1211 char addr_buf[INET6_ADDRSTRLEN];
1212 struct sockaddr_storage ss;
1213 socklen_t length = sizeof(ss);
1214 const char *p;
1215 int ret;
1216 char name_buf[MAX_DNS_NAME_LENGTH];
1217 char tmp_name[MAX_DNS_NAME_LENGTH];
1219 /* reverse lookups can be *very* expensive, and in many
1220 situations won't work because many networks don't link dhcp
1221 with dns. To avoid the delay we avoid the lookup if
1222 possible */
1223 if (!lp_hostname_lookups() && (force_lookup == false)) {
1224 length = sizeof(nc.ss);
1225 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1226 (struct sockaddr *)&nc.ss, &length);
1227 store_nc(&nc);
1228 lookup_nc(&nc);
1229 return nc.name ? nc.name : "UNKNOWN";
1232 lookup_nc(&nc);
1234 memset(&ss, '\0', sizeof(ss));
1235 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1237 /* it might be the same as the last one - save some DNS work */
1238 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1239 return nc.name ? nc.name : "UNKNOWN";
1242 /* Not the same. We need to lookup. */
1243 if (fd == -1) {
1244 return "UNKNOWN";
1247 /* Look up the remote host name. */
1248 ret = sys_getnameinfo((struct sockaddr *)&ss,
1249 length,
1250 name_buf,
1251 sizeof(name_buf),
1252 NULL,
1256 if (ret) {
1257 DEBUG(1,("get_peer_name: getnameinfo failed "
1258 "for %s with error %s\n",
1260 gai_strerror(ret)));
1261 strlcpy(name_buf, p, sizeof(name_buf));
1262 } else {
1263 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1264 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1265 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1269 /* can't pass the same source and dest strings in when you
1270 use --enable-developer or the clobber_region() call will
1271 get you */
1273 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1274 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1275 if (strstr(name_buf,"..")) {
1276 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1279 nc.name = name_buf;
1280 nc.ss = ss;
1282 store_nc(&nc);
1283 lookup_nc(&nc);
1284 return nc.name ? nc.name : "UNKNOWN";
1287 /*******************************************************************
1288 Return the IP addr of the remote end of a socket as a string.
1289 ******************************************************************/
1291 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1293 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1296 /*******************************************************************
1297 Create protected unix domain socket.
1299 Some unixes cannot set permissions on a ux-dom-sock, so we
1300 have to make sure that the directory contains the protection
1301 permissions instead.
1302 ******************************************************************/
1304 int create_pipe_sock(const char *socket_dir,
1305 const char *socket_name,
1306 mode_t dir_perms)
1308 #ifdef HAVE_UNIXSOCKET
1309 struct sockaddr_un sunaddr;
1310 struct stat st;
1311 int sock;
1312 mode_t old_umask;
1313 char *path = NULL;
1315 old_umask = umask(0);
1317 /* Create the socket directory or reuse the existing one */
1319 if (lstat(socket_dir, &st) == -1) {
1320 if (errno == ENOENT) {
1321 /* Create directory */
1322 if (mkdir(socket_dir, dir_perms) == -1) {
1323 DEBUG(0, ("error creating socket directory "
1324 "%s: %s\n", socket_dir,
1325 strerror(errno)));
1326 goto out_umask;
1328 } else {
1329 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1330 socket_dir, strerror(errno)));
1331 goto out_umask;
1333 } else {
1334 /* Check ownership and permission on existing directory */
1335 if (!S_ISDIR(st.st_mode)) {
1336 DEBUG(0, ("socket directory %s isn't a directory\n",
1337 socket_dir));
1338 goto out_umask;
1340 if ((st.st_uid != sec_initial_uid()) ||
1341 ((st.st_mode & 0777) != dir_perms)) {
1342 DEBUG(0, ("invalid permissions on socket directory "
1343 "%s\n", socket_dir));
1344 goto out_umask;
1348 /* Create the socket file */
1350 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1352 if (sock == -1) {
1353 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1354 strerror(errno) ));
1355 goto out_close;
1358 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1359 goto out_close;
1362 unlink(path);
1363 memset(&sunaddr, 0, sizeof(sunaddr));
1364 sunaddr.sun_family = AF_UNIX;
1365 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1367 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1368 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1369 strerror(errno)));
1370 goto out_close;
1373 if (listen(sock, 5) == -1) {
1374 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1375 strerror(errno)));
1376 goto out_close;
1379 SAFE_FREE(path);
1381 umask(old_umask);
1382 return sock;
1384 out_close:
1385 SAFE_FREE(path);
1386 if (sock != -1)
1387 close(sock);
1389 out_umask:
1390 umask(old_umask);
1391 return -1;
1393 #else
1394 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1395 return -1;
1396 #endif /* HAVE_UNIXSOCKET */
1399 /****************************************************************************
1400 Get my own canonical name, including domain.
1401 ****************************************************************************/
1403 const char *get_mydnsfullname(void)
1405 struct addrinfo *res = NULL;
1406 char my_hostname[HOST_NAME_MAX];
1407 bool ret;
1408 DATA_BLOB tmp;
1410 if (memcache_lookup(NULL, SINGLETON_CACHE,
1411 data_blob_string_const_null("get_mydnsfullname"),
1412 &tmp)) {
1413 SMB_ASSERT(tmp.length > 0);
1414 return (const char *)tmp.data;
1417 /* get my host name */
1418 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1419 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1420 return NULL;
1423 /* Ensure null termination. */
1424 my_hostname[sizeof(my_hostname)-1] = '\0';
1426 ret = interpret_string_addr_internal(&res,
1427 my_hostname,
1428 AI_ADDRCONFIG|AI_CANONNAME);
1430 if (!ret || res == NULL) {
1431 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1432 "name %s [%s]\n",
1433 my_hostname,
1434 gai_strerror(ret) ));
1435 return NULL;
1439 * Make sure that getaddrinfo() returns the "correct" host name.
1442 if (res->ai_canonname == NULL) {
1443 DEBUG(3,("get_mydnsfullname: failed to get "
1444 "canonical name for %s\n",
1445 my_hostname));
1446 freeaddrinfo(res);
1447 return NULL;
1450 /* This copies the data, so we must do a lookup
1451 * afterwards to find the value to return.
1454 memcache_add(NULL, SINGLETON_CACHE,
1455 data_blob_string_const_null("get_mydnsfullname"),
1456 data_blob_string_const_null(res->ai_canonname));
1458 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1459 data_blob_string_const_null("get_mydnsfullname"),
1460 &tmp)) {
1461 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1462 strlen(res->ai_canonname) + 1);
1465 freeaddrinfo(res);
1467 return (const char *)tmp.data;
1470 /************************************************************
1471 Is this my ip address ?
1472 ************************************************************/
1474 static bool is_my_ipaddr(const char *ipaddr_str)
1476 struct sockaddr_storage ss;
1477 struct iface_struct *nics;
1478 int i, n;
1480 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1481 return false;
1484 if (ismyaddr((struct sockaddr *)&ss)) {
1485 return true;
1488 if (is_zero_addr(&ss) ||
1489 is_loopback_addr((struct sockaddr *)&ss)) {
1490 return false;
1493 n = get_interfaces(talloc_tos(), &nics);
1494 for (i=0; i<n; i++) {
1495 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1496 TALLOC_FREE(nics);
1497 return true;
1500 TALLOC_FREE(nics);
1501 return false;
1504 /************************************************************
1505 Is this my name ?
1506 ************************************************************/
1508 bool is_myname_or_ipaddr(const char *s)
1510 TALLOC_CTX *ctx = talloc_tos();
1511 char *name = NULL;
1512 const char *dnsname;
1513 char *servername = NULL;
1515 if (!s) {
1516 return false;
1519 /* Santize the string from '\\name' */
1520 name = talloc_strdup(ctx, s);
1521 if (!name) {
1522 return false;
1525 servername = strrchr_m(name, '\\' );
1526 if (!servername) {
1527 servername = name;
1528 } else {
1529 servername++;
1532 /* Optimize for the common case */
1533 if (strequal(servername, global_myname())) {
1534 return true;
1537 /* Check for an alias */
1538 if (is_myname(servername)) {
1539 return true;
1542 /* Check for loopback */
1543 if (strequal(servername, "127.0.0.1") ||
1544 strequal(servername, "::1")) {
1545 return true;
1548 if (strequal(servername, "localhost")) {
1549 return true;
1552 /* Maybe it's my dns name */
1553 dnsname = get_mydnsfullname();
1554 if (dnsname && strequal(servername, dnsname)) {
1555 return true;
1558 /* Maybe its an IP address? */
1559 if (is_ipaddress(servername)) {
1560 return is_my_ipaddr(servername);
1563 /* Handle possible CNAME records - convert to an IP addr. list. */
1565 /* Use DNS to resolve the name, check all addresses. */
1566 struct addrinfo *p = NULL;
1567 struct addrinfo *res = NULL;
1569 if (!interpret_string_addr_internal(&res,
1570 servername,
1571 AI_ADDRCONFIG)) {
1572 return false;
1575 for (p = res; p; p = p->ai_next) {
1576 char addr[INET6_ADDRSTRLEN];
1577 struct sockaddr_storage ss;
1579 ZERO_STRUCT(ss);
1580 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1581 print_sockaddr(addr,
1582 sizeof(addr),
1583 &ss);
1584 if (is_my_ipaddr(addr)) {
1585 freeaddrinfo(res);
1586 return true;
1589 freeaddrinfo(res);
1592 /* No match */
1593 return false;
1596 struct getaddrinfo_state {
1597 const char *node;
1598 const char *service;
1599 const struct addrinfo *hints;
1600 struct addrinfo *res;
1601 int ret;
1604 static void getaddrinfo_do(void *private_data);
1605 static void getaddrinfo_done(struct tevent_req *subreq);
1607 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1608 struct tevent_context *ev,
1609 struct fncall_context *ctx,
1610 const char *node,
1611 const char *service,
1612 const struct addrinfo *hints)
1614 struct tevent_req *req, *subreq;
1615 struct getaddrinfo_state *state;
1617 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1618 if (req == NULL) {
1619 return NULL;
1622 state->node = node;
1623 state->service = service;
1624 state->hints = hints;
1626 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1627 if (tevent_req_nomem(subreq, req)) {
1628 return tevent_req_post(req, ev);
1630 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1631 return req;
1634 static void getaddrinfo_do(void *private_data)
1636 struct getaddrinfo_state *state =
1637 (struct getaddrinfo_state *)private_data;
1639 state->ret = getaddrinfo(state->node, state->service, state->hints,
1640 &state->res);
1643 static void getaddrinfo_done(struct tevent_req *subreq)
1645 struct tevent_req *req = tevent_req_callback_data(
1646 subreq, struct tevent_req);
1647 int ret, err;
1649 ret = fncall_recv(subreq, &err);
1650 TALLOC_FREE(subreq);
1651 if (ret == -1) {
1652 tevent_req_error(req, err);
1653 return;
1655 tevent_req_done(req);
1658 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1660 struct getaddrinfo_state *state = tevent_req_data(
1661 req, struct getaddrinfo_state);
1662 int err;
1664 if (tevent_req_is_unix_error(req, &err)) {
1665 switch(err) {
1666 case ENOMEM:
1667 return EAI_MEMORY;
1668 default:
1669 return EAI_FAIL;
1672 if (state->ret == 0) {
1673 *res = state->res;
1675 return state->ret;
1678 int poll_one_fd(int fd, int events, int timeout, int *revents)
1680 struct pollfd *fds;
1681 int ret;
1682 int saved_errno;
1684 fds = TALLOC_ZERO_ARRAY(talloc_tos(), struct pollfd, 2);
1685 if (fds == NULL) {
1686 errno = ENOMEM;
1687 return -1;
1689 fds[0].fd = fd;
1690 fds[0].events = events;
1692 ret = sys_poll(fds, 1, timeout);
1695 * Assign whatever poll did, even in the ret<=0 case.
1697 *revents = fds[0].revents;
1698 saved_errno = errno;
1699 TALLOC_FREE(fds);
1700 errno = saved_errno;
1702 return ret;
1705 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1707 struct pollfd pfd;
1708 int ret;
1710 pfd.fd = fd;
1711 pfd.events = events;
1713 ret = sys_poll_intr(&pfd, 1, timeout);
1714 if (ret <= 0) {
1715 *revents = 0;
1716 return ret;
1718 *revents = pfd.revents;
1719 return 1;