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