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