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;
72 static ip_address bind_address;
73 static int bind_address_resolved;
76 resolve_bind_address (void)
78 struct address_list *al;
80 if (bind_address_resolved || opt.bind_address == NULL)
84 al = lookup_host (opt.bind_address, 1);
87 logprintf (LOG_NOTQUIET,
88 _("Unable to convert `%s' to a bind address. Reverting to ANY.\n"),
93 address_list_copy_one (al, 0, &bind_address);
94 address_list_release (al);
95 bind_address_resolved = 1;
100 const struct sockaddr *addr;
106 connect_with_timeout_callback (void *arg)
108 struct cwt_context *ctx = (struct cwt_context *)arg;
109 ctx->result = connect (ctx->fd, ctx->addr, ctx->addrlen);
112 /* Like connect, but specifies a timeout. If connecting takes longer
113 than TIMEOUT seconds, -1 is returned and errno is set to
117 connect_with_timeout (int fd, const struct sockaddr *addr, socklen_t addrlen,
120 struct cwt_context ctx;
123 ctx.addrlen = addrlen;
125 if (run_with_timeout (timeout, connect_with_timeout_callback, &ctx))
130 if (ctx.result == -1 && errno == EINTR)
135 /* A kludge, but still better than passing the host name all the way
136 to connect_to_one. */
137 static const char *connection_host_name;
140 set_connection_host_name (const char *host)
143 assert (connection_host_name == NULL);
145 assert (connection_host_name != NULL);
147 connection_host_name = host;
150 /* Connect to a remote host whose address has been resolved. */
152 connect_to_one (ip_address *addr, unsigned short port, int silent)
155 int sock, save_errno;
157 /* Set port and protocol */
158 wget_sockaddr_set_address (&sa, ip_default_family, port, addr);
162 char *pretty_addr = pretty_print_address (addr);
163 if (connection_host_name
164 && 0 != strcmp (connection_host_name, pretty_addr))
165 logprintf (LOG_VERBOSE, _("Connecting to %s[%s]:%hu... "),
166 connection_host_name, pretty_addr, port);
168 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "),
172 /* Make an internet socket, stream type. */
173 sock = socket (ip_default_family, SOCK_STREAM, 0);
177 /* For very small rate limits, set the buffer size (and hence,
178 hopefully, the size of the kernel window) to the size of the
179 limit. That way we don't sleep for more than 1s between network
181 if (opt.limit_rate && opt.limit_rate < 8192)
183 int bufsize = opt.limit_rate;
187 setsockopt (sock, SOL_SOCKET, SO_RCVBUF,
188 (char *)&bufsize, sizeof (bufsize));
190 /* When we add opt.limit_rate support for writing, as with
191 `--post-file', also set SO_SNDBUF here. */
194 resolve_bind_address ();
195 if (bind_address_resolved)
197 /* Bind the client side to the requested address. */
199 wget_sockaddr_set_address (&bsa, ip_default_family, 0, &bind_address);
200 if (bind (sock, &bsa.sa, sockaddr_len ()))
208 /* Connect the socket to the remote host. */
209 if (connect_with_timeout (sock, &sa.sa, sockaddr_len (),
210 opt.connect_timeout) < 0)
222 logprintf (LOG_VERBOSE, _("connected.\n"));
223 DEBUGP (("Created socket %d.\n", sock));
229 logprintf (LOG_VERBOSE, "failed: %s.\n", strerror (errno));
236 /* Connect to a remote host whose address has been resolved. */
238 connect_to_many (struct address_list *al, unsigned short port, int silent)
242 address_list_get_bounds (al, &start, &end);
243 for (i = start; i < end; i++)
247 address_list_copy_one (al, i, &addr);
249 sock = connect_to_one (&addr, port, silent);
254 address_list_set_faulty (al, i);
256 /* The attempt to connect has failed. Continue with the loop
257 and try next address. */
264 test_socket_open (int sock)
270 /* Check if we still have a valid (non-EOF) connection. From Andrew
271 * Maholski's code in the Unix Socket FAQ. */
273 FD_ZERO (&check_set);
274 FD_SET (sock, &check_set);
276 /* Wait one microsecond */
280 /* If we get a timeout, then that means still connected */
281 if (select (sock + 1, &check_set, NULL, NULL, &to) == 0)
283 /* Connection is valid (not EOF), so continue */
289 /* Without select, it's hard to know for sure. */
294 /* Bind the local port PORT. This does all the necessary work, which
295 is creating a socket, setting SO_REUSEADDR option on it, then
296 calling bind() and listen(). If *PORT is 0, a random port is
297 chosen by the system, and its value is stored to *PORT. The
298 internal variable MPORT is set to the value of the ensuing master
299 socket. Call acceptport() to block for and accept a connection. */
301 bindport (unsigned short *port, int family)
305 memset (&srv, 0, sizeof (wget_sockaddr));
309 if ((msock = socket (family, SOCK_STREAM, 0)) < 0)
313 if (setsockopt (msock, SOL_SOCKET, SO_REUSEADDR,
314 (char *)&optval, sizeof (optval)) < 0)
318 resolve_bind_address ();
319 wget_sockaddr_set_address (&srv, ip_default_family, htons (*port),
320 bind_address_resolved ? &bind_address : NULL);
321 if (bind (msock, &srv.sa, sockaddr_len ()) < 0)
327 DEBUGP (("Master socket fd %d bound.\n", msock));
330 socklen_t sa_len = sockaddr_len ();
331 if (getsockname (msock, &srv.sa, &sa_len) < 0)
337 *port = wget_sockaddr_get_port (&srv);
338 DEBUGP (("using port %i.\n", *port));
340 if (listen (msock, 1) < 0)
350 /* Wait for file descriptor FD to be available, timing out after
351 MAXTIME seconds. "Available" means readable if writep is 0,
354 Returns 1 if FD is available, 0 for timeout and -1 for error. */
357 select_fd (int fd, double maxtime, int writep)
360 fd_set *rd = NULL, *wrt = NULL;
361 struct timeval tmout;
366 *(writep ? &wrt : &rd) = &fds;
368 tmout.tv_sec = (long)maxtime;
369 tmout.tv_usec = 1000000L * (maxtime - (long)maxtime);
372 result = select (fd + 1, rd, wrt, NULL, &tmout);
373 while (result < 0 && errno == EINTR);
375 /* When we've timed out, set errno to ETIMEDOUT for the convenience
382 #endif /* HAVE_SELECT */
384 /* Call accept() on MSOCK and store the result to *SOCK. This assumes
385 that bindport() has been used to initialize MSOCK to a correct
386 value. It blocks the caller until a connection is established. If
387 no connection is established for OPT.CONNECT_TIMEOUT seconds, the
388 function exits with an error status. */
390 acceptport (int *sock)
392 socklen_t addrlen = sockaddr_len ();
395 if (select_fd (msock, opt.connect_timeout, 0) <= 0)
398 if ((*sock = accept (msock, addr, &addrlen)) < 0)
400 DEBUGP (("Created socket fd %d.\n", *sock));
404 /* Close SOCK, as well as the most recently remembered MSOCK, created
405 via bindport(). If SOCK is -1, close MSOCK only. */
409 /*shutdown (sock, 2);*/
417 /* Return the local IP address associated with the connection on FD. */
420 conaddr (int fd, ip_address *ip)
423 socklen_t addrlen = sizeof (mysrv);
424 if (getsockname (fd, &mysrv.sa, &addrlen) < 0)
427 switch (mysrv.sa.sa_family)
431 memcpy (ip, &mysrv.sin6.sin6_addr, 16);
435 map_ipv4_to_ip ((ip4_address *)&mysrv.sin.sin_addr, ip);
443 /* Read at most LEN bytes from FD, storing them to BUF. This is
444 virtually the same as read(), but takes care of EINTR braindamage
445 and uses select() to timeout the stale connections (a connection is
446 stale if more than OPT.READ_TIMEOUT time is spent in select() or
450 iread (int fd, char *buf, int len)
455 if (opt.read_timeout)
456 if (select_fd (fd, opt.read_timeout, 0) <= 0)
460 res = READ (fd, buf, len);
461 while (res == -1 && errno == EINTR);
466 /* Write LEN bytes from BUF to FD. This is similar to iread(), but
467 unlike iread(), it makes sure that all of BUF is actually written
468 to FD, so callers needn't bother with checking that the return
469 value equals to LEN. Instead, you should simply check for -1. */
472 iwrite (int fd, char *buf, int len)
476 /* `write' may write less than LEN bytes, thus the outward loop
477 keeps trying it until all was written, or an error occurred. The
478 inner loop is reserved for the usual EINTR f*kage, and the
479 innermost loop deals with the same during select(). */
483 if (opt.read_timeout)
484 if (select_fd (fd, opt.read_timeout, 1) <= 0)
488 res = WRITE (fd, buf, len);
489 while (res == -1 && errno == EINTR);