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