[GLUE] Rsync SAMBA_3_2_0 SVN r25598 in order to create the v3-2-test branch.
[samba.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         /* Check the incoming SMB signature. */
819         if (!srv_check_sign_mac(buffer, True)) {
820                 DEBUG(0, ("receive_smb: SMB Signature verification "
821                         "failed on incoming packet!\n"));
822                 if (smb_read_error == 0) {
823                         smb_read_error = READ_BAD_SIG;
824                 }
825                 return False;
826         }
827
828         return True;
829 }
830
831 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
832                            unsigned int timeout)
833 {
834         ssize_t len;
835
836         len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout);
837
838         if (len < 0) {
839                 return -1;
840         }
841
842         /* Check the incoming SMB signature. */
843         if (!srv_check_sign_mac(*buffer, True)) {
844                 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
845                           "incoming packet!\n"));
846                 if (smb_read_error == 0) {
847                         smb_read_error = READ_BAD_SIG;
848                 }
849                 return -1;
850         }
851
852         return len;
853 }
854
855 /****************************************************************************
856  Send an smb to a fd.
857 ****************************************************************************/
858
859 BOOL send_smb(int fd, char *buffer)
860 {
861         size_t len;
862         size_t nwritten=0;
863         ssize_t ret;
864
865         /* Sign the outgoing packet if required. */
866         srv_calculate_sign_mac(buffer);
867
868         len = smb_len(buffer) + 4;
869
870         while (nwritten < len) {
871                 ret = write_data(fd,buffer+nwritten,len - nwritten);
872                 if (ret <= 0) {
873                         DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
874                                 (int)len,(int)ret, strerror(errno) ));
875                         return False;
876                 }
877                 nwritten += ret;
878         }
879
880         return True;
881 }
882
883 /****************************************************************************
884  Open a socket of the specified type, port, and address for incoming data.
885 ****************************************************************************/
886
887 int open_socket_in(int type,
888                 int port,
889                 int dlevel,
890                 uint32 socket_addr,
891                 BOOL rebind )
892 {
893         struct sockaddr_in sock;
894         int res;
895
896         memset( (char *)&sock, '\0', sizeof(sock) );
897
898 #ifdef HAVE_SOCK_SIN_LEN
899         sock.sin_len         = sizeof(sock);
900 #endif
901         sock.sin_port        = htons( port );
902         sock.sin_family      = AF_INET;
903         sock.sin_addr.s_addr = socket_addr;
904
905         res = socket( AF_INET, type, 0 );
906         if( res == -1 ) {
907                 if( DEBUGLVL(0) ) {
908                         dbgtext( "open_socket_in(): socket() call failed: " );
909                         dbgtext( "%s\n", strerror( errno ) );
910                 }
911                 return -1;
912         }
913
914         /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
915         {
916                 int val = rebind ? 1 : 0;
917                 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
918                                         (char *)&val,sizeof(val)) == -1 ) {
919                         if( DEBUGLVL( dlevel ) ) {
920                                 dbgtext( "open_socket_in(): setsockopt: " );
921                                 dbgtext( "SO_REUSEADDR = %s ",
922                                                 val?"True":"False" );
923                                 dbgtext( "on port %d failed ", port );
924                                 dbgtext( "with error = %s\n", strerror(errno) );
925                         }
926                 }
927 #ifdef SO_REUSEPORT
928                 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
929                                         (char *)&val,sizeof(val)) == -1 ) {
930                         if( DEBUGLVL( dlevel ) ) {
931                                 dbgtext( "open_socket_in(): setsockopt: ");
932                                 dbgtext( "SO_REUSEPORT = %s ",
933                                                 val?"True":"False" );
934                                 dbgtext( "on port %d failed ", port );
935                                 dbgtext( "with error = %s\n", strerror(errno) );
936                         }
937                 }
938 #endif /* SO_REUSEPORT */
939         }
940
941         /* now we've got a socket - we need to bind it */
942         if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
943                 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
944                                 port == SMB_PORT2 || port == NMB_PORT) ) {
945                         dbgtext( "bind failed on port %d ", port );
946                         dbgtext( "socket_addr = %s.\n",
947                                         inet_ntoa( sock.sin_addr ) );
948                         dbgtext( "Error = %s\n", strerror(errno) );
949                 }
950                 close( res );
951                 return -1;
952         }
953
954         DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
955
956         return( res );
957  }
958
959 /****************************************************************************
960  Create an outgoing socket. timeout is in milliseconds.
961 **************************************************************************/
962
963 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
964 {
965         struct sockaddr_in sock_out;
966         int res,ret;
967         int connect_loop = 10;
968         int increment = 10;
969
970         /* create a socket to write to */
971         res = socket(PF_INET, type, 0);
972         if (res == -1) {
973                 DEBUG(0,("socket error (%s)\n", strerror(errno)));
974                 return -1;
975         }
976
977         if (type != SOCK_STREAM)
978                 return(res);
979
980         memset((char *)&sock_out,'\0',sizeof(sock_out));
981         putip((char *)&sock_out.sin_addr,(char *)addr);
982
983         sock_out.sin_port = htons( port );
984         sock_out.sin_family = PF_INET;
985
986         /* set it non-blocking */
987         set_blocking(res,False);
988
989         DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
990
991         /* and connect it to the destination */
992   connect_again:
993
994         ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
995
996         /* Some systems return EAGAIN when they mean EINPROGRESS */
997         if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
998                         errno == EAGAIN) && (connect_loop < timeout) ) {
999                 smb_msleep(connect_loop);
1000                 timeout -= connect_loop;
1001                 connect_loop += increment;
1002                 if (increment < 250) {
1003                         /* After 8 rounds we end up at a max of 255 msec */
1004                         increment *= 1.5;
1005                 }
1006                 goto connect_again;
1007         }
1008
1009         if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
1010                         errno == EAGAIN)) {
1011                 DEBUG(1,("timeout connecting to %s:%d\n",
1012                                         inet_ntoa(*addr),port));
1013                 close(res);
1014                 return -1;
1015         }
1016
1017 #ifdef EISCONN
1018         if (ret < 0 && errno == EISCONN) {
1019                 errno = 0;
1020                 ret = 0;
1021         }
1022 #endif
1023
1024         if (ret < 0) {
1025                 DEBUG(2,("error connecting to %s:%d (%s)\n",
1026                                 inet_ntoa(*addr),port,strerror(errno)));
1027                 close(res);
1028                 return -1;
1029         }
1030
1031         /* set it blocking again */
1032         set_blocking(res,True);
1033
1034         return res;
1035 }
1036
1037 /****************************************************************************
1038  Create an outgoing TCP socket to any of the addrs. This is for
1039  simultaneous connects to port 445 and 139 of a host or even a variety
1040  of DC's all of which are equivalent for our purposes.
1041 **************************************************************************/
1042
1043 BOOL open_any_socket_out(struct sockaddr_in *addrs, int num_addrs,
1044                          int timeout, int *fd_index, int *fd)
1045 {
1046         int i, resulting_index, res;
1047         int *sockets;
1048         BOOL good_connect;
1049
1050         fd_set r_fds, wr_fds;
1051         struct timeval tv;
1052         int maxfd;
1053
1054         int connect_loop = 10000; /* 10 milliseconds */
1055
1056         timeout *= 1000;        /* convert to microseconds */
1057
1058         sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1059
1060         if (sockets == NULL)
1061                 return False;
1062
1063         resulting_index = -1;
1064
1065         for (i=0; i<num_addrs; i++)
1066                 sockets[i] = -1;
1067
1068         for (i=0; i<num_addrs; i++) {
1069                 sockets[i] = socket(PF_INET, SOCK_STREAM, 0);
1070                 if (sockets[i] < 0)
1071                         goto done;
1072                 set_blocking(sockets[i], False);
1073         }
1074
1075  connect_again:
1076         good_connect = False;
1077
1078         for (i=0; i<num_addrs; i++) {
1079
1080                 if (sockets[i] == -1)
1081                         continue;
1082
1083                 if (connect(sockets[i], (struct sockaddr *)&(addrs[i]),
1084                             sizeof(*addrs)) == 0) {
1085                         /* Rather unlikely as we are non-blocking, but it
1086                          * might actually happen. */
1087                         resulting_index = i;
1088                         goto done;
1089                 }
1090
1091                 if (errno == EINPROGRESS || errno == EALREADY ||
1092 #ifdef EISCONN
1093                         errno == EISCONN ||
1094 #endif
1095                     errno == EAGAIN || errno == EINTR) {
1096                         /* These are the error messages that something is
1097                            progressing. */
1098                         good_connect = True;
1099                 } else if (errno != 0) {
1100                         /* There was a direct error */
1101                         close(sockets[i]);
1102                         sockets[i] = -1;
1103                 }
1104         }
1105
1106         if (!good_connect) {
1107                 /* All of the connect's resulted in real error conditions */
1108                 goto done;
1109         }
1110
1111         /* Lets see if any of the connect attempts succeeded */
1112
1113         maxfd = 0;
1114         FD_ZERO(&wr_fds);
1115         FD_ZERO(&r_fds);
1116
1117         for (i=0; i<num_addrs; i++) {
1118                 if (sockets[i] == -1)
1119                         continue;
1120                 FD_SET(sockets[i], &wr_fds);
1121                 FD_SET(sockets[i], &r_fds);
1122                 if (sockets[i]>maxfd)
1123                         maxfd = sockets[i];
1124         }
1125
1126         tv.tv_sec = 0;
1127         tv.tv_usec = connect_loop;
1128
1129         res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1130
1131         if (res < 0)
1132                 goto done;
1133
1134         if (res == 0)
1135                 goto next_round;
1136
1137         for (i=0; i<num_addrs; i++) {
1138
1139                 if (sockets[i] == -1)
1140                         continue;
1141
1142                 /* Stevens, Network Programming says that if there's a
1143                  * successful connect, the socket is only writable. Upon an
1144                  * error, it's both readable and writable. */
1145
1146                 if (FD_ISSET(sockets[i], &r_fds) &&
1147                     FD_ISSET(sockets[i], &wr_fds)) {
1148                         /* readable and writable, so it's an error */
1149                         close(sockets[i]);
1150                         sockets[i] = -1;
1151                         continue;
1152                 }
1153
1154                 if (!FD_ISSET(sockets[i], &r_fds) &&
1155                     FD_ISSET(sockets[i], &wr_fds)) {
1156                         /* Only writable, so it's connected */
1157                         resulting_index = i;
1158                         goto done;
1159                 }
1160         }
1161
1162  next_round:
1163
1164         timeout -= connect_loop;
1165         if (timeout <= 0)
1166                 goto done;
1167         connect_loop *= 1.5;
1168         if (connect_loop > timeout)
1169                 connect_loop = timeout;
1170         goto connect_again;
1171
1172  done:
1173         for (i=0; i<num_addrs; i++) {
1174                 if (i == resulting_index)
1175                         continue;
1176                 if (sockets[i] >= 0)
1177                         close(sockets[i]);
1178         }
1179
1180         if (resulting_index >= 0) {
1181                 *fd_index = resulting_index;
1182                 *fd = sockets[*fd_index];
1183                 set_blocking(*fd, True);
1184         }
1185
1186         free(sockets);
1187
1188         return (resulting_index >= 0);
1189 }
1190 /****************************************************************************
1191  Open a connected UDP socket to host on port
1192 **************************************************************************/
1193
1194 int open_udp_socket(const char *host, int port)
1195 {
1196         int type = SOCK_DGRAM;
1197         struct sockaddr_in sock_out;
1198         int res;
1199         struct in_addr *addr;
1200
1201         addr = interpret_addr2(host);
1202
1203         res = socket(PF_INET, type, 0);
1204         if (res == -1) {
1205                 return -1;
1206         }
1207
1208         memset((char *)&sock_out,'\0',sizeof(sock_out));
1209         putip((char *)&sock_out.sin_addr,(char *)addr);
1210         sock_out.sin_port = htons(port);
1211         sock_out.sin_family = PF_INET;
1212
1213         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
1214                 close(res);
1215                 return -1;
1216         }
1217
1218         return res;
1219 }
1220
1221 /*******************************************************************
1222  Matchname - determine if host name matches IP address. Used to
1223  confirm a hostname lookup to prevent spoof attacks.
1224 ******************************************************************/
1225
1226 static BOOL matchname(char *remotehost,struct in_addr  addr)
1227 {
1228         struct hostent *hp;
1229         int     i;
1230
1231         if ((hp = sys_gethostbyname(remotehost)) == 0) {
1232                 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n",
1233                                         remotehost));
1234                 return False;
1235         }
1236
1237         /*
1238          * Make sure that gethostbyname() returns the "correct" host name.
1239          * Unfortunately, gethostbyname("localhost") sometimes yields
1240          * "localhost.domain". Since the latter host name comes from the
1241          * local DNS, we just have to trust it (all bets are off if the local
1242          * DNS is perverted). We always check the address list, though.
1243          */
1244
1245         if (!strequal(remotehost, hp->h_name)
1246             && !strequal(remotehost, "localhost")) {
1247                 DEBUG(0,("host name/name mismatch: %s != %s\n",
1248                          remotehost, hp->h_name));
1249                 return False;
1250         }
1251
1252         /* Look up the host address in the address list we just got. */
1253         for (i = 0; hp->h_addr_list[i]; i++) {
1254                 if (memcmp(hp->h_addr_list[i], (char *)&addr,sizeof(addr)) == 0)
1255                         return True;
1256         }
1257
1258         /*
1259          * The host name does not map to the original host address. Perhaps
1260          * someone has compromised a name server. More likely someone botched
1261          * it, but that could be dangerous, too.
1262          */
1263
1264         DEBUG(0,("host name/address mismatch: %s != %s\n",
1265                  inet_ntoa(addr), hp->h_name));
1266         return False;
1267 }
1268
1269 /*******************************************************************
1270  Return the DNS name of the remote end of a socket.
1271 ******************************************************************/
1272
1273 char *get_peer_name(int fd, BOOL force_lookup)
1274 {
1275         static pstring name_buf;
1276         pstring tmp_name;
1277         static fstring addr_buf;
1278         struct hostent *hp;
1279         struct in_addr addr;
1280         char *p;
1281
1282         /* reverse lookups can be *very* expensive, and in many
1283            situations won't work because many networks don't link dhcp
1284            with dns. To avoid the delay we avoid the lookup if
1285            possible */
1286         if (!lp_hostname_lookups() && (force_lookup == False)) {
1287                 return get_peer_addr(fd);
1288         }
1289
1290         p = get_peer_addr(fd);
1291
1292         /* it might be the same as the last one - save some DNS work */
1293         if (strcmp(p, addr_buf) == 0)
1294                 return name_buf;
1295
1296         pstrcpy(name_buf,"UNKNOWN");
1297         if (fd == -1)
1298                 return name_buf;
1299
1300         fstrcpy(addr_buf, p);
1301
1302         addr = *interpret_addr2(p);
1303
1304         /* Look up the remote host name. */
1305         if ((hp = gethostbyaddr((char *)&addr.s_addr,
1306                                         sizeof(addr.s_addr), AF_INET)) == 0) {
1307                 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1308                 pstrcpy(name_buf, p);
1309         } else {
1310                 pstrcpy(name_buf,(char *)hp->h_name);
1311                 if (!matchname(name_buf, addr)) {
1312                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1313                         pstrcpy(name_buf,"UNKNOWN");
1314                 }
1315         }
1316
1317         /* can't pass the same source and dest strings in when you
1318            use --enable-developer or the clobber_region() call will
1319            get you */
1320
1321         pstrcpy( tmp_name, name_buf );
1322         alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1323         if (strstr(name_buf,"..")) {
1324                 pstrcpy(name_buf, "UNKNOWN");
1325         }
1326
1327         return name_buf;
1328 }
1329
1330 /*******************************************************************
1331  Return the IP addr of the remote end of a socket as a string.
1332  ******************************************************************/
1333
1334 char *get_peer_addr(int fd)
1335 {
1336         struct sockaddr sa;
1337         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1338         socklen_t length = sizeof(sa);
1339         static fstring addr_buf;
1340
1341         fstrcpy(addr_buf,"0.0.0.0");
1342
1343         if (fd == -1) {
1344                 return addr_buf;
1345         }
1346
1347         if (getpeername(fd, &sa, &length) < 0) {
1348                 DEBUG(0,("getpeername failed. Error was %s\n",
1349                                         strerror(errno) ));
1350                 return addr_buf;
1351         }
1352
1353         fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1354
1355         return addr_buf;
1356 }
1357
1358 /*******************************************************************
1359  Create protected unix domain socket.
1360
1361  Some unixes cannot set permissions on a ux-dom-sock, so we
1362  have to make sure that the directory contains the protection
1363  permissions instead.
1364  ******************************************************************/
1365
1366 int create_pipe_sock(const char *socket_dir,
1367                      const char *socket_name,
1368                      mode_t dir_perms)
1369 {
1370 #ifdef HAVE_UNIXSOCKET
1371         struct sockaddr_un sunaddr;
1372         struct stat st;
1373         int sock;
1374         mode_t old_umask;
1375         pstring path;
1376
1377         old_umask = umask(0);
1378
1379         /* Create the socket directory or reuse the existing one */
1380
1381         if (lstat(socket_dir, &st) == -1) {
1382                 if (errno == ENOENT) {
1383                         /* Create directory */
1384                         if (mkdir(socket_dir, dir_perms) == -1) {
1385                                 DEBUG(0, ("error creating socket directory "
1386                                         "%s: %s\n", socket_dir,
1387                                         strerror(errno)));
1388                                 goto out_umask;
1389                         }
1390                 } else {
1391                         DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1392                                 socket_dir, strerror(errno)));
1393                         goto out_umask;
1394                 }
1395         } else {
1396                 /* Check ownership and permission on existing directory */
1397                 if (!S_ISDIR(st.st_mode)) {
1398                         DEBUG(0, ("socket directory %s isn't a directory\n",
1399                                 socket_dir));
1400                         goto out_umask;
1401                 }
1402                 if ((st.st_uid != sec_initial_uid()) ||
1403                                 ((st.st_mode & 0777) != dir_perms)) {
1404                         DEBUG(0, ("invalid permissions on socket directory "
1405                                 "%s\n", socket_dir));
1406                         goto out_umask;
1407                 }
1408         }
1409
1410         /* Create the socket file */
1411
1412         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1413
1414         if (sock == -1) {
1415                 perror("socket");
1416                 goto out_umask;
1417         }
1418
1419         pstr_sprintf(path, "%s/%s", socket_dir, socket_name);
1420
1421         unlink(path);
1422         memset(&sunaddr, 0, sizeof(sunaddr));
1423         sunaddr.sun_family = AF_UNIX;
1424         safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1425
1426         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1427                 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1428                         strerror(errno)));
1429                 goto out_close;
1430         }
1431
1432         if (listen(sock, 5) == -1) {
1433                 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1434                         strerror(errno)));
1435                 goto out_close;
1436         }
1437
1438         umask(old_umask);
1439         return sock;
1440
1441 out_close:
1442         close(sock);
1443
1444 out_umask:
1445         umask(old_umask);
1446         return -1;
1447
1448 #else
1449         DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1450         return -1;
1451 #endif /* HAVE_UNIXSOCKET */
1452 }