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