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