When running as --daemon in the background and using a "log file" rsyncd.conf
[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                 log_release();
251
252                 FD_ZERO(&fds);
253                 FD_SET(s, &fds);
254
255                 if (select(s+1, &fds, NULL, NULL, NULL) != 1) {
256                         continue;
257                 }
258
259                 if(!FD_ISSET(s, &fds)) continue;
260
261                 fd = accept(s,&addr,&in_addrlen);
262
263                 if (fd == -1) continue;
264
265                 signal(SIGCHLD, SIG_IGN);
266
267                 /* we shouldn't have any children left hanging around
268                    but I have had reports that on Digital Unix zombies
269                    are produced, so this ensures that they are reaped */
270 #ifdef WNOHANG
271                 while (waitpid(-1, NULL, WNOHANG) > 0);
272 #endif
273
274                 if (fork()==0) {
275                         close(s);
276
277                         _exit(fn(fd));
278                 }
279
280                 close(fd);
281         }
282 }
283
284
285 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
286
287 struct
288 {
289   char *name;
290   int level;
291   int option;
292   int value;
293   int opttype;
294 } socket_options[] = {
295   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
296   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
297   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
298 #ifdef TCP_NODELAY
299   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
300 #endif
301 #ifdef IPTOS_LOWDELAY
302   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
303 #endif
304 #ifdef IPTOS_THROUGHPUT
305   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
306 #endif
307 #ifdef SO_SNDBUF
308   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
309 #endif
310 #ifdef SO_RCVBUF
311   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
312 #endif
313 #ifdef SO_SNDLOWAT
314   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
315 #endif
316 #ifdef SO_RCVLOWAT
317   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
318 #endif
319 #ifdef SO_SNDTIMEO
320   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
321 #endif
322 #ifdef SO_RCVTIMEO
323   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
324 #endif
325   {NULL,0,0,0,0}};
326
327         
328
329 /****************************************************************************
330 set user socket options
331 ****************************************************************************/
332 void set_socket_options(int fd, char *options)
333 {
334         char *tok;
335         if (!options || !*options) return;
336
337         options = strdup(options);
338         
339         if (!options) out_of_memory("set_socket_options");
340
341         for (tok=strtok(options, " \t,"); tok; tok=strtok(NULL," \t,")) {
342                 int ret=0,i;
343                 int value = 1;
344                 char *p;
345                 int got_value = 0;
346
347                 if ((p = strchr(tok,'='))) {
348                         *p = 0;
349                         value = atoi(p+1);
350                         got_value = 1;
351                 }
352
353                 for (i=0;socket_options[i].name;i++)
354                         if (strcmp(socket_options[i].name,tok)==0)
355                                 break;
356
357                 if (!socket_options[i].name) {
358                         rprintf(FERROR,"Unknown socket option %s\n",tok);
359                         continue;
360                 }
361
362                 switch (socket_options[i].opttype) {
363                 case OPT_BOOL:
364                 case OPT_INT:
365                         ret = setsockopt(fd,socket_options[i].level,
366                                          socket_options[i].option,(char *)&value,sizeof(int));
367                         break;
368                         
369                 case OPT_ON:
370                         if (got_value)
371                                 rprintf(FERROR,"syntax error - %s does not take a value\n",tok);
372
373                         {
374                                 int on = socket_options[i].value;
375                                 ret = setsockopt(fd,socket_options[i].level,
376                                                  socket_options[i].option,(char *)&on,sizeof(int));
377                         }
378                         break;    
379                 }
380                 
381                 if (ret != 0)
382                         rprintf(FERROR,"Failed to set socket option %s\n",tok);
383         }
384
385         free(options);
386 }
387
388 /****************************************************************************
389 become a daemon, discarding the controlling terminal
390 ****************************************************************************/
391 void become_daemon(void)
392 {
393         int i;
394
395         if (fork()) {
396                 _exit(0);
397         }
398
399         /* detach from the terminal */
400 #ifdef HAVE_SETSID
401         setsid();
402 #else
403 #ifdef TIOCNOTTY
404         i = open("/dev/tty", O_RDWR);
405         if (i >= 0) {
406                 ioctl(i, (int) TIOCNOTTY, (char *)0);      
407                 close(i);
408         }
409 #endif /* TIOCNOTTY */
410 #endif
411         /* make sure that stdin, stdout an stderr don't stuff things
412            up (library functions, for example) */
413         for (i=0;i<3;i++) {
414                 close(i); 
415                 open("/dev/null", O_RDWR);
416         }
417 }
418
419 /*******************************************************************
420  return the IP addr of the client as a string 
421  ******************************************************************/
422 char *client_addr(int fd)
423 {
424         struct sockaddr sa;
425         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
426         int     length = sizeof(sa);
427         static char addr_buf[100];
428         static int initialised;
429
430         if (initialised) return addr_buf;
431
432         initialised = 1;
433
434         if (getpeername(fd, &sa, &length)) {
435                 exit_cleanup(RERR_SOCKETIO);
436         }
437         
438         strlcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr), sizeof(addr_buf));
439         return addr_buf;
440 }
441
442
443 /*******************************************************************
444  return the DNS name of the client 
445  ******************************************************************/
446 char *client_name(int fd)
447 {
448         struct sockaddr sa;
449         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
450         int     length = sizeof(sa);
451         static char name_buf[100];
452         struct hostent *hp;
453         char **p;
454         char *def = "UNKNOWN";
455         static int initialised;
456
457         if (initialised) return name_buf;
458
459         initialised = 1;
460
461         strcpy(name_buf,def);
462
463         if (getpeername(fd, &sa, &length)) {
464                 exit_cleanup(RERR_SOCKETIO);
465         }
466
467         /* Look up the remote host name. */
468         if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
469                                 sizeof(sockin->sin_addr),
470                                 AF_INET))) {
471                 strlcpy(name_buf,(char *)hp->h_name,sizeof(name_buf));
472         }
473
474
475         /* do a forward lookup as well to prevent spoofing */
476         hp = gethostbyname(name_buf);
477         if (!hp) {
478                 strcpy(name_buf,def);
479                 rprintf(FERROR,"reverse name lookup failed\n");
480         } else {
481                 for (p=hp->h_addr_list;*p;p++) {
482                         if (memcmp(*p, &sockin->sin_addr, hp->h_length) == 0) {
483                                 break;
484                         }
485                 }
486                 if (!*p) {
487                         strcpy(name_buf,def);
488                         rprintf(FERROR,"reverse name lookup mismatch - spoofed address?\n");
489                 } 
490         }
491
492         return name_buf;
493 }
494
495 /*******************************************************************
496 convert a string to an IP address. The string can be a name or
497 dotted decimal number
498   ******************************************************************/
499 struct in_addr *ip_address(const char *str)
500 {
501         static struct in_addr ret;
502         struct hostent *hp;
503
504         /* try as an IP address */
505         if (inet_aton(str, &ret) != 0) {
506                 return &ret;
507         }
508
509         /* otherwise assume it's a network name of some sort and use 
510            gethostbyname */
511         if ((hp = gethostbyname(str)) == 0) {
512                 rprintf(FERROR, "gethostbyname: Unknown host. %s\n",str);
513                 return NULL;
514         }
515
516         if (hp->h_addr == NULL) {
517                 rprintf(FERROR, "gethostbyname: host address is invalid for host %s\n",str);
518                 return NULL;
519         }
520
521         if (hp->h_length > sizeof(ret)) {
522                 rprintf(FERROR, "gethostbyname: host address is too large\n");
523                 return NULL;
524         }
525
526         memcpy(&ret.s_addr, hp->h_addr, hp->h_length);
527
528         return(&ret);
529 }