First cut at fix for the EINTR problem... More needs to be done I think.
[tprouty/samba.git] / source / lib / util_sock.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Tim Potter      2000-2001
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 #ifdef WITH_SSL
25 #include <openssl/ssl.h>
26 #undef Realloc  /* SSLeay defines this and samba has a function of this name */
27 extern SSL  *ssl;
28 extern int  sslFd;
29 #endif  /* WITH_SSL */
30
31 /* the last IP received from */
32 struct in_addr lastip;
33
34 /* the last port received from */
35 int lastport=0;
36
37 int smb_read_error = 0;
38
39 /****************************************************************************
40  Determine if a file descriptor is in fact a socket.
41 ****************************************************************************/
42
43 BOOL is_a_socket(int fd)
44 {
45   int v,l;
46   l = sizeof(int);
47   return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
48 }
49
50 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
51
52 typedef struct smb_socket_option
53 {
54   char *name;
55   int level;
56   int option;
57   int value;
58   int opttype;
59 } smb_socket_option;
60
61 smb_socket_option socket_options[] = {
62   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
63   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
64   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
65 #ifdef TCP_NODELAY
66   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
67 #endif
68 #ifdef IPTOS_LOWDELAY
69   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
70 #endif
71 #ifdef IPTOS_THROUGHPUT
72   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
73 #endif
74 #ifdef SO_REUSEPORT
75   {"SO_REUSEPORT",      SOL_SOCKET,    SO_REUSEPORT,    0,                 OPT_BOOL},
76 #endif
77 #ifdef SO_SNDBUF
78   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
79 #endif
80 #ifdef SO_RCVBUF
81   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
82 #endif
83 #ifdef SO_SNDLOWAT
84   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
85 #endif
86 #ifdef SO_RCVLOWAT
87   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
88 #endif
89 #ifdef SO_SNDTIMEO
90   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
91 #endif
92 #ifdef SO_RCVTIMEO
93   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
94 #endif
95   {NULL,0,0,0,0}};
96
97 /****************************************************************************
98  Print socket options.
99 ****************************************************************************/
100 static void print_socket_options(int s)
101 {
102         int value, vlen = 4;
103         smb_socket_option *p = &socket_options[0];
104
105         for (; p->name != NULL; p++) {
106                 if (getsockopt(s, p->level, p->option, (void *)&value, &vlen) == -1) {
107                         DEBUG(5,("Could not test socket option %s.\n", p->name));
108                 } else {
109                         DEBUG(5,("socket option %s = %d\n",p->name,value));
110                 }
111         }
112  }
113
114 /****************************************************************************
115  Set user socket options.
116 ****************************************************************************/
117
118 void set_socket_options(int fd, char *options)
119 {
120         fstring tok;
121
122         while (next_token(&options,tok," \t,", sizeof(tok))) {
123                 int ret=0,i;
124                 int value = 1;
125                 char *p;
126                 BOOL got_value = False;
127
128                 if ((p = strchr_m(tok,'='))) {
129                         *p = 0;
130                         value = atoi(p+1);
131                         got_value = True;
132                 }
133
134                 for (i=0;socket_options[i].name;i++)
135                         if (strequal(socket_options[i].name,tok))
136                                 break;
137
138                 if (!socket_options[i].name) {
139                         DEBUG(0,("Unknown socket option %s\n",tok));
140                         continue;
141                 }
142
143                 switch (socket_options[i].opttype) {
144                 case OPT_BOOL:
145                 case OPT_INT:
146                         ret = setsockopt(fd,socket_options[i].level,
147                                                 socket_options[i].option,(char *)&value,sizeof(int));
148                         break;
149
150                 case OPT_ON:
151                         if (got_value)
152                                 DEBUG(0,("syntax error - %s does not take a value\n",tok));
153
154                         {
155                                 int on = socket_options[i].value;
156                                 ret = setsockopt(fd,socket_options[i].level,
157                                                         socket_options[i].option,(char *)&on,sizeof(int));
158                         }
159                         break;    
160                 }
161       
162                 if (ret != 0)
163                         DEBUG(0,("Failed to set socket option %s (Error %s)\n",tok, strerror(errno) ));
164         }
165
166         print_socket_options(fd);
167 }
168
169 /****************************************************************************
170  Read from a socket.
171 ****************************************************************************/
172
173 ssize_t read_udp_socket(int fd,char *buf,size_t len)
174 {
175         ssize_t ret;
176         struct sockaddr_in sock;
177         socklen_t socklen = sizeof(sock);
178
179         memset((char *)&sock,'\0',socklen);
180         memset((char *)&lastip,'\0',sizeof(lastip));
181         ret = (ssize_t)recvfrom(fd,buf,len,0,(struct sockaddr *)&sock,&socklen);
182         if (ret <= 0) {
183                 DEBUG(2,("read socket failed. ERRNO=%s\n",strerror(errno)));
184                 return(0);
185         }
186
187         lastip = sock.sin_addr;
188         lastport = ntohs(sock.sin_port);
189
190         DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %d\n",
191                         inet_ntoa(lastip), lastport, ret));
192
193         return(ret);
194 }
195
196 /*******************************************************************
197  checks if read data is outstanding.
198  ********************************************************************/
199 int read_data_outstanding(int fd, unsigned int time_out)
200 {
201         int selrtn;
202         fd_set fds;
203         struct timeval timeout;
204
205         FD_ZERO(&fds);
206         FD_SET(fd, &fds);
207
208         timeout.tv_sec = (time_t) (time_out / 1000);
209         timeout.tv_usec = (long)(1000 * (time_out % 1000));
210
211         selrtn = sys_select_intr(fd + 1, &fds, NULL, NULL, &timeout);
212
213         if (selrtn <= 0)
214         {
215                 return selrtn;
216         }
217         return FD_ISSET(fd, &fds) ? 1 : 0;
218 }
219
220 /****************************************************************************
221  Read data from a socket with a timout in msec.
222  mincount = if timeout, minimum to read before returning
223  maxcount = number to be read.
224  time_out = timeout in milliseconds
225 ****************************************************************************/
226
227 static ssize_t read_socket_with_timeout(int fd,char *buf,size_t mincnt,size_t maxcnt,unsigned int time_out)
228 {
229         fd_set fds;
230         int selrtn;
231         ssize_t readret;
232         size_t nread = 0;
233         struct timeval timeout;
234         
235         /* just checking .... */
236         if (maxcnt <= 0)
237                 return(0);
238         
239         smb_read_error = 0;
240         
241         /* Blocking read */
242         if (time_out <= 0) {
243                 if (mincnt == 0) mincnt = maxcnt;
244                 
245                 while (nread < mincnt) {
246 #ifdef WITH_SSL
247                         if (fd == sslFd) {
248                                 readret = SSL_read(ssl, buf + nread, maxcnt - nread);
249                         } else {
250                                 readret = sys_read(fd, buf + nread, maxcnt - nread);
251                         }
252 #else /* WITH_SSL */
253                         readret = sys_read(fd, buf + nread, maxcnt - nread);
254 #endif /* WITH_SSL */
255                         
256                         if (readret == 0) {
257                                 DEBUG(5,("read_socket_with_timeout: blocking read. EOF from client.\n"));
258                                 smb_read_error = READ_EOF;
259                                 return -1;
260                         }
261                         
262                         if (readret == -1) {
263                                 DEBUG(0,("read_socket_with_timeout: read error = %s.\n", strerror(errno) ));
264                                 smb_read_error = READ_ERROR;
265                                 return -1;
266                         }
267                         nread += readret;
268                 }
269                 return((ssize_t)nread);
270         }
271         
272         /* Most difficult - timeout read */
273         /* If this is ever called on a disk file and 
274            mincnt is greater then the filesize then
275            system performance will suffer severely as 
276            select always returns true on disk files */
277         
278         /* Set initial timeout */
279         timeout.tv_sec = (time_t)(time_out / 1000);
280         timeout.tv_usec = (long)(1000 * (time_out % 1000));
281         
282         for (nread=0; nread < mincnt; ) {      
283                 FD_ZERO(&fds);
284                 FD_SET(fd,&fds);
285                 
286                 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
287                 
288                 /* Check if error */
289                 if (selrtn == -1) {
290                         /* something is wrong. Maybe the socket is dead? */
291                         DEBUG(0,("read_socket_with_timeout: timeout read. select error = %s.\n", strerror(errno) ));
292                         smb_read_error = READ_ERROR;
293                         return -1;
294                 }
295                 
296                 /* Did we timeout ? */
297                 if (selrtn == 0) {
298                         DEBUG(10,("read_socket_with_timeout: timeout read. select timed out.\n"));
299                         smb_read_error = READ_TIMEOUT;
300                         return -1;
301                 }
302                 
303 #ifdef WITH_SSL
304                 if (fd == sslFd) {
305                         readret = SSL_read(ssl, buf + nread, maxcnt - nread);
306                 }else{
307                         readret = sys_read(fd, buf + nread, maxcnt - nread);
308                 }
309 #else /* WITH_SSL */
310                 readret = sys_read(fd, buf+nread, maxcnt-nread);
311 #endif /* WITH_SSL */
312                 
313                 if (readret == 0) {
314                         /* we got EOF on the file descriptor */
315                         DEBUG(5,("read_socket_with_timeout: timeout read. EOF from client.\n"));
316                         smb_read_error = READ_EOF;
317                         return -1;
318                 }
319                 
320                 if (readret == -1) {
321                         /* the descriptor is probably dead */
322                         DEBUG(0,("read_socket_with_timeout: timeout read. read error = %s.\n", strerror(errno) ));
323                         smb_read_error = READ_ERROR;
324                         return -1;
325                 }
326                 
327                 nread += readret;
328         }
329         
330         /* Return the number we got */
331         return (ssize_t)nread;
332 }
333
334 /****************************************************************************
335  Read data from a fd with a timout in msec.
336  mincount = if timeout, minimum to read before returning
337  maxcount = number to be read.
338  time_out = timeout in milliseconds
339 ****************************************************************************/
340
341 ssize_t read_with_timeout(int fd, char *buf, size_t mincnt, size_t maxcnt,
342                           unsigned int time_out)
343 {
344         ssize_t readret;
345         size_t nread = 0;
346         
347         /* just checking .... */
348         if (maxcnt <= 0)
349                 return(0);
350         
351         /* Blocking read */
352         if (time_out <= 0) {
353                 if (mincnt == 0) mincnt = maxcnt;
354                 
355                 while (nread < mincnt) {
356 #ifdef WITH_SSL
357                         if(fd == sslFd){
358                                 readret = SSL_read(ssl, buf + nread, maxcnt - nread);
359                         }else{
360                                 readret = sys_read(fd, buf + nread, maxcnt - nread);
361                         }
362 #else /* WITH_SSL */
363                         readret = sys_read(fd, buf + nread, maxcnt - nread);
364 #endif /* WITH_SSL */
365                         
366                         if (readret <= 0)
367                                 return readret;
368                         
369                         nread += readret;
370                 }
371                 return((ssize_t)nread);
372         }
373         
374         /* Most difficult - timeout read */
375         /* If this is ever called on a disk file and 
376            mincnt is greater then the filesize then
377            system performance will suffer severely as 
378            select always returns true on disk files */
379         
380         for (nread=0; nread < mincnt; ) {      
381                 int selrtn = read_data_outstanding(fd, time_out);
382                 
383                 if(selrtn <= 0)
384                         return selrtn;
385                 
386 #ifdef WITH_SSL
387                 if(fd == sslFd){
388                         readret = SSL_read(ssl, buf + nread, maxcnt - nread);
389                 }else{
390                         readret = sys_read(fd, buf + nread, maxcnt - nread);
391                 }
392 #else /* WITH_SSL */
393                 readret = sys_read(fd, buf+nread, maxcnt-nread);
394 #endif /* WITH_SSL */
395                 
396                 if (readret <= 0)
397                         return readret;
398                 
399                 nread += readret;
400         }
401         
402         /* Return the number we got */
403         return((ssize_t)nread);
404 }
405
406 /****************************************************************************
407 send a keepalive packet (rfc1002)
408 ****************************************************************************/
409
410 BOOL send_keepalive(int client)
411 {
412         unsigned char buf[4];
413
414         buf[0] = SMBkeepalive;
415         buf[1] = buf[2] = buf[3] = 0;
416
417         return(write_socket_data(client,(char *)buf,4) == 4);
418 }
419
420 /****************************************************************************
421   read data from the client, reading exactly N bytes. 
422 ****************************************************************************/
423
424 ssize_t read_data(int fd,char *buffer,size_t N)
425 {
426         ssize_t ret;
427         size_t total=0;  
428  
429         smb_read_error = 0;
430
431         while (total < N) {
432 #ifdef WITH_SSL
433                 if(fd == sslFd){
434                         ret = SSL_read(ssl, buffer + total, N - total);
435                 }else{
436                         ret = sys_read(fd,buffer + total,N - total);
437                 }
438 #else /* WITH_SSL */
439                 ret = sys_read(fd,buffer + total,N - total);
440 #endif /* WITH_SSL */
441
442                 if (ret == 0) {
443                         DEBUG(10,("read_data: read of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
444                         smb_read_error = READ_EOF;
445                         return 0;
446                 }
447
448                 if (ret == -1) {
449                         DEBUG(0,("read_data: read failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
450                         smb_read_error = READ_ERROR;
451                         return -1;
452                 }
453                 total += ret;
454         }
455         return (ssize_t)total;
456 }
457
458 /****************************************************************************
459  Read data from a socket, reading exactly N bytes. 
460 ****************************************************************************/
461
462 static ssize_t read_socket_data(int fd,char *buffer,size_t N)
463 {
464         ssize_t ret;
465         size_t total=0;  
466  
467         smb_read_error = 0;
468
469         while (total < N) {
470 #ifdef WITH_SSL
471                 if(fd == sslFd){
472                         ret = SSL_read(ssl, buffer + total, N - total);
473                 }else{
474                         ret = sys_read(fd,buffer + total,N - total);
475     }
476 #else /* WITH_SSL */
477                 ret = sys_read(fd,buffer + total,N - total);
478 #endif /* WITH_SSL */
479
480                 if (ret == 0) {
481                         DEBUG(10,("read_socket_data: recv of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
482                         smb_read_error = READ_EOF;
483                         return 0;
484                 }
485
486                 if (ret == -1) {
487                         DEBUG(0,("read_socket_data: recv failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
488                         smb_read_error = READ_ERROR;
489                         return -1;
490                 }
491                 total += ret;
492         }
493         return (ssize_t)total;
494 }
495
496 /****************************************************************************
497  Write data to a fd.
498 ****************************************************************************/
499
500 ssize_t write_data(int fd,char *buffer,size_t N)
501 {
502         size_t total=0;
503         ssize_t ret;
504
505         while (total < N) {
506 #ifdef WITH_SSL
507                 if(fd == sslFd){
508                         ret = SSL_write(ssl,buffer + total,N - total);
509                 }else{
510                         ret = sys_write(fd,buffer + total,N - total);
511                 }
512 #else /* WITH_SSL */
513                 ret = sys_write(fd,buffer + total,N - total);
514 #endif /* WITH_SSL */
515
516                 if (ret == -1) {
517                         DEBUG(0,("write_data: write failure. Error = %s\n", strerror(errno) ));
518                         return -1;
519                 }
520                 if (ret == 0)
521                         return total;
522
523                 total += ret;
524         }
525         return (ssize_t)total;
526 }
527
528 /****************************************************************************
529  Write data to a socket - use send rather than write.
530 ****************************************************************************/
531
532 ssize_t write_socket_data(int fd,char *buffer,size_t N)
533 {
534         size_t total=0;
535         ssize_t ret;
536
537         while (total < N) {
538 #ifdef WITH_SSL
539                 if(fd == sslFd){
540                         ret = SSL_write(ssl,buffer + total,N - total);
541                 }else{
542                         ret = sys_send(fd,buffer + total,N - total, 0);
543     }
544 #else /* WITH_SSL */
545                 ret = sys_send(fd,buffer + total,N - total,0);
546 #endif /* WITH_SSL */
547
548                 if (ret == -1) {
549                         DEBUG(0,("write_socket_data: write failure. Error = %s\n", strerror(errno) ));
550                         return -1;
551                 }
552                 if (ret == 0)
553                         return total;
554
555                 total += ret;
556         }
557         return (ssize_t)total;
558 }
559
560 /****************************************************************************
561 write to a socket
562 ****************************************************************************/
563
564 ssize_t write_socket(int fd,char *buf,size_t len)
565 {
566         ssize_t ret=0;
567
568         DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
569         ret = write_socket_data(fd,buf,len);
570       
571         DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
572         if(ret <= 0)
573                 DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n", 
574                         (int)len, fd, strerror(errno) ));
575
576         return(ret);
577 }
578
579 /****************************************************************************
580 read 4 bytes of a smb packet and return the smb length of the packet
581 store the result in the buffer
582 This version of the function will return a length of zero on receiving
583 a keepalive packet.
584 timeout is in milliseconds.
585 ****************************************************************************/
586
587 static ssize_t read_smb_length_return_keepalive(int fd,char *inbuf,unsigned int timeout)
588 {
589         ssize_t len=0;
590         int msg_type;
591         BOOL ok = False;
592
593         while (!ok) {
594                 if (timeout > 0)
595                         ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout) == 4);
596                 else 
597                         ok = (read_socket_data(fd,inbuf,4) == 4);
598
599                 if (!ok)
600                         return(-1);
601
602                 len = smb_len(inbuf);
603                 msg_type = CVAL(inbuf,0);
604
605                 if (msg_type == SMBkeepalive) 
606                         DEBUG(5,("Got keepalive packet\n"));
607         }
608
609         DEBUG(10,("got smb length of %d\n",len));
610
611         return(len);
612 }
613
614 /****************************************************************************
615 read 4 bytes of a smb packet and return the smb length of the packet
616 store the result in the buffer. This version of the function will
617 never return a session keepalive (length of zero).
618 timeout is in milliseconds.
619 ****************************************************************************/
620
621 ssize_t read_smb_length(int fd,char *inbuf,unsigned int timeout)
622 {
623         ssize_t len;
624
625         for(;;) {
626                 len = read_smb_length_return_keepalive(fd, inbuf, timeout);
627
628                 if(len < 0)
629                         return len;
630
631                 /* Ignore session keepalives. */
632                 if(CVAL(inbuf,0) != SMBkeepalive)
633                         break;
634         }
635
636         DEBUG(10,("read_smb_length: got smb length of %d\n",len));
637
638         return len;
639 }
640
641 /****************************************************************************
642   read an smb from a fd. Note that the buffer *MUST* be of size
643   BUFFER_SIZE+SAFETY_MARGIN.
644   The timeout is in milliseconds. 
645   This function will return on a
646   receipt of a session keepalive packet.
647 ****************************************************************************/
648
649 BOOL receive_smb(int fd,char *buffer, unsigned int timeout)
650 {
651         ssize_t len,ret;
652
653         smb_read_error = 0;
654
655         memset(buffer,'\0',smb_size + 100);
656
657         len = read_smb_length_return_keepalive(fd,buffer,timeout);
658         if (len < 0) {
659                 DEBUG(10,("receive_smb: length < 0!\n"));
660
661                 /*
662                  * Correct fix. smb_read_error may have already been
663                  * set. Only set it here if not already set. Global
664                  * variables still suck :-). JRA.
665                  */
666
667                 if (smb_read_error == 0)
668                         smb_read_error = READ_ERROR;
669                 return False;
670         }
671
672         /*
673          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
674          * of header. Don't print the error if this fits.... JRA.
675          */
676
677         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
678                 DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
679                 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
680
681                         /*
682                          * Correct fix. smb_read_error may have already been
683                          * set. Only set it here if not already set. Global
684                          * variables still suck :-). JRA.
685                          */
686
687                         if (smb_read_error == 0)
688                                 smb_read_error = READ_ERROR;
689                         return False;
690                 }
691         }
692
693         if(len > 0) {
694                 ret = read_socket_data(fd,buffer+4,len);
695                 if (ret != len) {
696                         if (smb_read_error == 0)
697                                 smb_read_error = READ_ERROR;
698                         return False;
699                 }
700         }
701
702         return(True);
703 }
704
705 /****************************************************************************
706   read an smb from a fd ignoring all keepalive packets. Note that the buffer 
707   *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
708   The timeout is in milliseconds
709
710   This is exactly the same as receive_smb except that it never returns
711   a session keepalive packet (just as receive_smb used to do).
712   receive_smb was changed to return keepalives as the oplock processing means this call
713   should never go into a blocking read.
714 ****************************************************************************/
715
716 BOOL client_receive_smb(int fd,char *buffer, unsigned int timeout)
717 {
718   BOOL ret;
719
720   for(;;)
721   {
722     ret = receive_smb(fd, buffer, timeout);
723
724     if (!ret)
725     {
726       DEBUG(10,("client_receive_smb failed\n"));
727       show_msg(buffer);
728       return ret;
729     }
730
731     /* Ignore session keepalive packets. */
732     if(CVAL(buffer,0) != SMBkeepalive)
733       break;
734   }
735   show_msg(buffer);
736   return ret;
737 }
738
739 /****************************************************************************
740   send an smb to a fd 
741 ****************************************************************************/
742
743 BOOL send_smb(int fd,char *buffer)
744 {
745         size_t len;
746         size_t nwritten=0;
747         ssize_t ret;
748         len = smb_len(buffer) + 4;
749
750         while (nwritten < len) {
751                 ret = write_socket(fd,buffer+nwritten,len - nwritten);
752                 if (ret <= 0) {
753                         DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
754                                 (int)len,(int)ret, strerror(errno) ));
755                         return False;
756                 }
757                 nwritten += ret;
758         }
759
760         return True;
761 }
762
763 /****************************************************************************
764 send a single packet to a port on another machine
765 ****************************************************************************/
766
767 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
768 {
769   BOOL ret;
770   int out_fd;
771   struct sockaddr_in sock_out;
772
773   /* create a socket to write to */
774   out_fd = socket(AF_INET, type, 0);
775   if (out_fd == -1) 
776     {
777       DEBUG(0,("socket failed"));
778       return False;
779     }
780
781   /* set the address and port */
782   memset((char *)&sock_out,'\0',sizeof(sock_out));
783   putip((char *)&sock_out.sin_addr,(char *)&ip);
784   sock_out.sin_port = htons( port );
785   sock_out.sin_family = AF_INET;
786   
787   if (DEBUGLEVEL > 0)
788     DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
789              len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
790         
791   /* send it */
792   ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
793
794   if (!ret)
795     DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
796              inet_ntoa(ip),port,strerror(errno)));
797
798   close(out_fd);
799   return(ret);
800 }
801
802 /****************************************************************************
803  Open a socket of the specified type, port, and address for incoming data.
804 ****************************************************************************/
805
806 int open_socket_in( int type, int port, int dlevel, uint32 socket_addr, BOOL rebind )
807 {
808         struct sockaddr_in sock;
809         int res;
810
811         memset( (char *)&sock, '\0', sizeof(sock) );
812
813 #ifdef HAVE_SOCK_SIN_LEN
814         sock.sin_len         = sizeof(sock);
815 #endif
816         sock.sin_port        = htons( port );
817         sock.sin_family      = AF_INET;
818         sock.sin_addr.s_addr = socket_addr;
819
820         res = socket( AF_INET, type, 0 );
821         if( res == -1 ) {
822                 if( DEBUGLVL(0) ) {
823                         dbgtext( "open_socket_in(): socket() call failed: " );
824                         dbgtext( "%s\n", strerror( errno ) );
825                 }
826                 return -1;
827         }
828
829         /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
830         {
831                 int val = rebind ? 1 : 0;
832                 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val)) == -1 ) {
833                         if( DEBUGLVL( dlevel ) ) {
834                                 dbgtext( "open_socket_in(): setsockopt: " );
835                                 dbgtext( "SO_REUSEADDR = %s ", val?"True":"False" );
836                                 dbgtext( "on port %d failed ", port );
837                                 dbgtext( "with error = %s\n", strerror(errno) );
838                         }
839                 }
840 #ifdef SO_REUSEPORT
841                 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,(char *)&val,sizeof(val)) == -1 ) {
842                         if( DEBUGLVL( dlevel ) ) {
843                                 dbgtext( "open_socket_in(): setsockopt: ");
844                                 dbgtext( "SO_REUSEPORT = %s ", val?"True":"False" );
845                                 dbgtext( "on port %d failed ", port );
846                                 dbgtext( "with error = %s\n", strerror(errno) );
847                         }
848                 }
849 #endif /* SO_REUSEPORT */
850         }
851
852         /* now we've got a socket - we need to bind it */
853         if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
854                 if( DEBUGLVL(dlevel) && (port == SMB_PORT || port == NMB_PORT) ) {
855                         dbgtext( "bind failed on port %d ", port );
856                         dbgtext( "socket_addr = %s.\n", inet_ntoa( sock.sin_addr ) );
857                         dbgtext( "Error = %s\n", strerror(errno) );
858                 }
859                 close( res ); 
860                 return( -1 ); 
861         }
862
863         DEBUG( 3, ( "bind succeeded on port %d\n", port ) );
864
865         return( res );
866  }
867
868 /****************************************************************************
869   create an outgoing socket. timeout is in milliseconds.
870   **************************************************************************/
871
872 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
873 {
874   struct sockaddr_in sock_out;
875   int res,ret;
876   int connect_loop = 250; /* 250 milliseconds */
877   int loops = (timeout) / connect_loop;
878
879   /* create a socket to write to */
880   res = socket(PF_INET, type, 0);
881   if (res == -1) 
882     { DEBUG(0,("socket error\n")); return -1; }
883
884   if (type != SOCK_STREAM) return(res);
885   
886   memset((char *)&sock_out,'\0',sizeof(sock_out));
887   putip((char *)&sock_out.sin_addr,(char *)addr);
888   
889   sock_out.sin_port = htons( port );
890   sock_out.sin_family = PF_INET;
891
892   /* set it non-blocking */
893   set_blocking(res,False);
894
895   DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
896   
897   /* and connect it to the destination */
898 connect_again:
899   ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
900
901   /* Some systems return EAGAIN when they mean EINPROGRESS */
902   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
903         errno == EAGAIN) && loops--) {
904     msleep(connect_loop);
905     goto connect_again;
906   }
907
908   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
909          errno == EAGAIN)) {
910       DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
911       close(res);
912       return -1;
913   }
914
915 #ifdef EISCONN
916   if (ret < 0 && errno == EISCONN) {
917     errno = 0;
918     ret = 0;
919   }
920 #endif
921
922   if (ret < 0) {
923     DEBUG(2,("error connecting to %s:%d (%s)\n",
924              inet_ntoa(*addr),port,strerror(errno)));
925     close(res);
926     return -1;
927   }
928
929   /* set it blocking again */
930   set_blocking(res,True);
931
932   return res;
933 }
934
935 /*
936   open a connected UDP socket to host on port
937 */
938 int open_udp_socket(const char *host, int port)
939 {
940         int type = SOCK_DGRAM;
941         struct sockaddr_in sock_out;
942         int res;
943         struct in_addr *addr;
944
945         addr = interpret_addr2(host);
946
947         res = socket(PF_INET, type, 0);
948         if (res == -1) {
949                 return -1;
950         }
951
952         memset((char *)&sock_out,'\0',sizeof(sock_out));
953         putip((char *)&sock_out.sin_addr,(char *)addr);
954         sock_out.sin_port = htons(port);
955         sock_out.sin_family = PF_INET;
956
957         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
958                 close(res);
959                 return -1;
960         }
961
962         return res;
963 }
964
965
966 /* the following 3 client_*() functions are nasty ways of allowing
967    some generic functions to get info that really should be hidden in
968    particular modules */
969 static int client_fd = -1;
970
971 void client_setfd(int fd)
972 {
973         client_fd = fd;
974 }
975
976 char *client_name(void)
977 {
978         return get_socket_name(client_fd);
979 }
980
981 char *client_addr(void)
982 {
983         return get_socket_addr(client_fd);
984 }
985
986 /*******************************************************************
987  matchname - determine if host name matches IP address. Used to
988  confirm a hostname lookup to prevent spoof attacks
989  ******************************************************************/
990 static BOOL matchname(char *remotehost,struct in_addr  addr)
991 {
992         struct hostent *hp;
993         int     i;
994         
995         if ((hp = sys_gethostbyname(remotehost)) == 0) {
996                 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n", remotehost));
997                 return False;
998         } 
999
1000         /*
1001          * Make sure that gethostbyname() returns the "correct" host name.
1002          * Unfortunately, gethostbyname("localhost") sometimes yields
1003          * "localhost.domain". Since the latter host name comes from the
1004          * local DNS, we just have to trust it (all bets are off if the local
1005          * DNS is perverted). We always check the address list, though.
1006          */
1007         
1008         if (strcasecmp(remotehost, hp->h_name)
1009             && strcasecmp(remotehost, "localhost")) {
1010                 DEBUG(0,("host name/name mismatch: %s != %s\n",
1011                          remotehost, hp->h_name));
1012                 return False;
1013         }
1014         
1015         /* Look up the host address in the address list we just got. */
1016         for (i = 0; hp->h_addr_list[i]; i++) {
1017                 if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
1018                         return True;
1019         }
1020         
1021         /*
1022          * The host name does not map to the original host address. Perhaps
1023          * someone has compromised a name server. More likely someone botched
1024          * it, but that could be dangerous, too.
1025          */
1026         
1027         DEBUG(0,("host name/address mismatch: %s != %s\n",
1028                  inet_ntoa(addr), hp->h_name));
1029         return False;
1030 }
1031
1032  
1033 /*******************************************************************
1034  return the DNS name of the remote end of a socket
1035  ******************************************************************/
1036 char *get_socket_name(int fd)
1037 {
1038         static pstring name_buf;
1039         static fstring addr_buf;
1040         struct hostent *hp;
1041         struct in_addr addr;
1042         char *p;
1043
1044         /* reverse lookups can be *very* expensive, and in many
1045            situations won't work because many networks don't link dhcp
1046            with dns. To avoid the delay we avoid the lookup if
1047            possible */
1048         if (!lp_hostname_lookups()) {
1049                 return get_socket_addr(fd);
1050         }
1051         
1052         p = get_socket_addr(fd);
1053
1054         /* it might be the same as the last one - save some DNS work */
1055         if (strcmp(p, addr_buf) == 0) return name_buf;
1056
1057         pstrcpy(name_buf,"UNKNOWN");
1058         if (fd == -1) return name_buf;
1059
1060         fstrcpy(addr_buf, p);
1061
1062         addr = *interpret_addr2(p);
1063         
1064         /* Look up the remote host name. */
1065         if ((hp = gethostbyaddr((char *)&addr.s_addr, sizeof(addr.s_addr), AF_INET)) == 0) {
1066                 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1067                 pstrcpy(name_buf, p);
1068         } else {
1069                 pstrcpy(name_buf,(char *)hp->h_name);
1070                 if (!matchname(name_buf, addr)) {
1071                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1072                         pstrcpy(name_buf,"UNKNOWN");
1073                 }
1074         }
1075
1076         alpha_strcpy(name_buf, name_buf, "_-.", sizeof(name_buf));
1077         if (strstr(name_buf,"..")) {
1078                 pstrcpy(name_buf, "UNKNOWN");
1079         }
1080
1081         return name_buf;
1082 }
1083
1084 /*******************************************************************
1085  return the IP addr of the remote end of a socket as a string 
1086  ******************************************************************/
1087 char *get_socket_addr(int fd)
1088 {
1089         struct sockaddr sa;
1090         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1091         int     length = sizeof(sa);
1092         static fstring addr_buf;
1093
1094         fstrcpy(addr_buf,"0.0.0.0");
1095
1096         if (fd == -1) {
1097                 return addr_buf;
1098         }
1099         
1100         if (getpeername(fd, &sa, &length) < 0) {
1101                 DEBUG(0,("getpeername failed. Error was %s\n", strerror(errno) ));
1102                 return addr_buf;
1103         }
1104         
1105         fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1106         
1107         return addr_buf;
1108 }
1109
1110 /*******************************************************************
1111  opens and connects to a unix pipe socket
1112  ******************************************************************/
1113 int open_pipe_sock(char *path)
1114 {
1115         int sock;
1116         struct sockaddr_un sa;
1117
1118         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1119
1120         if (sock < 0)
1121         {
1122                 DEBUG(0, ("unix socket open failed\n"));
1123                 return sock;
1124         }
1125
1126         ZERO_STRUCT(sa);
1127         sa.sun_family = AF_UNIX;
1128         safe_strcpy(sa.sun_path, path, sizeof(sa.sun_path)-1);
1129
1130         DEBUG(10, ("socket open succeeded.  file name: %s\n", sa.sun_path));
1131
1132         if (connect(sock, (struct sockaddr*) &sa, sizeof(sa)) < 0)
1133         {
1134                 DEBUG(0,("socket connect to %s failed\n", sa.sun_path));
1135                 close(sock);
1136                 return -1;
1137         }
1138
1139         return sock;
1140 }
1141
1142 /*******************************************************************
1143  Create protected unix domain socket.
1144
1145  some unixen cannot set permissions on a ux-dom-sock, so we
1146  have to make sure that the directory contains the protection
1147  permissions, instead.
1148  ******************************************************************/
1149 int create_pipe_sock(const char *socket_dir,
1150                                         const char *socket_name,
1151                                         mode_t dir_perms)
1152 {
1153         struct sockaddr_un sunaddr;
1154         struct stat st;
1155         int sock;
1156         mode_t old_umask;
1157         pstring path;
1158         
1159         /* Create the socket directory or reuse the existing one */
1160         
1161         if (lstat(socket_dir, &st) == -1) {
1162                 
1163                 if (errno == ENOENT) {
1164                         
1165                         /* Create directory */
1166                         
1167                         if (mkdir(socket_dir, dir_perms) == -1) {
1168                                 DEBUG(0, ("error creating socket directory "
1169                                           "%s: %s\n", socket_dir, 
1170                                           strerror(errno)));
1171                                 return -1;
1172                         }
1173                         
1174                 } else {
1175                         
1176                         DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1177                                   socket_dir, strerror(errno)));
1178                         return -1;
1179                 }
1180                 
1181         } else {
1182                 
1183                 /* Check ownership and permission on existing directory */
1184                 
1185                 if (!S_ISDIR(st.st_mode)) {
1186                         DEBUG(0, ("socket directory %s isn't a directory\n",
1187                                   socket_dir));
1188                         return -1;
1189                 }
1190                 
1191                 if ((st.st_uid != sec_initial_uid()) || 
1192                     ((st.st_mode & 0777) != dir_perms)) {
1193                         DEBUG(0, ("invalid permissions on socket directory "
1194                                   "%s\n", socket_dir));
1195                         return -1;
1196                 }
1197         }
1198         
1199         /* Create the socket file */
1200         
1201         old_umask = umask(0);
1202         
1203         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1204         
1205         if (sock == -1) {
1206                 perror("socket");
1207                 umask(old_umask);
1208                 return -1;
1209         }
1210         
1211         snprintf(path, sizeof(path), "%s/%s", socket_dir, socket_name);
1212         
1213         unlink(path);
1214         memset(&sunaddr, 0, sizeof(sunaddr));
1215         sunaddr.sun_family = AF_UNIX;
1216         safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1217         
1218         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1219                 DEBUG(0, ("bind failed on pipe socket %s: %s\n",
1220                           path,
1221                           strerror(errno)));
1222                 close(sock);
1223                 umask(old_umask);
1224                 return -1;
1225         }
1226         
1227         if (listen(sock, 5) == -1) {
1228                 DEBUG(0, ("listen failed on pipe socket %s: %s\n",
1229                           path,
1230                           strerror(errno)));
1231                 close(sock);
1232                 umask(old_umask);
1233                 return -1;
1234         }
1235         
1236         umask(old_umask);
1237         
1238         /* Success! */
1239         
1240         return sock;
1241 }
1242
1243 /*******************************************************************
1244 this is like socketpair but uses tcp. It is used by the Samba
1245 regression test code
1246 The function guarantees that nobody else can attach to the socket,
1247 or if they do that this function fails and the socket gets closed
1248 returns 0 on success, -1 on failure
1249 the resulting file descriptors are symmetrical
1250  ******************************************************************/
1251 static int socketpair_tcp(int fd[2])
1252 {
1253         int listener;
1254         struct sockaddr_in sock;
1255         struct sockaddr_in sock2;
1256         socklen_t socklen = sizeof(sock);
1257         int connect_done = 0;
1258         
1259         fd[0] = fd[1] = listener = -1;
1260
1261         memset(&sock, 0, sizeof(sock));
1262         
1263         if ((listener = socket(PF_INET, SOCK_STREAM, 0)) == -1) goto failed;
1264
1265         memset(&sock2, 0, sizeof(sock2));
1266 #ifdef HAVE_SOCK_SIN_LEN
1267         sock2.sin_len = sizeof(sock2);
1268 #endif
1269         sock2.sin_family = PF_INET;
1270
1271         bind(listener, (struct sockaddr *)&sock2, sizeof(sock2));
1272
1273         if (listen(listener, 1) != 0) goto failed;
1274
1275         if (getsockname(listener, (struct sockaddr *)&sock, &socklen) != 0) goto failed;
1276
1277         if ((fd[1] = socket(PF_INET, SOCK_STREAM, 0)) == -1) goto failed;
1278
1279         set_blocking(fd[1], 0);
1280
1281         sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1282
1283         if (connect(fd[1],(struct sockaddr *)&sock,sizeof(sock)) == -1) {
1284                 if (errno != EINPROGRESS) goto failed;
1285         } else {
1286                 connect_done = 1;
1287         }
1288
1289         if ((fd[0] = accept(listener, (struct sockaddr *)&sock, &socklen)) == -1) goto failed;
1290
1291         close(listener);
1292         if (connect_done == 0) {
1293                 if (connect(fd[1],(struct sockaddr *)&sock,sizeof(sock)) != 0
1294                     && errno != EISCONN) goto failed;
1295         }
1296
1297         set_blocking(fd[1], 1);
1298
1299         /* all OK! */
1300         return 0;
1301
1302  failed:
1303         if (fd[0] != -1) close(fd[0]);
1304         if (fd[1] != -1) close(fd[1]);
1305         if (listener != -1) close(listener);
1306         return -1;
1307 }
1308
1309
1310 /*******************************************************************
1311 run a program on a local tcp socket, this is used to launch smbd
1312 when regression testing
1313 the return value is a socket which is attached to a subprocess
1314 running "prog". stdin and stdout are attached. stderr is left
1315 attached to the original stderr
1316  ******************************************************************/
1317 int sock_exec(const char *prog)
1318 {
1319         int fd[2];
1320         if (socketpair_tcp(fd) != 0) {
1321                 DEBUG(0,("socketpair_tcp failed (%s)\n", strerror(errno)));
1322                 return -1;
1323         }
1324         if (fork() == 0) {
1325                 close(fd[0]);
1326                 close(0);
1327                 close(1);
1328                 dup(fd[1]);
1329                 dup(fd[1]);
1330                 exit(system(prog));
1331         }
1332         close(fd[1]);
1333         return fd[0];
1334 }