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