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