s3:libsmb: remove unused enum smb_read_errors infrastructure
[metze/samba/wip.git] / source3 / lib / util_sock.c
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
7
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.
12
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.
17
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/>.
20 */
21
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"
31
32 const char *client_name(int fd)
33 {
34         return get_peer_name(fd,false);
35 }
36
37 const char *client_addr(int fd, char *addr, size_t addrlen)
38 {
39         return get_peer_addr(fd,addr,addrlen);
40 }
41
42 #if 0
43 /* Not currently used. JRA. */
44 int client_socket_port(int fd)
45 {
46         return get_socket_port(fd);
47 }
48 #endif
49
50 /****************************************************************************
51  Determine if a file descriptor is in fact a socket.
52 ****************************************************************************/
53
54 bool is_a_socket(int fd)
55 {
56         int v;
57         socklen_t l;
58         l = sizeof(int);
59         return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
60 }
61
62 /****************************************************************************
63  Read from a socket.
64 ****************************************************************************/
65
66 ssize_t read_udp_v4_socket(int fd,
67                         char *buf,
68                         size_t len,
69                         struct sockaddr_storage *psa)
70 {
71         ssize_t ret;
72         socklen_t socklen = sizeof(*psa);
73         struct sockaddr_in *si = (struct sockaddr_in *)psa;
74
75         memset((char *)psa,'\0',socklen);
76
77         ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
78                         (struct sockaddr *)psa,&socklen);
79         if (ret <= 0) {
80                 /* Don't print a low debug error for a non-blocking socket. */
81                 if (errno == EAGAIN) {
82                         DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
83                 } else {
84                         DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
85                                 strerror(errno)));
86                 }
87                 return 0;
88         }
89
90         if (psa->ss_family != AF_INET) {
91                 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
92                         "(not IPv4)\n", (int)psa->ss_family));
93                 return 0;
94         }
95
96         DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
97                         inet_ntoa(si->sin_addr),
98                         si->sin_port,
99                         (unsigned long)ret));
100
101         return ret;
102 }
103
104 /****************************************************************************
105  Read data from a file descriptor with a timout in msec.
106  mincount = if timeout, minimum to read before returning
107  maxcount = number to be read.
108  time_out = timeout in milliseconds
109  NB. This can be called with a non-socket fd, don't change
110  sys_read() to sys_recv() or other socket call.
111 ****************************************************************************/
112
113 NTSTATUS read_fd_with_timeout(int fd, char *buf,
114                                   size_t mincnt, size_t maxcnt,
115                                   unsigned int time_out,
116                                   size_t *size_ret)
117 {
118         int pollrtn;
119         ssize_t readret;
120         size_t nread = 0;
121
122         /* just checking .... */
123         if (maxcnt <= 0)
124                 return NT_STATUS_OK;
125
126         /* Blocking read */
127         if (time_out == 0) {
128                 if (mincnt == 0) {
129                         mincnt = maxcnt;
130                 }
131
132                 while (nread < mincnt) {
133                         readret = sys_read(fd, buf + nread, maxcnt - nread);
134
135                         if (readret == 0) {
136                                 DEBUG(5,("read_fd_with_timeout: "
137                                         "blocking read. EOF from client.\n"));
138                                 return NT_STATUS_END_OF_FILE;
139                         }
140
141                         if (readret == -1) {
142                                 return map_nt_error_from_unix(errno);
143                         }
144                         nread += readret;
145                 }
146                 goto done;
147         }
148
149         /* Most difficult - timeout read */
150         /* If this is ever called on a disk file and
151            mincnt is greater then the filesize then
152            system performance will suffer severely as
153            select always returns true on disk files */
154
155         for (nread=0; nread < mincnt; ) {
156                 int revents;
157
158                 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
159                                            &revents);
160
161                 /* Check if error */
162                 if (pollrtn == -1) {
163                         return map_nt_error_from_unix(errno);
164                 }
165
166                 /* Did we timeout ? */
167                 if ((pollrtn == 0) ||
168                     ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
169                         DEBUG(10,("read_fd_with_timeout: timeout read. "
170                                 "select timed out.\n"));
171                         return NT_STATUS_IO_TIMEOUT;
172                 }
173
174                 readret = sys_read(fd, buf+nread, maxcnt-nread);
175
176                 if (readret == 0) {
177                         /* we got EOF on the file descriptor */
178                         DEBUG(5,("read_fd_with_timeout: timeout read. "
179                                 "EOF from client.\n"));
180                         return NT_STATUS_END_OF_FILE;
181                 }
182
183                 if (readret == -1) {
184                         return map_nt_error_from_unix(errno);
185                 }
186
187                 nread += readret;
188         }
189
190  done:
191         /* Return the number we got */
192         if (size_ret) {
193                 *size_ret = nread;
194         }
195         return NT_STATUS_OK;
196 }
197
198 /****************************************************************************
199  Read data from an fd, reading exactly N bytes.
200  NB. This can be called with a non-socket fd, don't add dependencies
201  on socket calls.
202 ****************************************************************************/
203
204 NTSTATUS read_data(int fd, char *buffer, size_t N)
205 {
206         return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
207 }
208
209 /****************************************************************************
210  Write all data from an iov array
211  NB. This can be called with a non-socket fd, don't add dependencies
212  on socket calls.
213 ****************************************************************************/
214
215 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
216 {
217         int i;
218         size_t to_send;
219         ssize_t thistime;
220         size_t sent;
221         struct iovec *iov_copy, *iov;
222
223         to_send = 0;
224         for (i=0; i<iovcnt; i++) {
225                 to_send += orig_iov[i].iov_len;
226         }
227
228         thistime = sys_writev(fd, orig_iov, iovcnt);
229         if ((thistime <= 0) || (thistime == to_send)) {
230                 return thistime;
231         }
232         sent = thistime;
233
234         /*
235          * We could not send everything in one call. Make a copy of iov that
236          * we can mess with. We keep a copy of the array start in iov_copy for
237          * the TALLOC_FREE, because we're going to modify iov later on,
238          * discarding elements.
239          */
240
241         iov_copy = (struct iovec *)talloc_memdup(
242                 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
243
244         if (iov_copy == NULL) {
245                 errno = ENOMEM;
246                 return -1;
247         }
248         iov = iov_copy;
249
250         while (sent < to_send) {
251                 /*
252                  * We have to discard "thistime" bytes from the beginning
253                  * iov array, "thistime" contains the number of bytes sent
254                  * via writev last.
255                  */
256                 while (thistime > 0) {
257                         if (thistime < iov[0].iov_len) {
258                                 char *new_base =
259                                         (char *)iov[0].iov_base + thistime;
260                                 iov[0].iov_base = (void *)new_base;
261                                 iov[0].iov_len -= thistime;
262                                 break;
263                         }
264                         thistime -= iov[0].iov_len;
265                         iov += 1;
266                         iovcnt -= 1;
267                 }
268
269                 thistime = sys_writev(fd, iov, iovcnt);
270                 if (thistime <= 0) {
271                         break;
272                 }
273                 sent += thistime;
274         }
275
276         TALLOC_FREE(iov_copy);
277         return sent;
278 }
279
280 /****************************************************************************
281  Write data to a fd.
282  NB. This can be called with a non-socket fd, don't add dependencies
283  on socket calls.
284 ****************************************************************************/
285
286 ssize_t write_data(int fd, const char *buffer, size_t N)
287 {
288         struct iovec iov;
289
290         iov.iov_base = discard_const_p(void, buffer);
291         iov.iov_len = N;
292         return write_data_iov(fd, &iov, 1);
293 }
294
295 /****************************************************************************
296  Send a keepalive packet (rfc1002).
297 ****************************************************************************/
298
299 bool send_keepalive(int client)
300 {
301         unsigned char buf[4];
302
303         buf[0] = SMBkeepalive;
304         buf[1] = buf[2] = buf[3] = 0;
305
306         return(write_data(client,(char *)buf,4) == 4);
307 }
308
309 /****************************************************************************
310  Read 4 bytes of a smb packet and return the smb length of the packet.
311  Store the result in the buffer.
312  This version of the function will return a length of zero on receiving
313  a keepalive packet.
314  Timeout is in milliseconds.
315 ****************************************************************************/
316
317 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
318                                           unsigned int timeout,
319                                           size_t *len)
320 {
321         int msg_type;
322         NTSTATUS status;
323
324         status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
325
326         if (!NT_STATUS_IS_OK(status)) {
327                 return status;
328         }
329
330         *len = smb_len(inbuf);
331         msg_type = CVAL(inbuf,0);
332
333         if (msg_type == SMBkeepalive) {
334                 DEBUG(5,("Got keepalive packet\n"));
335         }
336
337         DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
338
339         return NT_STATUS_OK;
340 }
341
342 /****************************************************************************
343  Read an smb from a fd.
344  The timeout is in milliseconds.
345  This function will return on receipt of a session keepalive packet.
346  maxlen is the max number of bytes to return, not including the 4 byte
347  length. If zero it means buflen limit.
348  Doesn't check the MAC on signed packets.
349 ****************************************************************************/
350
351 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
352                          size_t maxlen, size_t *p_len)
353 {
354         size_t len;
355         NTSTATUS status;
356
357         status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
358
359         if (!NT_STATUS_IS_OK(status)) {
360                 DEBUG(0, ("read_fd_with_timeout failed, read "
361                           "error = %s.\n", nt_errstr(status)));
362                 return status;
363         }
364
365         if (len > buflen) {
366                 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
367                                         (unsigned long)len));
368                 return NT_STATUS_INVALID_PARAMETER;
369         }
370
371         if(len > 0) {
372                 if (maxlen) {
373                         len = MIN(len,maxlen);
374                 }
375
376                 status = read_fd_with_timeout(
377                         fd, buffer+4, len, len, timeout, &len);
378
379                 if (!NT_STATUS_IS_OK(status)) {
380                         DEBUG(0, ("read_fd_with_timeout failed, read error = "
381                                   "%s.\n", nt_errstr(status)));
382                         return status;
383                 }
384
385                 /* not all of samba3 properly checks for packet-termination
386                  * of strings. This ensures that we don't run off into
387                  * empty space. */
388                 SSVAL(buffer+4,len, 0);
389         }
390
391         *p_len = len;
392         return NT_STATUS_OK;
393 }
394
395 /****************************************************************************
396  Open a socket of the specified type, port, and address for incoming data.
397 ****************************************************************************/
398
399 int open_socket_in(int type,
400                 uint16_t port,
401                 int dlevel,
402                 const struct sockaddr_storage *psock,
403                 bool rebind)
404 {
405         struct sockaddr_storage sock;
406         int res;
407         socklen_t slen = sizeof(struct sockaddr_in);
408
409         sock = *psock;
410
411 #if defined(HAVE_IPV6)
412         if (sock.ss_family == AF_INET6) {
413                 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
414                 slen = sizeof(struct sockaddr_in6);
415         }
416 #endif
417         if (sock.ss_family == AF_INET) {
418                 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
419         }
420
421         res = socket(sock.ss_family, type, 0 );
422         if( res == -1 ) {
423                 if( DEBUGLVL(0) ) {
424                         dbgtext( "open_socket_in(): socket() call failed: " );
425                         dbgtext( "%s\n", strerror( errno ) );
426                 }
427                 return -1;
428         }
429
430         /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
431         {
432                 int val = rebind ? 1 : 0;
433                 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
434                                         (char *)&val,sizeof(val)) == -1 ) {
435                         if( DEBUGLVL( dlevel ) ) {
436                                 dbgtext( "open_socket_in(): setsockopt: " );
437                                 dbgtext( "SO_REUSEADDR = %s ",
438                                                 val?"true":"false" );
439                                 dbgtext( "on port %d failed ", port );
440                                 dbgtext( "with error = %s\n", strerror(errno) );
441                         }
442                 }
443 #ifdef SO_REUSEPORT
444                 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
445                                         (char *)&val,sizeof(val)) == -1 ) {
446                         if( DEBUGLVL( dlevel ) ) {
447                                 dbgtext( "open_socket_in(): setsockopt: ");
448                                 dbgtext( "SO_REUSEPORT = %s ",
449                                                 val?"true":"false");
450                                 dbgtext( "on port %d failed ", port);
451                                 dbgtext( "with error = %s\n", strerror(errno));
452                         }
453                 }
454 #endif /* SO_REUSEPORT */
455         }
456
457 #ifdef HAVE_IPV6
458         /*
459          * As IPV6_V6ONLY is the default on some systems,
460          * we better try to be consistent and always use it.
461          *
462          * This also avoids using IPv4 via AF_INET6 sockets
463          * and makes sure %I never resolves to a '::ffff:192.168.0.1'
464          * string.
465          */
466         if (sock.ss_family == AF_INET6) {
467                 int val = 1;
468                 int ret;
469
470                 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
471                                  (const void *)&val, sizeof(val));
472                 if (ret == -1) {
473                         if(DEBUGLVL(0)) {
474                                 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
475                                 dbgtext("%s\n", strerror(errno));
476                         }
477                         close(res);
478                         return -1;
479                 }
480         }
481 #endif
482
483         /* now we've got a socket - we need to bind it */
484         if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
485                 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
486                                 port == SMB_PORT2 || port == NMB_PORT) ) {
487                         char addr[INET6_ADDRSTRLEN];
488                         print_sockaddr(addr, sizeof(addr),
489                                         &sock);
490                         dbgtext( "bind failed on port %d ", port);
491                         dbgtext( "socket_addr = %s.\n", addr);
492                         dbgtext( "Error = %s\n", strerror(errno));
493                 }
494                 close(res);
495                 return -1;
496         }
497
498         DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
499         return( res );
500  }
501
502 struct open_socket_out_state {
503         int fd;
504         struct event_context *ev;
505         struct sockaddr_storage ss;
506         socklen_t salen;
507         uint16_t port;
508         int wait_usec;
509 };
510
511 static void open_socket_out_connected(struct tevent_req *subreq);
512
513 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
514 {
515         if (s->fd != -1) {
516                 close(s->fd);
517         }
518         return 0;
519 }
520
521 /****************************************************************************
522  Create an outgoing socket. timeout is in milliseconds.
523 **************************************************************************/
524
525 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
526                                         struct event_context *ev,
527                                         const struct sockaddr_storage *pss,
528                                         uint16_t port,
529                                         int timeout)
530 {
531         char addr[INET6_ADDRSTRLEN];
532         struct tevent_req *result, *subreq;
533         struct open_socket_out_state *state;
534         NTSTATUS status;
535
536         result = tevent_req_create(mem_ctx, &state,
537                                    struct open_socket_out_state);
538         if (result == NULL) {
539                 return NULL;
540         }
541         state->ev = ev;
542         state->ss = *pss;
543         state->port = port;
544         state->wait_usec = 10000;
545         state->salen = -1;
546
547         state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
548         if (state->fd == -1) {
549                 status = map_nt_error_from_unix(errno);
550                 goto post_status;
551         }
552         talloc_set_destructor(state, open_socket_out_state_destructor);
553
554         if (!tevent_req_set_endtime(
555                     result, ev, timeval_current_ofs_msec(timeout))) {
556                 goto fail;
557         }
558
559 #if defined(HAVE_IPV6)
560         if (pss->ss_family == AF_INET6) {
561                 struct sockaddr_in6 *psa6;
562                 psa6 = (struct sockaddr_in6 *)&state->ss;
563                 psa6->sin6_port = htons(port);
564                 if (psa6->sin6_scope_id == 0
565                     && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
566                         setup_linklocal_scope_id(
567                                 (struct sockaddr *)&(state->ss));
568                 }
569                 state->salen = sizeof(struct sockaddr_in6);
570         }
571 #endif
572         if (pss->ss_family == AF_INET) {
573                 struct sockaddr_in *psa;
574                 psa = (struct sockaddr_in *)&state->ss;
575                 psa->sin_port = htons(port);
576                 state->salen = sizeof(struct sockaddr_in);
577         }
578
579         if (pss->ss_family == AF_UNIX) {
580                 state->salen = sizeof(struct sockaddr_un);
581         }
582
583         print_sockaddr(addr, sizeof(addr), &state->ss);
584         DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
585
586         subreq = async_connect_send(state, state->ev, state->fd,
587                                     (struct sockaddr *)&state->ss,
588                                     state->salen);
589         if ((subreq == NULL)
590             || !tevent_req_set_endtime(
591                     subreq, state->ev,
592                     timeval_current_ofs(0, state->wait_usec))) {
593                 goto fail;
594         }
595         tevent_req_set_callback(subreq, open_socket_out_connected, result);
596         return result;
597
598  post_status:
599         tevent_req_nterror(result, status);
600         return tevent_req_post(result, ev);
601  fail:
602         TALLOC_FREE(result);
603         return NULL;
604 }
605
606 static void open_socket_out_connected(struct tevent_req *subreq)
607 {
608         struct tevent_req *req =
609                 tevent_req_callback_data(subreq, struct tevent_req);
610         struct open_socket_out_state *state =
611                 tevent_req_data(req, struct open_socket_out_state);
612         int ret;
613         int sys_errno;
614
615         ret = async_connect_recv(subreq, &sys_errno);
616         TALLOC_FREE(subreq);
617         if (ret == 0) {
618                 tevent_req_done(req);
619                 return;
620         }
621
622         if (
623 #ifdef ETIMEDOUT
624                 (sys_errno == ETIMEDOUT) ||
625 #endif
626                 (sys_errno == EINPROGRESS) ||
627                 (sys_errno == EALREADY) ||
628                 (sys_errno == EAGAIN)) {
629
630                 /*
631                  * retry
632                  */
633
634                 if (state->wait_usec < 250000) {
635                         state->wait_usec *= 1.5;
636                 }
637
638                 subreq = async_connect_send(state, state->ev, state->fd,
639                                             (struct sockaddr *)&state->ss,
640                                             state->salen);
641                 if (tevent_req_nomem(subreq, req)) {
642                         return;
643                 }
644                 if (!tevent_req_set_endtime(
645                             subreq, state->ev,
646                             timeval_current_ofs_usec(state->wait_usec))) {
647                         tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
648                         return;
649                 }
650                 tevent_req_set_callback(subreq, open_socket_out_connected, req);
651                 return;
652         }
653
654 #ifdef EISCONN
655         if (sys_errno == EISCONN) {
656                 tevent_req_done(req);
657                 return;
658         }
659 #endif
660
661         /* real error */
662         tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
663 }
664
665 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
666 {
667         struct open_socket_out_state *state =
668                 tevent_req_data(req, struct open_socket_out_state);
669         NTSTATUS status;
670
671         if (tevent_req_is_nterror(req, &status)) {
672                 return status;
673         }
674         *pfd = state->fd;
675         state->fd = -1;
676         return NT_STATUS_OK;
677 }
678
679 /**
680 * @brief open a socket
681 *
682 * @param pss a struct sockaddr_storage defining the address to connect to
683 * @param port to connect to
684 * @param timeout in MILLISECONDS
685 * @param pfd file descriptor returned
686 *
687 * @return NTSTATUS code
688 */
689 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
690                          int timeout, int *pfd)
691 {
692         TALLOC_CTX *frame = talloc_stackframe();
693         struct event_context *ev;
694         struct tevent_req *req;
695         NTSTATUS status = NT_STATUS_NO_MEMORY;
696
697         ev = event_context_init(frame);
698         if (ev == NULL) {
699                 goto fail;
700         }
701
702         req = open_socket_out_send(frame, ev, pss, port, timeout);
703         if (req == NULL) {
704                 goto fail;
705         }
706         if (!tevent_req_poll(req, ev)) {
707                 status = NT_STATUS_INTERNAL_ERROR;
708                 goto fail;
709         }
710         status = open_socket_out_recv(req, pfd);
711  fail:
712         TALLOC_FREE(frame);
713         return status;
714 }
715
716 struct open_socket_out_defer_state {
717         struct event_context *ev;
718         struct sockaddr_storage ss;
719         uint16_t port;
720         int timeout;
721         int fd;
722 };
723
724 static void open_socket_out_defer_waited(struct tevent_req *subreq);
725 static void open_socket_out_defer_connected(struct tevent_req *subreq);
726
727 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
728                                               struct event_context *ev,
729                                               struct timeval wait_time,
730                                               const struct sockaddr_storage *pss,
731                                               uint16_t port,
732                                               int timeout)
733 {
734         struct tevent_req *req, *subreq;
735         struct open_socket_out_defer_state *state;
736
737         req = tevent_req_create(mem_ctx, &state,
738                                 struct open_socket_out_defer_state);
739         if (req == NULL) {
740                 return NULL;
741         }
742         state->ev = ev;
743         state->ss = *pss;
744         state->port = port;
745         state->timeout = timeout;
746
747         subreq = tevent_wakeup_send(
748                 state, ev,
749                 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
750         if (subreq == NULL) {
751                 goto fail;
752         }
753         tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
754         return req;
755  fail:
756         TALLOC_FREE(req);
757         return NULL;
758 }
759
760 static void open_socket_out_defer_waited(struct tevent_req *subreq)
761 {
762         struct tevent_req *req = tevent_req_callback_data(
763                 subreq, struct tevent_req);
764         struct open_socket_out_defer_state *state = tevent_req_data(
765                 req, struct open_socket_out_defer_state);
766         bool ret;
767
768         ret = tevent_wakeup_recv(subreq);
769         TALLOC_FREE(subreq);
770         if (!ret) {
771                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
772                 return;
773         }
774
775         subreq = open_socket_out_send(state, state->ev, &state->ss,
776                                       state->port, state->timeout);
777         if (tevent_req_nomem(subreq, req)) {
778                 return;
779         }
780         tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
781 }
782
783 static void open_socket_out_defer_connected(struct tevent_req *subreq)
784 {
785         struct tevent_req *req = tevent_req_callback_data(
786                 subreq, struct tevent_req);
787         struct open_socket_out_defer_state *state = tevent_req_data(
788                 req, struct open_socket_out_defer_state);
789         NTSTATUS status;
790
791         status = open_socket_out_recv(subreq, &state->fd);
792         TALLOC_FREE(subreq);
793         if (!NT_STATUS_IS_OK(status)) {
794                 tevent_req_nterror(req, status);
795                 return;
796         }
797         tevent_req_done(req);
798 }
799
800 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
801 {
802         struct open_socket_out_defer_state *state = tevent_req_data(
803                 req, struct open_socket_out_defer_state);
804         NTSTATUS status;
805
806         if (tevent_req_is_nterror(req, &status)) {
807                 return status;
808         }
809         *pfd = state->fd;
810         state->fd = -1;
811         return NT_STATUS_OK;
812 }
813
814 /****************************************************************************
815  Open a connected UDP socket to host on port
816 **************************************************************************/
817
818 int open_udp_socket(const char *host, int port)
819 {
820         struct sockaddr_storage ss;
821         int res;
822
823         if (!interpret_string_addr(&ss, host, 0)) {
824                 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
825                         host));
826                 return -1;
827         }
828
829         res = socket(ss.ss_family, SOCK_DGRAM, 0);
830         if (res == -1) {
831                 return -1;
832         }
833
834 #if defined(HAVE_IPV6)
835         if (ss.ss_family == AF_INET6) {
836                 struct sockaddr_in6 *psa6;
837                 psa6 = (struct sockaddr_in6 *)&ss;
838                 psa6->sin6_port = htons(port);
839                 if (psa6->sin6_scope_id == 0
840                                 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
841                         setup_linklocal_scope_id(
842                                 (struct sockaddr *)&ss);
843                 }
844         }
845 #endif
846         if (ss.ss_family == AF_INET) {
847                 struct sockaddr_in *psa;
848                 psa = (struct sockaddr_in *)&ss;
849                 psa->sin_port = htons(port);
850         }
851
852         if (sys_connect(res,(struct sockaddr *)&ss)) {
853                 close(res);
854                 return -1;
855         }
856
857         return res;
858 }
859
860 /*******************************************************************
861  Return the IP addr of the remote end of a socket as a string.
862  Optionally return the struct sockaddr_storage.
863  ******************************************************************/
864
865 static const char *get_peer_addr_internal(int fd,
866                                 char *addr_buf,
867                                 size_t addr_buf_len,
868                                 struct sockaddr *pss,
869                                 socklen_t *plength)
870 {
871         struct sockaddr_storage ss;
872         socklen_t length = sizeof(ss);
873
874         strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
875
876         if (fd == -1) {
877                 return addr_buf;
878         }
879
880         if (pss == NULL) {
881                 pss = (struct sockaddr *)&ss;
882                 plength = &length;
883         }
884
885         if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
886                 int level = (errno == ENOTCONN) ? 2 : 0;
887                 DEBUG(level, ("getpeername failed. Error was %s\n",
888                                strerror(errno)));
889                 return addr_buf;
890         }
891
892         print_sockaddr_len(addr_buf,
893                         addr_buf_len,
894                         pss,
895                         *plength);
896         return addr_buf;
897 }
898
899 /*******************************************************************
900  Matchname - determine if host name matches IP address. Used to
901  confirm a hostname lookup to prevent spoof attacks.
902 ******************************************************************/
903
904 static bool matchname(const char *remotehost,
905                 const struct sockaddr *pss,
906                 socklen_t len)
907 {
908         struct addrinfo *res = NULL;
909         struct addrinfo *ailist = NULL;
910         char addr_buf[INET6_ADDRSTRLEN];
911         bool ret = interpret_string_addr_internal(&ailist,
912                         remotehost,
913                         AI_ADDRCONFIG|AI_CANONNAME);
914
915         if (!ret || ailist == NULL) {
916                 DEBUG(3,("matchname: getaddrinfo failed for "
917                         "name %s [%s]\n",
918                         remotehost,
919                         gai_strerror(ret) ));
920                 return false;
921         }
922
923         /*
924          * Make sure that getaddrinfo() returns the "correct" host name.
925          */
926
927         if (ailist->ai_canonname == NULL ||
928                 (!strequal(remotehost, ailist->ai_canonname) &&
929                  !strequal(remotehost, "localhost"))) {
930                 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
931                          remotehost,
932                          ailist->ai_canonname ?
933                                  ailist->ai_canonname : "(NULL)"));
934                 freeaddrinfo(ailist);
935                 return false;
936         }
937
938         /* Look up the host address in the address list we just got. */
939         for (res = ailist; res; res = res->ai_next) {
940                 if (!res->ai_addr) {
941                         continue;
942                 }
943                 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
944                                         (const struct sockaddr *)pss)) {
945                         freeaddrinfo(ailist);
946                         return true;
947                 }
948         }
949
950         /*
951          * The host name does not map to the original host address. Perhaps
952          * someone has compromised a name server. More likely someone botched
953          * it, but that could be dangerous, too.
954          */
955
956         DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
957                 print_sockaddr_len(addr_buf,
958                         sizeof(addr_buf),
959                         pss,
960                         len),
961                  ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
962
963         if (ailist) {
964                 freeaddrinfo(ailist);
965         }
966         return false;
967 }
968
969 /*******************************************************************
970  Deal with the singleton cache.
971 ******************************************************************/
972
973 struct name_addr_pair {
974         struct sockaddr_storage ss;
975         const char *name;
976 };
977
978 /*******************************************************************
979  Lookup a name/addr pair. Returns memory allocated from memcache.
980 ******************************************************************/
981
982 static bool lookup_nc(struct name_addr_pair *nc)
983 {
984         DATA_BLOB tmp;
985
986         ZERO_STRUCTP(nc);
987
988         if (!memcache_lookup(
989                         NULL, SINGLETON_CACHE,
990                         data_blob_string_const_null("get_peer_name"),
991                         &tmp)) {
992                 return false;
993         }
994
995         memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
996         nc->name = (const char *)tmp.data + sizeof(nc->ss);
997         return true;
998 }
999
1000 /*******************************************************************
1001  Save a name/addr pair.
1002 ******************************************************************/
1003
1004 static void store_nc(const struct name_addr_pair *nc)
1005 {
1006         DATA_BLOB tmp;
1007         size_t namelen = strlen(nc->name);
1008
1009         tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1010         if (!tmp.data) {
1011                 return;
1012         }
1013         memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1014         memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1015
1016         memcache_add(NULL, SINGLETON_CACHE,
1017                         data_blob_string_const_null("get_peer_name"),
1018                         tmp);
1019         data_blob_free(&tmp);
1020 }
1021
1022 /*******************************************************************
1023  Return the DNS name of the remote end of a socket.
1024 ******************************************************************/
1025
1026 const char *get_peer_name(int fd, bool force_lookup)
1027 {
1028         struct name_addr_pair nc;
1029         char addr_buf[INET6_ADDRSTRLEN];
1030         struct sockaddr_storage ss;
1031         socklen_t length = sizeof(ss);
1032         const char *p;
1033         int ret;
1034         char name_buf[MAX_DNS_NAME_LENGTH];
1035         char tmp_name[MAX_DNS_NAME_LENGTH];
1036
1037         /* reverse lookups can be *very* expensive, and in many
1038            situations won't work because many networks don't link dhcp
1039            with dns. To avoid the delay we avoid the lookup if
1040            possible */
1041         if (!lp_hostname_lookups() && (force_lookup == false)) {
1042                 length = sizeof(nc.ss);
1043                 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1044                         (struct sockaddr *)&nc.ss, &length);
1045                 store_nc(&nc);
1046                 lookup_nc(&nc);
1047                 return nc.name ? nc.name : "UNKNOWN";
1048         }
1049
1050         lookup_nc(&nc);
1051
1052         memset(&ss, '\0', sizeof(ss));
1053         p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1054
1055         /* it might be the same as the last one - save some DNS work */
1056         if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1057                 return nc.name ? nc.name : "UNKNOWN";
1058         }
1059
1060         /* Not the same. We need to lookup. */
1061         if (fd == -1) {
1062                 return "UNKNOWN";
1063         }
1064
1065         /* Look up the remote host name. */
1066         ret = sys_getnameinfo((struct sockaddr *)&ss,
1067                         length,
1068                         name_buf,
1069                         sizeof(name_buf),
1070                         NULL,
1071                         0,
1072                         0);
1073
1074         if (ret) {
1075                 DEBUG(1,("get_peer_name: getnameinfo failed "
1076                         "for %s with error %s\n",
1077                         p,
1078                         gai_strerror(ret)));
1079                 strlcpy(name_buf, p, sizeof(name_buf));
1080         } else {
1081                 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1082                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1083                         strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1084                 }
1085         }
1086
1087         strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1088         alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1089         if (strstr(name_buf,"..")) {
1090                 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1091         }
1092
1093         nc.name = name_buf;
1094         nc.ss = ss;
1095
1096         store_nc(&nc);
1097         lookup_nc(&nc);
1098         return nc.name ? nc.name : "UNKNOWN";
1099 }
1100
1101 /*******************************************************************
1102  Return the IP addr of the remote end of a socket as a string.
1103  ******************************************************************/
1104
1105 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1106 {
1107         return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1108 }
1109
1110 int get_remote_hostname(const struct tsocket_address *remote_address,
1111                         char **name,
1112                         TALLOC_CTX *mem_ctx)
1113 {
1114         char name_buf[MAX_DNS_NAME_LENGTH];
1115         char tmp_name[MAX_DNS_NAME_LENGTH];
1116         struct name_addr_pair nc;
1117         struct sockaddr_storage ss;
1118         ssize_t len;
1119         int rc;
1120
1121         if (!lp_hostname_lookups()) {
1122                 nc.name = tsocket_address_inet_addr_string(remote_address,
1123                                                            mem_ctx);
1124                 if (nc.name == NULL) {
1125                         return -1;
1126                 }
1127
1128                 len = tsocket_address_bsd_sockaddr(remote_address,
1129                                                    (struct sockaddr *) &nc.ss,
1130                                                    sizeof(struct sockaddr_storage));
1131                 if (len < 0) {
1132                         return -1;
1133                 }
1134
1135                 store_nc(&nc);
1136                 lookup_nc(&nc);
1137
1138                 if (nc.name == NULL) {
1139                         *name = talloc_strdup(mem_ctx, "UNKNOWN");
1140                 } else {
1141                         *name = talloc_strdup(mem_ctx, nc.name);
1142                 }
1143                 return 0;
1144         }
1145
1146         lookup_nc(&nc);
1147
1148         ZERO_STRUCT(ss);
1149
1150         len = tsocket_address_bsd_sockaddr(remote_address,
1151                                            (struct sockaddr *) &ss,
1152                                            sizeof(struct sockaddr_storage));
1153         if (len < 0) {
1154                 return -1;
1155         }
1156
1157         /* it might be the same as the last one - save some DNS work */
1158         if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1159                 if (nc.name == NULL) {
1160                         *name = talloc_strdup(mem_ctx, "UNKNOWN");
1161                 } else {
1162                         *name = talloc_strdup(mem_ctx, nc.name);
1163                 }
1164                 return 0;
1165         }
1166
1167         /* Look up the remote host name. */
1168         rc = sys_getnameinfo((struct sockaddr *) &ss,
1169                              len,
1170                              name_buf,
1171                              sizeof(name_buf),
1172                              NULL,
1173                              0,
1174                              0);
1175         if (rc < 0) {
1176                 char *p;
1177
1178                 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1179                 if (p == NULL) {
1180                         return -1;
1181                 }
1182
1183                 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1184                          p,
1185                          gai_strerror(rc)));
1186                 strlcpy(name_buf, p, sizeof(name_buf));
1187
1188                 TALLOC_FREE(p);
1189         } else {
1190                 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1191                         DEBUG(0,("matchname failed on %s\n", name_buf));
1192                         strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1193                 }
1194         }
1195
1196         strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1197         alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1198         if (strstr(name_buf,"..")) {
1199                 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1200         }
1201
1202         nc.name = name_buf;
1203         nc.ss = ss;
1204
1205         store_nc(&nc);
1206         lookup_nc(&nc);
1207
1208         if (nc.name == NULL) {
1209                 *name = talloc_strdup(mem_ctx, "UNKOWN");
1210         } else {
1211                 *name = talloc_strdup(mem_ctx, nc.name);
1212         }
1213
1214         return 0;
1215 }
1216
1217 /*******************************************************************
1218  Create protected unix domain socket.
1219
1220  Some unixes cannot set permissions on a ux-dom-sock, so we
1221  have to make sure that the directory contains the protection
1222  permissions instead.
1223  ******************************************************************/
1224
1225 int create_pipe_sock(const char *socket_dir,
1226                      const char *socket_name,
1227                      mode_t dir_perms)
1228 {
1229 #ifdef HAVE_UNIXSOCKET
1230         struct sockaddr_un sunaddr;
1231         struct stat st;
1232         int sock;
1233         mode_t old_umask;
1234         char *path = NULL;
1235
1236         old_umask = umask(0);
1237
1238         /* Create the socket directory or reuse the existing one */
1239
1240         if (lstat(socket_dir, &st) == -1) {
1241                 if (errno == ENOENT) {
1242                         /* Create directory */
1243                         if (mkdir(socket_dir, dir_perms) == -1) {
1244                                 DEBUG(0, ("error creating socket directory "
1245                                         "%s: %s\n", socket_dir,
1246                                         strerror(errno)));
1247                                 goto out_umask;
1248                         }
1249                 } else {
1250                         DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1251                                 socket_dir, strerror(errno)));
1252                         goto out_umask;
1253                 }
1254         } else {
1255                 /* Check ownership and permission on existing directory */
1256                 if (!S_ISDIR(st.st_mode)) {
1257                         DEBUG(0, ("socket directory '%s' isn't a directory\n",
1258                                 socket_dir));
1259                         goto out_umask;
1260                 }
1261                 if (st.st_uid != sec_initial_uid()) {
1262                         DEBUG(0, ("invalid ownership on directory "
1263                                   "'%s'\n", socket_dir));
1264                         umask(old_umask);
1265                         goto out_umask;
1266                 }
1267                 if ((st.st_mode & 0777) != dir_perms) {
1268                         DEBUG(0, ("invalid permissions on directory "
1269                                   "'%s': has 0%o should be 0%o\n", socket_dir,
1270                                   (st.st_mode & 0777), dir_perms));
1271                         umask(old_umask);
1272                         goto out_umask;
1273                 }
1274         }
1275
1276         /* Create the socket file */
1277
1278         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1279
1280         if (sock == -1) {
1281                 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1282                         strerror(errno) ));
1283                 goto out_close;
1284         }
1285
1286         if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1287                 goto out_close;
1288         }
1289
1290         unlink(path);
1291         memset(&sunaddr, 0, sizeof(sunaddr));
1292         sunaddr.sun_family = AF_UNIX;
1293         strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1294
1295         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1296                 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1297                         strerror(errno)));
1298                 goto out_close;
1299         }
1300
1301         if (listen(sock, 5) == -1) {
1302                 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1303                         strerror(errno)));
1304                 goto out_close;
1305         }
1306
1307         SAFE_FREE(path);
1308
1309         umask(old_umask);
1310         return sock;
1311
1312 out_close:
1313         SAFE_FREE(path);
1314         if (sock != -1)
1315                 close(sock);
1316
1317 out_umask:
1318         umask(old_umask);
1319         return -1;
1320
1321 #else
1322         DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1323         return -1;
1324 #endif /* HAVE_UNIXSOCKET */
1325 }
1326
1327 /****************************************************************************
1328  Get my own canonical name, including domain.
1329 ****************************************************************************/
1330
1331 const char *get_mydnsfullname(void)
1332 {
1333         struct addrinfo *res = NULL;
1334         char my_hostname[HOST_NAME_MAX];
1335         bool ret;
1336         DATA_BLOB tmp;
1337
1338         if (memcache_lookup(NULL, SINGLETON_CACHE,
1339                         data_blob_string_const_null("get_mydnsfullname"),
1340                         &tmp)) {
1341                 SMB_ASSERT(tmp.length > 0);
1342                 return (const char *)tmp.data;
1343         }
1344
1345         /* get my host name */
1346         if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1347                 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1348                 return NULL;
1349         }
1350
1351         /* Ensure null termination. */
1352         my_hostname[sizeof(my_hostname)-1] = '\0';
1353
1354         ret = interpret_string_addr_internal(&res,
1355                                 my_hostname,
1356                                 AI_ADDRCONFIG|AI_CANONNAME);
1357
1358         if (!ret || res == NULL) {
1359                 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1360                         "name %s [%s]\n",
1361                         my_hostname,
1362                         gai_strerror(ret) ));
1363                 return NULL;
1364         }
1365
1366         /*
1367          * Make sure that getaddrinfo() returns the "correct" host name.
1368          */
1369
1370         if (res->ai_canonname == NULL) {
1371                 DEBUG(3,("get_mydnsfullname: failed to get "
1372                         "canonical name for %s\n",
1373                         my_hostname));
1374                 freeaddrinfo(res);
1375                 return NULL;
1376         }
1377
1378         /* This copies the data, so we must do a lookup
1379          * afterwards to find the value to return.
1380          */
1381
1382         memcache_add(NULL, SINGLETON_CACHE,
1383                         data_blob_string_const_null("get_mydnsfullname"),
1384                         data_blob_string_const_null(res->ai_canonname));
1385
1386         if (!memcache_lookup(NULL, SINGLETON_CACHE,
1387                         data_blob_string_const_null("get_mydnsfullname"),
1388                         &tmp)) {
1389                 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1390                                 strlen(res->ai_canonname) + 1);
1391         }
1392
1393         freeaddrinfo(res);
1394
1395         return (const char *)tmp.data;
1396 }
1397
1398 /************************************************************
1399  Is this my ip address ?
1400 ************************************************************/
1401
1402 static bool is_my_ipaddr(const char *ipaddr_str)
1403 {
1404         struct sockaddr_storage ss;
1405         struct iface_struct *nics;
1406         int i, n;
1407
1408         if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1409                 return false;
1410         }
1411
1412         if (is_zero_addr(&ss)) {
1413                 return false;
1414         }
1415
1416         if (ismyaddr((struct sockaddr *)&ss) ||
1417                         is_loopback_addr((struct sockaddr *)&ss)) {
1418                 return true;
1419         }
1420
1421         n = get_interfaces(talloc_tos(), &nics);
1422         for (i=0; i<n; i++) {
1423                 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1424                         TALLOC_FREE(nics);
1425                         return true;
1426                 }
1427         }
1428         TALLOC_FREE(nics);
1429         return false;
1430 }
1431
1432 /************************************************************
1433  Is this my name ?
1434 ************************************************************/
1435
1436 bool is_myname_or_ipaddr(const char *s)
1437 {
1438         TALLOC_CTX *ctx = talloc_tos();
1439         char *name = NULL;
1440         const char *dnsname;
1441         char *servername = NULL;
1442
1443         if (!s) {
1444                 return false;
1445         }
1446
1447         /* Santize the string from '\\name' */
1448         name = talloc_strdup(ctx, s);
1449         if (!name) {
1450                 return false;
1451         }
1452
1453         servername = strrchr_m(name, '\\' );
1454         if (!servername) {
1455                 servername = name;
1456         } else {
1457                 servername++;
1458         }
1459
1460         /* Optimize for the common case */
1461         if (strequal(servername, lp_netbios_name())) {
1462                 return true;
1463         }
1464
1465         /* Check for an alias */
1466         if (is_myname(servername)) {
1467                 return true;
1468         }
1469
1470         /* Check for loopback */
1471         if (strequal(servername, "127.0.0.1") ||
1472                         strequal(servername, "::1")) {
1473                 return true;
1474         }
1475
1476         if (strequal(servername, "localhost")) {
1477                 return true;
1478         }
1479
1480         /* Maybe it's my dns name */
1481         dnsname = get_mydnsfullname();
1482         if (dnsname && strequal(servername, dnsname)) {
1483                 return true;
1484         }
1485
1486         /* Maybe its an IP address? */
1487         if (is_ipaddress(servername)) {
1488                 return is_my_ipaddr(servername);
1489         }
1490
1491         /* Handle possible CNAME records - convert to an IP addr. list. */
1492         {
1493                 /* Use DNS to resolve the name, check all addresses. */
1494                 struct addrinfo *p = NULL;
1495                 struct addrinfo *res = NULL;
1496
1497                 if (!interpret_string_addr_internal(&res,
1498                                 servername,
1499                                 AI_ADDRCONFIG)) {
1500                         return false;
1501                 }
1502
1503                 for (p = res; p; p = p->ai_next) {
1504                         char addr[INET6_ADDRSTRLEN];
1505                         struct sockaddr_storage ss;
1506
1507                         ZERO_STRUCT(ss);
1508                         memcpy(&ss, p->ai_addr, p->ai_addrlen);
1509                         print_sockaddr(addr,
1510                                         sizeof(addr),
1511                                         &ss);
1512                         if (is_my_ipaddr(addr)) {
1513                                 freeaddrinfo(res);
1514                                 return true;
1515                         }
1516                 }
1517                 freeaddrinfo(res);
1518         }
1519
1520         /* No match */
1521         return false;
1522 }
1523
1524 struct getaddrinfo_state {
1525         const char *node;
1526         const char *service;
1527         const struct addrinfo *hints;
1528         struct addrinfo *res;
1529         int ret;
1530 };
1531
1532 static void getaddrinfo_do(void *private_data);
1533 static void getaddrinfo_done(struct tevent_req *subreq);
1534
1535 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1536                                     struct tevent_context *ev,
1537                                     struct fncall_context *ctx,
1538                                     const char *node,
1539                                     const char *service,
1540                                     const struct addrinfo *hints)
1541 {
1542         struct tevent_req *req, *subreq;
1543         struct getaddrinfo_state *state;
1544
1545         req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1546         if (req == NULL) {
1547                 return NULL;
1548         }
1549
1550         state->node = node;
1551         state->service = service;
1552         state->hints = hints;
1553
1554         subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1555         if (tevent_req_nomem(subreq, req)) {
1556                 return tevent_req_post(req, ev);
1557         }
1558         tevent_req_set_callback(subreq, getaddrinfo_done, req);
1559         return req;
1560 }
1561
1562 static void getaddrinfo_do(void *private_data)
1563 {
1564         struct getaddrinfo_state *state =
1565                 (struct getaddrinfo_state *)private_data;
1566
1567         state->ret = getaddrinfo(state->node, state->service, state->hints,
1568                                  &state->res);
1569 }
1570
1571 static void getaddrinfo_done(struct tevent_req *subreq)
1572 {
1573         struct tevent_req *req = tevent_req_callback_data(
1574                 subreq, struct tevent_req);
1575         int ret, err;
1576
1577         ret = fncall_recv(subreq, &err);
1578         TALLOC_FREE(subreq);
1579         if (ret == -1) {
1580                 tevent_req_error(req, err);
1581                 return;
1582         }
1583         tevent_req_done(req);
1584 }
1585
1586 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1587 {
1588         struct getaddrinfo_state *state = tevent_req_data(
1589                 req, struct getaddrinfo_state);
1590         int err;
1591
1592         if (tevent_req_is_unix_error(req, &err)) {
1593                 switch(err) {
1594                 case ENOMEM:
1595                         return EAI_MEMORY;
1596                 default:
1597                         return EAI_FAIL;
1598                 }
1599         }
1600         if (state->ret == 0) {
1601                 *res = state->res;
1602         }
1603         return state->ret;
1604 }
1605
1606 int poll_one_fd(int fd, int events, int timeout, int *revents)
1607 {
1608         struct pollfd *fds;
1609         int ret;
1610         int saved_errno;
1611
1612         fds = talloc_zero_array(talloc_tos(), struct pollfd, 2);
1613         if (fds == NULL) {
1614                 errno = ENOMEM;
1615                 return -1;
1616         }
1617         fds[0].fd = fd;
1618         fds[0].events = events;
1619
1620         ret = sys_poll(fds, 1, timeout);
1621
1622         /*
1623          * Assign whatever poll did, even in the ret<=0 case.
1624          */
1625         *revents = fds[0].revents;
1626         saved_errno = errno;
1627         TALLOC_FREE(fds);
1628         errno = saved_errno;
1629
1630         return ret;
1631 }
1632
1633 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1634 {
1635         struct pollfd pfd;
1636         int ret;
1637
1638         pfd.fd = fd;
1639         pfd.events = events;
1640
1641         ret = sys_poll_intr(&pfd, 1, timeout);
1642         if (ret <= 0) {
1643                 *revents = 0;
1644                 return ret;
1645         }
1646         *revents = pfd.revents;
1647         return 1;
1648 }