Only set smb_read_error if not already set.
[jra/samba/.git] / source3 / 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 = read(fd, buf + nread, maxcnt - nread);
251                         }
252 #else /* WITH_SSL */
253                         readret = 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 = read(fd, buf + nread, maxcnt - nread);
308                 }
309 #else /* WITH_SSL */
310                 readret = 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 = read(fd, buf + nread, maxcnt - nread);
361                         }
362 #else /* WITH_SSL */
363                         readret = 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 = read(fd, buf + nread, maxcnt - nread);
391                 }
392 #else /* WITH_SSL */
393                 readret = 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   {
433 #ifdef WITH_SSL
434     if(fd == sslFd){
435       ret = SSL_read(ssl, buffer + total, N - total);
436     }else{
437       ret = read(fd,buffer + total,N - total);
438     }
439 #else /* WITH_SSL */
440     ret = read(fd,buffer + total,N - total);
441 #endif /* WITH_SSL */
442
443     if (ret == 0)
444     {
445       DEBUG(10,("read_data: read of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
446       smb_read_error = READ_EOF;
447       return 0;
448     }
449     if (ret == -1)
450     {
451       DEBUG(0,("read_data: read failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
452       smb_read_error = READ_ERROR;
453       return -1;
454     }
455     total += ret;
456   }
457   return (ssize_t)total;
458 }
459
460 /****************************************************************************
461  Read data from a socket, reading exactly N bytes. 
462 ****************************************************************************/
463
464 static ssize_t read_socket_data(int fd,char *buffer,size_t N)
465 {
466   ssize_t  ret;
467   size_t total=0;  
468  
469   smb_read_error = 0;
470
471   while (total < N)
472   {
473 #ifdef WITH_SSL
474     if(fd == sslFd){
475       ret = SSL_read(ssl, buffer + total, N - total);
476     }else{
477       ret = read(fd,buffer + total,N - total);
478     }
479 #else /* WITH_SSL */
480     ret = read(fd,buffer + total,N - total);
481 #endif /* WITH_SSL */
482
483     if (ret == 0)
484     {
485       DEBUG(10,("read_socket_data: recv of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
486       smb_read_error = READ_EOF;
487       return 0;
488     }
489     if (ret == -1)
490     {
491       DEBUG(0,("read_socket_data: recv failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
492       smb_read_error = READ_ERROR;
493       return -1;
494     }
495     total += ret;
496   }
497   return (ssize_t)total;
498 }
499
500 /****************************************************************************
501  Write data to a fd.
502 ****************************************************************************/
503
504 ssize_t write_data(int fd,char *buffer,size_t N)
505 {
506   size_t total=0;
507   ssize_t ret;
508
509   while (total < N)
510   {
511 #ifdef WITH_SSL
512     if(fd == sslFd){
513       ret = SSL_write(ssl,buffer + total,N - total);
514     }else{
515       ret = write(fd,buffer + total,N - total);
516     }
517 #else /* WITH_SSL */
518     ret = write(fd,buffer + total,N - total);
519 #endif /* WITH_SSL */
520
521     if (ret == -1) {
522       DEBUG(0,("write_data: write failure. Error = %s\n", strerror(errno) ));
523       return -1;
524     }
525     if (ret == 0) return total;
526
527     total += ret;
528   }
529   return (ssize_t)total;
530 }
531
532 /****************************************************************************
533  Write data to a socket - use send rather than write.
534 ****************************************************************************/
535
536 ssize_t write_socket_data(int fd,char *buffer,size_t N)
537 {
538   size_t total=0;
539   ssize_t ret;
540
541   while (total < N)
542   {
543 #ifdef WITH_SSL
544     if(fd == sslFd){
545       ret = SSL_write(ssl,buffer + total,N - total);
546     }else{
547       ret = send(fd,buffer + total,N - total, 0);
548     }
549 #else /* WITH_SSL */
550     ret = send(fd,buffer + total,N - total,0);
551 #endif /* WITH_SSL */
552
553     if (ret == -1) {
554       DEBUG(0,("write_socket_data: write failure. Error = %s\n", strerror(errno) ));
555       return -1;
556     }
557     if (ret == 0) return total;
558
559     total += ret;
560   }
561   return (ssize_t)total;
562 }
563
564 /****************************************************************************
565 write to a socket
566 ****************************************************************************/
567
568 ssize_t write_socket(int fd,char *buf,size_t len)
569 {
570   ssize_t ret=0;
571
572   DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
573   ret = write_socket_data(fd,buf,len);
574       
575   DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
576   if(ret <= 0)
577     DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n", 
578        (int)len, fd, strerror(errno) ));
579
580   return(ret);
581 }
582
583 /****************************************************************************
584 read 4 bytes of a smb packet and return the smb length of the packet
585 store the result in the buffer
586 This version of the function will return a length of zero on receiving
587 a keepalive packet.
588 timeout is in milliseconds.
589 ****************************************************************************/
590
591 static ssize_t read_smb_length_return_keepalive(int fd,char *inbuf,unsigned int timeout)
592 {
593   ssize_t len=0;
594   int msg_type;
595   BOOL ok = False;
596
597   while (!ok)
598   {
599     if (timeout > 0)
600       ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout) == 4);
601     else 
602       ok = (read_socket_data(fd,inbuf,4) == 4);
603
604     if (!ok)
605       return(-1);
606
607     len = smb_len(inbuf);
608     msg_type = CVAL(inbuf,0);
609
610     if (msg_type == SMBkeepalive) 
611       DEBUG(5,("Got keepalive packet\n"));
612   }
613
614   DEBUG(10,("got smb length of %d\n",len));
615
616   return(len);
617 }
618
619 /****************************************************************************
620 read 4 bytes of a smb packet and return the smb length of the packet
621 store the result in the buffer. This version of the function will
622 never return a session keepalive (length of zero).
623 timeout is in milliseconds.
624 ****************************************************************************/
625
626 ssize_t read_smb_length(int fd,char *inbuf,unsigned int timeout)
627 {
628   ssize_t len;
629
630   for(;;)
631   {
632     len = read_smb_length_return_keepalive(fd, inbuf, timeout);
633
634     if(len < 0)
635       return len;
636
637     /* Ignore session keepalives. */
638     if(CVAL(inbuf,0) != SMBkeepalive)
639       break;
640   }
641
642   DEBUG(10,("read_smb_length: got smb length of %d\n",len));
643
644   return len;
645 }
646
647 /****************************************************************************
648   read an smb from a fd. Note that the buffer *MUST* be of size
649   BUFFER_SIZE+SAFETY_MARGIN.
650   The timeout is in milliseconds. 
651   This function will return on a
652   receipt of a session keepalive packet.
653 ****************************************************************************/
654
655 BOOL receive_smb(int fd,char *buffer, unsigned int timeout)
656 {
657         ssize_t len,ret;
658
659         smb_read_error = 0;
660
661         memset(buffer,'\0',smb_size + 100);
662
663         len = read_smb_length_return_keepalive(fd,buffer,timeout);
664         if (len < 0) {
665                 DEBUG(10,("receive_smb: length < 0!\n"));
666
667                 /*
668                  * Correct fix. smb_read_error may have already been
669                  * set. Only set it here if not already set. Global
670                  * variables still suck :-). JRA.
671                  */
672
673                 if (smb_read_error == 0)
674                         smb_read_error = READ_ERROR;
675                 return False;
676         }
677
678         /*
679          * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
680      * of header. Don't print the error if this fits.... JRA.
681          */
682
683         if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
684                 DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
685                 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
686
687                         /*
688                          * Correct fix. smb_read_error may have already been
689                          * set. Only set it here if not already set. Global
690                          * variables still suck :-). JRA.
691                          */
692
693                         if (smb_read_error == 0)
694                                 smb_read_error = READ_ERROR;
695                         return False;
696                 }
697         }
698
699         if(len > 0) {
700                 ret = read_socket_data(fd,buffer+4,len);
701                 if (ret != len) {
702                         if (smb_read_error == 0)
703                                 smb_read_error = READ_ERROR;
704                         return False;
705                 }
706         }
707
708         return(True);
709 }
710
711 /****************************************************************************
712   read an smb from a fd ignoring all keepalive packets. Note that the buffer 
713   *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
714   The timeout is in milliseconds
715
716   This is exactly the same as receive_smb except that it never returns
717   a session keepalive packet (just as receive_smb used to do).
718   receive_smb was changed to return keepalives as the oplock processing means this call
719   should never go into a blocking read.
720 ****************************************************************************/
721
722 BOOL client_receive_smb(int fd,char *buffer, unsigned int timeout)
723 {
724   BOOL ret;
725
726   for(;;)
727   {
728     ret = receive_smb(fd, buffer, timeout);
729
730     if (!ret)
731     {
732       DEBUG(10,("client_receive_smb failed\n"));
733       show_msg(buffer);
734       return ret;
735     }
736
737     /* Ignore session keepalive packets. */
738     if(CVAL(buffer,0) != SMBkeepalive)
739       break;
740   }
741   show_msg(buffer);
742   return ret;
743 }
744
745 /****************************************************************************
746   send an smb to a fd 
747 ****************************************************************************/
748
749 BOOL send_smb(int fd,char *buffer)
750 {
751         size_t len;
752         size_t nwritten=0;
753         ssize_t ret;
754         len = smb_len(buffer) + 4;
755
756         while (nwritten < len) {
757                 ret = write_socket(fd,buffer+nwritten,len - nwritten);
758                 if (ret <= 0) {
759                         DEBUG(0,("Error writing %d bytes to client. %d. (%s)\n",
760                                 (int)len,(int)ret, strerror(errno) ));
761                         return False;
762                 }
763                 nwritten += ret;
764         }
765
766         return True;
767 }
768
769 /****************************************************************************
770 send a single packet to a port on another machine
771 ****************************************************************************/
772
773 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
774 {
775   BOOL ret;
776   int out_fd;
777   struct sockaddr_in sock_out;
778
779   /* create a socket to write to */
780   out_fd = socket(AF_INET, type, 0);
781   if (out_fd == -1) 
782     {
783       DEBUG(0,("socket failed"));
784       return False;
785     }
786
787   /* set the address and port */
788   memset((char *)&sock_out,'\0',sizeof(sock_out));
789   putip((char *)&sock_out.sin_addr,(char *)&ip);
790   sock_out.sin_port = htons( port );
791   sock_out.sin_family = AF_INET;
792   
793   if (DEBUGLEVEL > 0)
794     DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
795              len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
796         
797   /* send it */
798   ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
799
800   if (!ret)
801     DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
802              inet_ntoa(ip),port,strerror(errno)));
803
804   close(out_fd);
805   return(ret);
806 }
807
808 /****************************************************************************
809  Open a socket of the specified type, port, and address for incoming data.
810 ****************************************************************************/
811
812 int open_socket_in( int type, int port, int dlevel, uint32 socket_addr, BOOL rebind )
813 {
814         struct sockaddr_in sock;
815         int res;
816
817         memset( (char *)&sock, '\0', sizeof(sock) );
818
819 #ifdef HAVE_SOCK_SIN_LEN
820         sock.sin_len         = sizeof(sock);
821 #endif
822         sock.sin_port        = htons( port );
823         sock.sin_family      = AF_INET;
824         sock.sin_addr.s_addr = socket_addr;
825
826         res = socket( AF_INET, type, 0 );
827         if( res == -1 ) {
828                 if( DEBUGLVL(0) ) {
829                         dbgtext( "open_socket_in(): socket() call failed: " );
830                         dbgtext( "%s\n", strerror( errno ) );
831                 }
832                 return -1;
833         }
834
835         /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
836         {
837                 int val = rebind ? 1 : 0;
838                 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val)) == -1 ) {
839                         if( DEBUGLVL( dlevel ) ) {
840                                 dbgtext( "open_socket_in(): setsockopt: " );
841                                 dbgtext( "SO_REUSEADDR = %s ", val?"True":"False" );
842                                 dbgtext( "on port %d failed ", port );
843                                 dbgtext( "with error = %s\n", strerror(errno) );
844                         }
845                 }
846 #ifdef SO_REUSEPORT
847                 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,(char *)&val,sizeof(val)) == -1 ) {
848                         if( DEBUGLVL( dlevel ) ) {
849                                 dbgtext( "open_socket_in(): setsockopt: ");
850                                 dbgtext( "SO_REUSEPORT = %s ", val?"True":"False" );
851                                 dbgtext( "on port %d failed ", port );
852                                 dbgtext( "with error = %s\n", strerror(errno) );
853                         }
854                 }
855 #endif /* SO_REUSEPORT */
856         }
857
858         /* now we've got a socket - we need to bind it */
859         if( bind( res, (struct sockaddr *)&sock, sizeof(sock) ) == -1 ) {
860                 if( DEBUGLVL(dlevel) && (port == SMB_PORT || port == NMB_PORT) ) {
861                         dbgtext( "bind failed on port %d ", port );
862                         dbgtext( "socket_addr = %s.\n", inet_ntoa( sock.sin_addr ) );
863                         dbgtext( "Error = %s\n", strerror(errno) );
864                 }
865                 close( res ); 
866                 return( -1 ); 
867         }
868
869         DEBUG( 3, ( "bind succeeded on port %d\n", port ) );
870
871         return( res );
872  }
873
874 /****************************************************************************
875   create an outgoing socket. timeout is in milliseconds.
876   **************************************************************************/
877
878 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
879 {
880   struct sockaddr_in sock_out;
881   int res,ret;
882   int connect_loop = 250; /* 250 milliseconds */
883   int loops = (timeout) / connect_loop;
884
885   /* create a socket to write to */
886   res = socket(PF_INET, type, 0);
887   if (res == -1) 
888     { DEBUG(0,("socket error\n")); return -1; }
889
890   if (type != SOCK_STREAM) return(res);
891   
892   memset((char *)&sock_out,'\0',sizeof(sock_out));
893   putip((char *)&sock_out.sin_addr,(char *)addr);
894   
895   sock_out.sin_port = htons( port );
896   sock_out.sin_family = PF_INET;
897
898   /* set it non-blocking */
899   set_blocking(res,False);
900
901   DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
902   
903   /* and connect it to the destination */
904 connect_again:
905   ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
906
907   /* Some systems return EAGAIN when they mean EINPROGRESS */
908   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
909         errno == EAGAIN) && loops--) {
910     msleep(connect_loop);
911     goto connect_again;
912   }
913
914   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
915          errno == EAGAIN)) {
916       DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
917       close(res);
918       return -1;
919   }
920
921 #ifdef EISCONN
922   if (ret < 0 && errno == EISCONN) {
923     errno = 0;
924     ret = 0;
925   }
926 #endif
927
928   if (ret < 0) {
929     DEBUG(2,("error connecting to %s:%d (%s)\n",
930              inet_ntoa(*addr),port,strerror(errno)));
931     close(res);
932     return -1;
933   }
934
935   /* set it blocking again */
936   set_blocking(res,True);
937
938   return res;
939 }
940
941 /*
942   open a connected UDP socket to host on port
943 */
944 int open_udp_socket(const char *host, int port)
945 {
946         int type = SOCK_DGRAM;
947         struct sockaddr_in sock_out;
948         int res;
949         struct in_addr *addr;
950
951         addr = interpret_addr2(host);
952
953         res = socket(PF_INET, type, 0);
954         if (res == -1) {
955                 return -1;
956         }
957
958         memset((char *)&sock_out,'\0',sizeof(sock_out));
959         putip((char *)&sock_out.sin_addr,(char *)addr);
960         sock_out.sin_port = htons(port);
961         sock_out.sin_family = PF_INET;
962
963         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
964                 close(res);
965                 return -1;
966         }
967
968         return res;
969 }
970
971
972 /* the following 3 client_*() functions are nasty ways of allowing
973    some generic functions to get info that really should be hidden in
974    particular modules */
975 static int client_fd = -1;
976
977 void client_setfd(int fd)
978 {
979         client_fd = fd;
980 }
981
982 char *client_name(void)
983 {
984         return get_socket_name(client_fd);
985 }
986
987 char *client_addr(void)
988 {
989         return get_socket_addr(client_fd);
990 }
991
992 /*******************************************************************
993  matchname - determine if host name matches IP address. Used to
994  confirm a hostname lookup to prevent spoof attacks
995  ******************************************************************/
996 static BOOL matchname(char *remotehost,struct in_addr  addr)
997 {
998         struct hostent *hp;
999         int     i;
1000         
1001         if ((hp = sys_gethostbyname(remotehost)) == 0) {
1002                 DEBUG(0,("sys_gethostbyname(%s): lookup failure.\n", remotehost));
1003                 return False;
1004         } 
1005
1006         /*
1007          * Make sure that gethostbyname() returns the "correct" host name.
1008          * Unfortunately, gethostbyname("localhost") sometimes yields
1009          * "localhost.domain". Since the latter host name comes from the
1010          * local DNS, we just have to trust it (all bets are off if the local
1011          * DNS is perverted). We always check the address list, though.
1012          */
1013         
1014         if (strcasecmp(remotehost, hp->h_name)
1015             && strcasecmp(remotehost, "localhost")) {
1016                 DEBUG(0,("host name/name mismatch: %s != %s\n",
1017                          remotehost, hp->h_name));
1018                 return False;
1019         }
1020         
1021         /* Look up the host address in the address list we just got. */
1022         for (i = 0; hp->h_addr_list[i]; i++) {
1023                 if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
1024                         return True;
1025         }
1026         
1027         /*
1028          * The host name does not map to the original host address. Perhaps
1029          * someone has compromised a name server. More likely someone botched
1030          * it, but that could be dangerous, too.
1031          */
1032         
1033         DEBUG(0,("host name/address mismatch: %s != %s\n",
1034                  inet_ntoa(addr), hp->h_name));
1035         return False;
1036 }
1037
1038  
1039 /*******************************************************************
1040  return the DNS name of the remote end of a socket
1041  ******************************************************************/
1042 char *get_socket_name(int fd)
1043 {
1044         static pstring name_buf;
1045         static fstring addr_buf;
1046         struct hostent *hp;
1047         struct in_addr addr;
1048         char *p;
1049
1050         /* reverse lookups can be *very* expensive, and in many
1051            situations won't work because many networks don't link dhcp
1052            with dns. To avoid the delay we avoid the lookup if
1053            possible */
1054         if (!lp_hostname_lookups()) {
1055                 return get_socket_addr(fd);
1056         }
1057         
1058         p = get_socket_addr(fd);
1059
1060         /* it might be the same as the last one - save some DNS work */
1061         if (strcmp(p, addr_buf) == 0) return name_buf;
1062
1063         pstrcpy(name_buf,"UNKNOWN");
1064         if (fd == -1) return name_buf;
1065
1066         fstrcpy(addr_buf, p);
1067
1068         addr = *interpret_addr2(p);
1069         
1070         /* Look up the remote host name. */
1071         if ((hp = gethostbyaddr((char *)&addr.s_addr, sizeof(addr.s_addr), AF_INET)) == 0) {
1072                 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1073                 pstrcpy(name_buf, p);
1074         } else {
1075                 pstrcpy(name_buf,(char *)hp->h_name);
1076                 if (!matchname(name_buf, addr)) {
1077                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1078                         pstrcpy(name_buf,"UNKNOWN");
1079                 }
1080         }
1081
1082         alpha_strcpy(name_buf, name_buf, "_-.", sizeof(name_buf));
1083         if (strstr(name_buf,"..")) {
1084                 pstrcpy(name_buf, "UNKNOWN");
1085         }
1086
1087         return name_buf;
1088 }
1089
1090 /*******************************************************************
1091  return the IP addr of the remote end of a socket as a string 
1092  ******************************************************************/
1093 char *get_socket_addr(int fd)
1094 {
1095         struct sockaddr sa;
1096         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1097         int     length = sizeof(sa);
1098         static fstring addr_buf;
1099
1100         fstrcpy(addr_buf,"0.0.0.0");
1101
1102         if (fd == -1) {
1103                 return addr_buf;
1104         }
1105         
1106         if (getpeername(fd, &sa, &length) < 0) {
1107                 DEBUG(0,("getpeername failed. Error was %s\n", strerror(errno) ));
1108                 return addr_buf;
1109         }
1110         
1111         fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1112         
1113         return addr_buf;
1114 }
1115
1116 /*******************************************************************
1117  opens and connects to a unix pipe socket
1118  ******************************************************************/
1119 int open_pipe_sock(char *path)
1120 {
1121         int sock;
1122         struct sockaddr_un sa;
1123
1124         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1125
1126         if (sock < 0)
1127         {
1128                 DEBUG(0, ("unix socket open failed\n"));
1129                 return sock;
1130         }
1131
1132         ZERO_STRUCT(sa);
1133         sa.sun_family = AF_UNIX;
1134         safe_strcpy(sa.sun_path, path, sizeof(sa.sun_path)-1);
1135
1136         DEBUG(10, ("socket open succeeded.  file name: %s\n", sa.sun_path));
1137
1138         if (connect(sock, (struct sockaddr*) &sa, sizeof(sa)) < 0)
1139         {
1140                 DEBUG(0,("socket connect to %s failed\n", sa.sun_path));
1141                 close(sock);
1142                 return -1;
1143         }
1144
1145         return sock;
1146 }
1147
1148 /*******************************************************************
1149  Create protected unix domain socket.
1150
1151  some unixen cannot set permissions on a ux-dom-sock, so we
1152  have to make sure that the directory contains the protection
1153  permissions, instead.
1154  ******************************************************************/
1155 int create_pipe_sock(const char *socket_dir,
1156                                         const char *socket_name,
1157                                         mode_t dir_perms)
1158 {
1159         struct sockaddr_un sunaddr;
1160         struct stat st;
1161         int sock;
1162         mode_t old_umask;
1163         pstring path;
1164         
1165         /* Create the socket directory or reuse the existing one */
1166         
1167         if (lstat(socket_dir, &st) == -1) {
1168                 
1169                 if (errno == ENOENT) {
1170                         
1171                         /* Create directory */
1172                         
1173                         if (mkdir(socket_dir, dir_perms) == -1) {
1174                                 DEBUG(0, ("error creating socket directory "
1175                                           "%s: %s\n", socket_dir, 
1176                                           strerror(errno)));
1177                                 return -1;
1178                         }
1179                         
1180                 } else {
1181                         
1182                         DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1183                                   socket_dir, strerror(errno)));
1184                         return -1;
1185                 }
1186                 
1187         } else {
1188                 
1189                 /* Check ownership and permission on existing directory */
1190                 
1191                 if (!S_ISDIR(st.st_mode)) {
1192                         DEBUG(0, ("socket directory %s isn't a directory\n",
1193                                   socket_dir));
1194                         return -1;
1195                 }
1196                 
1197                 if ((st.st_uid != sec_initial_uid()) || 
1198                     ((st.st_mode & 0777) != dir_perms)) {
1199                         DEBUG(0, ("invalid permissions on socket directory "
1200                                   "%s\n", socket_dir));
1201                         return -1;
1202                 }
1203         }
1204         
1205         /* Create the socket file */
1206         
1207         old_umask = umask(0);
1208         
1209         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1210         
1211         if (sock == -1) {
1212                 perror("socket");
1213                 umask(old_umask);
1214                 return -1;
1215         }
1216         
1217         snprintf(path, sizeof(path), "%s/%s", socket_dir, socket_name);
1218         
1219         unlink(path);
1220         memset(&sunaddr, 0, sizeof(sunaddr));
1221         sunaddr.sun_family = AF_UNIX;
1222         safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
1223         
1224         if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1225                 DEBUG(0, ("bind failed on pipe socket %s: %s\n",
1226                           path,
1227                           strerror(errno)));
1228                 close(sock);
1229                 umask(old_umask);
1230                 return -1;
1231         }
1232         
1233         if (listen(sock, 5) == -1) {
1234                 DEBUG(0, ("listen failed on pipe socket %s: %s\n",
1235                           path,
1236                           strerror(errno)));
1237                 close(sock);
1238                 umask(old_umask);
1239                 return -1;
1240         }
1241         
1242         umask(old_umask);
1243         
1244         /* Success! */
1245         
1246         return sock;
1247 }
1248
1249 /*******************************************************************
1250 this is like socketpair but uses tcp. It is used by the Samba
1251 regression test code
1252 The function guarantees that nobody else can attach to the socket,
1253 or if they do that this function fails and the socket gets closed
1254 returns 0 on success, -1 on failure
1255 the resulting file descriptors are symmetrical
1256  ******************************************************************/
1257 static int socketpair_tcp(int fd[2])
1258 {
1259         int listener;
1260         struct sockaddr_in sock;
1261         struct sockaddr_in sock2;
1262         socklen_t socklen = sizeof(sock);
1263         int connect_done = 0;
1264         
1265         fd[0] = fd[1] = listener = -1;
1266
1267         memset(&sock, 0, sizeof(sock));
1268         
1269         if ((listener = socket(PF_INET, SOCK_STREAM, 0)) == -1) goto failed;
1270
1271         memset(&sock2, 0, sizeof(sock2));
1272 #ifdef HAVE_SOCK_SIN_LEN
1273         sock2.sin_len = sizeof(sock2);
1274 #endif
1275         sock2.sin_family = PF_INET;
1276
1277         bind(listener, (struct sockaddr *)&sock2, sizeof(sock2));
1278
1279         if (listen(listener, 1) != 0) goto failed;
1280
1281         if (getsockname(listener, (struct sockaddr *)&sock, &socklen) != 0) goto failed;
1282
1283         if ((fd[1] = socket(PF_INET, SOCK_STREAM, 0)) == -1) goto failed;
1284
1285         set_blocking(fd[1], 0);
1286
1287         sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1288
1289         if (connect(fd[1],(struct sockaddr *)&sock,sizeof(sock)) == -1) {
1290                 if (errno != EINPROGRESS) goto failed;
1291         } else {
1292                 connect_done = 1;
1293         }
1294
1295         if ((fd[0] = accept(listener, (struct sockaddr *)&sock, &socklen)) == -1) goto failed;
1296
1297         close(listener);
1298         if (connect_done == 0) {
1299                 if (connect(fd[1],(struct sockaddr *)&sock,sizeof(sock)) != 0
1300                     && errno != EISCONN) goto failed;
1301         }
1302
1303         set_blocking(fd[1], 1);
1304
1305         /* all OK! */
1306         return 0;
1307
1308  failed:
1309         if (fd[0] != -1) close(fd[0]);
1310         if (fd[1] != -1) close(fd[1]);
1311         if (listener != -1) close(listener);
1312         return -1;
1313 }
1314
1315
1316 /*******************************************************************
1317 run a program on a local tcp socket, this is used to launch smbd
1318 when regression testing
1319 the return value is a socket which is attached to a subprocess
1320 running "prog". stdin and stdout are attached. stderr is left
1321 attached to the original stderr
1322  ******************************************************************/
1323 int sock_exec(const char *prog)
1324 {
1325         int fd[2];
1326         if (socketpair_tcp(fd) != 0) {
1327                 DEBUG(0,("socketpair_tcp failed (%s)\n", strerror(errno)));
1328                 return -1;
1329         }
1330         if (fork() == 0) {
1331                 close(fd[0]);
1332                 close(0);
1333                 close(1);
1334                 dup(fd[1]);
1335                 dup(fd[1]);
1336                 exit(system(prog));
1337         }
1338         close(fd[1]);
1339         return fd[0];
1340 }