sysquota: we need to list nfs4 as a separate fs name for the sys_get_nfs_quota backend
[kai/samba.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] = NBSSkeepalive;
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 == NBSSkeepalive) {
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 == NMB_PORT ||
486                                          port == NBT_SMB_PORT ||
487                                          port == TCP_SMB_PORT) ) {
488                         char addr[INET6_ADDRSTRLEN];
489                         print_sockaddr(addr, sizeof(addr),
490                                         &sock);
491                         dbgtext( "bind failed on port %d ", port);
492                         dbgtext( "socket_addr = %s.\n", addr);
493                         dbgtext( "Error = %s\n", strerror(errno));
494                 }
495                 close(res);
496                 return -1;
497         }
498
499         DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
500         return( res );
501  }
502
503 struct open_socket_out_state {
504         int fd;
505         struct event_context *ev;
506         struct sockaddr_storage ss;
507         socklen_t salen;
508         uint16_t port;
509         int wait_usec;
510 };
511
512 static void open_socket_out_connected(struct tevent_req *subreq);
513
514 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
515 {
516         if (s->fd != -1) {
517                 close(s->fd);
518         }
519         return 0;
520 }
521
522 /****************************************************************************
523  Create an outgoing socket. timeout is in milliseconds.
524 **************************************************************************/
525
526 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
527                                         struct event_context *ev,
528                                         const struct sockaddr_storage *pss,
529                                         uint16_t port,
530                                         int timeout)
531 {
532         char addr[INET6_ADDRSTRLEN];
533         struct tevent_req *result, *subreq;
534         struct open_socket_out_state *state;
535         NTSTATUS status;
536
537         result = tevent_req_create(mem_ctx, &state,
538                                    struct open_socket_out_state);
539         if (result == NULL) {
540                 return NULL;
541         }
542         state->ev = ev;
543         state->ss = *pss;
544         state->port = port;
545         state->wait_usec = 10000;
546         state->salen = -1;
547
548         state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
549         if (state->fd == -1) {
550                 status = map_nt_error_from_unix(errno);
551                 goto post_status;
552         }
553         talloc_set_destructor(state, open_socket_out_state_destructor);
554
555         if (!tevent_req_set_endtime(
556                     result, ev, timeval_current_ofs_msec(timeout))) {
557                 goto fail;
558         }
559
560 #if defined(HAVE_IPV6)
561         if (pss->ss_family == AF_INET6) {
562                 struct sockaddr_in6 *psa6;
563                 psa6 = (struct sockaddr_in6 *)&state->ss;
564                 psa6->sin6_port = htons(port);
565                 if (psa6->sin6_scope_id == 0
566                     && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
567                         setup_linklocal_scope_id(
568                                 (struct sockaddr *)&(state->ss));
569                 }
570                 state->salen = sizeof(struct sockaddr_in6);
571         }
572 #endif
573         if (pss->ss_family == AF_INET) {
574                 struct sockaddr_in *psa;
575                 psa = (struct sockaddr_in *)&state->ss;
576                 psa->sin_port = htons(port);
577                 state->salen = sizeof(struct sockaddr_in);
578         }
579
580         if (pss->ss_family == AF_UNIX) {
581                 state->salen = sizeof(struct sockaddr_un);
582         }
583
584         print_sockaddr(addr, sizeof(addr), &state->ss);
585         DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
586
587         subreq = async_connect_send(state, state->ev, state->fd,
588                                     (struct sockaddr *)&state->ss,
589                                     state->salen);
590         if ((subreq == NULL)
591             || !tevent_req_set_endtime(
592                     subreq, state->ev,
593                     timeval_current_ofs(0, state->wait_usec))) {
594                 goto fail;
595         }
596         tevent_req_set_callback(subreq, open_socket_out_connected, result);
597         return result;
598
599  post_status:
600         tevent_req_nterror(result, status);
601         return tevent_req_post(result, ev);
602  fail:
603         TALLOC_FREE(result);
604         return NULL;
605 }
606
607 static void open_socket_out_connected(struct tevent_req *subreq)
608 {
609         struct tevent_req *req =
610                 tevent_req_callback_data(subreq, struct tevent_req);
611         struct open_socket_out_state *state =
612                 tevent_req_data(req, struct open_socket_out_state);
613         int ret;
614         int sys_errno;
615
616         ret = async_connect_recv(subreq, &sys_errno);
617         TALLOC_FREE(subreq);
618         if (ret == 0) {
619                 tevent_req_done(req);
620                 return;
621         }
622
623         if (
624 #ifdef ETIMEDOUT
625                 (sys_errno == ETIMEDOUT) ||
626 #endif
627                 (sys_errno == EINPROGRESS) ||
628                 (sys_errno == EALREADY) ||
629                 (sys_errno == EAGAIN)) {
630
631                 /*
632                  * retry
633                  */
634
635                 if (state->wait_usec < 250000) {
636                         state->wait_usec *= 1.5;
637                 }
638
639                 subreq = async_connect_send(state, state->ev, state->fd,
640                                             (struct sockaddr *)&state->ss,
641                                             state->salen);
642                 if (tevent_req_nomem(subreq, req)) {
643                         return;
644                 }
645                 if (!tevent_req_set_endtime(
646                             subreq, state->ev,
647                             timeval_current_ofs_usec(state->wait_usec))) {
648                         tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
649                         return;
650                 }
651                 tevent_req_set_callback(subreq, open_socket_out_connected, req);
652                 return;
653         }
654
655 #ifdef EISCONN
656         if (sys_errno == EISCONN) {
657                 tevent_req_done(req);
658                 return;
659         }
660 #endif
661
662         /* real error */
663         tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
664 }
665
666 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
667 {
668         struct open_socket_out_state *state =
669                 tevent_req_data(req, struct open_socket_out_state);
670         NTSTATUS status;
671
672         if (tevent_req_is_nterror(req, &status)) {
673                 return status;
674         }
675         *pfd = state->fd;
676         state->fd = -1;
677         return NT_STATUS_OK;
678 }
679
680 /**
681 * @brief open a socket
682 *
683 * @param pss a struct sockaddr_storage defining the address to connect to
684 * @param port to connect to
685 * @param timeout in MILLISECONDS
686 * @param pfd file descriptor returned
687 *
688 * @return NTSTATUS code
689 */
690 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
691                          int timeout, int *pfd)
692 {
693         TALLOC_CTX *frame = talloc_stackframe();
694         struct event_context *ev;
695         struct tevent_req *req;
696         NTSTATUS status = NT_STATUS_NO_MEMORY;
697
698         ev = event_context_init(frame);
699         if (ev == NULL) {
700                 goto fail;
701         }
702
703         req = open_socket_out_send(frame, ev, pss, port, timeout);
704         if (req == NULL) {
705                 goto fail;
706         }
707         if (!tevent_req_poll(req, ev)) {
708                 status = NT_STATUS_INTERNAL_ERROR;
709                 goto fail;
710         }
711         status = open_socket_out_recv(req, pfd);
712  fail:
713         TALLOC_FREE(frame);
714         return status;
715 }
716
717 struct open_socket_out_defer_state {
718         struct event_context *ev;
719         struct sockaddr_storage ss;
720         uint16_t port;
721         int timeout;
722         int fd;
723 };
724
725 static void open_socket_out_defer_waited(struct tevent_req *subreq);
726 static void open_socket_out_defer_connected(struct tevent_req *subreq);
727
728 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
729                                               struct event_context *ev,
730                                               struct timeval wait_time,
731                                               const struct sockaddr_storage *pss,
732                                               uint16_t port,
733                                               int timeout)
734 {
735         struct tevent_req *req, *subreq;
736         struct open_socket_out_defer_state *state;
737
738         req = tevent_req_create(mem_ctx, &state,
739                                 struct open_socket_out_defer_state);
740         if (req == NULL) {
741                 return NULL;
742         }
743         state->ev = ev;
744         state->ss = *pss;
745         state->port = port;
746         state->timeout = timeout;
747
748         subreq = tevent_wakeup_send(
749                 state, ev,
750                 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
751         if (subreq == NULL) {
752                 goto fail;
753         }
754         tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
755         return req;
756  fail:
757         TALLOC_FREE(req);
758         return NULL;
759 }
760
761 static void open_socket_out_defer_waited(struct tevent_req *subreq)
762 {
763         struct tevent_req *req = tevent_req_callback_data(
764                 subreq, struct tevent_req);
765         struct open_socket_out_defer_state *state = tevent_req_data(
766                 req, struct open_socket_out_defer_state);
767         bool ret;
768
769         ret = tevent_wakeup_recv(subreq);
770         TALLOC_FREE(subreq);
771         if (!ret) {
772                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
773                 return;
774         }
775
776         subreq = open_socket_out_send(state, state->ev, &state->ss,
777                                       state->port, state->timeout);
778         if (tevent_req_nomem(subreq, req)) {
779                 return;
780         }
781         tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
782 }
783
784 static void open_socket_out_defer_connected(struct tevent_req *subreq)
785 {
786         struct tevent_req *req = tevent_req_callback_data(
787                 subreq, struct tevent_req);
788         struct open_socket_out_defer_state *state = tevent_req_data(
789                 req, struct open_socket_out_defer_state);
790         NTSTATUS status;
791
792         status = open_socket_out_recv(subreq, &state->fd);
793         TALLOC_FREE(subreq);
794         if (!NT_STATUS_IS_OK(status)) {
795                 tevent_req_nterror(req, status);
796                 return;
797         }
798         tevent_req_done(req);
799 }
800
801 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
802 {
803         struct open_socket_out_defer_state *state = tevent_req_data(
804                 req, struct open_socket_out_defer_state);
805         NTSTATUS status;
806
807         if (tevent_req_is_nterror(req, &status)) {
808                 return status;
809         }
810         *pfd = state->fd;
811         state->fd = -1;
812         return NT_STATUS_OK;
813 }
814
815 /****************************************************************************
816  Open a connected UDP socket to host on port
817 **************************************************************************/
818
819 int open_udp_socket(const char *host, int port)
820 {
821         struct sockaddr_storage ss;
822         int res;
823         socklen_t salen;
824
825         if (!interpret_string_addr(&ss, host, 0)) {
826                 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
827                         host));
828                 return -1;
829         }
830
831         res = socket(ss.ss_family, SOCK_DGRAM, 0);
832         if (res == -1) {
833                 return -1;
834         }
835
836 #if defined(HAVE_IPV6)
837         if (ss.ss_family == AF_INET6) {
838                 struct sockaddr_in6 *psa6;
839                 psa6 = (struct sockaddr_in6 *)&ss;
840                 psa6->sin6_port = htons(port);
841                 if (psa6->sin6_scope_id == 0
842                                 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
843                         setup_linklocal_scope_id(
844                                 (struct sockaddr *)&ss);
845                 }
846                 salen = sizeof(struct sockaddr_in6);
847         } else 
848 #endif
849         if (ss.ss_family == AF_INET) {
850                 struct sockaddr_in *psa;
851                 psa = (struct sockaddr_in *)&ss;
852                 psa->sin_port = htons(port);
853             salen = sizeof(struct sockaddr_in);
854         } else {
855                 DEBUG(1, ("unknown socket family %d", ss.ss_family));
856                 return -1;
857         }
858
859         if (connect(res, (struct sockaddr *)&ss, salen)) {
860                 close(res);
861                 return -1;
862         }
863
864         return res;
865 }
866
867 /*******************************************************************
868  Return the IP addr of the remote end of a socket as a string.
869  Optionally return the struct sockaddr_storage.
870  ******************************************************************/
871
872 static const char *get_peer_addr_internal(int fd,
873                                 char *addr_buf,
874                                 size_t addr_buf_len,
875                                 struct sockaddr *pss,
876                                 socklen_t *plength)
877 {
878         struct sockaddr_storage ss;
879         socklen_t length = sizeof(ss);
880
881         strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
882
883         if (fd == -1) {
884                 return addr_buf;
885         }
886
887         if (pss == NULL) {
888                 pss = (struct sockaddr *)&ss;
889                 plength = &length;
890         }
891
892         if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
893                 int level = (errno == ENOTCONN) ? 2 : 0;
894                 DEBUG(level, ("getpeername failed. Error was %s\n",
895                                strerror(errno)));
896                 return addr_buf;
897         }
898
899         print_sockaddr_len(addr_buf,
900                         addr_buf_len,
901                         pss,
902                         *plength);
903         return addr_buf;
904 }
905
906 /*******************************************************************
907  Matchname - determine if host name matches IP address. Used to
908  confirm a hostname lookup to prevent spoof attacks.
909 ******************************************************************/
910
911 static bool matchname(const char *remotehost,
912                 const struct sockaddr *pss,
913                 socklen_t len)
914 {
915         struct addrinfo *res = NULL;
916         struct addrinfo *ailist = NULL;
917         char addr_buf[INET6_ADDRSTRLEN];
918         bool ret = interpret_string_addr_internal(&ailist,
919                         remotehost,
920                         AI_ADDRCONFIG|AI_CANONNAME);
921
922         if (!ret || ailist == NULL) {
923                 DEBUG(3,("matchname: getaddrinfo failed for "
924                         "name %s [%s]\n",
925                         remotehost,
926                         gai_strerror(ret) ));
927                 return false;
928         }
929
930         /*
931          * Make sure that getaddrinfo() returns the "correct" host name.
932          */
933
934         if (ailist->ai_canonname == NULL ||
935                 (!strequal(remotehost, ailist->ai_canonname) &&
936                  !strequal(remotehost, "localhost"))) {
937                 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
938                          remotehost,
939                          ailist->ai_canonname ?
940                                  ailist->ai_canonname : "(NULL)"));
941                 freeaddrinfo(ailist);
942                 return false;
943         }
944
945         /* Look up the host address in the address list we just got. */
946         for (res = ailist; res; res = res->ai_next) {
947                 if (!res->ai_addr) {
948                         continue;
949                 }
950                 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
951                                         (const struct sockaddr *)pss)) {
952                         freeaddrinfo(ailist);
953                         return true;
954                 }
955         }
956
957         /*
958          * The host name does not map to the original host address. Perhaps
959          * someone has compromised a name server. More likely someone botched
960          * it, but that could be dangerous, too.
961          */
962
963         DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
964                 print_sockaddr_len(addr_buf,
965                         sizeof(addr_buf),
966                         pss,
967                         len),
968                  ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
969
970         if (ailist) {
971                 freeaddrinfo(ailist);
972         }
973         return false;
974 }
975
976 /*******************************************************************
977  Deal with the singleton cache.
978 ******************************************************************/
979
980 struct name_addr_pair {
981         struct sockaddr_storage ss;
982         const char *name;
983 };
984
985 /*******************************************************************
986  Lookup a name/addr pair. Returns memory allocated from memcache.
987 ******************************************************************/
988
989 static bool lookup_nc(struct name_addr_pair *nc)
990 {
991         DATA_BLOB tmp;
992
993         ZERO_STRUCTP(nc);
994
995         if (!memcache_lookup(
996                         NULL, SINGLETON_CACHE,
997                         data_blob_string_const_null("get_peer_name"),
998                         &tmp)) {
999                 return false;
1000         }
1001
1002         memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1003         nc->name = (const char *)tmp.data + sizeof(nc->ss);
1004         return true;
1005 }
1006
1007 /*******************************************************************
1008  Save a name/addr pair.
1009 ******************************************************************/
1010
1011 static void store_nc(const struct name_addr_pair *nc)
1012 {
1013         DATA_BLOB tmp;
1014         size_t namelen = strlen(nc->name);
1015
1016         tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1017         if (!tmp.data) {
1018                 return;
1019         }
1020         memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1021         memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1022
1023         memcache_add(NULL, SINGLETON_CACHE,
1024                         data_blob_string_const_null("get_peer_name"),
1025                         tmp);
1026         data_blob_free(&tmp);
1027 }
1028
1029 /*******************************************************************
1030  Return the DNS name of the remote end of a socket.
1031 ******************************************************************/
1032
1033 const char *get_peer_name(int fd, bool force_lookup)
1034 {
1035         struct name_addr_pair nc;
1036         char addr_buf[INET6_ADDRSTRLEN];
1037         struct sockaddr_storage ss;
1038         socklen_t length = sizeof(ss);
1039         const char *p;
1040         int ret;
1041         char name_buf[MAX_DNS_NAME_LENGTH];
1042         char tmp_name[MAX_DNS_NAME_LENGTH];
1043
1044         /* reverse lookups can be *very* expensive, and in many
1045            situations won't work because many networks don't link dhcp
1046            with dns. To avoid the delay we avoid the lookup if
1047            possible */
1048         if (!lp_hostname_lookups() && (force_lookup == false)) {
1049                 length = sizeof(nc.ss);
1050                 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1051                         (struct sockaddr *)&nc.ss, &length);
1052                 store_nc(&nc);
1053                 lookup_nc(&nc);
1054                 return nc.name ? nc.name : "UNKNOWN";
1055         }
1056
1057         lookup_nc(&nc);
1058
1059         memset(&ss, '\0', sizeof(ss));
1060         p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1061
1062         /* it might be the same as the last one - save some DNS work */
1063         if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1064                 return nc.name ? nc.name : "UNKNOWN";
1065         }
1066
1067         /* Not the same. We need to lookup. */
1068         if (fd == -1) {
1069                 return "UNKNOWN";
1070         }
1071
1072         /* Look up the remote host name. */
1073         ret = sys_getnameinfo((struct sockaddr *)&ss,
1074                         length,
1075                         name_buf,
1076                         sizeof(name_buf),
1077                         NULL,
1078                         0,
1079                         0);
1080
1081         if (ret) {
1082                 DEBUG(1,("get_peer_name: getnameinfo failed "
1083                         "for %s with error %s\n",
1084                         p,
1085                         gai_strerror(ret)));
1086                 strlcpy(name_buf, p, sizeof(name_buf));
1087         } else {
1088                 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1089                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1090                         strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1091                 }
1092         }
1093
1094         strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1095         alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1096         if (strstr(name_buf,"..")) {
1097                 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1098         }
1099
1100         nc.name = name_buf;
1101         nc.ss = ss;
1102
1103         store_nc(&nc);
1104         lookup_nc(&nc);
1105         return nc.name ? nc.name : "UNKNOWN";
1106 }
1107
1108 /*******************************************************************
1109  Return the IP addr of the remote end of a socket as a string.
1110  ******************************************************************/
1111
1112 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1113 {
1114         return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1115 }
1116
1117 int get_remote_hostname(const struct tsocket_address *remote_address,
1118                         char **name,
1119                         TALLOC_CTX *mem_ctx)
1120 {
1121         char name_buf[MAX_DNS_NAME_LENGTH];
1122         char tmp_name[MAX_DNS_NAME_LENGTH];
1123         struct name_addr_pair nc;
1124         struct sockaddr_storage ss;
1125         ssize_t len;
1126         int rc;
1127
1128         if (!lp_hostname_lookups()) {
1129                 nc.name = tsocket_address_inet_addr_string(remote_address,
1130                                                            mem_ctx);
1131                 if (nc.name == NULL) {
1132                         return -1;
1133                 }
1134
1135                 len = tsocket_address_bsd_sockaddr(remote_address,
1136                                                    (struct sockaddr *) &nc.ss,
1137                                                    sizeof(struct sockaddr_storage));
1138                 if (len < 0) {
1139                         return -1;
1140                 }
1141
1142                 store_nc(&nc);
1143                 lookup_nc(&nc);
1144
1145                 if (nc.name == NULL) {
1146                         *name = talloc_strdup(mem_ctx, "UNKNOWN");
1147                 } else {
1148                         *name = talloc_strdup(mem_ctx, nc.name);
1149                 }
1150                 return 0;
1151         }
1152
1153         lookup_nc(&nc);
1154
1155         ZERO_STRUCT(ss);
1156
1157         len = tsocket_address_bsd_sockaddr(remote_address,
1158                                            (struct sockaddr *) &ss,
1159                                            sizeof(struct sockaddr_storage));
1160         if (len < 0) {
1161                 return -1;
1162         }
1163
1164         /* it might be the same as the last one - save some DNS work */
1165         if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1166                 if (nc.name == NULL) {
1167                         *name = talloc_strdup(mem_ctx, "UNKNOWN");
1168                 } else {
1169                         *name = talloc_strdup(mem_ctx, nc.name);
1170                 }
1171                 return 0;
1172         }
1173
1174         /* Look up the remote host name. */
1175         rc = sys_getnameinfo((struct sockaddr *) &ss,
1176                              len,
1177                              name_buf,
1178                              sizeof(name_buf),
1179                              NULL,
1180                              0,
1181                              0);
1182         if (rc < 0) {
1183                 char *p;
1184
1185                 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1186                 if (p == NULL) {
1187                         return -1;
1188                 }
1189
1190                 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1191                          p,
1192                          gai_strerror(rc)));
1193                 strlcpy(name_buf, p, sizeof(name_buf));
1194
1195                 TALLOC_FREE(p);
1196         } else {
1197                 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1198                         DEBUG(0,("matchname failed on %s\n", name_buf));
1199                         strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1200                 }
1201         }
1202
1203         strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1204         alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1205         if (strstr(name_buf,"..")) {
1206                 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1207         }
1208
1209         nc.name = name_buf;
1210         nc.ss = ss;
1211
1212         store_nc(&nc);
1213         lookup_nc(&nc);
1214
1215         if (nc.name == NULL) {
1216                 *name = talloc_strdup(mem_ctx, "UNKOWN");
1217         } else {
1218                 *name = talloc_strdup(mem_ctx, nc.name);
1219         }
1220
1221         return 0;
1222 }
1223
1224 /*******************************************************************
1225  Create protected unix domain socket.
1226
1227  Some unixes cannot set permissions on a ux-dom-sock, so we
1228  have to make sure that the directory contains the protection
1229  permissions instead.
1230  ******************************************************************/
1231
1232 int create_pipe_sock(const char *socket_dir,
1233                      const char *socket_name,
1234                      mode_t dir_perms)
1235 {
1236 #ifdef HAVE_UNIXSOCKET
1237         struct sockaddr_un sunaddr;
1238         struct stat st;
1239         int sock;
1240         mode_t old_umask;
1241         char *path = NULL;
1242
1243         old_umask = umask(0);
1244
1245         /* Create the socket directory or reuse the existing one */
1246
1247         if (lstat(socket_dir, &st) == -1) {
1248                 if (errno == ENOENT) {
1249                         /* Create directory */
1250                         if (mkdir(socket_dir, dir_perms) == -1) {
1251                                 DEBUG(0, ("error creating socket directory "
1252                                         "%s: %s\n", socket_dir,
1253                                         strerror(errno)));
1254                                 goto out_umask;
1255                         }
1256                 } else {
1257                         DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1258                                 socket_dir, strerror(errno)));
1259                         goto out_umask;
1260                 }
1261         } else {
1262                 /* Check ownership and permission on existing directory */
1263                 if (!S_ISDIR(st.st_mode)) {
1264                         DEBUG(0, ("socket directory '%s' isn't a directory\n",
1265                                 socket_dir));
1266                         goto out_umask;
1267                 }
1268                 if (st.st_uid != sec_initial_uid()) {
1269                         DEBUG(0, ("invalid ownership on directory "
1270                                   "'%s'\n", socket_dir));
1271                         umask(old_umask);
1272                         goto out_umask;
1273                 }
1274                 if ((st.st_mode & 0777) != dir_perms) {
1275                         DEBUG(0, ("invalid permissions on directory "
1276                                   "'%s': has 0%o should be 0%o\n", socket_dir,
1277                                   (st.st_mode & 0777), dir_perms));
1278                         umask(old_umask);
1279                         goto out_umask;
1280                 }
1281         }
1282
1283         /* Create the socket file */
1284
1285         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1286
1287         if (sock == -1) {
1288                 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1289                         strerror(errno) ));
1290                 goto out_close;
1291         }
1292
1293         if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1294                 goto out_close;
1295         }
1296
1297         unlink(path);
1298         memset(&sunaddr, 0, sizeof(sunaddr));
1299         sunaddr.sun_family = AF_UNIX;
1300         strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1301
1302         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1303                 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1304                         strerror(errno)));
1305                 goto out_close;
1306         }
1307
1308         SAFE_FREE(path);
1309
1310         umask(old_umask);
1311         return sock;
1312
1313 out_close:
1314         SAFE_FREE(path);
1315         if (sock != -1)
1316                 close(sock);
1317
1318 out_umask:
1319         umask(old_umask);
1320         return -1;
1321
1322 #else
1323         DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1324         return -1;
1325 #endif /* HAVE_UNIXSOCKET */
1326 }
1327
1328 /****************************************************************************
1329  Get my own canonical name, including domain.
1330 ****************************************************************************/
1331
1332 const char *get_mydnsfullname(void)
1333 {
1334         struct addrinfo *res = NULL;
1335         char my_hostname[HOST_NAME_MAX];
1336         bool ret;
1337         DATA_BLOB tmp;
1338
1339         if (memcache_lookup(NULL, SINGLETON_CACHE,
1340                         data_blob_string_const_null("get_mydnsfullname"),
1341                         &tmp)) {
1342                 SMB_ASSERT(tmp.length > 0);
1343                 return (const char *)tmp.data;
1344         }
1345
1346         /* get my host name */
1347         if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1348                 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1349                 return NULL;
1350         }
1351
1352         /* Ensure null termination. */
1353         my_hostname[sizeof(my_hostname)-1] = '\0';
1354
1355         ret = interpret_string_addr_internal(&res,
1356                                 my_hostname,
1357                                 AI_ADDRCONFIG|AI_CANONNAME);
1358
1359         if (!ret || res == NULL) {
1360                 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1361                         "name %s [%s]\n",
1362                         my_hostname,
1363                         gai_strerror(ret) ));
1364                 return NULL;
1365         }
1366
1367         /*
1368          * Make sure that getaddrinfo() returns the "correct" host name.
1369          */
1370
1371         if (res->ai_canonname == NULL) {
1372                 DEBUG(3,("get_mydnsfullname: failed to get "
1373                         "canonical name for %s\n",
1374                         my_hostname));
1375                 freeaddrinfo(res);
1376                 return NULL;
1377         }
1378
1379         /* This copies the data, so we must do a lookup
1380          * afterwards to find the value to return.
1381          */
1382
1383         memcache_add(NULL, SINGLETON_CACHE,
1384                         data_blob_string_const_null("get_mydnsfullname"),
1385                         data_blob_string_const_null(res->ai_canonname));
1386
1387         if (!memcache_lookup(NULL, SINGLETON_CACHE,
1388                         data_blob_string_const_null("get_mydnsfullname"),
1389                         &tmp)) {
1390                 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1391                                 strlen(res->ai_canonname) + 1);
1392         }
1393
1394         freeaddrinfo(res);
1395
1396         return (const char *)tmp.data;
1397 }
1398
1399 /************************************************************
1400  Is this my ip address ?
1401 ************************************************************/
1402
1403 static bool is_my_ipaddr(const char *ipaddr_str)
1404 {
1405         struct sockaddr_storage ss;
1406         struct iface_struct *nics;
1407         int i, n;
1408
1409         if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1410                 return false;
1411         }
1412
1413         if (is_zero_addr(&ss)) {
1414                 return false;
1415         }
1416
1417         if (ismyaddr((struct sockaddr *)&ss) ||
1418                         is_loopback_addr((struct sockaddr *)&ss)) {
1419                 return true;
1420         }
1421
1422         n = get_interfaces(talloc_tos(), &nics);
1423         for (i=0; i<n; i++) {
1424                 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1425                         TALLOC_FREE(nics);
1426                         return true;
1427                 }
1428         }
1429         TALLOC_FREE(nics);
1430         return false;
1431 }
1432
1433 /************************************************************
1434  Is this my name ?
1435 ************************************************************/
1436
1437 bool is_myname_or_ipaddr(const char *s)
1438 {
1439         TALLOC_CTX *ctx = talloc_tos();
1440         char *name = NULL;
1441         const char *dnsname;
1442         char *servername = NULL;
1443
1444         if (!s) {
1445                 return false;
1446         }
1447
1448         /* Santize the string from '\\name' */
1449         name = talloc_strdup(ctx, s);
1450         if (!name) {
1451                 return false;
1452         }
1453
1454         servername = strrchr_m(name, '\\' );
1455         if (!servername) {
1456                 servername = name;
1457         } else {
1458                 servername++;
1459         }
1460
1461         /* Optimize for the common case */
1462         if (strequal(servername, lp_netbios_name())) {
1463                 return true;
1464         }
1465
1466         /* Check for an alias */
1467         if (is_myname(servername)) {
1468                 return true;
1469         }
1470
1471         /* Check for loopback */
1472         if (strequal(servername, "127.0.0.1") ||
1473                         strequal(servername, "::1")) {
1474                 return true;
1475         }
1476
1477         if (strequal(servername, "localhost")) {
1478                 return true;
1479         }
1480
1481         /* Maybe it's my dns name */
1482         dnsname = get_mydnsfullname();
1483         if (dnsname && strequal(servername, dnsname)) {
1484                 return true;
1485         }
1486
1487         /* Maybe its an IP address? */
1488         if (is_ipaddress(servername)) {
1489                 return is_my_ipaddr(servername);
1490         }
1491
1492         /* Handle possible CNAME records - convert to an IP addr. list. */
1493         {
1494                 /* Use DNS to resolve the name, check all addresses. */
1495                 struct addrinfo *p = NULL;
1496                 struct addrinfo *res = NULL;
1497
1498                 if (!interpret_string_addr_internal(&res,
1499                                 servername,
1500                                 AI_ADDRCONFIG)) {
1501                         return false;
1502                 }
1503
1504                 for (p = res; p; p = p->ai_next) {
1505                         char addr[INET6_ADDRSTRLEN];
1506                         struct sockaddr_storage ss;
1507
1508                         ZERO_STRUCT(ss);
1509                         memcpy(&ss, p->ai_addr, p->ai_addrlen);
1510                         print_sockaddr(addr,
1511                                         sizeof(addr),
1512                                         &ss);
1513                         if (is_my_ipaddr(addr)) {
1514                                 freeaddrinfo(res);
1515                                 return true;
1516                         }
1517                 }
1518                 freeaddrinfo(res);
1519         }
1520
1521         /* No match */
1522         return false;
1523 }
1524
1525 struct getaddrinfo_state {
1526         const char *node;
1527         const char *service;
1528         const struct addrinfo *hints;
1529         struct addrinfo *res;
1530         int ret;
1531 };
1532
1533 static void getaddrinfo_do(void *private_data);
1534 static void getaddrinfo_done(struct tevent_req *subreq);
1535
1536 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1537                                     struct tevent_context *ev,
1538                                     struct fncall_context *ctx,
1539                                     const char *node,
1540                                     const char *service,
1541                                     const struct addrinfo *hints)
1542 {
1543         struct tevent_req *req, *subreq;
1544         struct getaddrinfo_state *state;
1545
1546         req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1547         if (req == NULL) {
1548                 return NULL;
1549         }
1550
1551         state->node = node;
1552         state->service = service;
1553         state->hints = hints;
1554
1555         subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1556         if (tevent_req_nomem(subreq, req)) {
1557                 return tevent_req_post(req, ev);
1558         }
1559         tevent_req_set_callback(subreq, getaddrinfo_done, req);
1560         return req;
1561 }
1562
1563 static void getaddrinfo_do(void *private_data)
1564 {
1565         struct getaddrinfo_state *state =
1566                 (struct getaddrinfo_state *)private_data;
1567
1568         state->ret = getaddrinfo(state->node, state->service, state->hints,
1569                                  &state->res);
1570 }
1571
1572 static void getaddrinfo_done(struct tevent_req *subreq)
1573 {
1574         struct tevent_req *req = tevent_req_callback_data(
1575                 subreq, struct tevent_req);
1576         int ret, err;
1577
1578         ret = fncall_recv(subreq, &err);
1579         TALLOC_FREE(subreq);
1580         if (ret == -1) {
1581                 tevent_req_error(req, err);
1582                 return;
1583         }
1584         tevent_req_done(req);
1585 }
1586
1587 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1588 {
1589         struct getaddrinfo_state *state = tevent_req_data(
1590                 req, struct getaddrinfo_state);
1591         int err;
1592
1593         if (tevent_req_is_unix_error(req, &err)) {
1594                 switch(err) {
1595                 case ENOMEM:
1596                         return EAI_MEMORY;
1597                 default:
1598                         return EAI_FAIL;
1599                 }
1600         }
1601         if (state->ret == 0) {
1602                 *res = state->res;
1603         }
1604         return state->ret;
1605 }
1606
1607 int poll_one_fd(int fd, int events, int timeout, int *revents)
1608 {
1609         struct pollfd *fds;
1610         int ret;
1611         int saved_errno;
1612
1613         fds = talloc_zero_array(talloc_tos(), struct pollfd, 1);
1614         if (fds == NULL) {
1615                 errno = ENOMEM;
1616                 return -1;
1617         }
1618         fds[0].fd = fd;
1619         fds[0].events = events;
1620
1621         ret = poll(fds, 1, timeout);
1622
1623         /*
1624          * Assign whatever poll did, even in the ret<=0 case.
1625          */
1626         *revents = fds[0].revents;
1627         saved_errno = errno;
1628         TALLOC_FREE(fds);
1629         errno = saved_errno;
1630
1631         return ret;
1632 }
1633
1634 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1635 {
1636         struct pollfd pfd;
1637         int ret;
1638
1639         pfd.fd = fd;
1640         pfd.events = events;
1641
1642         ret = sys_poll_intr(&pfd, 1, timeout);
1643         if (ret <= 0) {
1644                 *revents = 0;
1645                 return ret;
1646         }
1647         *revents = pfd.revents;
1648         return 1;
1649 }