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