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