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