1 /* Establishing and handling network connections.
2 Copyright (C) 1995, 1996, 1997, 2001, 2002 Free Software Foundation, Inc.
4 This file is part of GNU Wget.
6 GNU Wget 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.
11 GNU Wget 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.
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables. You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL". If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so. If you do not wish to do
28 so, delete this exception statement from your version. */
34 #include <sys/types.h>
41 # include <sys/socket.h>
43 # include <netinet/in.h>
45 # include <arpa/inet.h>
47 #endif /* not WINDOWS */
54 #endif /* HAVE_STRING_H */
55 #ifdef HAVE_SYS_SELECT_H
56 # include <sys/select.h>
57 #endif /* HAVE_SYS_SELECT_H */
68 /* Variables shared by bindport and acceptport: */
69 static int msock = -1;
70 /*static struct sockaddr *addr;*/
73 resolve_bind_address (int flags, ip_address *addr)
75 struct address_list *al = NULL;
76 int bind_address_resolved = 0;
78 if (opt.bind_address != NULL)
80 al = lookup_host (opt.bind_address, flags | LH_SILENT | LH_PASSIVE);
84 logprintf (LOG_NOTQUIET,
85 _("Unable to convert `%s' to a bind address. Reverting to ANY.\n"),
89 bind_address_resolved = 1;
94 const char *unspecified_address = "0.0.0.0";
96 if (flags & BIND_ON_IPV6_ONLY)
97 unspecified_address = "::";
99 al = lookup_host (unspecified_address, LH_SILENT | LH_PASSIVE);
104 address_list_copy_one (al, 0, addr);
105 address_list_release (al);
107 return bind_address_resolved;
112 const struct sockaddr *addr;
118 connect_with_timeout_callback (void *arg)
120 struct cwt_context *ctx = (struct cwt_context *)arg;
121 ctx->result = connect (ctx->fd, ctx->addr, ctx->addrlen);
124 /* Like connect, but specifies a timeout. If connecting takes longer
125 than TIMEOUT seconds, -1 is returned and errno is set to
129 connect_with_timeout (int fd, const struct sockaddr *addr, socklen_t addrlen,
132 struct cwt_context ctx;
135 ctx.addrlen = addrlen;
137 if (run_with_timeout (timeout, connect_with_timeout_callback, &ctx))
142 if (ctx.result == -1 && errno == EINTR)
147 /* A kludge, but still better than passing the host name all the way
148 to connect_to_one. */
149 static const char *connection_host_name;
152 set_connection_host_name (const char *host)
155 assert (connection_host_name == NULL);
157 assert (connection_host_name != NULL);
159 connection_host_name = host;
162 /* Connect to a remote host whose address has been resolved. */
164 connect_to_one (ip_address *addr, unsigned short port, int silent)
166 struct sockaddr_storage ss;
167 struct sockaddr *sa = (struct sockaddr *)&ss;
168 int sock, save_errno;
170 /* Set port and protocol */
171 sockaddr_set_address (sa, port, addr);
175 const char *pretty_addr = pretty_print_address (addr);
176 if (connection_host_name
177 && 0 != strcmp (connection_host_name, pretty_addr))
178 logprintf (LOG_VERBOSE, _("Connecting to %s[%s]:%hu... "),
179 connection_host_name, pretty_addr, port);
181 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "),
185 /* Make an internet socket, stream type. */
186 sock = socket (sa->sa_family, SOCK_STREAM, 0);
190 /* For very small rate limits, set the buffer size (and hence,
191 hopefully, the size of the kernel window) to the size of the
192 limit. That way we don't sleep for more than 1s between network
194 if (opt.limit_rate && opt.limit_rate < 8192)
196 int bufsize = opt.limit_rate;
200 setsockopt (sock, SOL_SOCKET, SO_RCVBUF,
201 (char *)&bufsize, sizeof (bufsize));
203 /* When we add opt.limit_rate support for writing, as with
204 `--post-file', also set SO_SNDBUF here. */
207 if (opt.bind_address)
209 /* Bind the client side to the requested address. */
210 ip_address bind_address;
211 if (resolve_bind_address (0, &bind_address))
213 struct sockaddr_storage bss;
214 struct sockaddr *bsa = (struct sockaddr *)&bss;
215 sockaddr_set_address (bsa, 0, &bind_address);
216 if (bind (sock, bsa, sockaddr_len (bsa)))
225 /* Connect the socket to the remote host. */
226 if (connect_with_timeout (sock, sa, sockaddr_len (sa),
227 opt.connect_timeout) < 0)
239 logprintf (LOG_VERBOSE, _("connected.\n"));
240 DEBUGP (("Created socket %d.\n", sock));
246 logprintf (LOG_VERBOSE, "failed: %s.\n", strerror (errno));
253 /* Connect to a remote host whose address has been resolved. */
255 connect_to_many (struct address_list *al, unsigned short port, int silent)
259 address_list_get_bounds (al, &start, &end);
260 for (i = start; i < end; i++)
264 address_list_copy_one (al, i, &addr);
266 sock = connect_to_one (&addr, port, silent);
271 address_list_set_faulty (al, i);
273 /* The attempt to connect has failed. Continue with the loop
274 and try next address. */
281 test_socket_open (int sock)
287 /* Check if we still have a valid (non-EOF) connection. From Andrew
288 * Maholski's code in the Unix Socket FAQ. */
290 FD_ZERO (&check_set);
291 FD_SET (sock, &check_set);
293 /* Wait one microsecond */
297 /* If we get a timeout, then that means still connected */
298 if (select (sock + 1, &check_set, NULL, NULL, &to) == 0)
300 /* Connection is valid (not EOF), so continue */
306 /* Without select, it's hard to know for sure. */
311 /* Bind the local port PORT. This does all the necessary work, which
312 is creating a socket, setting SO_REUSEADDR option on it, then
313 calling bind() and listen(). If *PORT is 0, a random port is
314 chosen by the system, and its value is stored to *PORT. The
315 internal variable MPORT is set to the value of the ensuing master
316 socket. Call acceptport() to block for and accept a connection. */
319 bindport (const ip_address *bind_address, unsigned short *port)
321 int family = AF_INET;
323 struct sockaddr_storage ss;
324 struct sockaddr *sa = (struct sockaddr *)&ss;
325 memset (&ss, 0, sizeof (ss));
330 if (bind_address->type == IPv6_ADDRESS)
334 if ((msock = socket (family, SOCK_STREAM, 0)) < 0)
339 if (setsockopt (msock, SOL_SOCKET, SO_REUSEADDR,
340 (char *)&optval, sizeof (optval)) < 0)
345 # ifdef HAVE_IPV6_V6ONLY
346 if (family == AF_INET6)
349 /* if setsockopt fails, go on anyway */
350 setsockopt (msock, IPPROTO_IPV6, IPV6_V6ONLY,
351 (char *)&optval, sizeof (optval));
356 sockaddr_set_address (sa, htons (*port), bind_address);
357 if (bind (msock, sa, sockaddr_len (sa)) < 0)
363 DEBUGP (("Master socket fd %d bound.\n", msock));
366 socklen_t sa_len = sockaddr_len (sa);
367 if (getsockname (msock, sa, &sa_len) < 0)
373 *port = sockaddr_get_port (sa);
374 DEBUGP (("binding to address %s using port %i.\n",
375 pretty_print_address (bind_address), *port));
377 if (listen (msock, 1) < 0)
387 /* Wait for file descriptor FD to be available, timing out after
388 MAXTIME seconds. "Available" means readable if writep is 0,
391 Returns 1 if FD is available, 0 for timeout and -1 for error. */
394 select_fd (int fd, double maxtime, int writep)
397 fd_set *rd = NULL, *wrt = NULL;
398 struct timeval tmout;
403 *(writep ? &wrt : &rd) = &fds;
405 tmout.tv_sec = (long)maxtime;
406 tmout.tv_usec = 1000000L * (maxtime - (long)maxtime);
409 result = select (fd + 1, rd, wrt, NULL, &tmout);
410 while (result < 0 && errno == EINTR);
412 /* When we've timed out, set errno to ETIMEDOUT for the convenience
419 #endif /* HAVE_SELECT */
421 /* Call accept() on MSOCK and store the result to *SOCK. This assumes
422 that bindport() has been used to initialize MSOCK to a correct
423 value. It blocks the caller until a connection is established. If
424 no connection is established for OPT.CONNECT_TIMEOUT seconds, the
425 function exits with an error status. */
427 acceptport (int *sock)
429 struct sockaddr_storage ss;
430 struct sockaddr *sa = (struct sockaddr *)&ss;
431 socklen_t addrlen = sizeof (ss);
434 if (select_fd (msock, opt.connect_timeout, 0) <= 0)
437 if ((*sock = accept (msock, sa, &addrlen)) < 0)
439 DEBUGP (("Created socket fd %d.\n", *sock));
443 /* Close SOCK, as well as the most recently remembered MSOCK, created
444 via bindport(). If SOCK is -1, close MSOCK only. */
448 /*shutdown (sock, 2);*/
456 /* Return the local IP address associated with the connection on FD. */
459 conaddr (int fd, ip_address *ip)
461 struct sockaddr_storage ss;
462 struct sockaddr *sa = (struct sockaddr *)&ss;
463 socklen_t addrlen = sizeof (ss);
465 if (getsockname (fd, sa, &addrlen) < 0)
468 switch (sa->sa_family)
472 ip->type = IPv6_ADDRESS;
473 ip->addr.ipv6.addr = ((struct sockaddr_in6 *)sa)->sin6_addr;
474 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
475 ip->addr.ipv6.scope_id = ((struct sockaddr_in6 *)sa)->sin6_scope_id;
477 DEBUGP (("conaddr is: %s\n", pretty_print_address (ip)));
481 ip->type = IPv4_ADDRESS;
482 ip->addr.ipv4.addr = ((struct sockaddr_in *)sa)->sin_addr;
483 DEBUGP (("conaddr is: %s\n", pretty_print_address (ip)));
492 /* Read at most LEN bytes from FD, storing them to BUF. This is
493 virtually the same as read(), but takes care of EINTR braindamage
494 and uses select() to timeout the stale connections (a connection is
495 stale if more than OPT.READ_TIMEOUT time is spent in select() or
499 iread (int fd, char *buf, int len)
504 if (opt.read_timeout)
505 if (select_fd (fd, opt.read_timeout, 0) <= 0)
509 res = READ (fd, buf, len);
510 while (res == -1 && errno == EINTR);
515 /* Write LEN bytes from BUF to FD. This is similar to iread(), but
516 unlike iread(), it makes sure that all of BUF is actually written
517 to FD, so callers needn't bother with checking that the return
518 value equals to LEN. Instead, you should simply check for -1. */
521 iwrite (int fd, char *buf, int len)
525 /* `write' may write less than LEN bytes, thus the outward loop
526 keeps trying it until all was written, or an error occurred. The
527 inner loop is reserved for the usual EINTR f*kage, and the
528 innermost loop deals with the same during select(). */
532 if (opt.read_timeout)
533 if (select_fd (fd, opt.read_timeout, 1) <= 0)
537 res = WRITE (fd, buf, len);
538 while (res == -1 && errno == EINTR);