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