added --address option for virtual hosting
[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)
93 {
94         int type = SOCK_STREAM;
95         struct sockaddr_in sock_out;
96         int res;
97         struct hostent *hp;
98         char *h;
99         unsigned p;
100         int proxied = 0;
101         char buffer[1024];
102         char *cp;
103
104         /* if we have a RSYNC_PROXY env variable then redirect our connetcion via a web proxy
105            at the given address. The format is hostname:port */
106         h = getenv("RSYNC_PROXY");
107         proxied = (h != NULL) && (*h != '\0');
108
109         if (proxied) {
110                 strlcpy(buffer, h, sizeof(buffer));
111                 cp = strchr(buffer, ':');
112                 if (cp == NULL) {
113                         rprintf(FERROR, "invalid proxy specification\n");
114                         return -1;
115                 }
116                 *cp++ = '\0';
117                 p = atoi(cp);
118                 h = buffer;
119         } else {
120                 h = host;
121                 p = port;
122         }
123
124         res = socket(PF_INET, type, 0);
125         if (res == -1) {
126                 return -1;
127         }
128
129         hp = gethostbyname(h);
130         if (!hp) {
131                 rprintf(FERROR,"unknown host: %s\n", h);
132                 close(res);
133                 return -1;
134         }
135
136         memcpy(&sock_out.sin_addr, hp->h_addr, hp->h_length);
137         sock_out.sin_port = htons(p);
138         sock_out.sin_family = PF_INET;
139
140         if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
141                 rprintf(FERROR,"failed to connect to %s - %s\n", h, strerror(errno));
142                 close(res);
143                 return -1;
144         }
145
146         if (proxied && establish_proxy_connection(res, host, port) != 0) {
147                 close(res);
148                 return -1;
149         }
150
151         set_nonblocking(res);
152
153         return res;
154 }
155
156
157 /****************************************************************************
158 open a socket of the specified type, port and address for incoming data
159 ****************************************************************************/
160 static int open_socket_in(int type, int port, struct in_addr *address)
161 {
162         struct hostent *hp;
163         struct sockaddr_in sock;
164         char host_name[MAXHOSTNAMELEN];
165         int res;
166         int one=1;
167
168         /* get my host name */
169         if (gethostname(host_name, sizeof(host_name)) == -1) { 
170                 rprintf(FERROR,"gethostname failed\n"); 
171                 return -1; 
172         } 
173
174         /* get host info */
175         if ((hp = gethostbyname(host_name)) == 0) {
176                 rprintf(FERROR,"gethostbyname: Unknown host %s\n",host_name);
177                 return -1;
178         }
179   
180         memset((char *)&sock,0,sizeof(sock));
181         memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
182         sock.sin_port = htons(port);
183         sock.sin_family = hp->h_addrtype;
184         if (address) {
185                 sock.sin_addr = *address;
186         } else {
187                 sock.sin_addr.s_addr = INADDR_ANY;
188         }
189         res = socket(hp->h_addrtype, type, 0);
190         if (res == -1) { 
191                 rprintf(FERROR,"socket failed\n"); 
192                 return -1; 
193         }
194
195         setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
196
197         /* now we've got a socket - we need to bind it */
198         if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) == -1) { 
199                 rprintf(FERROR,"bind failed on port %d\n", port);
200                 close(res); 
201                 return -1;
202         }
203
204         return res;
205 }
206
207
208 /****************************************************************************
209 determine if a file descriptor is in fact a socket
210 ****************************************************************************/
211 int is_a_socket(int fd)
212 {
213         int v,l;
214         l = sizeof(int);
215         return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
216 }
217
218
219 void start_accept_loop(int port, int (*fn)(int ))
220 {
221         int s;
222         extern struct in_addr socket_address;
223
224         /* open an incoming socket */
225         s = open_socket_in(SOCK_STREAM, port, &socket_address);
226         if (s == -1)
227                 exit_cleanup(RERR_SOCKETIO);
228
229         /* ready to listen */
230         if (listen(s, 5) == -1) {
231                 close(s);
232                 exit_cleanup(RERR_SOCKETIO);
233         }
234
235
236         /* now accept incoming connections - forking a new process
237            for each incoming connection */
238         while (1) {
239                 fd_set fds;
240                 int fd;
241                 struct sockaddr addr;
242                 int in_addrlen = sizeof(addr);
243
244                 FD_ZERO(&fds);
245                 FD_SET(s, &fds);
246
247                 if (select(s+1, &fds, NULL, NULL, NULL) != 1) {
248                         continue;
249                 }
250
251                 if(!FD_ISSET(s, &fds)) continue;
252
253                 fd = accept(s,&addr,&in_addrlen);
254
255                 if (fd == -1) continue;
256
257                 signal(SIGCHLD, SIG_IGN);
258
259                 /* we shouldn't have any children left hanging around
260                    but I have had reports that on Digital Unix zombies
261                    are produced, so this ensures that they are reaped */
262 #ifdef WNOHANG
263                 while (waitpid(-1, NULL, WNOHANG) > 0);
264 #endif
265
266                 if (fork()==0) {
267                         close(s);
268
269                         set_nonblocking(fd);
270
271                         _exit(fn(fd));
272                 }
273
274                 close(fd);
275         }
276 }
277
278
279 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
280
281 struct
282 {
283   char *name;
284   int level;
285   int option;
286   int value;
287   int opttype;
288 } socket_options[] = {
289   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
290   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
291   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
292 #ifdef TCP_NODELAY
293   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
294 #endif
295 #ifdef IPTOS_LOWDELAY
296   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
297 #endif
298 #ifdef IPTOS_THROUGHPUT
299   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
300 #endif
301 #ifdef SO_SNDBUF
302   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
303 #endif
304 #ifdef SO_RCVBUF
305   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
306 #endif
307 #ifdef SO_SNDLOWAT
308   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
309 #endif
310 #ifdef SO_RCVLOWAT
311   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
312 #endif
313 #ifdef SO_SNDTIMEO
314   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
315 #endif
316 #ifdef SO_RCVTIMEO
317   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
318 #endif
319   {NULL,0,0,0,0}};
320
321         
322
323 /****************************************************************************
324 set user socket options
325 ****************************************************************************/
326 void set_socket_options(int fd, char *options)
327 {
328         char *tok;
329         if (!options || !*options) return;
330
331         options = strdup(options);
332         
333         if (!options) out_of_memory("set_socket_options");
334
335         for (tok=strtok(options, " \t,"); tok; tok=strtok(NULL," \t,")) {
336                 int ret=0,i;
337                 int value = 1;
338                 char *p;
339                 int got_value = 0;
340
341                 if ((p = strchr(tok,'='))) {
342                         *p = 0;
343                         value = atoi(p+1);
344                         got_value = 1;
345                 }
346
347                 for (i=0;socket_options[i].name;i++)
348                         if (strcmp(socket_options[i].name,tok)==0)
349                                 break;
350
351                 if (!socket_options[i].name) {
352                         rprintf(FERROR,"Unknown socket option %s\n",tok);
353                         continue;
354                 }
355
356                 switch (socket_options[i].opttype) {
357                 case OPT_BOOL:
358                 case OPT_INT:
359                         ret = setsockopt(fd,socket_options[i].level,
360                                          socket_options[i].option,(char *)&value,sizeof(int));
361                         break;
362                         
363                 case OPT_ON:
364                         if (got_value)
365                                 rprintf(FERROR,"syntax error - %s does not take a value\n",tok);
366
367                         {
368                                 int on = socket_options[i].value;
369                                 ret = setsockopt(fd,socket_options[i].level,
370                                                  socket_options[i].option,(char *)&on,sizeof(int));
371                         }
372                         break;    
373                 }
374                 
375                 if (ret != 0)
376                         rprintf(FERROR,"Failed to set socket option %s\n",tok);
377         }
378
379         free(options);
380 }
381
382 /****************************************************************************
383 become a daemon, discarding the controlling terminal
384 ****************************************************************************/
385 void become_daemon(void)
386 {
387         int i;
388
389         if (fork()) {
390                 _exit(0);
391         }
392
393         /* detach from the terminal */
394 #ifdef HAVE_SETSID
395         setsid();
396 #else
397 #ifdef TIOCNOTTY
398         i = open("/dev/tty", O_RDWR);
399         if (i >= 0) {
400                 ioctl(i, (int) TIOCNOTTY, (char *)0);      
401                 close(i);
402         }
403 #endif /* TIOCNOTTY */
404 #endif
405         /* make sure that stdin, stdout an stderr don't stuff things
406            up (library functions, for example) */
407         for (i=0;i<3;i++) {
408                 close(i); 
409                 open("/dev/null", O_RDWR);
410         }
411 }
412
413 /*******************************************************************
414  return the IP addr of the client as a string 
415  ******************************************************************/
416 char *client_addr(int fd)
417 {
418         struct sockaddr sa;
419         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
420         int     length = sizeof(sa);
421         static char addr_buf[100];
422         static int initialised;
423
424         if (initialised) return addr_buf;
425
426         initialised = 1;
427
428         if (getpeername(fd, &sa, &length)) {
429                 exit_cleanup(RERR_SOCKETIO);
430         }
431         
432         strlcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr), sizeof(addr_buf));
433         return addr_buf;
434 }
435
436
437 /*******************************************************************
438  return the DNS name of the client 
439  ******************************************************************/
440 char *client_name(int fd)
441 {
442         struct sockaddr sa;
443         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
444         int     length = sizeof(sa);
445         static char name_buf[100];
446         struct hostent *hp;
447         char **p;
448         char *def = "UNKNOWN";
449         static int initialised;
450
451         if (initialised) return name_buf;
452
453         initialised = 1;
454
455         strcpy(name_buf,def);
456
457         if (getpeername(fd, &sa, &length)) {
458                 exit_cleanup(RERR_SOCKETIO);
459         }
460
461         /* Look up the remote host name. */
462         if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
463                                 sizeof(sockin->sin_addr),
464                                 AF_INET))) {
465                 strlcpy(name_buf,(char *)hp->h_name,sizeof(name_buf));
466         }
467
468
469         /* do a forward lookup as well to prevent spoofing */
470         hp = gethostbyname(name_buf);
471         if (!hp) {
472                 strcpy(name_buf,def);
473                 rprintf(FERROR,"reverse name lookup failed\n");
474         } else {
475                 for (p=hp->h_addr_list;*p;p++) {
476                         if (memcmp(*p, &sockin->sin_addr, hp->h_length) == 0) {
477                                 break;
478                         }
479                 }
480                 if (!*p) {
481                         strcpy(name_buf,def);
482                         rprintf(FERROR,"reverse name lookup mismatch - spoofed address?\n");
483                 } 
484         }
485
486         return name_buf;
487 }
488
489 /*******************************************************************
490 convert a string to an IP address. The string can be a name or
491 dotted decimal number
492   ******************************************************************/
493 struct in_addr *ip_address(const char *str)
494 {
495         static struct in_addr ret;
496         struct hostent *hp;
497
498         /* try as an IP address */
499         if (inet_aton(str, &ret) != 0) {
500                 return &ret;
501         }
502
503         /* otherwise assume it's a network name of some sort and use 
504            gethostbyname */
505         if ((hp = gethostbyname(str)) == 0) {
506                 rprintf(FERROR, "gethostbyname: Unknown host. %s\n",str);
507                 return NULL;
508         }
509
510         if (hp->h_addr == NULL) {
511                 rprintf(FERROR, "gethostbyname: host address is invalid for host %s\n",str);
512                 return NULL;
513         }
514
515         if (hp->h_length > sizeof(ret)) {
516                 rprintf(FERROR, "gethostbyname: host address is too large\n");
517                 return NULL;
518         }
519
520         memcpy(&ret.s_addr, hp->h_addr, hp->h_length);
521
522         return(&ret);
523 }