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