Fix unintended consequence change for IPv6 noticed
[metze/old/v3-2-winbind-ndr.git] / source / 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 /* the following 3 client_*() functions are nasty ways of allowing
25    some generic functions to get info that really should be hidden in
26    particular modules */
27 static int client_fd = -1;
28 /* What to print out on a client disconnect error. */
29 static char client_ip_string[INET6_ADDRSTRLEN];
30
31 /****************************************************************************
32  Pritn out an IPv4 or IPv6 address from a struct sockaddr_storage.
33 ****************************************************************************/
34
35 char *print_sockaddr(char *dest,
36                         size_t destlen,
37                         struct sockaddr_storage *psa)
38 {
39         if (destlen > 0) {
40                 dest[0] = '\0';
41         }
42 #ifdef AF_INET6
43         if (psa->ss_family == AF_INET6) {
44                 inet_ntop(AF_INET6,
45                         &((struct sockaddr_in6 *)psa)->sin6_addr,
46                         dest,
47                         destlen);
48         }
49 #endif
50         if (psa->ss_family == AF_INET) {
51                 inet_ntop(AF_INET,
52                         &((struct sockaddr_in *)psa)->sin_addr,
53                         dest,
54                         destlen);
55         }
56         return dest;
57 }
58
59 void client_setfd(int fd)
60 {
61         client_fd = fd;
62         safe_strcpy(client_ip_string,
63                         get_peer_addr(client_fd),
64                         sizeof(client_ip_string)-1);
65 }
66
67 static char *get_socket_addr(int fd)
68 {
69         struct sockaddr_storage sa;
70         socklen_t length = sizeof(sa);
71         static char addr_buf[INET6_ADDRSTRLEN];
72
73         /* Ok, returning a hard coded IPv4 address
74          * is bogus, but it's just as bogus as a
75          * zero IPv6 address. No good choice here.
76          */
77
78         safe_strcpy(addr_buf, "0.0.0.0", sizeof(addr_buf)-1);
79
80         if (fd == -1) {
81                 return addr_buf;
82         }
83
84         if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
85                 DEBUG(0,("getsockname failed. Error was %s\n",
86                         strerror(errno) ));
87                 return addr_buf;
88         }
89
90         return print_sockaddr(addr_buf, sizeof(addr_buf), &sa);
91 }
92
93 static int get_socket_port(int fd)
94 {
95         struct sockaddr_storage sa;
96         socklen_t length = sizeof(sa);
97
98         if (fd == -1) {
99                 return -1;
100         }
101
102         if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
103                 DEBUG(0,("getpeername failed. Error was %s\n",
104                         strerror(errno) ));
105                 return -1;
106         }
107
108 #ifdef AF_INET6
109         if (sa.ss_family == AF_INET6) {
110                 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
111         }
112 #endif
113         if (sa.ss_family == AF_INET) {
114                 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
115         }
116         return -1;
117 }
118
119 char *client_name(void)
120 {
121         return get_peer_name(client_fd,False);
122 }
123
124 char *client_addr(void)
125 {
126         return get_peer_addr(client_fd);
127 }
128
129 char *client_socket_addr(void)
130 {
131         return get_socket_addr(client_fd);
132 }
133
134 int client_socket_port(void)
135 {
136         return get_socket_port(client_fd);
137 }
138
139 int smb_read_error = 0;
140
141 /****************************************************************************
142  Determine if a file descriptor is in fact a socket.
143 ****************************************************************************/
144
145 BOOL is_a_socket(int fd)
146 {
147         int v;
148         socklen_t l;
149         l = sizeof(int);
150         return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
151 }
152
153 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
154
155 typedef struct smb_socket_option {
156         const char *name;
157         int level;
158         int option;
159         int value;
160         int opttype;
161 } smb_socket_option;
162
163 static const smb_socket_option socket_options[] = {
164   {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
165   {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
166   {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
167 #ifdef TCP_NODELAY
168   {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
169 #endif
170 #ifdef TCP_KEEPCNT
171   {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
172 #endif
173 #ifdef TCP_KEEPIDLE
174   {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
175 #endif
176 #ifdef TCP_KEEPINTVL
177   {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
178 #endif
179 #ifdef IPTOS_LOWDELAY
180   {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
181 #endif
182 #ifdef IPTOS_THROUGHPUT
183   {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
184 #endif
185 #ifdef SO_REUSEPORT
186   {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
187 #endif
188 #ifdef SO_SNDBUF
189   {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
190 #endif
191 #ifdef SO_RCVBUF
192   {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
193 #endif
194 #ifdef SO_SNDLOWAT
195   {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
196 #endif
197 #ifdef SO_RCVLOWAT
198   {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
199 #endif
200 #ifdef SO_SNDTIMEO
201   {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
202 #endif
203 #ifdef SO_RCVTIMEO
204   {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
205 #endif
206 #ifdef TCP_FASTACK
207   {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
208 #endif
209   {NULL,0,0,0,0}};
210
211 /****************************************************************************
212  Print socket options.
213 ****************************************************************************/
214
215 static void print_socket_options(int s)
216 {
217         int value;
218         socklen_t vlen = 4;
219         const smb_socket_option *p = &socket_options[0];
220
221         /* wrapped in if statement to prevent streams
222          * leak in SCO Openserver 5.0 */
223         /* reported on samba-technical  --jerry */
224         if ( DEBUGLEVEL >= 5 ) {
225                 for (; p->name != NULL; p++) {
226                         if (getsockopt(s, p->level, p->option,
227                                                 (void *)&value, &vlen) == -1) {
228                                 DEBUG(5,("Could not test socket option %s.\n",
229                                                         p->name));
230                         } else {
231                                 DEBUG(5,("socket option %s = %d\n",
232                                                         p->name,value));
233                         }
234                 }
235         }
236  }
237
238 /****************************************************************************
239  Set user socket options.
240 ****************************************************************************/
241
242 void set_socket_options(int fd, const char *options)
243 {
244         fstring tok;
245
246         while (next_token(&options,tok," \t,", sizeof(tok))) {
247                 int ret=0,i;
248                 int value = 1;
249                 char *p;
250                 BOOL got_value = False;
251
252                 if ((p = strchr_m(tok,'='))) {
253                         *p = 0;
254                         value = atoi(p+1);
255                         got_value = True;
256                 }
257
258                 for (i=0;socket_options[i].name;i++)
259                         if (strequal(socket_options[i].name,tok))
260                                 break;
261
262                 if (!socket_options[i].name) {
263                         DEBUG(0,("Unknown socket option %s\n",tok));
264                         continue;
265                 }
266
267                 switch (socket_options[i].opttype) {
268                 case OPT_BOOL:
269                 case OPT_INT:
270                         ret = setsockopt(fd,socket_options[i].level,
271                                         socket_options[i].option,
272                                         (char *)&value,sizeof(int));
273                         break;
274
275                 case OPT_ON:
276                         if (got_value)
277                                 DEBUG(0,("syntax error - %s "
278                                         "does not take a value\n",tok));
279
280                         {
281                                 int on = socket_options[i].value;
282                                 ret = setsockopt(fd,socket_options[i].level,
283                                         socket_options[i].option,
284                                         (char *)&on,sizeof(int));
285                         }
286                         break;
287                 }
288
289                 if (ret != 0) {
290                         DEBUG(0,("Failed to set socket option %s (Error %s)\n",
291                                 tok, strerror(errno) ));
292                 }
293         }
294
295         print_socket_options(fd);
296 }
297
298 /****************************************************************************
299  Read from a socket.
300 ****************************************************************************/
301
302 ssize_t read_udp_v4_socket(int fd,
303                         char *buf,
304                         size_t len,
305                         struct sockaddr_storage *psa)
306 {
307         ssize_t ret;
308         socklen_t socklen = sizeof(*psa);
309         struct sockaddr_in *si = (struct sockaddr_in *)psa;
310
311         memset((char *)psa,'\0',socklen);
312
313         ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
314                         (struct sockaddr *)psa,&socklen);
315         if (ret <= 0) {
316                 /* Don't print a low debug error for a non-blocking socket. */
317                 if (errno == EAGAIN) {
318                         DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
319                 } else {
320                         DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
321                                 strerror(errno)));
322                 }
323                 return 0;
324         }
325
326         if (psa->ss_family != AF_INET) {
327                 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
328                         "(not IPv4)\n", (int)psa->ss_family));
329                 return 0;
330         }
331
332         DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
333                         inet_ntoa(si->sin_addr),
334                         si->sin_port,
335                         (unsigned long)ret));
336
337         return ret;
338 }
339
340 /****************************************************************************
341  Read data from a socket with a timout in msec.
342  mincount = if timeout, minimum to read before returning
343  maxcount = number to be read.
344  time_out = timeout in milliseconds
345 ****************************************************************************/
346
347 ssize_t read_socket_with_timeout(int fd,
348                                 char *buf,
349                                 size_t mincnt,
350                                 size_t maxcnt,
351                                 unsigned int time_out)
352 {
353         fd_set fds;
354         int selrtn;
355         ssize_t readret;
356         size_t nread = 0;
357         struct timeval timeout;
358
359         /* just checking .... */
360         if (maxcnt <= 0)
361                 return(0);
362
363         smb_read_error = 0;
364
365         /* Blocking read */
366         if (time_out == 0) {
367                 if (mincnt == 0) {
368                         mincnt = maxcnt;
369                 }
370
371                 while (nread < mincnt) {
372                         readret = sys_read(fd, buf + nread, maxcnt - nread);
373
374                         if (readret == 0) {
375                                 DEBUG(5,("read_socket_with_timeout: "
376                                         "blocking read. EOF from client.\n"));
377                                 smb_read_error = READ_EOF;
378                                 return -1;
379                         }
380
381                         if (readret == -1) {
382                                 if (fd == client_fd) {
383                                         /* Try and give an error message
384                                          * saying what client failed. */
385                                         DEBUG(0,("read_socket_with_timeout: "
386                                                 "client %s read error = %s.\n",
387                                                 client_ip_string,
388                                                 strerror(errno) ));
389                                 } else {
390                                         DEBUG(0,("read_socket_with_timeout: "
391                                                 "read error = %s.\n",
392                                                 strerror(errno) ));
393                                 }
394                                 smb_read_error = READ_ERROR;
395                                 return -1;
396                         }
397                         nread += readret;
398                 }
399                 return((ssize_t)nread);
400         }
401
402         /* Most difficult - timeout read */
403         /* If this is ever called on a disk file and
404            mincnt is greater then the filesize then
405            system performance will suffer severely as
406            select always returns true on disk files */
407
408         /* Set initial timeout */
409         timeout.tv_sec = (time_t)(time_out / 1000);
410         timeout.tv_usec = (long)(1000 * (time_out % 1000));
411
412         for (nread=0; nread < mincnt; ) {
413                 FD_ZERO(&fds);
414                 FD_SET(fd,&fds);
415
416                 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
417
418                 /* Check if error */
419                 if (selrtn == -1) {
420                         /* something is wrong. Maybe the socket is dead? */
421                         if (fd == client_fd) {
422                                 /* Try and give an error message saying
423                                  * what client failed. */
424                                 DEBUG(0,("read_socket_with_timeout: timeout "
425                                 "read for client %s. select error = %s.\n",
426                                 client_ip_string, strerror(errno) ));
427                         } else {
428                                 DEBUG(0,("read_socket_with_timeout: timeout "
429                                 "read. select error = %s.\n",
430                                 strerror(errno) ));
431                         }
432                         smb_read_error = READ_ERROR;
433                         return -1;
434                 }
435
436                 /* Did we timeout ? */
437                 if (selrtn == 0) {
438                         DEBUG(10,("read_socket_with_timeout: timeout read. "
439                                 "select timed out.\n"));
440                         smb_read_error = READ_TIMEOUT;
441                         return -1;
442                 }
443
444                 readret = sys_read(fd, buf+nread, maxcnt-nread);
445
446                 if (readret == 0) {
447                         /* we got EOF on the file descriptor */
448                         DEBUG(5,("read_socket_with_timeout: timeout read. "
449                                 "EOF from client.\n"));
450                         smb_read_error = READ_EOF;
451                         return -1;
452                 }
453
454                 if (readret == -1) {
455                         /* the descriptor is probably dead */
456                         if (fd == client_fd) {
457                                 /* Try and give an error message
458                                  * saying what client failed. */
459                                 DEBUG(0,("read_socket_with_timeout: timeout "
460                                         "read to client %s. read error = %s.\n",
461                                         client_ip_string, strerror(errno) ));
462                         } else {
463                                 DEBUG(0,("read_socket_with_timeout: timeout "
464                                         "read. read error = %s.\n",
465                                         strerror(errno) ));
466                         }
467                         smb_read_error = READ_ERROR;
468                         return -1;
469                 }
470
471                 nread += readret;
472         }
473
474         /* Return the number we got */
475         return (ssize_t)nread;
476 }
477
478 /****************************************************************************
479  Read data from the client, reading exactly N bytes.
480 ****************************************************************************/
481
482 ssize_t read_data(int fd,char *buffer,size_t N)
483 {
484         ssize_t ret;
485         size_t total=0;
486
487         smb_read_error = 0;
488
489         while (total < N) {
490                 ret = sys_read(fd,buffer + total,N - total);
491
492                 if (ret == 0) {
493                         DEBUG(10,("read_data: read of %d returned 0. "
494                                 "Error = %s\n",
495                                 (int)(N - total), strerror(errno) ));
496                         smb_read_error = READ_EOF;
497                         return 0;
498                 }
499
500                 if (ret == -1) {
501                         if (fd == client_fd) {
502                                 /* Try and give an error message saying
503                                  * what client failed. */
504                                 DEBUG(0,("read_data: read failure for %d "
505                                         "bytes to client %s. Error = %s\n",
506                                         (int)(N - total),
507                                         client_ip_string,
508                                         strerror(errno) ));
509                         } else {
510                                 DEBUG(0,("read_data: read failure for %d. "
511                                         "Error = %s\n",
512                                         (int)(N - total),
513                                         strerror(errno) ));
514                         }
515                         smb_read_error = READ_ERROR;
516                         return -1;
517                 }
518                 total += ret;
519         }
520         return (ssize_t)total;
521 }
522
523 /****************************************************************************
524  Write data to a fd.
525 ****************************************************************************/
526
527 ssize_t write_data(int fd, const char *buffer, size_t N)
528 {
529         size_t total=0;
530         ssize_t ret;
531
532         while (total < N) {
533                 ret = sys_write(fd,buffer + total,N - total);
534
535                 if (ret == -1) {
536                         if (fd == client_fd) {
537                                 /* Try and give an error message saying
538                                  * what client failed. */
539                                 DEBUG(0,("write_data: write failure in "
540                                         "writing to client %s. Error %s\n",
541                                         client_ip_string, strerror(errno) ));
542                         } else {
543                                 DEBUG(0,("write_data: write failure. "
544                                         "Error = %s\n", strerror(errno) ));
545                         }
546                         return -1;
547                 }
548
549                 if (ret == 0) {
550                         return total;
551                 }
552
553                 total += ret;
554         }
555         return (ssize_t)total;
556 }
557
558 /****************************************************************************
559  Send a keepalive packet (rfc1002).
560 ****************************************************************************/
561
562 BOOL send_keepalive(int client)
563 {
564         unsigned char buf[4];
565
566         buf[0] = SMBkeepalive;
567         buf[1] = buf[2] = buf[3] = 0;
568
569         return(write_data(client,(char *)buf,4) == 4);
570 }
571
572 /****************************************************************************
573  Read 4 bytes of a smb packet and return the smb length of the packet.
574  Store the result in the buffer.
575  This version of the function will return a length of zero on receiving
576  a keepalive packet.
577  Timeout is in milliseconds.
578 ****************************************************************************/
579
580 static ssize_t read_smb_length_return_keepalive(int fd,
581                                                 char *inbuf,
582                                                 unsigned int timeout)
583 {
584         ssize_t len=0;
585         int msg_type;
586         BOOL ok = False;
587
588         while (!ok) {
589                 if (timeout > 0) {
590                         ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout)
591                                         == 4);
592                 } else {
593                         ok = (read_data(fd,inbuf,4) == 4);
594                 }
595                 if (!ok) {
596                         return -1;
597                 }
598
599                 len = smb_len(inbuf);
600                 msg_type = CVAL(inbuf,0);
601
602                 if (msg_type == SMBkeepalive) {
603                         DEBUG(5,("Got keepalive packet\n"));
604                 }
605         }
606
607         DEBUG(10,("got smb length of %lu\n",(unsigned long)len));
608
609         return(len);
610 }
611
612 /****************************************************************************
613  Read 4 bytes of a smb packet and return the smb length of the packet.
614  Store the result in the buffer. This version of the function will
615  never return a session keepalive (length of zero).
616  Timeout is in milliseconds.
617 ****************************************************************************/
618
619 ssize_t read_smb_length(int fd, char *inbuf, unsigned int timeout)
620 {
621         ssize_t len;
622
623         for(;;) {
624                 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
625
626                 if(len < 0)
627                         return len;
628
629                 /* Ignore session keepalives. */
630                 if(CVAL(inbuf,0) != SMBkeepalive)
631                         break;
632         }
633
634         DEBUG(10,("read_smb_length: got smb length of %lu\n",
635                   (unsigned long)len));
636
637         return len;
638 }
639
640 /****************************************************************************
641  Read an smb from a fd. Note that the buffer *MUST* be of size
642  BUFFER_SIZE+SAFETY_MARGIN.
643  The timeout is in milliseconds.
644  This function will return on receipt of a session keepalive packet.
645  maxlen is the max number of bytes to return, not including the 4 byte
646  length. If zero it means BUFFER_SIZE+SAFETY_MARGIN limit.
647  Doesn't check the MAC on signed packets.
648 ****************************************************************************/
649
650 ssize_t receive_smb_raw(int fd,
651                         char *buffer,
652                         unsigned int timeout,
653                         size_t maxlen)
654 {
655         ssize_t len,ret;
656
657         smb_read_error = 0;
658
659         len = read_smb_length_return_keepalive(fd,buffer,timeout);
660         if (len < 0) {
661                 DEBUG(10,("receive_smb_raw: length < 0!\n"));
662
663                 /*
664                  * Correct fix. smb_read_error may have already been
665                  * set. Only set it here if not already set. Global
666                  * variables still suck :-). JRA.
667                  */
668
669                 if (smb_read_error == 0)
670                         smb_read_error = READ_ERROR;
671                 return -1;
672         }
673
674         /*
675          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
676          * of header. Don't print the error if this fits.... JRA.
677          */
678
679         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
680                 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
681                                         (unsigned long)len));
682                 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
683
684                         /*
685                          * Correct fix. smb_read_error may have already been
686                          * set. Only set it here if not already set. Global
687                          * variables still suck :-). JRA.
688                          */
689
690                         if (smb_read_error == 0)
691                                 smb_read_error = READ_ERROR;
692                         return -1;
693                 }
694         }
695
696         if(len > 0) {
697                 if (maxlen) {
698                         len = MIN(len,maxlen);
699                 }
700
701                 if (timeout > 0) {
702                         ret = read_socket_with_timeout(fd,
703                                         buffer+4,
704                                         len,
705                                         len,
706                                         timeout);
707                 } else {
708                         ret = read_data(fd,buffer+4,len);
709                 }
710
711                 if (ret != len) {
712                         if (smb_read_error == 0) {
713                                 smb_read_error = READ_ERROR;
714                         }
715                         return -1;
716                 }
717
718                 /* not all of samba3 properly checks for packet-termination
719                  * of strings. This ensures that we don't run off into
720                  * empty space. */
721                 SSVAL(buffer+4,len, 0);
722         }
723
724         return len;
725 }
726
727 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx, int fd,
728                                       char **buffer, unsigned int timeout)
729 {
730         char lenbuf[4];
731         ssize_t len,ret;
732
733         smb_read_error = 0;
734
735         len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
736         if (len < 0) {
737                 DEBUG(10,("receive_smb_raw: length < 0!\n"));
738
739                 /*
740                  * Correct fix. smb_read_error may have already been
741                  * set. Only set it here if not already set. Global
742                  * variables still suck :-). JRA.
743                  */
744
745                 if (smb_read_error == 0)
746                         smb_read_error = READ_ERROR;
747                 return -1;
748         }
749
750         /*
751          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
752          * of header. Don't print the error if this fits.... JRA.
753          */
754
755         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
756                 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
757                                         (unsigned long)len));
758                 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
759
760                         /*
761                          * Correct fix. smb_read_error may have already been
762                          * set. Only set it here if not already set. Global
763                          * variables still suck :-). JRA.
764                          */
765
766                         if (smb_read_error == 0)
767                                 smb_read_error = READ_ERROR;
768                         return -1;
769                 }
770         }
771
772         /*
773          * The +4 here can't wrap, we've checked the length above already.
774          */
775
776         *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
777
778         if (*buffer == NULL) {
779                 DEBUG(0, ("Could not allocate inbuf of length %d\n",
780                           (int)len+4));
781                 if (smb_read_error == 0)
782                         smb_read_error = READ_ERROR;
783                 return -1;
784         }
785
786         memcpy(*buffer, lenbuf, sizeof(lenbuf));
787
788         if(len > 0) {
789                 if (timeout > 0) {
790                         ret = read_socket_with_timeout(fd,(*buffer)+4, len,
791                                                        len, timeout);
792                 } else {
793                         ret = read_data(fd, (*buffer)+4, len);
794                 }
795
796                 if (ret != len) {
797                         if (smb_read_error == 0) {
798                                 smb_read_error = READ_ERROR;
799                         }
800                         return -1;
801                 }
802         }
803
804         return len + 4;
805 }
806
807 /****************************************************************************
808  Wrapper for receive_smb_raw().
809  Checks the MAC on signed packets.
810 ****************************************************************************/
811
812 BOOL receive_smb(int fd, char *buffer, unsigned int timeout)
813 {
814         if (receive_smb_raw(fd, buffer, timeout, 0) < 0) {
815                 return False;
816         }
817
818         if (srv_encryption_on()) {
819                 NTSTATUS status = srv_decrypt_buffer(buffer);
820                 if (!NT_STATUS_IS_OK(status)) {
821                         DEBUG(0, ("receive_smb: SMB decryption failed "
822                                 "on incoming packet! Error %s\n",
823                                 nt_errstr(status) ));
824                         if (smb_read_error == 0) {
825                                 smb_read_error = READ_BAD_DECRYPT;
826                         }
827                         return False;
828                 }
829         }
830
831         /* Check the incoming SMB signature. */
832         if (!srv_check_sign_mac(buffer, True)) {
833                 DEBUG(0, ("receive_smb: SMB Signature verification "
834                         "failed on incoming packet!\n"));
835                 if (smb_read_error == 0) {
836                         smb_read_error = READ_BAD_SIG;
837                 }
838                 return False;
839         }
840
841         return True;
842 }
843
844 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
845                            unsigned int timeout)
846 {
847         ssize_t len;
848
849         len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
850
851         if (len < 0) {
852                 return -1;
853         }
854
855         if (srv_encryption_on()) {
856                 NTSTATUS status = srv_decrypt_buffer(*buffer);
857                 if (!NT_STATUS_IS_OK(status)) {
858                         DEBUG(0, ("receive_smb: SMB decryption failed on "
859                                   "incoming packet! Error %s\n",
860                                   nt_errstr(status) ));
861                         if (smb_read_error == 0) {
862                                 smb_read_error = READ_BAD_DECRYPT;
863                         }
864                         return -1;
865                 }
866         }
867
868         /* Check the incoming SMB signature. */
869         if (!srv_check_sign_mac(*buffer, True)) {
870                 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
871                           "incoming packet!\n"));
872                 if (smb_read_error == 0) {
873                         smb_read_error = READ_BAD_SIG;
874                 }
875                 return -1;
876         }
877
878         return len;
879 }
880
881 /****************************************************************************
882  Send an smb to a fd.
883 ****************************************************************************/
884
885 BOOL send_smb(int fd, char *buffer)
886 {
887         size_t len;
888         size_t nwritten=0;
889         ssize_t ret;
890         char *buf_out = buffer;
891
892         /* Sign the outgoing packet if required. */
893         srv_calculate_sign_mac(buf_out);
894
895         if (srv_encryption_on()) {
896                 NTSTATUS status = srv_encrypt_buffer(buffer, &buf_out);
897                 if (!NT_STATUS_IS_OK(status)) {
898                         DEBUG(0, ("send_smb: SMB encryption failed "
899                                 "on outgoing packet! Error %s\n",
900                                 nt_errstr(status) ));
901                         return False;
902                 }
903         }
904
905         len = smb_len(buf_out) + 4;
906
907         while (nwritten < len) {
908                 ret = write_data(fd,buf_out+nwritten,len - nwritten);
909                 if (ret <= 0) {
910                         DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
911                                 (int)len,(int)ret, strerror(errno) ));
912                         srv_free_enc_buffer(buf_out);
913                         return False;
914                 }
915                 nwritten += ret;
916         }
917
918         srv_free_enc_buffer(buf_out);
919         return True;
920 }
921
922 /****************************************************************************
923  Open a socket of the specified type, port, and address for incoming data.
924 ****************************************************************************/
925
926 int open_socket_in(int type,
927                 int port,
928                 int dlevel,
929                 uint32 socket_addr,
930                 BOOL rebind )
931 {
932         struct sockaddr_in sock;
933         int res;
934
935         memset( (char *)&sock, '\0', sizeof(sock) );
936
937 #ifdef HAVE_SOCK_SIN_LEN
938         sock.sin_len         = sizeof(sock);
939 #endif
940         sock.sin_port        = htons( port );
941         sock.sin_family      = AF_INET;
942         sock.sin_addr.s_addr = socket_addr;
943
944         res = socket( AF_INET, type, 0 );
945         if( res == -1 ) {
946                 if( DEBUGLVL(0) ) {
947                         dbgtext( "open_socket_in(): socket() call failed: " );
948                         dbgtext( "%s\n", strerror( errno ) );
949                 }
950                 return -1;
951         }
952
953         /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
954         {
955                 int val = rebind ? 1 : 0;
956                 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
957                                         (char *)&val,sizeof(val)) == -1 ) {
958                         if( DEBUGLVL( dlevel ) ) {
959                                 dbgtext( "open_socket_in(): setsockopt: " );
960                                 dbgtext( "SO_REUSEADDR = %s ",
961                                                 val?"True":"False" );
962                                 dbgtext( "on port %d failed ", port );
963                                 dbgtext( "with error = %s\n", strerror(errno) );
964                         }
965                 }
966 #ifdef SO_REUSEPORT
967                 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
968                                         (char *)&val,sizeof(val)) == -1 ) {
969                         if( DEBUGLVL( dlevel ) ) {
970                                 dbgtext( "open_socket_in(): setsockopt: ");
971                                 dbgtext( "SO_REUSEPORT = %s ",
972                                                 val?"True":"False" );
973                                 dbgtext( "on port %d failed ", port );
974                                 dbgtext( "with error = %s\n", strerror(errno) );
975                         }
976                 }
977 #endif /* SO_REUSEPORT */
978         }
979
980         /* now we've got a socket - we need to bind it */
981         if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
982                 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
983                                 port == SMB_PORT2 || port == NMB_PORT) ) {
984                         dbgtext( "bind failed on port %d ", port );
985                         dbgtext( "socket_addr = %s.\n",
986                                         inet_ntoa( sock.sin_addr ) );
987                         dbgtext( "Error = %s\n", strerror(errno) );
988                 }
989                 close( res );
990                 return -1;
991         }
992
993         DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
994
995         return( res );
996  }
997
998 /****************************************************************************
999  Create an outgoing socket. timeout is in milliseconds.
1000 **************************************************************************/
1001
1002 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
1003 {
1004         struct sockaddr_in sock_out;
1005         int res,ret;
1006         int connect_loop = 10;
1007         int increment = 10;
1008
1009         /* create a socket to write to */
1010         res = socket(PF_INET, type, 0);
1011         if (res == -1) {
1012                 DEBUG(0,("socket error (%s)\n", strerror(errno)));
1013                 return -1;
1014         }
1015
1016         if (type != SOCK_STREAM)
1017                 return(res);
1018
1019         memset((char *)&sock_out,'\0',sizeof(sock_out));
1020         putip((char *)&sock_out.sin_addr,(char *)addr);
1021
1022         sock_out.sin_port = htons( port );
1023         sock_out.sin_family = PF_INET;
1024
1025         /* set it non-blocking */
1026         set_blocking(res,False);
1027
1028         DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
1029
1030         /* and connect it to the destination */
1031   connect_again:
1032
1033         ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
1034
1035         /* Some systems return EAGAIN when they mean EINPROGRESS */
1036         if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1037                         errno == EAGAIN) && (connect_loop < timeout) ) {
1038                 smb_msleep(connect_loop);
1039                 timeout -= connect_loop;
1040                 connect_loop += increment;
1041                 if (increment < 250) {
1042                         /* After 8 rounds we end up at a max of 255 msec */
1043                         increment *= 1.5;
1044                 }
1045                 goto connect_again;
1046         }
1047
1048         if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1049                         errno == EAGAIN)) {
1050                 DEBUG(1,("timeout connecting to %s:%d\n",
1051                                         inet_ntoa(*addr),port));
1052                 close(res);
1053                 return -1;
1054         }
1055
1056 #ifdef EISCONN
1057         if (ret < 0 && errno == EISCONN) {
1058                 errno = 0;
1059                 ret = 0;
1060         }
1061 #endif
1062
1063         if (ret < 0) {
1064                 DEBUG(2,("error connecting to %s:%d (%s)\n",
1065                                 inet_ntoa(*addr),port,strerror(errno)));
1066                 close(res);
1067                 return -1;
1068         }
1069
1070         /* set it blocking again */
1071         set_blocking(res,True);
1072
1073         return res;
1074 }
1075
1076 /****************************************************************************
1077  Create an outgoing TCP socket to any of the addrs. This is for
1078  simultaneous connects to port 445 and 139 of a host or even a variety
1079  of DC's all of which are equivalent for our purposes.
1080 **************************************************************************/
1081
1082 BOOL open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1083                          int timeout, int *fd_index, int *fd)
1084 {
1085         int i, resulting_index, res;
1086         int *sockets;
1087         BOOL good_connect;
1088
1089         fd_set r_fds, wr_fds;
1090         struct timeval tv;
1091         int maxfd;
1092
1093         int connect_loop = 10000; /* 10 milliseconds */
1094
1095         timeout *= 1000;        /* convert to microseconds */
1096
1097         sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1098
1099         if (sockets == NULL)
1100                 return False;
1101
1102         resulting_index = -1;
1103
1104         for (i=0; i<num_addrs; i++)
1105                 sockets[i] = -1;
1106
1107         for (i=0; i<num_addrs; i++) {
1108                 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1109                 if (sockets[i] < 0)
1110                         goto done;
1111                 set_blocking(sockets[i], False);
1112         }
1113
1114  connect_again:
1115         good_connect = False;
1116
1117         for (i=0; i<num_addrs; i++) {
1118
1119                 if (sockets[i] == -1)
1120                         continue;
1121
1122                 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1123                             sizeof(*addrs)) == 0) {
1124                         /* Rather unlikely as we are non-blocking, but it
1125                          * might actually happen. */
1126                         resulting_index = i;
1127                         goto done;
1128                 }
1129
1130                 if (errno == EINPROGRESS || errno == EALREADY ||
1131 #ifdef EISCONN
1132                         errno == EISCONN ||
1133 #endif
1134                     errno == EAGAIN || errno == EINTR) {
1135                         /* These are the error messages that something is
1136                            progressing. */
1137                         good_connect = True;
1138                 } else if (errno != 0) {
1139                         /* There was a direct error */
1140                         close(sockets[i]);
1141                         sockets[i] = -1;
1142                 }
1143         }
1144
1145         if (!good_connect) {
1146                 /* All of the connect's resulted in real error conditions */
1147                 goto done;
1148         }
1149
1150         /* Lets see if any of the connect attempts succeeded */
1151
1152         maxfd = 0;
1153         FD_ZERO(&wr_fds);
1154         FD_ZERO(&r_fds);
1155
1156         for (i=0; i<num_addrs; i++) {
1157                 if (sockets[i] == -1)
1158                         continue;
1159                 FD_SET(sockets[i], &wr_fds);
1160                 FD_SET(sockets[i], &r_fds);
1161                 if (sockets[i]>maxfd)
1162                         maxfd = sockets[i];
1163         }
1164
1165         tv.tv_sec = 0;
1166         tv.tv_usec = connect_loop;
1167
1168         res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1169
1170         if (res < 0)
1171                 goto done;
1172
1173         if (res == 0)
1174                 goto next_round;
1175
1176         for (i=0; i<num_addrs; i++) {
1177
1178                 if (sockets[i] == -1)
1179                         continue;
1180
1181                 /* Stevens, Network Programming says that if there's a
1182                  * successful connect, the socket is only writable. Upon an
1183                  * error, it's both readable and writable. */
1184
1185                 if (FD_ISSET(sockets[i], &r_fds) &&
1186                     FD_ISSET(sockets[i], &wr_fds)) {
1187                         /* readable and writable, so it's an error */
1188                         close(sockets[i]);
1189                         sockets[i] = -1;
1190                         continue;
1191                 }
1192
1193                 if (!FD_ISSET(sockets[i], &r_fds) &&
1194                     FD_ISSET(sockets[i], &wr_fds)) {
1195                         /* Only writable, so it's connected */
1196                         resulting_index = i;
1197                         goto done;
1198                 }
1199         }
1200
1201  next_round:
1202
1203         timeout -= connect_loop;
1204         if (timeout <= 0)
1205                 goto done;
1206         connect_loop *= 1.5;
1207         if (connect_loop > timeout)
1208                 connect_loop = timeout;
1209         goto connect_again;
1210
1211  done:
1212         for (i=0; i<num_addrs; i++) {
1213                 if (i == resulting_index)
1214                         continue;
1215                 if (sockets[i] >= 0)
1216                         close(sockets[i]);
1217         }
1218
1219         if (resulting_index >= 0) {
1220                 *fd_index = resulting_index;
1221                 *fd = sockets[*fd_index];
1222                 set_blocking(*fd, True);
1223         }
1224
1225         free(sockets);
1226
1227         return (resulting_index >= 0);
1228 }
1229 /****************************************************************************
1230  Open a connected UDP socket to host on port
1231 **************************************************************************/
1232
1233 int open_udp_socket(const char *host, int port)
1234 {
1235         int type = SOCK_DGRAM;
1236         struct sockaddr_in sock_out;
1237         int res;
1238         struct in_addr *addr;
1239
1240         addr = interpret_addr2(host);
1241
1242         res = socket(PF_INET, type, 0);
1243         if (res == -1) {
1244                 return -1;
1245         }
1246
1247         memset((char *)&sock_out,'\0',sizeof(sock_out));
1248         putip((char *)&sock_out.sin_addr,(char *)addr);
1249         sock_out.sin_port = htons(port);
1250         sock_out.sin_family = PF_INET;
1251
1252         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1253                 close(res);
1254                 return -1;
1255         }
1256
1257         return res;
1258 }
1259
1260 /*******************************************************************
1261  Matchname - determine if host name matches IP address. Used to
1262  confirm a hostname lookup to prevent spoof attacks.
1263 ******************************************************************/
1264
1265 static BOOL matchname(char *remotehost,struct in_addr  addr)
1266 {
1267         struct hostent *hp;
1268         int     i;
1269
1270         if ((hp = sys_gethostbyname(remotehost)) == 0) {
1271                 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n",
1272                                         remotehost));
1273                 return False;
1274         }
1275
1276         /*
1277          * Make sure that gethostbyname() returns the "correct" host name.
1278          * Unfortunately, gethostbyname("localhost") sometimes yields
1279          * "localhost.domain". Since the latter host name comes from the
1280          * local DNS, we just have to trust it (all bets are off if the local
1281          * DNS is perverted). We always check the address list, though.
1282          */
1283
1284         if (!strequal(remotehost, hp->h_name)
1285             && !strequal(remotehost, "localhost")) {
1286                 DEBUG(0,("host name/name mismatch: %s != %s\n",
1287                          remotehost, hp->h_name));
1288                 return False;
1289         }
1290
1291         /* Look up the host address in the address list we just got. */
1292         for (i = 0; hp->h_addr_list[i]; i++) {
1293                 if (memcmp(hp->h_addr_list[i], (char *)&addr,sizeof(addr)) == 0)
1294                         return True;
1295         }
1296
1297         /*
1298          * The host name does not map to the original host address. Perhaps
1299          * someone has compromised a name server. More likely someone botched
1300          * it, but that could be dangerous, too.
1301          */
1302
1303         DEBUG(0,("host name/address mismatch: %s != %s\n",
1304                  inet_ntoa(addr), hp->h_name));
1305         return False;
1306 }
1307
1308 /*******************************************************************
1309  Return the DNS name of the remote end of a socket.
1310 ******************************************************************/
1311
1312 char *get_peer_name(int fd, BOOL force_lookup)
1313 {
1314         static pstring name_buf;
1315         pstring tmp_name;
1316         static fstring addr_buf;
1317         struct hostent *hp;
1318         struct in_addr addr;
1319         char *p;
1320
1321         /* reverse lookups can be *very* expensive, and in many
1322            situations won't work because many networks don't link dhcp
1323            with dns. To avoid the delay we avoid the lookup if
1324            possible */
1325         if (!lp_hostname_lookups() && (force_lookup == False)) {
1326                 return get_peer_addr(fd);
1327         }
1328
1329         p = get_peer_addr(fd);
1330
1331         /* it might be the same as the last one - save some DNS work */
1332         if (strcmp(p, addr_buf) == 0)
1333                 return name_buf;
1334
1335         pstrcpy(name_buf,"UNKNOWN");
1336         if (fd == -1)
1337                 return name_buf;
1338
1339         fstrcpy(addr_buf, p);
1340
1341         addr = *interpret_addr2(p);
1342
1343         /* Look up the remote host name. */
1344         if ((hp = gethostbyaddr((char *)&addr.s_addr,
1345                                         sizeof(addr.s_addr), AF_INET)) == 0) {
1346                 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1347                 pstrcpy(name_buf, p);
1348         } else {
1349                 pstrcpy(name_buf,(char *)hp->h_name);
1350                 if (!matchname(name_buf, addr)) {
1351                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1352                         pstrcpy(name_buf,"UNKNOWN");
1353                 }
1354         }
1355
1356         /* can't pass the same source and dest strings in when you
1357            use --enable-developer or the clobber_region() call will
1358            get you */
1359
1360         pstrcpy( tmp_name, name_buf );
1361         alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1362         if (strstr(name_buf,"..")) {
1363                 pstrcpy(name_buf, "UNKNOWN");
1364         }
1365
1366         return name_buf;
1367 }
1368
1369 /*******************************************************************
1370  Return the IP addr of the remote end of a socket as a string.
1371  ******************************************************************/
1372
1373 char *get_peer_addr(int fd)
1374 {
1375         struct sockaddr sa;
1376         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1377         socklen_t length = sizeof(sa);
1378         static fstring addr_buf;
1379
1380         fstrcpy(addr_buf,"0.0.0.0");
1381
1382         if (fd == -1) {
1383                 return addr_buf;
1384         }
1385
1386         if (getpeername(fd, &sa, &length) < 0) {
1387                 DEBUG(0,("getpeername failed. Error was %s\n",
1388                                         strerror(errno) ));
1389                 return addr_buf;
1390         }
1391
1392         fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1393
1394         return addr_buf;
1395 }
1396
1397 /*******************************************************************
1398  Create protected unix domain socket.
1399
1400  Some unixes cannot set permissions on a ux-dom-sock, so we
1401  have to make sure that the directory contains the protection
1402  permissions instead.
1403  ******************************************************************/
1404
1405 int create_pipe_sock(const char *socket_dir,
1406                      const char *socket_name,
1407                      mode_t dir_perms)
1408 {
1409 #ifdef HAVE_UNIXSOCKET
1410         struct sockaddr_un sunaddr;
1411         struct stat st;
1412         int sock;
1413         mode_t old_umask;
1414         pstring path;
1415
1416         old_umask = umask(0);
1417
1418         /* Create the socket directory or reuse the existing one */
1419
1420         if (lstat(socket_dir, &st) == -1) {
1421                 if (errno == ENOENT) {
1422                         /* Create directory */
1423                         if (mkdir(socket_dir, dir_perms) == -1) {
1424                                 DEBUG(0, ("error creating socket directory "
1425                                         "%s: %s\n", socket_dir,
1426                                         strerror(errno)));
1427                                 goto out_umask;
1428                         }
1429                 } else {
1430                         DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1431                                 socket_dir, strerror(errno)));
1432                         goto out_umask;
1433                 }
1434         } else {
1435                 /* Check ownership and permission on existing directory */
1436                 if (!S_ISDIR(st.st_mode)) {
1437                         DEBUG(0, ("socket directory %s isn't a directory\n",
1438                                 socket_dir));
1439                         goto out_umask;
1440                 }
1441                 if ((st.st_uid != sec_initial_uid()) ||
1442                                 ((st.st_mode & 0777) != dir_perms)) {
1443                         DEBUG(0, ("invalid permissions on socket directory "
1444                                 "%s\n", socket_dir));
1445                         goto out_umask;
1446                 }
1447         }
1448
1449         /* Create the socket file */
1450
1451         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1452
1453         if (sock == -1) {
1454                 perror("socket");
1455                 goto out_umask;
1456         }
1457
1458         pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1459
1460         unlink(path);
1461         memset(&sunaddr, 0, sizeof(sunaddr));
1462         sunaddr.sun_family = AF_UNIX;
1463         safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1464
1465         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1466                 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1467                         strerror(errno)));
1468                 goto out_close;
1469         }
1470
1471         if (listen(sock, 5) == -1) {
1472                 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1473                         strerror(errno)));
1474                 goto out_close;
1475         }
1476
1477         umask(old_umask);
1478         return sock;
1479
1480 out_close:
1481         close(sock);
1482
1483 out_umask:
1484         umask(old_umask);
1485         return -1;
1486
1487 #else
1488         DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1489         return -1;
1490 #endif /* HAVE_UNIXSOCKET */
1491 }