finally got sick of the "extern int Client" code and the stupid
[jra/samba/.git] / source3 / lib / util_sock.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Samba utility functions
5    Copyright (C) Andrew Tridgell 1992-1998
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 <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 extern int DEBUGLEVEL;
32
33 BOOL passive = False;
34
35 /* the last IP received from */
36 struct in_addr lastip;
37
38 /* the last port received from */
39 int lastport=0;
40
41 int smb_read_error = 0;
42
43 /****************************************************************************
44  Determine if a file descriptor is in fact a socket.
45 ****************************************************************************/
46
47 BOOL is_a_socket(int fd)
48 {
49   int v,l;
50   l = sizeof(int);
51   return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
52 }
53
54 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
55
56 struct
57 {
58   char *name;
59   int level;
60   int option;
61   int value;
62   int opttype;
63 } socket_options[] = {
64   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
65   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
66   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
67 #ifdef TCP_NODELAY
68   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
69 #endif
70 #ifdef IPTOS_LOWDELAY
71   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
72 #endif
73 #ifdef IPTOS_THROUGHPUT
74   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
75 #endif
76 #ifdef SO_REUSEPORT
77   {"SO_REUSEPORT",      SOL_SOCKET,    SO_REUSEPORT,    0,                 OPT_BOOL},
78 #endif
79 #ifdef SO_SNDBUF
80   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
81 #endif
82 #ifdef SO_RCVBUF
83   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
84 #endif
85 #ifdef SO_SNDLOWAT
86   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
87 #endif
88 #ifdef SO_RCVLOWAT
89   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
90 #endif
91 #ifdef SO_SNDTIMEO
92   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
93 #endif
94 #ifdef SO_RCVTIMEO
95   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
96 #endif
97   {NULL,0,0,0,0}};
98
99 /****************************************************************************
100  Set user socket options.
101 ****************************************************************************/
102
103 void set_socket_options(int fd, char *options)
104 {
105         fstring tok;
106
107         while (next_token(&options,tok," \t,", sizeof(tok))) {
108                 int ret=0,i;
109                 int value = 1;
110                 char *p;
111                 BOOL got_value = False;
112
113                 if ((p = strchr(tok,'='))) {
114                         *p = 0;
115                         value = atoi(p+1);
116                         got_value = True;
117                 }
118
119                 for (i=0;socket_options[i].name;i++)
120                         if (strequal(socket_options[i].name,tok))
121                                 break;
122
123                 if (!socket_options[i].name) {
124                         DEBUG(0,("Unknown socket option %s\n",tok));
125                         continue;
126                 }
127
128                 switch (socket_options[i].opttype) {
129                 case OPT_BOOL:
130                 case OPT_INT:
131                         ret = setsockopt(fd,socket_options[i].level,
132                                                 socket_options[i].option,(char *)&value,sizeof(int));
133                         break;
134
135                 case OPT_ON:
136                         if (got_value)
137                                 DEBUG(0,("syntax error - %s does not take a value\n",tok));
138
139                         {
140                                 int on = socket_options[i].value;
141                                 ret = setsockopt(fd,socket_options[i].level,
142                                                         socket_options[i].option,(char *)&on,sizeof(int));
143                         }
144                         break;    
145                 }
146       
147                 if (ret != 0)
148                         DEBUG(0,("Failed to set socket option %s (Error %s)\n",tok, strerror(errno) ));
149         }
150 }
151
152 /****************************************************************************
153  Read from a socket.
154 ****************************************************************************/
155
156 ssize_t read_udp_socket(int fd,char *buf,size_t len)
157 {
158   ssize_t ret;
159   struct sockaddr_in sock;
160   int socklen;
161   
162   socklen = sizeof(sock);
163   memset((char *)&sock,'\0',socklen);
164   memset((char *)&lastip,'\0',sizeof(lastip));
165   ret = (ssize_t)recvfrom(fd,buf,len,0,(struct sockaddr *)&sock,&socklen);
166   if (ret <= 0) {
167     DEBUG(2,("read socket failed. ERRNO=%s\n",strerror(errno)));
168     return(0);
169   }
170
171   lastip = sock.sin_addr;
172   lastport = ntohs(sock.sin_port);
173
174   DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %d\n",
175              inet_ntoa(lastip), lastport, ret));
176
177   return(ret);
178 }
179
180 /****************************************************************************
181  Read data from a socket with a timout in msec.
182  mincount = if timeout, minimum to read before returning
183  maxcount = number to be read.
184  time_out = timeout in milliseconds
185 ****************************************************************************/
186
187 static ssize_t read_socket_with_timeout(int fd,char *buf,size_t mincnt,size_t maxcnt,unsigned int time_out)
188 {
189   fd_set fds;
190   int selrtn;
191   ssize_t readret;
192   size_t nread = 0;
193   struct timeval timeout;
194
195   /* just checking .... */
196   if (maxcnt <= 0)
197     return(0);
198
199   smb_read_error = 0;
200
201   /* Blocking read */
202   if (time_out <= 0) {
203     if (mincnt == 0) mincnt = maxcnt;
204
205     while (nread < mincnt) {
206 #ifdef WITH_SSL
207       if(fd == sslFd){
208         readret = SSL_read(ssl, buf + nread, maxcnt - nread);
209       }else{
210         readret = read(fd, buf + nread, maxcnt - nread);
211       }
212 #else /* WITH_SSL */
213       readret = read(fd, buf + nread, maxcnt - nread);
214 #endif /* WITH_SSL */
215
216       if (readret == 0) {
217         DEBUG(5,("read_socket_with_timeout: blocking read. EOF from client.\n"));
218         smb_read_error = READ_EOF;
219         return -1;
220       }
221
222       if (readret == -1) {
223         DEBUG(0,("read_socket_with_timeout: read error = %s.\n", strerror(errno) ));
224         smb_read_error = READ_ERROR;
225         return -1;
226       }
227       nread += readret;
228     }
229     return((ssize_t)nread);
230   }
231   
232   /* Most difficult - timeout read */
233   /* If this is ever called on a disk file and 
234      mincnt is greater then the filesize then
235      system performance will suffer severely as 
236      select always returns true on disk files */
237
238   /* Set initial timeout */
239   timeout.tv_sec = (time_t)(time_out / 1000);
240   timeout.tv_usec = (long)(1000 * (time_out % 1000));
241
242   for (nread=0; nread < mincnt; ) {      
243     FD_ZERO(&fds);
244     FD_SET(fd,&fds);
245       
246     selrtn = sys_select(fd+1,&fds,&timeout);
247
248     /* Check if error */
249     if(selrtn == -1) {
250       /* something is wrong. Maybe the socket is dead? */
251       DEBUG(0,("read_socket_with_timeout: timeout read. select error = %s.\n", strerror(errno) ));
252       smb_read_error = READ_ERROR;
253       return -1;
254     }
255
256     /* Did we timeout ? */
257     if (selrtn == 0) {
258       DEBUG(10,("read_socket_with_timeout: timeout read. select timed out.\n"));
259       smb_read_error = READ_TIMEOUT;
260       return -1;
261     }
262       
263 #ifdef WITH_SSL
264     if(fd == sslFd){
265       readret = SSL_read(ssl, buf + nread, maxcnt - nread);
266     }else{
267       readret = read(fd, buf + nread, maxcnt - nread);
268     }
269 #else /* WITH_SSL */
270     readret = read(fd, buf+nread, maxcnt-nread);
271 #endif /* WITH_SSL */
272
273     if (readret == 0) {
274       /* we got EOF on the file descriptor */
275       DEBUG(5,("read_socket_with_timeout: timeout read. EOF from client.\n"));
276       smb_read_error = READ_EOF;
277       return -1;
278     }
279
280     if (readret == -1) {
281       /* the descriptor is probably dead */
282       DEBUG(0,("read_socket_with_timeout: timeout read. read error = %s.\n", strerror(errno) ));
283       smb_read_error = READ_ERROR;
284       return -1;
285     }
286       
287     nread += readret;
288   }
289
290   /* Return the number we got */
291   return((ssize_t)nread);
292 }
293
294 /****************************************************************************
295  Read data from a fd with a timout in msec.
296  mincount = if timeout, minimum to read before returning
297  maxcount = number to be read.
298  time_out = timeout in milliseconds
299 ****************************************************************************/
300
301 ssize_t read_with_timeout(int fd,char *buf,size_t mincnt,size_t maxcnt,unsigned int time_out)
302 {
303   fd_set fds;
304   int selrtn;
305   ssize_t readret;
306   size_t nread = 0;
307   struct timeval timeout;
308
309   /* just checking .... */
310   if (maxcnt <= 0)
311     return(0);
312
313   /* Blocking read */
314   if (time_out <= 0) {
315     if (mincnt == 0) mincnt = maxcnt;
316
317     while (nread < mincnt) {
318 #ifdef WITH_SSL
319       if(fd == sslFd){
320         readret = SSL_read(ssl, buf + nread, maxcnt - nread);
321       }else{
322         readret = read(fd, buf + nread, maxcnt - nread);
323       }
324 #else /* WITH_SSL */
325       readret = read(fd, buf + nread, maxcnt - nread);
326 #endif /* WITH_SSL */
327
328       if (readret <= 0)
329         return readret;
330
331       nread += readret;
332     }
333     return((ssize_t)nread);
334   }
335   
336   /* Most difficult - timeout read */
337   /* If this is ever called on a disk file and 
338      mincnt is greater then the filesize then
339      system performance will suffer severely as 
340      select always returns true on disk files */
341
342   /* Set initial timeout */
343   timeout.tv_sec = (time_t)(time_out / 1000);
344   timeout.tv_usec = (long)(1000 * (time_out % 1000));
345
346   for (nread=0; nread < mincnt; ) {      
347     FD_ZERO(&fds);
348     FD_SET(fd,&fds);
349       
350     selrtn = sys_select(fd+1,&fds,&timeout);
351
352     if(selrtn <= 0)
353       return selrtn;
354       
355 #ifdef WITH_SSL
356     if(fd == sslFd){
357       readret = SSL_read(ssl, buf + nread, maxcnt - nread);
358     }else{
359       readret = read(fd, buf + nread, maxcnt - nread);
360     }
361 #else /* WITH_SSL */
362     readret = read(fd, buf+nread, maxcnt-nread);
363 #endif /* WITH_SSL */
364
365     if (readret <= 0)
366       return readret;
367
368     nread += readret;
369   }
370
371   /* Return the number we got */
372   return((ssize_t)nread);
373 }
374
375 /****************************************************************************
376 send a keepalive packet (rfc1002)
377 ****************************************************************************/
378
379 BOOL send_keepalive(int client)
380 {
381   unsigned char buf[4];
382
383   buf[0] = 0x85;
384   buf[1] = buf[2] = buf[3] = 0;
385
386   return(write_socket_data(client,(char *)buf,4) == 4);
387 }
388
389 /****************************************************************************
390   read data from the client, reading exactly N bytes. 
391 ****************************************************************************/
392
393 ssize_t read_data(int fd,char *buffer,size_t N)
394 {
395   ssize_t  ret;
396   size_t total=0;  
397  
398   smb_read_error = 0;
399
400   while (total < N)
401   {
402 #ifdef WITH_SSL
403     if(fd == sslFd){
404       ret = SSL_read(ssl, buffer + total, N - total);
405     }else{
406       ret = read(fd,buffer + total,N - total);
407     }
408 #else /* WITH_SSL */
409     ret = read(fd,buffer + total,N - total);
410 #endif /* WITH_SSL */
411
412     if (ret == 0)
413     {
414       DEBUG(10,("read_data: read of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
415       smb_read_error = READ_EOF;
416       return 0;
417     }
418     if (ret == -1)
419     {
420       DEBUG(0,("read_data: read failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
421       smb_read_error = READ_ERROR;
422       return -1;
423     }
424     total += ret;
425   }
426   return (ssize_t)total;
427 }
428
429 /****************************************************************************
430  Read data from a socket, reading exactly N bytes. 
431 ****************************************************************************/
432
433 static ssize_t read_socket_data(int fd,char *buffer,size_t N)
434 {
435   ssize_t  ret;
436   size_t total=0;  
437  
438   smb_read_error = 0;
439
440   while (total < N)
441   {
442 #ifdef WITH_SSL
443     if(fd == sslFd){
444       ret = SSL_read(ssl, buffer + total, N - total);
445     }else{
446       ret = read(fd,buffer + total,N - total);
447     }
448 #else /* WITH_SSL */
449     ret = read(fd,buffer + total,N - total);
450 #endif /* WITH_SSL */
451
452     if (ret == 0)
453     {
454       DEBUG(10,("read_socket_data: recv of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
455       smb_read_error = READ_EOF;
456       return 0;
457     }
458     if (ret == -1)
459     {
460       DEBUG(0,("read_socket_data: recv failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
461       smb_read_error = READ_ERROR;
462       return -1;
463     }
464     total += ret;
465   }
466   return (ssize_t)total;
467 }
468
469 /****************************************************************************
470  Write data to a fd.
471 ****************************************************************************/
472
473 ssize_t write_data(int fd,char *buffer,size_t N)
474 {
475   size_t total=0;
476   ssize_t ret;
477
478   while (total < N)
479   {
480 #ifdef WITH_SSL
481     if(fd == sslFd){
482       ret = SSL_write(ssl,buffer + total,N - total);
483     }else{
484       ret = write(fd,buffer + total,N - total);
485     }
486 #else /* WITH_SSL */
487     ret = write(fd,buffer + total,N - total);
488 #endif /* WITH_SSL */
489
490     if (ret == -1) {
491       DEBUG(0,("write_data: write failure. Error = %s\n", strerror(errno) ));
492       return -1;
493     }
494     if (ret == 0) return total;
495
496     total += ret;
497   }
498   return (ssize_t)total;
499 }
500
501 /****************************************************************************
502  Write data to a socket - use send rather than write.
503 ****************************************************************************/
504
505 ssize_t write_socket_data(int fd,char *buffer,size_t N)
506 {
507   size_t total=0;
508   ssize_t ret;
509
510   while (total < N)
511   {
512 #ifdef WITH_SSL
513     if(fd == sslFd){
514       ret = SSL_write(ssl,buffer + total,N - total);
515     }else{
516       ret = send(fd,buffer + total,N - total, 0);
517     }
518 #else /* WITH_SSL */
519     ret = send(fd,buffer + total,N - total,0);
520 #endif /* WITH_SSL */
521
522     if (ret == -1) {
523       DEBUG(0,("write_socket_data: write failure. Error = %s\n", strerror(errno) ));
524       return -1;
525     }
526     if (ret == 0) return total;
527
528     total += ret;
529   }
530   return (ssize_t)total;
531 }
532
533 /****************************************************************************
534 write to a socket
535 ****************************************************************************/
536
537 ssize_t write_socket(int fd,char *buf,size_t len)
538 {
539   ssize_t ret=0;
540
541   if (passive)
542     return(len);
543   DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
544   ret = write_socket_data(fd,buf,len);
545       
546   DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
547   if(ret <= 0)
548     DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n", 
549        (int)len, fd, strerror(errno) ));
550
551   return(ret);
552 }
553
554 /****************************************************************************
555 read 4 bytes of a smb packet and return the smb length of the packet
556 store the result in the buffer
557 This version of the function will return a length of zero on receiving
558 a keepalive packet.
559 timeout is in milliseconds.
560 ****************************************************************************/
561
562 static ssize_t read_smb_length_return_keepalive(int fd,char *inbuf,unsigned int timeout)
563 {
564   ssize_t len=0;
565   int msg_type;
566   BOOL ok = False;
567
568   while (!ok)
569   {
570     if (timeout > 0)
571       ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout) == 4);
572     else 
573       ok = (read_socket_data(fd,inbuf,4) == 4);
574
575     if (!ok)
576       return(-1);
577
578     len = smb_len(inbuf);
579     msg_type = CVAL(inbuf,0);
580
581     if (msg_type == 0x85) 
582       DEBUG(5,("Got keepalive packet\n"));
583   }
584
585   DEBUG(10,("got smb length of %d\n",len));
586
587   return(len);
588 }
589
590 /****************************************************************************
591 read 4 bytes of a smb packet and return the smb length of the packet
592 store the result in the buffer. This version of the function will
593 never return a session keepalive (length of zero).
594 timeout is in milliseconds.
595 ****************************************************************************/
596
597 ssize_t read_smb_length(int fd,char *inbuf,unsigned int timeout)
598 {
599   ssize_t len;
600
601   for(;;)
602   {
603     len = read_smb_length_return_keepalive(fd, inbuf, timeout);
604
605     if(len < 0)
606       return len;
607
608     /* Ignore session keepalives. */
609     if(CVAL(inbuf,0) != 0x85)
610       break;
611   }
612
613   DEBUG(10,("read_smb_length: got smb length of %d\n",len));
614
615   return len;
616 }
617
618 /****************************************************************************
619   read an smb from a fd. Note that the buffer *MUST* be of size
620   BUFFER_SIZE+SAFETY_MARGIN.
621   The timeout is in milliseconds. 
622   This function will return on a
623   receipt of a session keepalive packet.
624 ****************************************************************************/
625
626 BOOL receive_smb(int fd,char *buffer, unsigned int timeout)
627 {
628   ssize_t len,ret;
629
630   smb_read_error = 0;
631
632   memset(buffer,'\0',smb_size + 100);
633
634   len = read_smb_length_return_keepalive(fd,buffer,timeout);
635   if (len < 0)
636   {
637     DEBUG(10,("receive_smb: length < 0!\n"));
638     return(False);
639   }
640
641   if (len > BUFFER_SIZE) {
642     DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
643     if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
644     {
645         exit(1);
646     }
647   }
648
649   if(len > 0) {
650     ret = read_socket_data(fd,buffer+4,len);
651     if (ret != len) {
652       smb_read_error = READ_ERROR;
653       return False;
654     }
655   }
656   return(True);
657 }
658
659 /****************************************************************************
660   read an smb from a fd ignoring all keepalive packets. Note that the buffer 
661   *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
662   The timeout is in milliseconds
663
664   This is exactly the same as receive_smb except that it never returns
665   a session keepalive packet (just as receive_smb used to do).
666   receive_smb was changed to return keepalives as the oplock processing means this call
667   should never go into a blocking read.
668 ****************************************************************************/
669
670 BOOL client_receive_smb(int fd,char *buffer, unsigned int timeout)
671 {
672   BOOL ret;
673
674   for(;;)
675   {
676     ret = receive_smb(fd, buffer, timeout);
677
678     if (!ret)
679     {
680       DEBUG(10,("client_receive_smb failed\n"));
681       show_msg(buffer);
682       return ret;
683     }
684
685     /* Ignore session keepalive packets. */
686     if(CVAL(buffer,0) != 0x85)
687       break;
688   }
689   show_msg(buffer);
690   return ret;
691 }
692
693 /****************************************************************************
694   send an null session message to a fd
695 ****************************************************************************/
696
697 BOOL send_null_session_msg(int fd)
698 {
699   ssize_t ret;
700   uint32 blank = 0;
701   size_t len = 4;
702   size_t nwritten=0;
703   char *buffer = (char *)&blank;
704
705   while (nwritten < len)
706   {
707     ret = write_socket(fd,buffer+nwritten,len - nwritten);
708     if (ret <= 0)
709     {
710       DEBUG(0,("send_null_session_msg: Error writing %d bytes to client. %d. Exiting\n",(int)len,(int)ret));
711       exit(1);
712     }
713     nwritten += ret;
714   }
715
716   DEBUG(10,("send_null_session_msg: sent 4 null bytes to client.\n"));
717   return True;
718 }
719
720 /****************************************************************************
721   send an smb to a fd 
722 ****************************************************************************/
723
724 BOOL send_smb(int fd,char *buffer)
725 {
726   size_t len;
727   size_t nwritten=0;
728   ssize_t ret;
729   len = smb_len(buffer) + 4;
730
731   while (nwritten < len)
732   {
733     ret = write_socket(fd,buffer+nwritten,len - nwritten);
734     if (ret <= 0)
735     {
736       DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",(int)len,(int)ret));
737       exit(1);
738     }
739     nwritten += ret;
740   }
741
742   return True;
743 }
744
745 /****************************************************************************
746 send a single packet to a port on another machine
747 ****************************************************************************/
748
749 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
750 {
751   BOOL ret;
752   int out_fd;
753   struct sockaddr_in sock_out;
754
755   if (passive)
756     return(True);
757
758   /* create a socket to write to */
759   out_fd = socket(AF_INET, type, 0);
760   if (out_fd == -1) 
761     {
762       DEBUG(0,("socket failed"));
763       return False;
764     }
765
766   /* set the address and port */
767   memset((char *)&sock_out,'\0',sizeof(sock_out));
768   putip((char *)&sock_out.sin_addr,(char *)&ip);
769   sock_out.sin_port = htons( port );
770   sock_out.sin_family = AF_INET;
771   
772   if (DEBUGLEVEL > 0)
773     DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
774              len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
775         
776   /* send it */
777   ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
778
779   if (!ret)
780     DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
781              inet_ntoa(ip),port,strerror(errno)));
782
783   close(out_fd);
784   return(ret);
785 }
786
787 /****************************************************************************
788 open a socket of the specified type, port and address for incoming data
789 ****************************************************************************/
790
791 int open_socket_in(int type, int port, int dlevel,uint32 socket_addr, BOOL rebind)
792 {
793   struct hostent *hp;
794   struct sockaddr_in sock;
795   pstring host_name;
796   int res;
797
798   /* get my host name */
799   if (gethostname(host_name, MAXHOSTNAMELEN) == -1) 
800     { DEBUG(0,("gethostname failed\n")); return -1; } 
801
802   /* get host info */
803   if ((hp = Get_Hostbyname(host_name)) == 0) 
804     {
805       DEBUG(0,( "Get_Hostbyname: Unknown host %s\n",host_name));
806       return -1;
807     }
808   
809   memset((char *)&sock,'\0',sizeof(sock));
810   memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
811
812 #ifdef HAVE_SOCK_SIN_LEN
813   sock.sin_len = sizeof(sock);
814 #endif
815   sock.sin_port = htons( port );
816   sock.sin_family = hp->h_addrtype;
817   sock.sin_addr.s_addr = socket_addr;
818   res = socket(hp->h_addrtype, type, 0);
819   if (res == -1) 
820     { DEBUG(0,("socket failed\n")); return -1; }
821
822   {
823     int val=1;
824         if(rebind)
825                 val=1;
826         else
827                 val=0;
828     if(setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val)) == -1)
829                 DEBUG(dlevel,("setsockopt: SO_REUSEADDR=%d on port %d failed with error = %s\n",
830                         val, port, strerror(errno) ));
831 #ifdef SO_REUSEPORT
832     if(setsockopt(res,SOL_SOCKET,SO_REUSEPORT,(char *)&val,sizeof(val)) == -1)
833                 DEBUG(dlevel,("setsockopt: SO_REUSEPORT=%d on port %d failed with error = %s\n",
834                         val, port, strerror(errno) ));
835 #endif /* SO_REUSEPORT */
836   }
837
838   /* now we've got a socket - we need to bind it */
839   if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0) 
840     { 
841       if (port) {
842         if (port == SMB_PORT || port == NMB_PORT)
843           DEBUG(dlevel,("bind failed on port %d socket_addr=%s (%s)\n",
844                         port,inet_ntoa(sock.sin_addr),strerror(errno))); 
845         close(res); 
846
847         if (dlevel > 0 && port < 1000)
848           port = 7999;
849
850         if (port >= 1000 && port < 9000)
851           return(open_socket_in(type,port+1,dlevel,socket_addr,rebind));
852       }
853
854       return(-1); 
855     }
856   DEBUG(3,("bind succeeded on port %d\n",port));
857
858   return res;
859 }
860
861 /****************************************************************************
862   create an outgoing socket. timeout is in milliseconds.
863   **************************************************************************/
864
865 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
866 {
867   struct sockaddr_in sock_out;
868   int res,ret;
869   int connect_loop = 250; /* 250 milliseconds */
870   int loops = (timeout) / connect_loop;
871
872   /* create a socket to write to */
873   res = socket(PF_INET, type, 0);
874   if (res == -1) 
875     { DEBUG(0,("socket error\n")); return -1; }
876
877   if (type != SOCK_STREAM) return(res);
878   
879   memset((char *)&sock_out,'\0',sizeof(sock_out));
880   putip((char *)&sock_out.sin_addr,(char *)addr);
881   
882   sock_out.sin_port = htons( port );
883   sock_out.sin_family = PF_INET;
884
885   /* set it non-blocking */
886   set_blocking(res,False);
887
888   DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
889   
890   /* and connect it to the destination */
891 connect_again:
892   ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
893
894   /* Some systems return EAGAIN when they mean EINPROGRESS */
895   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
896         errno == EAGAIN) && loops--) {
897     msleep(connect_loop);
898     goto connect_again;
899   }
900
901   if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
902          errno == EAGAIN)) {
903       DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
904       close(res);
905       return -1;
906   }
907
908 #ifdef EISCONN
909   if (ret < 0 && errno == EISCONN) {
910     errno = 0;
911     ret = 0;
912   }
913 #endif
914
915   if (ret < 0) {
916     DEBUG(1,("error connecting to %s:%d (%s)\n",
917              inet_ntoa(*addr),port,strerror(errno)));
918     close(res);
919     return -1;
920   }
921
922   /* set it blocking again */
923   set_blocking(res,True);
924
925   return res;
926 }
927
928
929 /*******************************************************************
930  Reset the 'done' variables so after a client process is created
931  from a fork call these calls will be re-done. This should be
932  expanded if more variables need reseting.
933  ******************************************************************/
934
935
936 void reset_globals_after_fork(void)
937 {
938   /*
939    * Re-seed the random crypto generator, so all smbd's
940    * started from the same parent won't generate the same
941    * sequence.
942    */
943   {
944     unsigned char dummy;
945     generate_random_buffer( &dummy, 1, True);
946   } 
947 }
948
949 /* the following 3 client_*() functions are nasty ways of allowing
950    some generic functions to get info that really should be hidden in
951    particular modules */
952 static int client_fd = -1;
953
954 void client_setfd(int fd)
955 {
956         client_fd = fd;
957 }
958
959 char *client_name(void)
960 {
961         return get_socket_name(client_fd);
962 }
963
964 char *client_addr(void)
965 {
966         return get_socket_addr(client_fd);
967 }
968
969 /*******************************************************************
970  matchname - determine if host name matches IP address. Used to
971  confirm a hostname lookup to prevent spoof attacks
972  ******************************************************************/
973 static BOOL matchname(char *remotehost,struct in_addr  addr)
974 {
975         struct hostent *hp;
976         int     i;
977         
978         if ((hp = Get_Hostbyname(remotehost)) == 0) {
979                 DEBUG(0,("Get_Hostbyname(%s): lookup failure.\n", remotehost));
980                 return False;
981         } 
982
983         /*
984          * Make sure that gethostbyname() returns the "correct" host name.
985          * Unfortunately, gethostbyname("localhost") sometimes yields
986          * "localhost.domain". Since the latter host name comes from the
987          * local DNS, we just have to trust it (all bets are off if the local
988          * DNS is perverted). We always check the address list, though.
989          */
990         
991         if (strcasecmp(remotehost, hp->h_name)
992             && strcasecmp(remotehost, "localhost")) {
993                 DEBUG(0,("host name/name mismatch: %s != %s\n",
994                          remotehost, hp->h_name));
995                 return False;
996         }
997         
998         /* Look up the host address in the address list we just got. */
999         for (i = 0; hp->h_addr_list[i]; i++) {
1000                 if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
1001                         return True;
1002         }
1003         
1004         /*
1005          * The host name does not map to the original host address. Perhaps
1006          * someone has compromised a name server. More likely someone botched
1007          * it, but that could be dangerous, too.
1008          */
1009         
1010         DEBUG(0,("host name/address mismatch: %s != %s\n",
1011                  inet_ntoa(addr), hp->h_name));
1012         return False;
1013 }
1014
1015  
1016 /*******************************************************************
1017  return the DNS name of the remote end of a socket
1018  ******************************************************************/
1019 char *get_socket_name(int fd)
1020 {
1021         static pstring name_buf;
1022         static fstring addr_buf;
1023         struct hostent *hp;
1024         struct in_addr addr;
1025         char *p;
1026         
1027         p = get_socket_addr(fd);
1028
1029         /* it might be the same as the last one - save some DNS work */
1030         if (strcmp(p, addr_buf) == 0) return name_buf;
1031
1032         pstrcpy(name_buf,"UNKNOWN");
1033         if (fd == -1) return name_buf;
1034
1035         fstrcpy(addr_buf, p);
1036
1037         if (inet_aton(p, &addr) == 0) return name_buf;
1038         
1039         /* Look up the remote host name. */
1040         if ((hp = gethostbyaddr((char *)&addr.s_addr, sizeof(addr.s_addr), AF_INET)) == 0) {
1041                 DEBUG(1,("Gethostbyaddr failed for %s\n",p));
1042                 pstrcpy(name_buf, p);
1043         } else {
1044                 pstrcpy(name_buf,(char *)hp->h_name);
1045                 if (!matchname(name_buf, addr)) {
1046                         DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1047                         pstrcpy(name_buf,"UNKNOWN");
1048                 }
1049         }
1050         return name_buf;
1051 }
1052
1053 /*******************************************************************
1054  return the IP addr of the remote end of a socket as a string 
1055  ******************************************************************/
1056 char *get_socket_addr(int fd)
1057 {
1058         struct sockaddr sa;
1059         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
1060         int     length = sizeof(sa);
1061         static fstring addr_buf;
1062
1063         fstrcpy(addr_buf,"0.0.0.0");
1064
1065         if (fd == -1) {
1066                 return addr_buf;
1067         }
1068         
1069         if (getpeername(fd, &sa, &length) < 0) {
1070                 DEBUG(0,("getpeername failed. Error was %s\n", strerror(errno) ));
1071                 return addr_buf;
1072         }
1073         
1074         fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
1075         
1076         return addr_buf;
1077 }
1078
1079 /*******************************************************************
1080  opens and connects to a unix pipe socket
1081  ******************************************************************/
1082 int open_pipe_sock(char *path)
1083 {
1084         int sock;
1085         struct sockaddr_un sa;
1086
1087         sock = socket(AF_UNIX, SOCK_STREAM, 0);
1088
1089         if (sock < 0)
1090         {
1091                 DEBUG(0, ("unix socket open failed\n"));
1092                 return sock;
1093         }
1094
1095         ZERO_STRUCT(sa);
1096         sa.sun_family = AF_UNIX;
1097         safe_strcpy(sa.sun_path, path, sizeof(sa.sun_path)-1);
1098
1099         DEBUG(10, ("socket open succeeded.  file name: %s\n", sa.sun_path));
1100
1101         if (connect(sock, (struct sockaddr*) &sa, sizeof(sa)) < 0)
1102         {
1103                 DEBUG(0,("socket connect to %s failed\n", sa.sun_path));
1104                 close(sock);
1105                 return -1;
1106         }
1107
1108         return sock;
1109 }
1110
1111 int create_pipe_socket(char *dir, int dir_perms,
1112                                 char *path, int path_perms)
1113 {
1114         int s;
1115         struct sockaddr_un sa;
1116
1117         DEBUG(0,("create_pipe_socket: %s %d %s %d\n",
1118                    dir, dir_perms, path, path_perms));
1119
1120         DEBUG(0,("*** RACE CONDITION.  PLEASE SOMEONE EXAMINE create_pipe_Socket AND FIX IT ***\n"));
1121
1122         mkdir(dir, dir_perms);
1123
1124         if (chmod(dir, dir_perms) < 0)
1125         {
1126                 DEBUG(0, ("chmod on %s failed\n", dir));
1127                 return -1;
1128         }
1129
1130         if (!remove(path))
1131         {
1132                 DEBUG(0, ("remove on %s failed\n", path));
1133         }
1134                 
1135         /* start listening on unix socket */
1136         s = socket(AF_UNIX, SOCK_STREAM, 0);
1137
1138         if (s < 0)
1139         {
1140                 DEBUG(0, ("socket open failed\n"));
1141                 return -1;
1142         }
1143
1144         ZERO_STRUCT(sa);
1145         sa.sun_family = AF_UNIX;
1146         safe_strcpy(sa.sun_path, path, sizeof(sa.sun_path)-1);
1147
1148         if (bind(s, (struct sockaddr*) &sa, sizeof(sa)) < 0)
1149         {
1150                 DEBUG(0, ("socket bind to %s failed\n", sa.sun_path));
1151                 close(s);
1152                 remove(path);
1153                 return -1;
1154         }
1155
1156         if (s == -1)
1157         {
1158                 DEBUG(0,("bind failed\n"));
1159                 remove(path);
1160                 return -1;
1161         }
1162
1163         if (path_perms != 0)
1164         {
1165                 chmod(path, path_perms);
1166         }
1167
1168         if (listen(s, 5) == -1)
1169         {
1170                 DEBUG(0,("listen failed\n"));
1171                 return -1;
1172         }
1173
1174         DEBUG(5,("unix socket opened: %s\n", path));
1175
1176         return s;
1177 }