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