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;
78 if (opt.bind_address != NULL)
80 al = lookup_host (opt.bind_address, flags | LH_SILENT | LH_PASSIVE);
83 logprintf (LOG_NOTQUIET,
84 _("Unable to convert `%s' to a bind address. Reverting to ANY.\n"),
93 /* #### Is there really a need for this? Shouldn't we simply
94 return 0 and have the caller use sockaddr_set_address to
95 specify INADDR_ANY/in6addr_any? */
96 const char *unspecified_address = "0.0.0.0";
98 if (flags & BIND_ON_IPV6_ONLY)
99 unspecified_address = "::";
101 al = lookup_host (unspecified_address, LH_SILENT | LH_PASSIVE);
106 address_list_copy_one (al, 0, addr);
107 address_list_release (al);
114 const struct sockaddr *addr;
120 connect_with_timeout_callback (void *arg)
122 struct cwt_context *ctx = (struct cwt_context *)arg;
123 ctx->result = connect (ctx->fd, ctx->addr, ctx->addrlen);
126 /* Like connect, but specifies a timeout. If connecting takes longer
127 than TIMEOUT seconds, -1 is returned and errno is set to
131 connect_with_timeout (int fd, const struct sockaddr *addr, socklen_t addrlen,
134 struct cwt_context ctx;
137 ctx.addrlen = addrlen;
139 if (run_with_timeout (timeout, connect_with_timeout_callback, &ctx))
144 if (ctx.result == -1 && errno == EINTR)
149 /* A kludge, but still better than passing the host name all the way
150 to connect_to_one. */
151 static const char *connection_host_name;
154 set_connection_host_name (const char *host)
157 assert (connection_host_name == NULL);
159 assert (connection_host_name != NULL);
161 connection_host_name = host;
164 /* Connect to a remote host whose address has been resolved. */
166 connect_to_one (ip_address *addr, unsigned short port, int silent)
168 struct sockaddr_storage ss;
169 struct sockaddr *sa = (struct sockaddr *)&ss;
170 int sock, save_errno;
172 /* Set port and protocol */
173 sockaddr_set_address (sa, port, addr);
177 const char *pretty_addr = pretty_print_address (addr);
178 if (connection_host_name
179 && 0 != strcmp (connection_host_name, pretty_addr))
180 logprintf (LOG_VERBOSE, _("Connecting to %s[%s]:%hu... "),
181 connection_host_name, pretty_addr, port);
183 logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "),
187 /* Create the socket of the family appropriate for the address. */
188 sock = socket (sa->sa_family, SOCK_STREAM, 0);
192 /* For very small rate limits, set the buffer size (and hence,
193 hopefully, the size of the kernel window) to the size of the
194 limit. That way we don't sleep for more than 1s between network
196 if (opt.limit_rate && opt.limit_rate < 8192)
198 int bufsize = opt.limit_rate;
202 setsockopt (sock, SOL_SOCKET, SO_RCVBUF,
203 (char *)&bufsize, sizeof (bufsize));
205 /* When we add opt.limit_rate support for writing, as with
206 `--post-file', also set SO_SNDBUF here. */
209 if (opt.bind_address)
211 /* Bind the client side to the requested address. */
212 ip_address bind_address;
213 if (resolve_bind_address (0, &bind_address))
215 struct sockaddr_storage bss;
216 struct sockaddr *bsa = (struct sockaddr *)&bss;
217 sockaddr_set_address (bsa, 0, &bind_address);
218 if (bind (sock, bsa, sockaddr_len (bsa)))
227 /* Connect the socket to the remote host. */
228 if (connect_with_timeout (sock, sa, sockaddr_len (sa),
229 opt.connect_timeout) < 0)
241 logprintf (LOG_VERBOSE, _("connected.\n"));
242 DEBUGP (("Created socket %d.\n", sock));
248 logprintf (LOG_VERBOSE, "failed: %s.\n", strerror (errno));
255 /* Connect to a remote host whose address has been resolved. */
257 connect_to_many (struct address_list *al, unsigned short port, int silent)
261 address_list_get_bounds (al, &start, &end);
262 for (i = start; i < end; i++)
266 address_list_copy_one (al, i, &addr);
268 sock = connect_to_one (&addr, port, silent);
273 address_list_set_faulty (al, i);
275 /* The attempt to connect has failed. Continue with the loop
276 and try next address. */
283 test_socket_open (int sock)
289 /* Check if we still have a valid (non-EOF) connection. From Andrew
290 * Maholski's code in the Unix Socket FAQ. */
292 FD_ZERO (&check_set);
293 FD_SET (sock, &check_set);
295 /* Wait one microsecond */
299 /* If we get a timeout, then that means still connected */
300 if (select (sock + 1, &check_set, NULL, NULL, &to) == 0)
302 /* Connection is valid (not EOF), so continue */
308 /* Without select, it's hard to know for sure. */
313 /* Bind the local port PORT. This does all the necessary work, which
314 is creating a socket, setting SO_REUSEADDR option on it, then
315 calling bind() and listen(). If *PORT is 0, a random port is
316 chosen by the system, and its value is stored to *PORT. The
317 internal variable MPORT is set to the value of the ensuing master
318 socket. Call acceptport() to block for and accept a connection. */
321 bindport (const ip_address *bind_address, unsigned short *port)
323 int family = AF_INET;
325 struct sockaddr_storage ss;
326 struct sockaddr *sa = (struct sockaddr *)&ss;
327 memset (&ss, 0, sizeof (ss));
332 if (bind_address->type == IPV6_ADDRESS)
336 if ((msock = socket (family, SOCK_STREAM, 0)) < 0)
341 if (setsockopt (msock, SOL_SOCKET, SO_REUSEADDR,
342 (char *)&optval, sizeof (optval)) < 0)
347 # ifdef HAVE_IPV6_V6ONLY
348 if (family == AF_INET6)
351 /* if setsockopt fails, go on anyway */
352 setsockopt (msock, IPPROTO_IPV6, IPV6_V6ONLY,
353 (char *)&optval, sizeof (optval));
358 sockaddr_set_address (sa, htons (*port), bind_address);
359 if (bind (msock, sa, sockaddr_len (sa)) < 0)
365 DEBUGP (("Master socket fd %d bound.\n", msock));
368 socklen_t sa_len = sockaddr_len (sa);
369 if (getsockname (msock, sa, &sa_len) < 0)
375 *port = sockaddr_get_port (sa);
376 DEBUGP (("binding to address %s using port %i.\n",
377 pretty_print_address (bind_address), *port));
379 if (listen (msock, 1) < 0)
389 /* Wait for file descriptor FD to be available, timing out after
390 MAXTIME seconds. "Available" means readable if writep is 0,
393 Returns 1 if FD is available, 0 for timeout and -1 for error. */
396 select_fd (int fd, double maxtime, int writep)
399 fd_set *rd = NULL, *wrt = NULL;
400 struct timeval tmout;
405 *(writep ? &wrt : &rd) = &fds;
407 tmout.tv_sec = (long)maxtime;
408 tmout.tv_usec = 1000000L * (maxtime - (long)maxtime);
411 result = select (fd + 1, rd, wrt, NULL, &tmout);
412 while (result < 0 && errno == EINTR);
414 /* When we've timed out, set errno to ETIMEDOUT for the convenience
421 #endif /* HAVE_SELECT */
423 /* Call accept() on MSOCK and store the result to *SOCK. This assumes
424 that bindport() has been used to initialize MSOCK to a correct
425 value. It blocks the caller until a connection is established. If
426 no connection is established for OPT.CONNECT_TIMEOUT seconds, the
427 function exits with an error status. */
429 acceptport (int *sock)
431 struct sockaddr_storage ss;
432 struct sockaddr *sa = (struct sockaddr *)&ss;
433 socklen_t addrlen = sizeof (ss);
436 if (select_fd (msock, opt.connect_timeout, 0) <= 0)
439 if ((*sock = accept (msock, sa, &addrlen)) < 0)
441 DEBUGP (("Created socket fd %d.\n", *sock));
445 /* Close SOCK, as well as the most recently remembered MSOCK, created
446 via bindport(). If SOCK is -1, close MSOCK only. */
450 /*shutdown (sock, 2);*/
458 /* Return the local IP address associated with the connection on FD. */
461 conaddr (int fd, ip_address *ip)
463 struct sockaddr_storage storage;
464 struct sockaddr *sockaddr = (struct sockaddr *)&storage;
465 socklen_t addrlen = sizeof (storage);
467 if (getsockname (fd, sockaddr, &addrlen) < 0)
470 switch (sockaddr->sa_family)
475 struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&storage;
476 ip->type = IPV6_ADDRESS;
477 ADDRESS_IPV6_IN6_ADDR (ip) = sa6->sin6_addr;
478 #ifdef HAVE_SOCKADDR_IN6_SCOPE_ID
479 ADDRESS_IPV6_SCOPE (ip) = sa6->sin6_scope_id;
481 DEBUGP (("conaddr is: %s\n", pretty_print_address (ip)));
487 struct sockaddr_in *sa = (struct sockaddr_in *)&storage;
488 ip->type = IPV4_ADDRESS;
489 ADDRESS_IPV4_IN_ADDR (ip) = sa->sin_addr;
490 DEBUGP (("conaddr is: %s\n", pretty_print_address (ip)));
500 /* Read at most LEN bytes from FD, storing them to BUF. This is
501 virtually the same as read(), but takes care of EINTR braindamage
502 and uses select() to timeout the stale connections (a connection is
503 stale if more than OPT.READ_TIMEOUT time is spent in select() or
507 iread (int fd, char *buf, int len)
512 if (opt.read_timeout)
513 if (select_fd (fd, opt.read_timeout, 0) <= 0)
517 res = READ (fd, buf, len);
518 while (res == -1 && errno == EINTR);
523 /* Write LEN bytes from BUF to FD. This is similar to iread(), but
524 unlike iread(), it makes sure that all of BUF is actually written
525 to FD, so callers needn't bother with checking that the return
526 value equals to LEN. Instead, you should simply check for -1. */
529 iwrite (int fd, char *buf, int len)
533 /* `write' may write less than LEN bytes, thus the outward loop
534 keeps trying it until all was written, or an error occurred. The
535 inner loop is reserved for the usual EINTR f*kage, and the
536 innermost loop deals with the same during select(). */
540 if (opt.read_timeout)
541 if (select_fd (fd, opt.read_timeout, 1) <= 0)
545 res = WRITE (fd, buf, len);
546 while (res == -1 && errno == EINTR);