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