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