s3: We only need base_name in map_open_params_to_ntcreate
[Samba.git] / source3 / lib / util_sock.c
blob6ba1ab9758cf3ed4f6af9b9282c1fc2b83380066
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_KEEPALIVE_THRESHOLD
141 {"TCP_KEEPALIVE_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, 0, OPT_INT},
142 #endif
143 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
144 {"TCP_KEEPALIVE_ABORT_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, 0, OPT_INT},
145 #endif
146 {NULL,0,0,0,0}};
148 /****************************************************************************
149 Print socket options.
150 ****************************************************************************/
152 static void print_socket_options(int s)
154 int value;
155 socklen_t vlen = 4;
156 const smb_socket_option *p = &socket_options[0];
158 /* wrapped in if statement to prevent streams
159 * leak in SCO Openserver 5.0 */
160 /* reported on samba-technical --jerry */
161 if ( DEBUGLEVEL >= 5 ) {
162 DEBUG(5,("Socket options:\n"));
163 for (; p->name != NULL; p++) {
164 if (getsockopt(s, p->level, p->option,
165 (void *)&value, &vlen) == -1) {
166 DEBUGADD(5,("\tCould not test socket option %s.\n",
167 p->name));
168 } else {
169 DEBUGADD(5,("\t%s = %d\n",
170 p->name,value));
176 /****************************************************************************
177 Set user socket options.
178 ****************************************************************************/
180 void set_socket_options(int fd, const char *options)
182 TALLOC_CTX *ctx = talloc_stackframe();
183 char *tok;
185 while (next_token_talloc(ctx, &options, &tok," \t,")) {
186 int ret=0,i;
187 int value = 1;
188 char *p;
189 bool got_value = false;
191 if ((p = strchr_m(tok,'='))) {
192 *p = 0;
193 value = atoi(p+1);
194 got_value = true;
197 for (i=0;socket_options[i].name;i++)
198 if (strequal(socket_options[i].name,tok))
199 break;
201 if (!socket_options[i].name) {
202 DEBUG(0,("Unknown socket option %s\n",tok));
203 continue;
206 switch (socket_options[i].opttype) {
207 case OPT_BOOL:
208 case OPT_INT:
209 ret = setsockopt(fd,socket_options[i].level,
210 socket_options[i].option,
211 (char *)&value,sizeof(int));
212 break;
214 case OPT_ON:
215 if (got_value)
216 DEBUG(0,("syntax error - %s "
217 "does not take a value\n",tok));
220 int on = socket_options[i].value;
221 ret = setsockopt(fd,socket_options[i].level,
222 socket_options[i].option,
223 (char *)&on,sizeof(int));
225 break;
228 if (ret != 0) {
229 /* be aware that some systems like Solaris return
230 * EINVAL to a setsockopt() call when the client
231 * sent a RST previously - no need to worry */
232 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
233 tok, strerror(errno) ));
237 TALLOC_FREE(ctx);
238 print_socket_options(fd);
241 /****************************************************************************
242 Read from a socket.
243 ****************************************************************************/
245 ssize_t read_udp_v4_socket(int fd,
246 char *buf,
247 size_t len,
248 struct sockaddr_storage *psa)
250 ssize_t ret;
251 socklen_t socklen = sizeof(*psa);
252 struct sockaddr_in *si = (struct sockaddr_in *)psa;
254 memset((char *)psa,'\0',socklen);
256 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
257 (struct sockaddr *)psa,&socklen);
258 if (ret <= 0) {
259 /* Don't print a low debug error for a non-blocking socket. */
260 if (errno == EAGAIN) {
261 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
262 } else {
263 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
264 strerror(errno)));
266 return 0;
269 if (psa->ss_family != AF_INET) {
270 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
271 "(not IPv4)\n", (int)psa->ss_family));
272 return 0;
275 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
276 inet_ntoa(si->sin_addr),
277 si->sin_port,
278 (unsigned long)ret));
280 return ret;
283 /****************************************************************************
284 Read data from a file descriptor with a timout in msec.
285 mincount = if timeout, minimum to read before returning
286 maxcount = number to be read.
287 time_out = timeout in milliseconds
288 NB. This can be called with a non-socket fd, don't change
289 sys_read() to sys_recv() or other socket call.
290 ****************************************************************************/
292 NTSTATUS read_fd_with_timeout(int fd, char *buf,
293 size_t mincnt, size_t maxcnt,
294 unsigned int time_out,
295 size_t *size_ret)
297 int pollrtn;
298 ssize_t readret;
299 size_t nread = 0;
301 /* just checking .... */
302 if (maxcnt <= 0)
303 return NT_STATUS_OK;
305 /* Blocking read */
306 if (time_out == 0) {
307 if (mincnt == 0) {
308 mincnt = maxcnt;
311 while (nread < mincnt) {
312 readret = sys_read(fd, buf + nread, maxcnt - nread);
314 if (readret == 0) {
315 DEBUG(5,("read_fd_with_timeout: "
316 "blocking read. EOF from client.\n"));
317 return NT_STATUS_END_OF_FILE;
320 if (readret == -1) {
321 return map_nt_error_from_unix(errno);
323 nread += readret;
325 goto done;
328 /* Most difficult - timeout read */
329 /* If this is ever called on a disk file and
330 mincnt is greater then the filesize then
331 system performance will suffer severely as
332 select always returns true on disk files */
334 for (nread=0; nread < mincnt; ) {
335 int revents;
337 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
338 &revents);
340 /* Check if error */
341 if (pollrtn == -1) {
342 return map_nt_error_from_unix(errno);
345 /* Did we timeout ? */
346 if ((pollrtn == 0) ||
347 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
348 DEBUG(10,("read_fd_with_timeout: timeout read. "
349 "select timed out.\n"));
350 return NT_STATUS_IO_TIMEOUT;
353 readret = sys_read(fd, buf+nread, maxcnt-nread);
355 if (readret == 0) {
356 /* we got EOF on the file descriptor */
357 DEBUG(5,("read_fd_with_timeout: timeout read. "
358 "EOF from client.\n"));
359 return NT_STATUS_END_OF_FILE;
362 if (readret == -1) {
363 return map_nt_error_from_unix(errno);
366 nread += readret;
369 done:
370 /* Return the number we got */
371 if (size_ret) {
372 *size_ret = nread;
374 return NT_STATUS_OK;
377 /****************************************************************************
378 Read data from an fd, reading exactly N bytes.
379 NB. This can be called with a non-socket fd, don't add dependencies
380 on socket calls.
381 ****************************************************************************/
383 NTSTATUS read_data(int fd, char *buffer, size_t N)
385 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
388 /****************************************************************************
389 Write all data from an iov array
390 NB. This can be called with a non-socket fd, don't add dependencies
391 on socket calls.
392 ****************************************************************************/
394 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
396 int i;
397 size_t to_send;
398 ssize_t thistime;
399 size_t sent;
400 struct iovec *iov_copy, *iov;
402 to_send = 0;
403 for (i=0; i<iovcnt; i++) {
404 to_send += orig_iov[i].iov_len;
407 thistime = sys_writev(fd, orig_iov, iovcnt);
408 if ((thistime <= 0) || (thistime == to_send)) {
409 return thistime;
411 sent = thistime;
414 * We could not send everything in one call. Make a copy of iov that
415 * we can mess with. We keep a copy of the array start in iov_copy for
416 * the TALLOC_FREE, because we're going to modify iov later on,
417 * discarding elements.
420 iov_copy = (struct iovec *)TALLOC_MEMDUP(
421 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
423 if (iov_copy == NULL) {
424 errno = ENOMEM;
425 return -1;
427 iov = iov_copy;
429 while (sent < to_send) {
431 * We have to discard "thistime" bytes from the beginning
432 * iov array, "thistime" contains the number of bytes sent
433 * via writev last.
435 while (thistime > 0) {
436 if (thistime < iov[0].iov_len) {
437 char *new_base =
438 (char *)iov[0].iov_base + thistime;
439 iov[0].iov_base = (void *)new_base;
440 iov[0].iov_len -= thistime;
441 break;
443 thistime -= iov[0].iov_len;
444 iov += 1;
445 iovcnt -= 1;
448 thistime = sys_writev(fd, iov, iovcnt);
449 if (thistime <= 0) {
450 break;
452 sent += thistime;
455 TALLOC_FREE(iov_copy);
456 return sent;
459 /****************************************************************************
460 Write data to a fd.
461 NB. This can be called with a non-socket fd, don't add dependencies
462 on socket calls.
463 ****************************************************************************/
465 ssize_t write_data(int fd, const char *buffer, size_t N)
467 struct iovec iov;
469 iov.iov_base = CONST_DISCARD(void *, buffer);
470 iov.iov_len = N;
471 return write_data_iov(fd, &iov, 1);
474 /****************************************************************************
475 Send a keepalive packet (rfc1002).
476 ****************************************************************************/
478 bool send_keepalive(int client)
480 unsigned char buf[4];
482 buf[0] = SMBkeepalive;
483 buf[1] = buf[2] = buf[3] = 0;
485 return(write_data(client,(char *)buf,4) == 4);
488 /****************************************************************************
489 Read 4 bytes of a smb packet and return the smb length of the packet.
490 Store the result in the buffer.
491 This version of the function will return a length of zero on receiving
492 a keepalive packet.
493 Timeout is in milliseconds.
494 ****************************************************************************/
496 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
497 unsigned int timeout,
498 size_t *len)
500 int msg_type;
501 NTSTATUS status;
503 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
505 if (!NT_STATUS_IS_OK(status)) {
506 return status;
509 *len = smb_len(inbuf);
510 msg_type = CVAL(inbuf,0);
512 if (msg_type == SMBkeepalive) {
513 DEBUG(5,("Got keepalive packet\n"));
516 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
518 return NT_STATUS_OK;
521 /****************************************************************************
522 Read an smb from a fd.
523 The timeout is in milliseconds.
524 This function will return on receipt of a session keepalive packet.
525 maxlen is the max number of bytes to return, not including the 4 byte
526 length. If zero it means buflen limit.
527 Doesn't check the MAC on signed packets.
528 ****************************************************************************/
530 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
531 size_t maxlen, size_t *p_len)
533 size_t len;
534 NTSTATUS status;
536 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
538 if (!NT_STATUS_IS_OK(status)) {
539 DEBUG(0, ("read_fd_with_timeout failed, read "
540 "error = %s.\n", nt_errstr(status)));
541 return status;
544 if (len > buflen) {
545 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
546 (unsigned long)len));
547 return NT_STATUS_INVALID_PARAMETER;
550 if(len > 0) {
551 if (maxlen) {
552 len = MIN(len,maxlen);
555 status = read_fd_with_timeout(
556 fd, buffer+4, len, len, timeout, &len);
558 if (!NT_STATUS_IS_OK(status)) {
559 DEBUG(0, ("read_fd_with_timeout failed, read error = "
560 "%s.\n", nt_errstr(status)));
561 return status;
564 /* not all of samba3 properly checks for packet-termination
565 * of strings. This ensures that we don't run off into
566 * empty space. */
567 SSVAL(buffer+4,len, 0);
570 *p_len = len;
571 return NT_STATUS_OK;
574 /****************************************************************************
575 Open a socket of the specified type, port, and address for incoming data.
576 ****************************************************************************/
578 int open_socket_in(int type,
579 uint16_t port,
580 int dlevel,
581 const struct sockaddr_storage *psock,
582 bool rebind)
584 struct sockaddr_storage sock;
585 int res;
586 socklen_t slen = sizeof(struct sockaddr_in);
588 sock = *psock;
590 #if defined(HAVE_IPV6)
591 if (sock.ss_family == AF_INET6) {
592 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
593 slen = sizeof(struct sockaddr_in6);
595 #endif
596 if (sock.ss_family == AF_INET) {
597 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
600 res = socket(sock.ss_family, type, 0 );
601 if( res == -1 ) {
602 if( DEBUGLVL(0) ) {
603 dbgtext( "open_socket_in(): socket() call failed: " );
604 dbgtext( "%s\n", strerror( errno ) );
606 return -1;
609 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
611 int val = rebind ? 1 : 0;
612 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
613 (char *)&val,sizeof(val)) == -1 ) {
614 if( DEBUGLVL( dlevel ) ) {
615 dbgtext( "open_socket_in(): setsockopt: " );
616 dbgtext( "SO_REUSEADDR = %s ",
617 val?"true":"false" );
618 dbgtext( "on port %d failed ", port );
619 dbgtext( "with error = %s\n", strerror(errno) );
622 #ifdef SO_REUSEPORT
623 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
624 (char *)&val,sizeof(val)) == -1 ) {
625 if( DEBUGLVL( dlevel ) ) {
626 dbgtext( "open_socket_in(): setsockopt: ");
627 dbgtext( "SO_REUSEPORT = %s ",
628 val?"true":"false");
629 dbgtext( "on port %d failed ", port);
630 dbgtext( "with error = %s\n", strerror(errno));
633 #endif /* SO_REUSEPORT */
636 #ifdef HAVE_IPV6
638 * As IPV6_V6ONLY is the default on some systems,
639 * we better try to be consistent and always use it.
641 * This also avoids using IPv4 via AF_INET6 sockets
642 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
643 * string.
645 if (sock.ss_family == AF_INET6) {
646 int val = 1;
647 int ret;
649 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
650 (const void *)&val, sizeof(val));
651 if (ret == -1) {
652 if(DEBUGLVL(0)) {
653 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
654 dbgtext("%s\n", strerror(errno));
656 close(res);
657 return -1;
660 #endif
662 /* now we've got a socket - we need to bind it */
663 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
664 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
665 port == SMB_PORT2 || port == NMB_PORT) ) {
666 char addr[INET6_ADDRSTRLEN];
667 print_sockaddr(addr, sizeof(addr),
668 &sock);
669 dbgtext( "bind failed on port %d ", port);
670 dbgtext( "socket_addr = %s.\n", addr);
671 dbgtext( "Error = %s\n", strerror(errno));
673 close(res);
674 return -1;
677 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
678 return( res );
681 struct open_socket_out_state {
682 int fd;
683 struct event_context *ev;
684 struct sockaddr_storage ss;
685 socklen_t salen;
686 uint16_t port;
687 int wait_nsec;
690 static void open_socket_out_connected(struct tevent_req *subreq);
692 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
694 if (s->fd != -1) {
695 close(s->fd);
697 return 0;
700 /****************************************************************************
701 Create an outgoing socket. timeout is in milliseconds.
702 **************************************************************************/
704 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
705 struct event_context *ev,
706 const struct sockaddr_storage *pss,
707 uint16_t port,
708 int timeout)
710 char addr[INET6_ADDRSTRLEN];
711 struct tevent_req *result, *subreq;
712 struct open_socket_out_state *state;
713 NTSTATUS status;
715 result = tevent_req_create(mem_ctx, &state,
716 struct open_socket_out_state);
717 if (result == NULL) {
718 return NULL;
720 state->ev = ev;
721 state->ss = *pss;
722 state->port = port;
723 state->wait_nsec = 10000;
724 state->salen = -1;
726 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
727 if (state->fd == -1) {
728 status = map_nt_error_from_unix(errno);
729 goto post_status;
731 talloc_set_destructor(state, open_socket_out_state_destructor);
733 if (!tevent_req_set_endtime(
734 result, ev, timeval_current_ofs(0, timeout*1000))) {
735 goto fail;
738 #if defined(HAVE_IPV6)
739 if (pss->ss_family == AF_INET6) {
740 struct sockaddr_in6 *psa6;
741 psa6 = (struct sockaddr_in6 *)&state->ss;
742 psa6->sin6_port = htons(port);
743 if (psa6->sin6_scope_id == 0
744 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
745 setup_linklocal_scope_id(
746 (struct sockaddr *)&(state->ss));
748 state->salen = sizeof(struct sockaddr_in6);
750 #endif
751 if (pss->ss_family == AF_INET) {
752 struct sockaddr_in *psa;
753 psa = (struct sockaddr_in *)&state->ss;
754 psa->sin_port = htons(port);
755 state->salen = sizeof(struct sockaddr_in);
758 if (pss->ss_family == AF_UNIX) {
759 state->salen = sizeof(struct sockaddr_un);
762 print_sockaddr(addr, sizeof(addr), &state->ss);
763 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
765 subreq = async_connect_send(state, state->ev, state->fd,
766 (struct sockaddr *)&state->ss,
767 state->salen);
768 if ((subreq == NULL)
769 || !tevent_req_set_endtime(
770 subreq, state->ev,
771 timeval_current_ofs(0, state->wait_nsec))) {
772 goto fail;
774 tevent_req_set_callback(subreq, open_socket_out_connected, result);
775 return result;
777 post_status:
778 tevent_req_nterror(result, status);
779 return tevent_req_post(result, ev);
780 fail:
781 TALLOC_FREE(result);
782 return NULL;
785 static void open_socket_out_connected(struct tevent_req *subreq)
787 struct tevent_req *req =
788 tevent_req_callback_data(subreq, struct tevent_req);
789 struct open_socket_out_state *state =
790 tevent_req_data(req, struct open_socket_out_state);
791 int ret;
792 int sys_errno;
794 ret = async_connect_recv(subreq, &sys_errno);
795 TALLOC_FREE(subreq);
796 if (ret == 0) {
797 tevent_req_done(req);
798 return;
801 if (
802 #ifdef ETIMEDOUT
803 (sys_errno == ETIMEDOUT) ||
804 #endif
805 (sys_errno == EINPROGRESS) ||
806 (sys_errno == EALREADY) ||
807 (sys_errno == EAGAIN)) {
810 * retry
813 if (state->wait_nsec < 250000) {
814 state->wait_nsec *= 1.5;
817 subreq = async_connect_send(state, state->ev, state->fd,
818 (struct sockaddr *)&state->ss,
819 state->salen);
820 if (tevent_req_nomem(subreq, req)) {
821 return;
823 if (!tevent_req_set_endtime(
824 subreq, state->ev,
825 timeval_current_ofs(0, state->wait_nsec))) {
826 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
827 return;
829 tevent_req_set_callback(subreq, open_socket_out_connected, req);
830 return;
833 #ifdef EISCONN
834 if (sys_errno == EISCONN) {
835 tevent_req_done(req);
836 return;
838 #endif
840 /* real error */
841 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
844 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
846 struct open_socket_out_state *state =
847 tevent_req_data(req, struct open_socket_out_state);
848 NTSTATUS status;
850 if (tevent_req_is_nterror(req, &status)) {
851 return status;
853 *pfd = state->fd;
854 state->fd = -1;
855 return NT_STATUS_OK;
859 * @brief open a socket
861 * @param pss a struct sockaddr_storage defining the address to connect to
862 * @param port to connect to
863 * @param timeout in MILLISECONDS
864 * @param pfd file descriptor returned
866 * @return NTSTATUS code
868 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
869 int timeout, int *pfd)
871 TALLOC_CTX *frame = talloc_stackframe();
872 struct event_context *ev;
873 struct tevent_req *req;
874 NTSTATUS status = NT_STATUS_NO_MEMORY;
876 ev = event_context_init(frame);
877 if (ev == NULL) {
878 goto fail;
881 req = open_socket_out_send(frame, ev, pss, port, timeout);
882 if (req == NULL) {
883 goto fail;
885 if (!tevent_req_poll(req, ev)) {
886 status = NT_STATUS_INTERNAL_ERROR;
887 goto fail;
889 status = open_socket_out_recv(req, pfd);
890 fail:
891 TALLOC_FREE(frame);
892 return status;
895 struct open_socket_out_defer_state {
896 struct event_context *ev;
897 struct sockaddr_storage ss;
898 uint16_t port;
899 int timeout;
900 int fd;
903 static void open_socket_out_defer_waited(struct tevent_req *subreq);
904 static void open_socket_out_defer_connected(struct tevent_req *subreq);
906 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
907 struct event_context *ev,
908 struct timeval wait_time,
909 const struct sockaddr_storage *pss,
910 uint16_t port,
911 int timeout)
913 struct tevent_req *req, *subreq;
914 struct open_socket_out_defer_state *state;
916 req = tevent_req_create(mem_ctx, &state,
917 struct open_socket_out_defer_state);
918 if (req == NULL) {
919 return NULL;
921 state->ev = ev;
922 state->ss = *pss;
923 state->port = port;
924 state->timeout = timeout;
926 subreq = tevent_wakeup_send(
927 state, ev,
928 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
929 if (subreq == NULL) {
930 goto fail;
932 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
933 return req;
934 fail:
935 TALLOC_FREE(req);
936 return NULL;
939 static void open_socket_out_defer_waited(struct tevent_req *subreq)
941 struct tevent_req *req = tevent_req_callback_data(
942 subreq, struct tevent_req);
943 struct open_socket_out_defer_state *state = tevent_req_data(
944 req, struct open_socket_out_defer_state);
945 bool ret;
947 ret = tevent_wakeup_recv(subreq);
948 TALLOC_FREE(subreq);
949 if (!ret) {
950 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
951 return;
954 subreq = open_socket_out_send(state, state->ev, &state->ss,
955 state->port, state->timeout);
956 if (tevent_req_nomem(subreq, req)) {
957 return;
959 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
962 static void open_socket_out_defer_connected(struct tevent_req *subreq)
964 struct tevent_req *req = tevent_req_callback_data(
965 subreq, struct tevent_req);
966 struct open_socket_out_defer_state *state = tevent_req_data(
967 req, struct open_socket_out_defer_state);
968 NTSTATUS status;
970 status = open_socket_out_recv(subreq, &state->fd);
971 TALLOC_FREE(subreq);
972 if (!NT_STATUS_IS_OK(status)) {
973 tevent_req_nterror(req, status);
974 return;
976 tevent_req_done(req);
979 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
981 struct open_socket_out_defer_state *state = tevent_req_data(
982 req, struct open_socket_out_defer_state);
983 NTSTATUS status;
985 if (tevent_req_is_nterror(req, &status)) {
986 return status;
988 *pfd = state->fd;
989 state->fd = -1;
990 return NT_STATUS_OK;
993 /****************************************************************************
994 Open a connected UDP socket to host on port
995 **************************************************************************/
997 int open_udp_socket(const char *host, int port)
999 struct sockaddr_storage ss;
1000 int res;
1002 if (!interpret_string_addr(&ss, host, 0)) {
1003 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1004 host));
1005 return -1;
1008 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1009 if (res == -1) {
1010 return -1;
1013 #if defined(HAVE_IPV6)
1014 if (ss.ss_family == AF_INET6) {
1015 struct sockaddr_in6 *psa6;
1016 psa6 = (struct sockaddr_in6 *)&ss;
1017 psa6->sin6_port = htons(port);
1018 if (psa6->sin6_scope_id == 0
1019 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1020 setup_linklocal_scope_id(
1021 (struct sockaddr *)&ss);
1024 #endif
1025 if (ss.ss_family == AF_INET) {
1026 struct sockaddr_in *psa;
1027 psa = (struct sockaddr_in *)&ss;
1028 psa->sin_port = htons(port);
1031 if (sys_connect(res,(struct sockaddr *)&ss)) {
1032 close(res);
1033 return -1;
1036 return res;
1039 /*******************************************************************
1040 Return the IP addr of the remote end of a socket as a string.
1041 Optionally return the struct sockaddr_storage.
1042 ******************************************************************/
1044 static const char *get_peer_addr_internal(int fd,
1045 char *addr_buf,
1046 size_t addr_buf_len,
1047 struct sockaddr *pss,
1048 socklen_t *plength)
1050 struct sockaddr_storage ss;
1051 socklen_t length = sizeof(ss);
1053 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1055 if (fd == -1) {
1056 return addr_buf;
1059 if (pss == NULL) {
1060 pss = (struct sockaddr *)&ss;
1061 plength = &length;
1064 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1065 int level = (errno == ENOTCONN) ? 2 : 0;
1066 DEBUG(level, ("getpeername failed. Error was %s\n",
1067 strerror(errno)));
1068 return addr_buf;
1071 print_sockaddr_len(addr_buf,
1072 addr_buf_len,
1073 pss,
1074 *plength);
1075 return addr_buf;
1078 /*******************************************************************
1079 Matchname - determine if host name matches IP address. Used to
1080 confirm a hostname lookup to prevent spoof attacks.
1081 ******************************************************************/
1083 static bool matchname(const char *remotehost,
1084 const struct sockaddr *pss,
1085 socklen_t len)
1087 struct addrinfo *res = NULL;
1088 struct addrinfo *ailist = NULL;
1089 char addr_buf[INET6_ADDRSTRLEN];
1090 bool ret = interpret_string_addr_internal(&ailist,
1091 remotehost,
1092 AI_ADDRCONFIG|AI_CANONNAME);
1094 if (!ret || ailist == NULL) {
1095 DEBUG(3,("matchname: getaddrinfo failed for "
1096 "name %s [%s]\n",
1097 remotehost,
1098 gai_strerror(ret) ));
1099 return false;
1103 * Make sure that getaddrinfo() returns the "correct" host name.
1106 if (ailist->ai_canonname == NULL ||
1107 (!strequal(remotehost, ailist->ai_canonname) &&
1108 !strequal(remotehost, "localhost"))) {
1109 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1110 remotehost,
1111 ailist->ai_canonname ?
1112 ailist->ai_canonname : "(NULL)"));
1113 freeaddrinfo(ailist);
1114 return false;
1117 /* Look up the host address in the address list we just got. */
1118 for (res = ailist; res; res = res->ai_next) {
1119 if (!res->ai_addr) {
1120 continue;
1122 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1123 (struct sockaddr *)pss)) {
1124 freeaddrinfo(ailist);
1125 return true;
1130 * The host name does not map to the original host address. Perhaps
1131 * someone has compromised a name server. More likely someone botched
1132 * it, but that could be dangerous, too.
1135 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1136 print_sockaddr_len(addr_buf,
1137 sizeof(addr_buf),
1138 pss,
1139 len),
1140 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1142 if (ailist) {
1143 freeaddrinfo(ailist);
1145 return false;
1148 /*******************************************************************
1149 Deal with the singleton cache.
1150 ******************************************************************/
1152 struct name_addr_pair {
1153 struct sockaddr_storage ss;
1154 const char *name;
1157 /*******************************************************************
1158 Lookup a name/addr pair. Returns memory allocated from memcache.
1159 ******************************************************************/
1161 static bool lookup_nc(struct name_addr_pair *nc)
1163 DATA_BLOB tmp;
1165 ZERO_STRUCTP(nc);
1167 if (!memcache_lookup(
1168 NULL, SINGLETON_CACHE,
1169 data_blob_string_const_null("get_peer_name"),
1170 &tmp)) {
1171 return false;
1174 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1175 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1176 return true;
1179 /*******************************************************************
1180 Save a name/addr pair.
1181 ******************************************************************/
1183 static void store_nc(const struct name_addr_pair *nc)
1185 DATA_BLOB tmp;
1186 size_t namelen = strlen(nc->name);
1188 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1189 if (!tmp.data) {
1190 return;
1192 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1193 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1195 memcache_add(NULL, SINGLETON_CACHE,
1196 data_blob_string_const_null("get_peer_name"),
1197 tmp);
1198 data_blob_free(&tmp);
1201 /*******************************************************************
1202 Return the DNS name of the remote end of a socket.
1203 ******************************************************************/
1205 const char *get_peer_name(int fd, bool force_lookup)
1207 struct name_addr_pair nc;
1208 char addr_buf[INET6_ADDRSTRLEN];
1209 struct sockaddr_storage ss;
1210 socklen_t length = sizeof(ss);
1211 const char *p;
1212 int ret;
1213 char name_buf[MAX_DNS_NAME_LENGTH];
1214 char tmp_name[MAX_DNS_NAME_LENGTH];
1216 /* reverse lookups can be *very* expensive, and in many
1217 situations won't work because many networks don't link dhcp
1218 with dns. To avoid the delay we avoid the lookup if
1219 possible */
1220 if (!lp_hostname_lookups() && (force_lookup == false)) {
1221 length = sizeof(nc.ss);
1222 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1223 (struct sockaddr *)&nc.ss, &length);
1224 store_nc(&nc);
1225 lookup_nc(&nc);
1226 return nc.name ? nc.name : "UNKNOWN";
1229 lookup_nc(&nc);
1231 memset(&ss, '\0', sizeof(ss));
1232 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1234 /* it might be the same as the last one - save some DNS work */
1235 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1236 return nc.name ? nc.name : "UNKNOWN";
1239 /* Not the same. We need to lookup. */
1240 if (fd == -1) {
1241 return "UNKNOWN";
1244 /* Look up the remote host name. */
1245 ret = sys_getnameinfo((struct sockaddr *)&ss,
1246 length,
1247 name_buf,
1248 sizeof(name_buf),
1249 NULL,
1253 if (ret) {
1254 DEBUG(1,("get_peer_name: getnameinfo failed "
1255 "for %s with error %s\n",
1257 gai_strerror(ret)));
1258 strlcpy(name_buf, p, sizeof(name_buf));
1259 } else {
1260 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1261 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1262 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1266 /* can't pass the same source and dest strings in when you
1267 use --enable-developer or the clobber_region() call will
1268 get you */
1270 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1271 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1272 if (strstr(name_buf,"..")) {
1273 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1276 nc.name = name_buf;
1277 nc.ss = ss;
1279 store_nc(&nc);
1280 lookup_nc(&nc);
1281 return nc.name ? nc.name : "UNKNOWN";
1284 /*******************************************************************
1285 Return the IP addr of the remote end of a socket as a string.
1286 ******************************************************************/
1288 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1290 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1293 /*******************************************************************
1294 Create protected unix domain socket.
1296 Some unixes cannot set permissions on a ux-dom-sock, so we
1297 have to make sure that the directory contains the protection
1298 permissions instead.
1299 ******************************************************************/
1301 int create_pipe_sock(const char *socket_dir,
1302 const char *socket_name,
1303 mode_t dir_perms)
1305 #ifdef HAVE_UNIXSOCKET
1306 struct sockaddr_un sunaddr;
1307 struct stat st;
1308 int sock;
1309 mode_t old_umask;
1310 char *path = NULL;
1312 old_umask = umask(0);
1314 /* Create the socket directory or reuse the existing one */
1316 if (lstat(socket_dir, &st) == -1) {
1317 if (errno == ENOENT) {
1318 /* Create directory */
1319 if (mkdir(socket_dir, dir_perms) == -1) {
1320 DEBUG(0, ("error creating socket directory "
1321 "%s: %s\n", socket_dir,
1322 strerror(errno)));
1323 goto out_umask;
1325 } else {
1326 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1327 socket_dir, strerror(errno)));
1328 goto out_umask;
1330 } else {
1331 /* Check ownership and permission on existing directory */
1332 if (!S_ISDIR(st.st_mode)) {
1333 DEBUG(0, ("socket directory %s isn't a directory\n",
1334 socket_dir));
1335 goto out_umask;
1337 if ((st.st_uid != sec_initial_uid()) ||
1338 ((st.st_mode & 0777) != dir_perms)) {
1339 DEBUG(0, ("invalid permissions on socket directory "
1340 "%s\n", socket_dir));
1341 goto out_umask;
1345 /* Create the socket file */
1347 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1349 if (sock == -1) {
1350 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1351 strerror(errno) ));
1352 goto out_close;
1355 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1356 goto out_close;
1359 unlink(path);
1360 memset(&sunaddr, 0, sizeof(sunaddr));
1361 sunaddr.sun_family = AF_UNIX;
1362 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1364 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1365 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1366 strerror(errno)));
1367 goto out_close;
1370 if (listen(sock, 5) == -1) {
1371 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1372 strerror(errno)));
1373 goto out_close;
1376 SAFE_FREE(path);
1378 umask(old_umask);
1379 return sock;
1381 out_close:
1382 SAFE_FREE(path);
1383 if (sock != -1)
1384 close(sock);
1386 out_umask:
1387 umask(old_umask);
1388 return -1;
1390 #else
1391 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1392 return -1;
1393 #endif /* HAVE_UNIXSOCKET */
1396 /****************************************************************************
1397 Get my own canonical name, including domain.
1398 ****************************************************************************/
1400 const char *get_mydnsfullname(void)
1402 struct addrinfo *res = NULL;
1403 char my_hostname[HOST_NAME_MAX];
1404 bool ret;
1405 DATA_BLOB tmp;
1407 if (memcache_lookup(NULL, SINGLETON_CACHE,
1408 data_blob_string_const_null("get_mydnsfullname"),
1409 &tmp)) {
1410 SMB_ASSERT(tmp.length > 0);
1411 return (const char *)tmp.data;
1414 /* get my host name */
1415 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1416 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1417 return NULL;
1420 /* Ensure null termination. */
1421 my_hostname[sizeof(my_hostname)-1] = '\0';
1423 ret = interpret_string_addr_internal(&res,
1424 my_hostname,
1425 AI_ADDRCONFIG|AI_CANONNAME);
1427 if (!ret || res == NULL) {
1428 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1429 "name %s [%s]\n",
1430 my_hostname,
1431 gai_strerror(ret) ));
1432 return NULL;
1436 * Make sure that getaddrinfo() returns the "correct" host name.
1439 if (res->ai_canonname == NULL) {
1440 DEBUG(3,("get_mydnsfullname: failed to get "
1441 "canonical name for %s\n",
1442 my_hostname));
1443 freeaddrinfo(res);
1444 return NULL;
1447 /* This copies the data, so we must do a lookup
1448 * afterwards to find the value to return.
1451 memcache_add(NULL, SINGLETON_CACHE,
1452 data_blob_string_const_null("get_mydnsfullname"),
1453 data_blob_string_const_null(res->ai_canonname));
1455 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1456 data_blob_string_const_null("get_mydnsfullname"),
1457 &tmp)) {
1458 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1459 strlen(res->ai_canonname) + 1);
1462 freeaddrinfo(res);
1464 return (const char *)tmp.data;
1467 /************************************************************
1468 Is this my ip address ?
1469 ************************************************************/
1471 static bool is_my_ipaddr(const char *ipaddr_str)
1473 struct sockaddr_storage ss;
1474 struct iface_struct *nics;
1475 int i, n;
1477 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1478 return false;
1481 if (ismyaddr((struct sockaddr *)&ss)) {
1482 return true;
1485 if (is_zero_addr(&ss) ||
1486 is_loopback_addr((struct sockaddr *)&ss)) {
1487 return false;
1490 n = get_interfaces(talloc_tos(), &nics);
1491 for (i=0; i<n; i++) {
1492 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1493 TALLOC_FREE(nics);
1494 return true;
1497 TALLOC_FREE(nics);
1498 return false;
1501 /************************************************************
1502 Is this my name ?
1503 ************************************************************/
1505 bool is_myname_or_ipaddr(const char *s)
1507 TALLOC_CTX *ctx = talloc_tos();
1508 char *name = NULL;
1509 const char *dnsname;
1510 char *servername = NULL;
1512 if (!s) {
1513 return false;
1516 /* Santize the string from '\\name' */
1517 name = talloc_strdup(ctx, s);
1518 if (!name) {
1519 return false;
1522 servername = strrchr_m(name, '\\' );
1523 if (!servername) {
1524 servername = name;
1525 } else {
1526 servername++;
1529 /* Optimize for the common case */
1530 if (strequal(servername, global_myname())) {
1531 return true;
1534 /* Check for an alias */
1535 if (is_myname(servername)) {
1536 return true;
1539 /* Check for loopback */
1540 if (strequal(servername, "127.0.0.1") ||
1541 strequal(servername, "::1")) {
1542 return true;
1545 if (strequal(servername, "localhost")) {
1546 return true;
1549 /* Maybe it's my dns name */
1550 dnsname = get_mydnsfullname();
1551 if (dnsname && strequal(servername, dnsname)) {
1552 return true;
1555 /* Maybe its an IP address? */
1556 if (is_ipaddress(servername)) {
1557 return is_my_ipaddr(servername);
1560 /* Handle possible CNAME records - convert to an IP addr. list. */
1562 /* Use DNS to resolve the name, check all addresses. */
1563 struct addrinfo *p = NULL;
1564 struct addrinfo *res = NULL;
1566 if (!interpret_string_addr_internal(&res,
1567 servername,
1568 AI_ADDRCONFIG)) {
1569 return false;
1572 for (p = res; p; p = p->ai_next) {
1573 char addr[INET6_ADDRSTRLEN];
1574 struct sockaddr_storage ss;
1576 ZERO_STRUCT(ss);
1577 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1578 print_sockaddr(addr,
1579 sizeof(addr),
1580 &ss);
1581 if (is_my_ipaddr(addr)) {
1582 freeaddrinfo(res);
1583 return true;
1586 freeaddrinfo(res);
1589 /* No match */
1590 return false;
1593 struct getaddrinfo_state {
1594 const char *node;
1595 const char *service;
1596 const struct addrinfo *hints;
1597 struct addrinfo *res;
1598 int ret;
1601 static void getaddrinfo_do(void *private_data);
1602 static void getaddrinfo_done(struct tevent_req *subreq);
1604 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1605 struct tevent_context *ev,
1606 struct fncall_context *ctx,
1607 const char *node,
1608 const char *service,
1609 const struct addrinfo *hints)
1611 struct tevent_req *req, *subreq;
1612 struct getaddrinfo_state *state;
1614 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1615 if (req == NULL) {
1616 return NULL;
1619 state->node = node;
1620 state->service = service;
1621 state->hints = hints;
1623 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1624 if (tevent_req_nomem(subreq, req)) {
1625 return tevent_req_post(req, ev);
1627 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1628 return req;
1631 static void getaddrinfo_do(void *private_data)
1633 struct getaddrinfo_state *state =
1634 (struct getaddrinfo_state *)private_data;
1636 state->ret = getaddrinfo(state->node, state->service, state->hints,
1637 &state->res);
1640 static void getaddrinfo_done(struct tevent_req *subreq)
1642 struct tevent_req *req = tevent_req_callback_data(
1643 subreq, struct tevent_req);
1644 int ret, err;
1646 ret = fncall_recv(subreq, &err);
1647 TALLOC_FREE(subreq);
1648 if (ret == -1) {
1649 tevent_req_error(req, err);
1650 return;
1652 tevent_req_done(req);
1655 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1657 struct getaddrinfo_state *state = tevent_req_data(
1658 req, struct getaddrinfo_state);
1659 int err;
1661 if (tevent_req_is_unix_error(req, &err)) {
1662 switch(err) {
1663 case ENOMEM:
1664 return EAI_MEMORY;
1665 default:
1666 return EAI_FAIL;
1669 if (state->ret == 0) {
1670 *res = state->res;
1672 return state->ret;
1675 int poll_one_fd(int fd, int events, int timeout, int *revents)
1677 struct pollfd *fds;
1678 int ret;
1679 int saved_errno;
1681 fds = TALLOC_ZERO_ARRAY(talloc_tos(), struct pollfd, 2);
1682 if (fds == NULL) {
1683 errno = ENOMEM;
1684 return -1;
1686 fds[0].fd = fd;
1687 fds[0].events = events;
1689 ret = sys_poll(fds, 1, timeout);
1692 * Assign whatever poll did, even in the ret<=0 case.
1694 *revents = fds[0].revents;
1695 saved_errno = errno;
1696 TALLOC_FREE(fds);
1697 errno = saved_errno;
1699 return ret;
1702 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1704 struct pollfd pfd;
1705 int ret;
1707 pfd.fd = fd;
1708 pfd.events = events;
1710 ret = sys_poll_intr(&pfd, 1, timeout);
1711 if (ret <= 0) {
1712 *revents = 0;
1713 return ret;
1715 *revents = pfd.revents;
1716 return 1;