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