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