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