]> sjero.net Git - wget/blob - src/connect.c
252cf5126942ef622c8aa356901d0c494865a111
[wget] / src / connect.c
1 /* Establishing and handling network connections.
2    Copyright (C) 1995, 1996, 1997, 2001, 2002 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
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.
10
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.
15
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.
19
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.  */
29
30 #include <config.h>
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <sys/types.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38 #include <assert.h>
39
40 #ifndef WINDOWS
41 # include <sys/socket.h>
42 # include <netdb.h>
43 # include <netinet/in.h>
44 # ifndef __BEOS__
45 #  include <arpa/inet.h>
46 # endif
47 #endif /* not WINDOWS */
48
49 #include <errno.h>
50 #ifdef HAVE_STRING_H
51 # include <string.h>
52 #else
53 # include <strings.h>
54 #endif /* HAVE_STRING_H */
55 #ifdef HAVE_SYS_SELECT_H
56 # include <sys/select.h>
57 #endif /* HAVE_SYS_SELECT_H */
58
59 #include "wget.h"
60 #include "utils.h"
61 #include "host.h"
62 #include "connect.h"
63
64 #ifndef errno
65 extern int errno;
66 #endif
67
68 /* Variables shared by bindport and acceptport: */
69 static int msock = -1;
70 /*static struct sockaddr *addr;*/
71
72 static int
73 resolve_bind_address (int flags, ip_address *addr)
74 {
75   struct address_list *al = NULL;
76   int bind_address_resolved = 0;
77
78   if (opt.bind_address != NULL)
79     {
80       al = lookup_host (opt.bind_address, flags | LH_SILENT | LH_PASSIVE);
81
82       if (al == NULL)
83         {
84           logprintf (LOG_NOTQUIET,
85                      _("Unable to convert `%s' to a bind address.  Reverting to ANY.\n"),
86                      opt.bind_address);
87         }
88       else 
89         bind_address_resolved = 1;
90     }
91
92   if (al == NULL)
93     {
94       const char *unspecified_address = "0.0.0.0";
95 #ifdef ENABLE_IPV6
96       if (flags & BIND_ON_IPV6_ONLY)
97         unspecified_address = "::";
98 #endif
99       al = lookup_host (unspecified_address, LH_SILENT | LH_PASSIVE);
100     }
101
102   assert (al != NULL);
103
104   address_list_copy_one (al, 0, addr);
105   address_list_release (al);
106
107   return bind_address_resolved;
108 }
109 \f
110 struct cwt_context {
111   int fd;
112   const struct sockaddr *addr;
113   socklen_t addrlen;
114   int result;
115 };
116
117 static void
118 connect_with_timeout_callback (void *arg)
119 {
120   struct cwt_context *ctx = (struct cwt_context *)arg;
121   ctx->result = connect (ctx->fd, ctx->addr, ctx->addrlen);
122 }
123
124 /* Like connect, but specifies a timeout.  If connecting takes longer
125    than TIMEOUT seconds, -1 is returned and errno is set to
126    ETIMEDOUT.  */
127
128 static int
129 connect_with_timeout (int fd, const struct sockaddr *addr, socklen_t addrlen,
130                       double timeout)
131 {
132   struct cwt_context ctx;
133   ctx.fd = fd;
134   ctx.addr = addr;
135   ctx.addrlen = addrlen;
136
137   if (run_with_timeout (timeout, connect_with_timeout_callback, &ctx))
138     {
139       errno = ETIMEDOUT;
140       return -1;
141     }
142   if (ctx.result == -1 && errno == EINTR)
143     errno = ETIMEDOUT;
144   return ctx.result;
145 }
146 \f
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;
150
151 void
152 set_connection_host_name (const char *host)
153 {
154   if (host)
155     assert (connection_host_name == NULL);
156   else
157     assert (connection_host_name != NULL);
158
159   connection_host_name = host;
160 }
161
162 /* Connect to a remote host whose address has been resolved. */
163 int
164 connect_to_one (ip_address *addr, unsigned short port, int silent)
165 {
166   struct sockaddr_storage ss;
167   struct sockaddr *sa = (struct sockaddr *)&ss;
168   int sock, save_errno;
169
170   /* Set port and protocol */
171   sockaddr_set_address (sa, port, addr);
172
173   if (!silent)
174     {
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);
180       else
181         logprintf (LOG_VERBOSE, _("Connecting to %s:%hu... "),
182                    pretty_addr, port);
183     }
184
185   /* Make an internet socket, stream type.  */
186   sock = socket (sa->sa_family, SOCK_STREAM, 0);
187   if (sock < 0)
188     goto out;
189
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
193      reads.  */
194   if (opt.limit_rate && opt.limit_rate < 8192)
195     {
196       int bufsize = opt.limit_rate;
197       if (bufsize < 512)
198         bufsize = 512;
199 #ifdef SO_RCVBUF
200       setsockopt (sock, SOL_SOCKET, SO_RCVBUF,
201                   (char *)&bufsize, sizeof (bufsize));
202 #endif
203       /* When we add opt.limit_rate support for writing, as with
204          `--post-file', also set SO_SNDBUF here.  */
205     }
206
207   if (opt.bind_address)
208     {
209       /* Bind the client side to the requested address. */
210       ip_address bind_address;
211       if (resolve_bind_address (0, &bind_address))
212         {
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)))
217             {
218               CLOSE (sock);
219               sock = -1;
220               goto out;
221             }
222         }
223     }
224
225   /* Connect the socket to the remote host.  */
226   if (connect_with_timeout (sock, sa, sockaddr_len (sa),
227                             opt.connect_timeout) < 0)
228     {
229       CLOSE (sock);
230       sock = -1;
231       goto out;
232     }
233
234  out:
235   if (sock >= 0)
236     {
237       /* Success. */
238       if (!silent)
239         logprintf (LOG_VERBOSE, _("connected.\n"));
240       DEBUGP (("Created socket %d.\n", sock));
241     }
242   else
243     {
244       save_errno = errno;
245       if (!silent)
246         logprintf (LOG_VERBOSE, "failed: %s.\n", strerror (errno));
247       errno = save_errno;
248     }
249
250   return sock;
251 }
252
253 /* Connect to a remote host whose address has been resolved. */
254 int
255 connect_to_many (struct address_list *al, unsigned short port, int silent)
256 {
257   int i, start, end;
258
259   address_list_get_bounds (al, &start, &end);
260   for (i = start; i < end; i++)
261     {
262       ip_address addr;
263       int sock;
264       address_list_copy_one (al, i, &addr);
265
266       sock = connect_to_one (&addr, port, silent);
267       if (sock >= 0)
268         /* Success. */
269         return sock;
270
271       address_list_set_faulty (al, i);
272
273       /* The attempt to connect has failed.  Continue with the loop
274          and try next address. */
275     }
276
277   return -1;
278 }
279
280 int
281 test_socket_open (int sock)
282 {
283 #ifdef HAVE_SELECT
284   fd_set check_set;
285   struct timeval to;
286
287   /* Check if we still have a valid (non-EOF) connection.  From Andrew
288    * Maholski's code in the Unix Socket FAQ.  */
289
290   FD_ZERO (&check_set);
291   FD_SET (sock, &check_set);
292
293   /* Wait one microsecond */
294   to.tv_sec = 0;
295   to.tv_usec = 1;
296
297   /* If we get a timeout, then that means still connected */
298   if (select (sock + 1, &check_set, NULL, NULL, &to) == 0)
299     {
300       /* Connection is valid (not EOF), so continue */
301       return 1;
302     }
303   else
304     return 0;
305 #else
306   /* Without select, it's hard to know for sure. */
307   return 1;
308 #endif
309 }
310
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.  */
317
318 uerr_t
319 bindport (const ip_address *bind_address, unsigned short *port)
320 {
321   int family = AF_INET;
322   int optval;
323   struct sockaddr_storage ss;
324   struct sockaddr *sa = (struct sockaddr *)&ss;
325   memset (&ss, 0, sizeof (ss));
326
327   msock = -1;
328
329 #ifdef ENABLE_IPV6
330   if (bind_address->type == IPv6_ADDRESS) 
331     family = AF_INET6;
332 #endif
333   
334   if ((msock = socket (family, SOCK_STREAM, 0)) < 0)
335     return CONSOCKERR;
336
337 #ifdef SO_REUSEADDR
338   optval = 1;
339   if (setsockopt (msock, SOL_SOCKET, SO_REUSEADDR,
340                   (char *)&optval, sizeof (optval)) < 0)
341     return CONSOCKERR;
342 #endif
343
344 #ifdef ENABLE_IPV6
345 # ifdef HAVE_IPV6_V6ONLY
346   if (family == AF_INET6)
347     {
348       optval = 1;
349       /* if setsockopt fails, go on anyway */
350       setsockopt (msock, IPPROTO_IPV6, IPV6_V6ONLY,
351                   (char *)&optval, sizeof (optval));
352     }
353 # endif
354 #endif
355   
356   sockaddr_set_address (sa, htons (*port), bind_address);
357   if (bind (msock, sa, sockaddr_len (sa)) < 0)
358     {
359       CLOSE (msock);
360       msock = -1;
361       return BINDERR;
362     }
363   DEBUGP (("Master socket fd %d bound.\n", msock));
364   if (!*port)
365     {
366       socklen_t sa_len = sockaddr_len (sa);
367       if (getsockname (msock, sa, &sa_len) < 0)
368         {
369           CLOSE (msock);
370           msock = -1;
371           return CONPORTERR;
372         }
373       *port = sockaddr_get_port (sa);
374       DEBUGP (("binding to address %s using port %i.\n", 
375                pretty_print_address (bind_address), *port));
376     }
377   if (listen (msock, 1) < 0)
378     {
379       CLOSE (msock);
380       msock = -1;
381       return LISTENERR;
382     }
383   return BINDOK;
384 }
385
386 #ifdef HAVE_SELECT
387 /* Wait for file descriptor FD to be available, timing out after
388    MAXTIME seconds.  "Available" means readable if writep is 0,
389    writeable otherwise.
390
391    Returns 1 if FD is available, 0 for timeout and -1 for error.  */
392
393 int
394 select_fd (int fd, double maxtime, int writep)
395 {
396   fd_set fds;
397   fd_set *rd = NULL, *wrt = NULL;
398   struct timeval tmout;
399   int result;
400
401   FD_ZERO (&fds);
402   FD_SET (fd, &fds);
403   *(writep ? &wrt : &rd) = &fds;
404
405   tmout.tv_sec = (long)maxtime;
406   tmout.tv_usec = 1000000L * (maxtime - (long)maxtime);
407
408   do
409     result = select (fd + 1, rd, wrt, NULL, &tmout);
410   while (result < 0 && errno == EINTR);
411
412   /* When we've timed out, set errno to ETIMEDOUT for the convenience
413      of the caller. */
414   if (result == 0)
415     errno = ETIMEDOUT;
416
417   return result;
418 }
419 #endif /* HAVE_SELECT */
420
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.  */
426 uerr_t
427 acceptport (int *sock)
428 {
429   struct sockaddr_storage ss;
430   struct sockaddr *sa = (struct sockaddr *)&ss;
431   socklen_t addrlen = sizeof (ss);
432
433 #ifdef HAVE_SELECT
434   if (select_fd (msock, opt.connect_timeout, 0) <= 0)
435     return ACCEPTERR;
436 #endif
437   if ((*sock = accept (msock, sa, &addrlen)) < 0)
438     return ACCEPTERR;
439   DEBUGP (("Created socket fd %d.\n", *sock));
440   return ACCEPTOK;
441 }
442
443 /* Close SOCK, as well as the most recently remembered MSOCK, created
444    via bindport().  If SOCK is -1, close MSOCK only.  */
445 void
446 closeport (int sock)
447 {
448   /*shutdown (sock, 2);*/
449   if (sock != -1)
450     CLOSE (sock);
451   if (msock != -1)
452     CLOSE (msock);
453   msock = -1;
454 }
455
456 /* Return the local IP address associated with the connection on FD.  */
457
458 int
459 conaddr (int fd, ip_address *ip)
460 {
461   struct sockaddr_storage ss;
462   struct sockaddr *sa = (struct sockaddr *)&ss;
463   socklen_t addrlen = sizeof (ss);      
464
465   if (getsockname (fd, sa, &addrlen) < 0)
466     return 0;
467
468   switch (sa->sa_family)
469     {
470 #ifdef ENABLE_IPV6
471     case AF_INET6:
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;
476 #endif
477       DEBUGP (("conaddr is: %s\n", pretty_print_address (ip)));
478       return 1;
479 #endif
480     case AF_INET:
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)));
484       return 1;
485     default:
486       abort ();
487     }
488
489   return 0;
490 }
491
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
496    read()).  */
497
498 int
499 iread (int fd, char *buf, int len)
500 {
501   int res;
502
503 #ifdef HAVE_SELECT
504   if (opt.read_timeout)
505     if (select_fd (fd, opt.read_timeout, 0) <= 0)
506       return -1;
507 #endif
508   do
509     res = READ (fd, buf, len);
510   while (res == -1 && errno == EINTR);
511
512   return res;
513 }
514
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.  */
519
520 int
521 iwrite (int fd, char *buf, int len)
522 {
523   int res = 0;
524
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().  */
529   while (len > 0)
530     {
531 #ifdef HAVE_SELECT
532       if (opt.read_timeout)
533         if (select_fd (fd, opt.read_timeout, 1) <= 0)
534           return -1;
535 #endif
536       do
537         res = WRITE (fd, buf, len);
538       while (res == -1 && errno == EINTR);
539       if (res <= 0)
540         break;
541       buf += res;
542       len -= res;
543     }
544   return res;
545 }