Include strerror message when there's a socket error.
[rsync/rsync.git] / socket.c
1 /* -*- c-file-style: "linux" -*-
2    
3    Copyright (C) 1998-2001 by Andrew Tridgell 
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         slprintf(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 hostent *hp;
174         struct sockaddr_in sock;
175         char host_name[MAXHOSTNAMELEN];
176         int res;
177         int one=1;
178
179         /* get my host name */
180         if (gethostname(host_name, sizeof(host_name)) == -1) { 
181                 rprintf(FERROR,"gethostname failed\n"); 
182                 return -1; 
183         } 
184
185         /* get host info */
186         if ((hp = gethostbyname(host_name)) == 0) {
187                 rprintf(FERROR,"gethostbyname: Unknown host %s\n",host_name);
188                 return -1;
189         }
190   
191         memset((char *)&sock,0,sizeof(sock));
192         memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
193         sock.sin_port = htons(port);
194         sock.sin_family = hp->h_addrtype;
195         if (address) {
196                 sock.sin_addr = *address;
197         } else {
198                 sock.sin_addr.s_addr = INADDR_ANY;
199         }
200         res = socket(hp->h_addrtype, type, 0);
201         if (res == -1) { 
202                 rprintf(FERROR,"socket failed: %s\n",
203                         strerror(errno)); 
204                 return -1; 
205         }
206
207         setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
208
209         /* now we've got a socket - we need to bind it */
210         if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) == -1) { 
211                 rprintf(FERROR,"bind failed on port %d: %s\n", port,
212                         strerror(errno));
213                 close(res); 
214                 return -1;
215         }
216
217         return res;
218 }
219
220
221 /*
222  * Determine if a file descriptor is in fact a socket
223  */
224 int is_a_socket(int fd)
225 {
226         int v, l;
227         l = sizeof(int);
228
229         /* Parameters to getsockopt, setsockopt etc are very
230          * unstandardized across platforms, so don't be surprised if
231          * there are compiler warnings on e.g. SCO OpenSwerver.  It
232          * seems they all eventually get the right idea.
233          *
234          * Debian says: ``The fifth argument of getsockopt and
235          * setsockopt is in reality an int [*] (and this is what BSD
236          * 4.* and libc4 and libc5 have).  Some POSIX confusion
237          * resulted in the present socklen_t.  The draft standard has
238          * not been adopted yet, but glibc2 already follows it and
239          * also has socklen_t [*]. See also accept(2).''
240          *
241          * We now return to your regularly scheduled programming.  */
242         return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
243 }
244
245
246 void start_accept_loop(int port, int (*fn)(int ))
247 {
248         int s;
249         extern struct in_addr socket_address;
250
251         /* open an incoming socket */
252         s = open_socket_in(SOCK_STREAM, port, &socket_address);
253         if (s == -1)
254                 exit_cleanup(RERR_SOCKETIO);
255
256         /* ready to listen */
257         if (listen(s, 5) == -1) {
258                 close(s);
259                 exit_cleanup(RERR_SOCKETIO);
260         }
261
262
263         /* now accept incoming connections - forking a new process
264            for each incoming connection */
265         while (1) {
266                 fd_set fds;
267                 int fd;
268                 struct sockaddr addr;
269                 int in_addrlen = sizeof(addr);
270
271                 /* close log file before the potentially very long select so
272                    file can be trimmed by another process instead of growing
273                    forever */
274                 log_close();
275
276                 FD_ZERO(&fds);
277                 FD_SET(s, &fds);
278
279                 if (select(s+1, &fds, NULL, NULL, NULL) != 1) {
280                         continue;
281                 }
282
283                 if(!FD_ISSET(s, &fds)) continue;
284
285                 /* See note above prototypes. */
286                 fd = accept(s,&addr,&in_addrlen);
287
288                 if (fd == -1) continue;
289
290                 signal(SIGCHLD, SIG_IGN);
291
292                 /* we shouldn't have any children left hanging around
293                    but I have had reports that on Digital Unix zombies
294                    are produced, so this ensures that they are reaped */
295 #ifdef WNOHANG
296                 while (waitpid(-1, NULL, WNOHANG) > 0);
297 #endif
298
299                 if (fork()==0) {
300                         close(s);
301
302                         /* open log file in child before possibly giving
303                            up privileges  */
304                         log_open();
305
306                         _exit(fn(fd));
307                 }
308
309                 close(fd);
310         }
311 }
312
313
314 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
315
316 struct
317 {
318   char *name;
319   int level;
320   int option;
321   int value;
322   int opttype;
323 } socket_options[] = {
324   {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
325   {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
326   {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
327 #ifdef TCP_NODELAY
328   {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
329 #endif
330 #ifdef IPTOS_LOWDELAY
331   {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
332 #endif
333 #ifdef IPTOS_THROUGHPUT
334   {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
335 #endif
336 #ifdef SO_SNDBUF
337   {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
338 #endif
339 #ifdef SO_RCVBUF
340   {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
341 #endif
342 #ifdef SO_SNDLOWAT
343   {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
344 #endif
345 #ifdef SO_RCVLOWAT
346   {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
347 #endif
348 #ifdef SO_SNDTIMEO
349   {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
350 #endif
351 #ifdef SO_RCVTIMEO
352   {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
353 #endif
354   {NULL,0,0,0,0}};
355
356         
357
358 /****************************************************************************
359 set user socket options
360 ****************************************************************************/
361 void set_socket_options(int fd, char *options)
362 {
363         char *tok;
364         if (!options || !*options) return;
365
366         options = strdup(options);
367         
368         if (!options) out_of_memory("set_socket_options");
369
370         for (tok=strtok(options, " \t,"); tok; tok=strtok(NULL," \t,")) {
371                 int ret=0,i;
372                 int value = 1;
373                 char *p;
374                 int got_value = 0;
375
376                 if ((p = strchr(tok,'='))) {
377                         *p = 0;
378                         value = atoi(p+1);
379                         got_value = 1;
380                 }
381
382                 for (i=0;socket_options[i].name;i++)
383                         if (strcmp(socket_options[i].name,tok)==0)
384                                 break;
385
386                 if (!socket_options[i].name) {
387                         rprintf(FERROR,"Unknown socket option %s\n",tok);
388                         continue;
389                 }
390
391                 switch (socket_options[i].opttype) {
392                 case OPT_BOOL:
393                 case OPT_INT:
394                         ret = setsockopt(fd,socket_options[i].level,
395                                          socket_options[i].option,(char *)&value,sizeof(int));
396                         break;
397                         
398                 case OPT_ON:
399                         if (got_value)
400                                 rprintf(FERROR,"syntax error - %s does not take a value\n",tok);
401
402                         {
403                                 int on = socket_options[i].value;
404                                 ret = setsockopt(fd,socket_options[i].level,
405                                                  socket_options[i].option,(char *)&on,sizeof(int));
406                         }
407                         break;    
408                 }
409                 
410                 if (ret != 0)
411                         rprintf(FERROR, "failed to set socket option %s: %s\n", tok,
412                                 strerror(errno));
413         }
414
415         free(options);
416 }
417
418 /****************************************************************************
419 become a daemon, discarding the controlling terminal
420 ****************************************************************************/
421 void become_daemon(void)
422 {
423         int i;
424
425         if (fork()) {
426                 _exit(0);
427         }
428
429         /* detach from the terminal */
430 #ifdef HAVE_SETSID
431         setsid();
432 #else
433 #ifdef TIOCNOTTY
434         i = open("/dev/tty", O_RDWR);
435         if (i >= 0) {
436                 ioctl(i, (int) TIOCNOTTY, (char *)0);      
437                 close(i);
438         }
439 #endif /* TIOCNOTTY */
440 #endif
441         /* make sure that stdin, stdout an stderr don't stuff things
442            up (library functions, for example) */
443         for (i=0;i<3;i++) {
444                 close(i); 
445                 open("/dev/null", O_RDWR);
446         }
447 }
448
449 /*******************************************************************
450  return the IP addr of the client as a string 
451  ******************************************************************/
452 char *client_addr(int fd)
453 {
454         struct sockaddr sa;
455         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
456         int     length = sizeof(sa);
457         static char addr_buf[100];
458         static int initialised;
459
460         if (initialised) return addr_buf;
461
462         initialised = 1;
463
464         if (getpeername(fd, &sa, &length)) {
465                 exit_cleanup(RERR_SOCKETIO);
466         }
467         
468         strlcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr), sizeof(addr_buf));
469         return addr_buf;
470 }
471
472
473 /*******************************************************************
474  return the DNS name of the client 
475  ******************************************************************/
476 char *client_name(int fd)
477 {
478         struct sockaddr sa;
479         struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
480         int     length = sizeof(sa);
481         static char name_buf[100];
482         struct hostent *hp;
483         char **p;
484         char *def = "UNKNOWN";
485         static int initialised;
486
487         if (initialised) return name_buf;
488
489         initialised = 1;
490
491         strcpy(name_buf,def);
492
493         if (getpeername(fd, &sa, &length)) {
494                 exit_cleanup(RERR_SOCKETIO);
495         }
496
497         /* Look up the remote host name. */
498         if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
499                                 sizeof(sockin->sin_addr),
500                                 AF_INET))) {
501                 strlcpy(name_buf,(char *)hp->h_name,sizeof(name_buf));
502         }
503
504
505         /* do a forward lookup as well to prevent spoofing */
506         hp = gethostbyname(name_buf);
507         if (!hp) {
508                 strcpy(name_buf,def);
509                 rprintf(FERROR,"reverse name lookup failed\n");
510         } else {
511                 for (p=hp->h_addr_list;*p;p++) {
512                         if (memcmp(*p, &sockin->sin_addr, hp->h_length) == 0) {
513                                 break;
514                         }
515                 }
516                 if (!*p) {
517                         strcpy(name_buf,def);
518                         rprintf(FERROR,"reverse name lookup mismatch - spoofed address?\n");
519                 } 
520         }
521
522         return name_buf;
523 }
524
525 /*******************************************************************
526 convert a string to an IP address. The string can be a name or
527 dotted decimal number
528   ******************************************************************/
529 struct in_addr *ip_address(const char *str)
530 {
531         static struct in_addr ret;
532         struct hostent *hp;
533
534         /* try as an IP address */
535         if (inet_aton(str, &ret) != 0) {
536                 return &ret;
537         }
538
539         /* otherwise assume it's a network name of some sort and use 
540            gethostbyname */
541         if ((hp = gethostbyname(str)) == 0) {
542                 rprintf(FERROR, "gethostbyname: Unknown host. %s\n",str);
543                 return NULL;
544         }
545
546         if (hp->h_addr == NULL) {
547                 rprintf(FERROR, "gethostbyname: host address is invalid for host %s\n",str);
548                 return NULL;
549         }
550
551         if (hp->h_length > sizeof(ret)) {
552                 rprintf(FERROR, "gethostbyname: host address is too large\n");
553                 return NULL;
554         }
555
556         memcpy(&ret.s_addr, hp->h_addr, hp->h_length);
557
558         return(&ret);
559 }