Use socklen_t for getpeername, since we hopefully now have it defined
[rsync/rsync.git] / socket.c
1 /* -*- c-file-style: "linux" -*-
2    
3    Copyright (C) 1998-2001 by Andrew Tridgell <tridge@samba.org>
4    
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9    
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14    
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 /*
21   socket functions used in rsync 
22
23   */
24
25 #include "rsync.h"
26
27
28 /* Establish a proxy connection on an open socket to a web roxy by
29  * using the CONNECT method. */
30 static int establish_proxy_connection(int fd, char *host, int port)
31 {
32         char buffer[1024];
33         char *cp;
34
35         snprintf(buffer, sizeof(buffer), "CONNECT %s:%d HTTP/1.0\r\n\r\n", host, port);
36         if (write(fd, buffer, strlen(buffer)) != strlen(buffer)) {
37                 rprintf(FERROR, "failed to write to proxy: %s\n",
38                         strerror(errno));
39                 return -1;
40         }
41
42         for (cp = buffer; cp < &buffer[sizeof(buffer) - 1]; cp++) {
43                 if (read(fd, cp, 1) != 1) {
44                         rprintf(FERROR, "failed to read from proxy: %s\n",
45                                 strerror(errno));
46                         return -1;
47                 }
48                 if (*cp == '\n')
49                         break;
50         }
51
52         if (*cp != '\n')
53                 cp++;
54         *cp-- = '\0';
55         if (*cp == '\r')
56                 *cp = '\0';
57         if (strncmp(buffer, "HTTP/", 5) != 0) {
58                 rprintf(FERROR, "bad response from proxy - %s\n",
59                         buffer);
60                 return -1;
61         }
62         for (cp = &buffer[5]; isdigit(*cp) || (*cp == '.'); cp++)
63                 ;
64         while (*cp == ' ')
65                 cp++;
66         if (*cp != '2') {
67                 rprintf(FERROR, "bad response from proxy - %s\n",
68                         buffer);
69                 return -1;
70         }
71         /* throw away the rest of the HTTP header */
72         while (1) {
73                 for (cp = buffer; cp < &buffer[sizeof(buffer) - 1];
74                      cp++) {
75                         if (read(fd, cp, 1) != 1) {
76                                 rprintf(FERROR, "failed to read from proxy: %s\n",
77                                         strerror(errno));
78                                 return -1;
79                         }
80                         if (*cp == '\n')
81                                 break;
82                 }
83                 if ((cp > buffer) && (*cp == '\n'))
84                         cp--;
85                 if ((cp == buffer) && ((*cp == '\n') || (*cp == '\r')))
86                         break;
87         }
88         return 0;
89 }
90
91
92 /* open a socket to a tcp remote host with the specified port 
93    based on code from Warren
94    proxy support by Stephen Rothwell */
95 int open_socket_out(char *host, int port, struct in_addr *address)
96 {
97         int type = SOCK_STREAM;
98         struct sockaddr_in sock_out;
99         struct sockaddr_in sock;
100         int res;
101         struct hostent *hp;
102         char *h;
103         unsigned p;
104         int proxied = 0;
105         char buffer[1024];
106         char *cp;
107
108         /* if we have a RSYNC_PROXY env variable then redirect our
109          * connetcion via a web proxy at the given address. The format
110          * is hostname:port */
111         h = getenv("RSYNC_PROXY");
112         proxied = (h != NULL) && (*h != '\0');
113
114         if (proxied) {
115                 strlcpy(buffer, h, sizeof(buffer));
116                 cp = strchr(buffer, ':');
117                 if (cp == NULL) {
118                         rprintf(FERROR,
119                                 "invalid proxy specification: should be HOST:PORT\n");
120                         return -1;
121                 }
122                 *cp++ = '\0';
123                 p = atoi(cp);
124                 h = buffer;
125         } else {
126                 h = host;
127                 p = port;
128         }
129
130         res = socket(PF_INET, type, 0);
131         if (res == -1) {
132                 return -1;
133         }
134
135         hp = gethostbyname(h);
136         if (!hp) {
137                 rprintf(FERROR,"unknown host: %s\n", h);
138                 close(res);
139                 return -1;
140         }
141
142         memcpy(&sock_out.sin_addr, hp->h_addr, hp->h_length);
143         sock_out.sin_port = htons(p);
144         sock_out.sin_family = PF_INET;
145
146         if (address) {
147                 sock.sin_addr = *address;
148                 sock.sin_port = 0;
149                 sock.sin_family = hp->h_addrtype;
150                 bind(res, (struct sockaddr * ) &sock,sizeof(sock));
151         }
152
153         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
154                 rprintf(FERROR,"failed to connect to %s - %s\n", h, strerror(errno));
155                 close(res);
156                 return -1;
157         }
158
159         if (proxied && establish_proxy_connection(res, host, port) != 0) {
160                 close(res);
161                 return -1;
162         }
163
164         return res;
165 }
166
167
168 /****************************************************************************
169 open a socket of the specified type, port and address for incoming data
170 ****************************************************************************/
171 static int open_socket_in(int type, int port, struct in_addr *address)
172 {
173         struct sockaddr_in sock;
174         int res;
175         int one=1;
176
177         memset((char *)&sock,0,sizeof(sock));
178         sock.sin_port = htons(port);
179         sock.sin_family = AF_INET;
180         if (address) {
181                 sock.sin_addr = *address;
182         } else {
183                 sock.sin_addr.s_addr = INADDR_ANY;
184         }
185         res = socket(AF_INET, type, 0);
186         if (res == -1) { 
187                 rprintf(FERROR,"socket failed: %s\n",
188                         strerror(errno)); 
189                 return -1; 
190         }
191
192         setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
193
194         /* now we've got a socket - we need to bind it */
195         if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) == -1) { 
196                 rprintf(FERROR,"bind failed on port %d: %s\n", port,
197                         strerror(errno));
198                 if (errno == EACCES && port < 1024) {
199                         rprintf(FERROR, "Note: you must be root to bind "
200                                 "to low-numbered ports");
201                 }
202                 close(res); 
203                 return -1;
204         }
205
206         return res;
207 }
208
209
210 /*
211  * Determine if a file descriptor is in fact a socket
212  */
213 int is_a_socket(int fd)
214 {
215         int v;
216         socklen_t l;
217         l = sizeof(int);
218
219         /* Parameters to getsockopt, setsockopt etc are very
220          * unstandardized across platforms, so don't be surprised if
221          * there are compiler warnings on e.g. SCO OpenSwerver or AIX.
222          * It seems they all eventually get the right idea.
223          *
224          * Debian says: ``The fifth argument of getsockopt and
225          * setsockopt is in reality an int [*] (and this is what BSD
226          * 4.* and libc4 and libc5 have).  Some POSIX confusion
227          * resulted in the present socklen_t.  The draft standard has
228          * not been adopted yet, but glibc2 already follows it and
229          * also has socklen_t [*]. See also accept(2).''
230          *
231          * We now return to your regularly scheduled programming.  */
232         return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
233 }
234
235
236 void start_accept_loop(int port, int (*fn)(int ))
237 {
238         int s;
239         extern struct in_addr socket_address;
240
241         /* open an incoming socket */
242         s = open_socket_in(SOCK_STREAM, port, &socket_address);
243         if (s == -1)
244                 exit_cleanup(RERR_SOCKETIO);
245
246         /* ready to listen */
247         if (listen(s, 5) == -1) {
248                 close(s);
249                 exit_cleanup(RERR_SOCKETIO);
250         }
251
252
253         /* now accept incoming connections - forking a new process
254            for each incoming connection */
255         while (1) {
256                 fd_set fds;
257                 int fd;
258                 struct sockaddr addr;
259                 socklen_t in_addrlen = sizeof(addr);
260
261                 /* close log file before the potentially very long select so
262                    file can be trimmed by another process instead of growing
263                    forever */
264                 log_close();
265
266                 FD_ZERO(&fds);
267                 FD_SET(s, &fds);
268
269                 if (select(s+1, &fds, NULL, NULL, NULL) != 1) {
270                         continue;
271                 }
272
273                 if(!FD_ISSET(s, &fds)) continue;
274
275                 /* See note above prototypes. */
276                 fd = accept(s,&addr, &in_addrlen);
277
278                 if (fd == -1) continue;
279
280                 signal(SIGCHLD, SIG_IGN);
281
282                 /* we shouldn't have any children left hanging around
283                    but I have had reports that on Digital Unix zombies
284                    are produced, so this ensures that they are reaped */
285 #ifdef WNOHANG
286                 while (waitpid(-1, NULL, WNOHANG) > 0);
287 #endif
288
289                 if (fork()==0) {
290                         close(s);
291
292                         /* open log file in child before possibly giving
293                            up privileges  */
294                         log_open();
295
296                         _exit(fn(fd));
297                 }
298
299                 close(fd);
300         }
301 }
302
303
304 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
305
306 struct
307 {
308   char *name;
309   int level;
310   int option;
311   int value;
312   int opttype;
313 } socket_options[] = {
314   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
315   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
316   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
317 #ifdef TCP_NODELAY
318   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
319 #endif
320 #ifdef IPTOS_LOWDELAY
321   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
322 #endif
323 #ifdef IPTOS_THROUGHPUT
324   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
325 #endif
326 #ifdef SO_SNDBUF
327   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
328 #endif
329 #ifdef SO_RCVBUF
330   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
331 #endif
332 #ifdef SO_SNDLOWAT
333   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
334 #endif
335 #ifdef SO_RCVLOWAT
336   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
337 #endif
338 #ifdef SO_SNDTIMEO
339   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
340 #endif
341 #ifdef SO_RCVTIMEO
342   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
343 #endif
344   {NULL,0,0,0,0}};
345
346         
347
348 /****************************************************************************
349 set user socket options
350 ****************************************************************************/
351 void set_socket_options(int fd, char *options)
352 {
353         char *tok;
354         if (!options || !*options) return;
355
356         options = strdup(options);
357         
358         if (!options) out_of_memory("set_socket_options");
359
360         for (tok=strtok(options, " \t,"); tok; tok=strtok(NULL," \t,")) {
361                 int ret=0,i;
362                 int value = 1;
363                 char *p;
364                 int got_value = 0;
365
366                 if ((p = strchr(tok,'='))) {
367                         *p = 0;
368                         value = atoi(p+1);
369                         got_value = 1;
370                 }
371
372                 for (i=0;socket_options[i].name;i++)
373                         if (strcmp(socket_options[i].name,tok)==0)
374                                 break;
375
376                 if (!socket_options[i].name) {
377                         rprintf(FERROR,"Unknown socket option %s\n",tok);
378                         continue;
379                 }
380
381                 switch (socket_options[i].opttype) {
382                 case OPT_BOOL:
383                 case OPT_INT:
384                         ret = setsockopt(fd,socket_options[i].level,
385                                          socket_options[i].option,(char *)&value,sizeof(int));
386                         break;
387                         
388                 case OPT_ON:
389                         if (got_value)
390                                 rprintf(FERROR,"syntax error - %s does not take a value\n",tok);
391
392                         {
393                                 int on = socket_options[i].value;
394                                 ret = setsockopt(fd,socket_options[i].level,
395                                                  socket_options[i].option,(char *)&on,sizeof(int));
396                         }
397                         break;    
398                 }
399                 
400                 if (ret != 0)
401                         rprintf(FERROR, "failed to set socket option %s: %s\n", tok,
402                                 strerror(errno));
403         }
404
405         free(options);
406 }
407
408 /****************************************************************************
409 become a daemon, discarding the controlling terminal
410 ****************************************************************************/
411 void become_daemon(void)
412 {
413         int i;
414
415         if (fork()) {
416                 _exit(0);
417         }
418
419         /* detach from the terminal */
420 #ifdef HAVE_SETSID
421         setsid();
422 #else
423 #ifdef TIOCNOTTY
424         i = open("/dev/tty", O_RDWR);
425         if (i >= 0) {
426                 ioctl(i, (int) TIOCNOTTY, (char *)0);      
427                 close(i);
428         }
429 #endif /* TIOCNOTTY */
430 #endif
431         /* make sure that stdin, stdout an stderr don't stuff things
432            up (library functions, for example) */
433         for (i=0;i<3;i++) {
434                 close(i); 
435                 open("/dev/null", O_RDWR);
436         }
437 }
438
439 /*******************************************************************
440  return the IP addr of the client as a string 
441  ******************************************************************/
442 char *client_addr(int fd)
443 {
444         struct sockaddr sa;
445         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
446         socklen_t length = sizeof(sa);
447         static char addr_buf[100];
448         static int initialised;
449
450         if (initialised) return addr_buf;
451
452         initialised = 1;
453
454         if (getpeername(fd, &sa, &length)) {
455                 exit_cleanup(RERR_SOCKETIO);
456         }
457         
458         strlcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr), sizeof(addr_buf));
459         return addr_buf;
460 }
461
462
463 /*******************************************************************
464  return the DNS name of the client 
465  ******************************************************************/
466 char *client_name(int fd)
467 {
468         struct sockaddr sa;
469         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
470         socklen_t length = sizeof(sa);
471         static char name_buf[100];
472         struct hostent *hp;
473         char **p;
474         char *def = "UNKNOWN";
475         static int initialised;
476
477         if (initialised) return name_buf;
478
479         initialised = 1;
480
481         strcpy(name_buf,def);
482
483         if (getpeername(fd, &sa, &length)) {
484                 exit_cleanup(RERR_SOCKETIO);
485         }
486
487         /* Look up the remote host name. */
488         if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
489                                 sizeof(sockin->sin_addr),
490                                 AF_INET))) {
491                 strlcpy(name_buf,(char *)hp->h_name,sizeof(name_buf));
492         }
493
494
495         /* do a forward lookup as well to prevent spoofing */
496         hp = gethostbyname(name_buf);
497         if (!hp) {
498                 strcpy (name_buf,def);
499                 rprintf (FERROR, "reverse name lookup for \"%s\" failed\n",
500                         name_buf);
501         } else {
502                 for (p=hp->h_addr_list;*p;p++) {
503                         if (memcmp(*p, &sockin->sin_addr, hp->h_length) == 0) {
504                                 break;
505                         }
506                 }
507                 if (!*p) {
508                         strcpy(name_buf,def);
509                         rprintf(FERROR,"reverse name lookup mismatch - spoofed address?\n");
510                 } 
511         }
512
513         return name_buf;
514 }
515
516 /**
517    Convert a string to an IP address. The string can be a name or
518    dotted decimal number.
519
520    Returns a pointer to a static in_addr struct -- if you call this
521    more than once then you should copy it.
522 */
523 struct in_addr *ip_address(const char *str)
524 {
525         static struct in_addr ret;
526         struct hostent *hp;
527
528         if (!str) {
529                 rprintf (FERROR, "ip_address received NULL name\n");
530                 return NULL;
531         }
532
533         /* try as an IP address */
534         if (inet_aton(str, &ret) != 0) {
535                 return &ret;
536         }
537
538         /* otherwise assume it's a network name of some sort and use 
539            gethostbyname */
540         if ((hp = gethostbyname(str)) == 0) {
541                 rprintf(FERROR, "gethostbyname failed for \"%s\": unknown host?\n",str);
542                 return NULL;
543         }
544
545         if (hp->h_addr == NULL) {
546                 rprintf(FERROR, "gethostbyname: host address is invalid for host \"%s\"\n",str);
547                 return NULL;
548         }
549
550         if (hp->h_length > sizeof(ret)) {
551                 rprintf(FERROR, "gethostbyname: host address for \"%s\" is too large\n",
552                         str);
553                 return NULL;
554         }
555
556         memcpy(&ret.s_addr, hp->h_addr, hp->h_length);
557
558         return(&ret);
559 }