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