]> sjero.net Git - wget/blob - src/retr.c
Automated merge.
[wget] / src / retr.c
1 /* File retrieval.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3    2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4
5 This file is part of GNU Wget.
6
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at
10 your option) any later version.
11
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Wget.  If not, see <http://www.gnu.org/licenses/>.
19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a
24 modified version of that library), containing parts covered by the
25 terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
26 grants you additional permission to convey the resulting work.
27 Corresponding Source for a non-source form of such a combination
28 shall include the source code for the parts of OpenSSL used as well
29 as that of the covered work.  */
30
31 #include "wget.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif /* HAVE_UNISTD_H */
38 #include <errno.h>
39 #include <string.h>
40 #include <assert.h>
41
42 #include "utils.h"
43 #include "retr.h"
44 #include "progress.h"
45 #include "url.h"
46 #include "recur.h"
47 #include "ftp.h"
48 #include "http.h"
49 #include "host.h"
50 #include "connect.h"
51 #include "hash.h"
52 #include "convert.h"
53 #include "ptimer.h"
54 #include "html-url.h"
55 #include "iri.h"
56
57 /* Total size of downloaded files.  Used to enforce quota.  */
58 SUM_SIZE_INT total_downloaded_bytes;
59
60 /* Total download time in seconds. */
61 double total_download_time;
62
63 /* If non-NULL, the stream to which output should be written.  This
64    stream is initialized when `-O' is used.  */
65 FILE *output_stream;
66
67 /* Whether output_document is a regular file we can manipulate,
68    i.e. not `-' or a device file. */
69 bool output_stream_regular;
70 \f
71 static struct {
72   wgint chunk_bytes;
73   double chunk_start;
74   double sleep_adjust;
75 } limit_data;
76
77 static void
78 limit_bandwidth_reset (void)
79 {
80   xzero (limit_data);
81 }
82
83 /* Limit the bandwidth by pausing the download for an amount of time.
84    BYTES is the number of bytes received from the network, and TIMER
85    is the timer that started at the beginning of download.  */
86
87 static void
88 limit_bandwidth (wgint bytes, struct ptimer *timer)
89 {
90   double delta_t = ptimer_read (timer) - limit_data.chunk_start;
91   double expected;
92
93   limit_data.chunk_bytes += bytes;
94
95   /* Calculate the amount of time we expect downloading the chunk
96      should take.  If in reality it took less time, sleep to
97      compensate for the difference.  */
98   expected = (double) limit_data.chunk_bytes / opt.limit_rate;
99
100   if (expected > delta_t)
101     {
102       double slp = expected - delta_t + limit_data.sleep_adjust;
103       double t0, t1;
104       if (slp < 0.2)
105         {
106           DEBUGP (("deferring a %.2f ms sleep (%s/%.2f).\n",
107                    slp * 1000, number_to_static_string (limit_data.chunk_bytes),
108                    delta_t));
109           return;
110         }
111       DEBUGP (("\nsleeping %.2f ms for %s bytes, adjust %.2f ms\n",
112                slp * 1000, number_to_static_string (limit_data.chunk_bytes),
113                limit_data.sleep_adjust));
114
115       t0 = ptimer_read (timer);
116       xsleep (slp);
117       t1 = ptimer_measure (timer);
118
119       /* Due to scheduling, we probably slept slightly longer (or
120          shorter) than desired.  Calculate the difference between the
121          desired and the actual sleep, and adjust the next sleep by
122          that amount.  */
123       limit_data.sleep_adjust = slp - (t1 - t0);
124       /* If sleep_adjust is very large, it's likely due to suspension
125          and not clock inaccuracy.  Don't enforce those.  */
126       if (limit_data.sleep_adjust > 0.5)
127         limit_data.sleep_adjust = 0.5;
128       else if (limit_data.sleep_adjust < -0.5)
129         limit_data.sleep_adjust = -0.5;
130     }
131
132   limit_data.chunk_bytes = 0;
133   limit_data.chunk_start = ptimer_read (timer);
134 }
135
136 #ifndef MIN
137 # define MIN(i, j) ((i) <= (j) ? (i) : (j))
138 #endif
139
140 /* Write data in BUF to OUT.  However, if *SKIP is non-zero, skip that
141    amount of data and decrease SKIP.  Increment *TOTAL by the amount
142    of data written.  */
143
144 static int
145 write_data (FILE *out, const char *buf, int bufsize, wgint *skip,
146             wgint *written, int flags)
147 {
148   static int cr_pending = 0;    /* Found CR in ASCII FTP data. */
149
150   if (!out)
151     return 1;
152   if (*skip > bufsize)
153     {
154       *skip -= bufsize;
155       return 1;
156     }
157   if (*skip)
158     {
159       buf += *skip;
160       bufsize -= *skip;
161       *skip = 0;
162       if (bufsize == 0)
163         return 1;
164     }
165
166 /* Note: This code assumes that "\n" is the universal line ending
167    character, as on UNIX and VMS.  If this is not true, then here's
168    where to change it.
169 */
170
171 #if 1
172 # define EOL_STRING "\n"
173 #else /* 1 */
174 # define EOL_STRING "\r\n"
175 #endif /* 1 [else] */
176 #define EOL_STRING_LEN (sizeof( EOL_STRING)- 1)
177
178   if (flags & rb_ftp_ascii)
179     {
180       const char *bufend;
181
182       /* ASCII transfer.  Put out lines delimited by CRLF. */
183       bufend = buf+ bufsize;
184       while (buf < bufend)
185         {
186           /* If CR, put out any pending CR, then set CR-pending flag. */
187           if (*buf == '\r')
188             {
189               if (cr_pending)
190                 {
191                   fwrite ("\r", 1, 1, out);
192                   *written += 1;
193                 }
194               cr_pending = 1;
195               buf++;
196               continue;
197             }
198
199           if (cr_pending)
200             {
201               if (*buf == '\n')
202                 {
203                   /* Found FTP EOL (CRLF).  Put out local EOL. */
204                   fwrite (EOL_STRING, 1, EOL_STRING_LEN, out);
205                   *written += EOL_STRING_LEN;
206                 }
207               else
208                 {
209                   /* Normal character.  Put out pending CR and it. */
210                   fwrite ("\r", 1, 1, out);
211                   fwrite (buf, 1, 1, out);
212                   *written += 2;
213                 }
214               buf++;
215               cr_pending = 0;
216             }
217           else
218             {
219               /* Normal character.  Put it out. */
220               fwrite (buf, 1, 1, out);
221               *written += 1;
222               buf++;
223             }
224         }
225     }
226   else
227     {
228       /* Image transfer.  Put out buffer. */
229       fwrite (buf, 1, bufsize, out);
230       *written += bufsize;
231     }
232
233   /* Immediately flush the downloaded data.  This should not hinder
234      performance: fast downloads will arrive in large 16K chunks
235      (which stdio would write out immediately anyway), and slow
236      downloads wouldn't be limited by disk speed.  */
237
238   /* 2005-04-20 SMS.
239      Perhaps it shouldn't hinder performance, but it sure does, at least
240      on VMS (more than 2X).  Rather than speculate on what it should or
241      shouldn't do, it might make more sense to test it.  Even better, it
242      might be nice to explain what possible benefit it could offer, as
243      it appears to be a clear invitation to poor performance with no
244      actual justification.  (Also, why 16K?  Anyone test other values?)
245   */
246 #ifndef __VMS
247   fflush (out);
248 #endif /* ndef __VMS */
249   return !ferror (out);
250 }
251
252 /* Read the contents of file descriptor FD until it the connection
253    terminates or a read error occurs.  The data is read in portions of
254    up to 16K and written to OUT as it arrives.  If opt.verbose is set,
255    the progress is shown.
256
257    TOREAD is the amount of data expected to arrive, normally only used
258    by the progress gauge.
259
260    STARTPOS is the position from which the download starts, used by
261    the progress gauge.  If QTYREAD is non-NULL, the value it points to
262    is incremented by the amount of data read from the network.  If
263    QTYWRITTEN is non-NULL, the value it points to is incremented by
264    the amount of data written to disk.  The time it took to download
265    the data is stored to ELAPSED.
266
267    The function exits and returns the amount of data read.  In case of
268    error while reading data, -1 is returned.  In case of error while
269    writing data, -2 is returned.  */
270
271 int
272 fd_read_body (int fd, FILE *out, wgint toread, wgint startpos,
273               wgint *qtyread, wgint *qtywritten, double *elapsed, int flags)
274 {
275   int ret = 0;
276
277   static char dlbuf[16384];
278   int dlbufsize = sizeof (dlbuf);
279
280   struct ptimer *timer = NULL;
281   double last_successful_read_tm = 0;
282
283   /* The progress gauge, set according to the user preferences. */
284   void *progress = NULL;
285
286   /* Non-zero if the progress gauge is interactive, i.e. if it can
287      continually update the display.  When true, smaller timeout
288      values are used so that the gauge can update the display when
289      data arrives slowly. */
290   bool progress_interactive = false;
291
292   bool exact = !!(flags & rb_read_exactly);
293   wgint skip = 0;
294
295   /* How much data we've read/written.  */
296   wgint sum_read = 0;
297   wgint sum_written = 0;
298
299   if (flags & rb_skip_startpos)
300     skip = startpos;
301
302   if (opt.verbose)
303     {
304       /* If we're skipping STARTPOS bytes, pass 0 as the INITIAL
305          argument to progress_create because the indicator doesn't
306          (yet) know about "skipping" data.  */
307       wgint start = skip ? 0 : startpos;
308       progress = progress_create (start, start + toread);
309       progress_interactive = progress_interactive_p (progress);
310     }
311
312   if (opt.limit_rate)
313     limit_bandwidth_reset ();
314
315   /* A timer is needed for tracking progress, for throttling, and for
316      tracking elapsed time.  If either of these are requested, start
317      the timer.  */
318   if (progress || opt.limit_rate || elapsed)
319     {
320       timer = ptimer_new ();
321       last_successful_read_tm = 0;
322     }
323
324   /* Use a smaller buffer for low requested bandwidths.  For example,
325      with --limit-rate=2k, it doesn't make sense to slurp in 16K of
326      data and then sleep for 8s.  With buffer size equal to the limit,
327      we never have to sleep for more than one second.  */
328   if (opt.limit_rate && opt.limit_rate < dlbufsize)
329     dlbufsize = opt.limit_rate;
330
331   /* Read from FD while there is data to read.  Normally toread==0
332      means that it is unknown how much data is to arrive.  However, if
333      EXACT is set, then toread==0 means what it says: that no data
334      should be read.  */
335   while (!exact || (sum_read < toread))
336     {
337       int rdsize = exact ? MIN (toread - sum_read, dlbufsize) : dlbufsize;
338       double tmout = opt.read_timeout;
339       if (progress_interactive)
340         {
341           /* For interactive progress gauges, always specify a ~1s
342              timeout, so that the gauge can be updated regularly even
343              when the data arrives very slowly or stalls.  */
344           tmout = 0.95;
345           if (opt.read_timeout)
346             {
347               double waittm;
348               waittm = ptimer_read (timer) - last_successful_read_tm;
349               if (waittm + tmout > opt.read_timeout)
350                 {
351                   /* Don't let total idle time exceed read timeout. */
352                   tmout = opt.read_timeout - waittm;
353                   if (tmout < 0)
354                     {
355                       /* We've already exceeded the timeout. */
356                       ret = -1, errno = ETIMEDOUT;
357                       break;
358                     }
359                 }
360             }
361         }
362       ret = fd_read (fd, dlbuf, rdsize, tmout);
363
364       if (progress_interactive && ret < 0 && errno == ETIMEDOUT)
365         ret = 0;                /* interactive timeout, handled above */
366       else if (ret <= 0)
367         break;                  /* EOF or read error */
368
369       if (progress || opt.limit_rate)
370         {
371           ptimer_measure (timer);
372           if (ret > 0)
373             last_successful_read_tm = ptimer_read (timer);
374         }
375
376       if (ret > 0)
377         {
378           sum_read += ret;
379           if (!write_data (out, dlbuf, ret, &skip, &sum_written, flags))
380             {
381               ret = -2;
382               goto out;
383             }
384         }
385
386       if (opt.limit_rate)
387         limit_bandwidth (ret, timer);
388
389       if (progress)
390         progress_update (progress, ret, ptimer_read (timer));
391 #ifdef WINDOWS
392       if (toread > 0 && !opt.quiet)
393         ws_percenttitle (100.0 *
394                          (startpos + sum_read) / (startpos + toread));
395 #endif
396     }
397   if (ret < -1)
398     ret = -1;
399
400  out:
401   if (progress)
402     progress_finish (progress, ptimer_read (timer));
403
404   if (elapsed)
405     *elapsed = ptimer_read (timer);
406   if (timer)
407     ptimer_destroy (timer);
408
409   if (qtyread)
410     *qtyread += sum_read;
411   if (qtywritten)
412     *qtywritten += sum_written;
413
414   return ret;
415 }
416 \f
417 /* Read a hunk of data from FD, up until a terminator.  The hunk is
418    limited by whatever the TERMINATOR callback chooses as its
419    terminator.  For example, if terminator stops at newline, the hunk
420    will consist of a line of data; if terminator stops at two
421    newlines, it can be used to read the head of an HTTP response.
422    Upon determining the boundary, the function returns the data (up to
423    the terminator) in malloc-allocated storage.
424
425    In case of read error, NULL is returned.  In case of EOF and no
426    data read, NULL is returned and errno set to 0.  In case of having
427    read some data, but encountering EOF before seeing the terminator,
428    the data that has been read is returned, but it will (obviously)
429    not contain the terminator.
430
431    The TERMINATOR function is called with three arguments: the
432    beginning of the data read so far, the beginning of the current
433    block of peeked-at data, and the length of the current block.
434    Depending on its needs, the function is free to choose whether to
435    analyze all data or just the newly arrived data.  If TERMINATOR
436    returns NULL, it means that the terminator has not been seen.
437    Otherwise it should return a pointer to the charactre immediately
438    following the terminator.
439
440    The idea is to be able to read a line of input, or otherwise a hunk
441    of text, such as the head of an HTTP request, without crossing the
442    boundary, so that the next call to fd_read etc. reads the data
443    after the hunk.  To achieve that, this function does the following:
444
445    1. Peek at incoming data.
446
447    2. Determine whether the peeked data, along with the previously
448       read data, includes the terminator.
449
450       2a. If yes, read the data until the end of the terminator, and
451           exit.
452
453       2b. If no, read the peeked data and goto 1.
454
455    The function is careful to assume as little as possible about the
456    implementation of peeking.  For example, every peek is followed by
457    a read.  If the read returns a different amount of data, the
458    process is retried until all data arrives safely.
459
460    SIZEHINT is the buffer size sufficient to hold all the data in the
461    typical case (it is used as the initial buffer size).  MAXSIZE is
462    the maximum amount of memory this function is allowed to allocate,
463    or 0 if no upper limit is to be enforced.
464
465    This function should be used as a building block for other
466    functions -- see fd_read_line as a simple example.  */
467
468 char *
469 fd_read_hunk (int fd, hunk_terminator_t terminator, long sizehint, long maxsize)
470 {
471   long bufsize = sizehint;
472   char *hunk = xmalloc (bufsize);
473   int tail = 0;                 /* tail position in HUNK */
474
475   assert (!maxsize || maxsize >= bufsize);
476
477   while (1)
478     {
479       const char *end;
480       int pklen, rdlen, remain;
481
482       /* First, peek at the available data. */
483
484       pklen = fd_peek (fd, hunk + tail, bufsize - 1 - tail, -1);
485       if (pklen < 0)
486         {
487           xfree (hunk);
488           return NULL;
489         }
490       end = terminator (hunk, hunk + tail, pklen);
491       if (end)
492         {
493           /* The data contains the terminator: we'll drain the data up
494              to the end of the terminator.  */
495           remain = end - (hunk + tail);
496           assert (remain >= 0);
497           if (remain == 0)
498             {
499               /* No more data needs to be read. */
500               hunk[tail] = '\0';
501               return hunk;
502             }
503           if (bufsize - 1 < tail + remain)
504             {
505               bufsize = tail + remain + 1;
506               hunk = xrealloc (hunk, bufsize);
507             }
508         }
509       else
510         /* No terminator: simply read the data we know is (or should
511            be) available.  */
512         remain = pklen;
513
514       /* Now, read the data.  Note that we make no assumptions about
515          how much data we'll get.  (Some TCP stacks are notorious for
516          read returning less data than the previous MSG_PEEK.)  */
517
518       rdlen = fd_read (fd, hunk + tail, remain, 0);
519       if (rdlen < 0)
520         {
521           xfree_null (hunk);
522           return NULL;
523         }
524       tail += rdlen;
525       hunk[tail] = '\0';
526
527       if (rdlen == 0)
528         {
529           if (tail == 0)
530             {
531               /* EOF without anything having been read */
532               xfree (hunk);
533               errno = 0;
534               return NULL;
535             }
536           else
537             /* EOF seen: return the data we've read. */
538             return hunk;
539         }
540       if (end && rdlen == remain)
541         /* The terminator was seen and the remaining data drained --
542            we got what we came for.  */
543         return hunk;
544
545       /* Keep looping until all the data arrives. */
546
547       if (tail == bufsize - 1)
548         {
549           /* Double the buffer size, but refuse to allocate more than
550              MAXSIZE bytes.  */
551           if (maxsize && bufsize >= maxsize)
552             {
553               xfree (hunk);
554               errno = ENOMEM;
555               return NULL;
556             }
557           bufsize <<= 1;
558           if (maxsize && bufsize > maxsize)
559             bufsize = maxsize;
560           hunk = xrealloc (hunk, bufsize);
561         }
562     }
563 }
564
565 static const char *
566 line_terminator (const char *start, const char *peeked, int peeklen)
567 {
568   const char *p = memchr (peeked, '\n', peeklen);
569   if (p)
570     /* p+1 because the line must include '\n' */
571     return p + 1;
572   return NULL;
573 }
574
575 /* The maximum size of the single line we agree to accept.  This is
576    not meant to impose an arbitrary limit, but to protect the user
577    from Wget slurping up available memory upon encountering malicious
578    or buggy server output.  Define it to 0 to remove the limit.  */
579 #define FD_READ_LINE_MAX 4096
580
581 /* Read one line from FD and return it.  The line is allocated using
582    malloc, but is never larger than FD_READ_LINE_MAX.
583
584    If an error occurs, or if no data can be read, NULL is returned.
585    In the former case errno indicates the error condition, and in the
586    latter case, errno is NULL.  */
587
588 char *
589 fd_read_line (int fd)
590 {
591   return fd_read_hunk (fd, line_terminator, 128, FD_READ_LINE_MAX);
592 }
593 \f
594 /* Return a printed representation of the download rate, along with
595    the units appropriate for the download speed.  */
596
597 const char *
598 retr_rate (wgint bytes, double secs)
599 {
600   static char res[20];
601   static const char *rate_names[] = {"B/s", "KB/s", "MB/s", "GB/s" };
602   int units;
603
604   double dlrate = calc_rate (bytes, secs, &units);
605   /* Use more digits for smaller numbers (regardless of unit used),
606      e.g. "1022", "247", "12.5", "2.38".  */
607   sprintf (res, "%.*f %s",
608            dlrate >= 99.95 ? 0 : dlrate >= 9.995 ? 1 : 2,
609            dlrate, rate_names[units]);
610
611   return res;
612 }
613
614 /* Calculate the download rate and trim it as appropriate for the
615    speed.  Appropriate means that if rate is greater than 1K/s,
616    kilobytes are used, and if rate is greater than 1MB/s, megabytes
617    are used.
618
619    UNITS is zero for B/s, one for KB/s, two for MB/s, and three for
620    GB/s.  */
621
622 double
623 calc_rate (wgint bytes, double secs, int *units)
624 {
625   double dlrate;
626
627   assert (secs >= 0);
628   assert (bytes >= 0);
629
630   if (secs == 0)
631     /* If elapsed time is exactly zero, it means we're under the
632        resolution of the timer.  This can easily happen on systems
633        that use time() for the timer.  Since the interval lies between
634        0 and the timer's resolution, assume half the resolution.  */
635     secs = ptimer_resolution () / 2.0;
636
637   dlrate = bytes / secs;
638   if (dlrate < 1024.0)
639     *units = 0;
640   else if (dlrate < 1024.0 * 1024.0)
641     *units = 1, dlrate /= 1024.0;
642   else if (dlrate < 1024.0 * 1024.0 * 1024.0)
643     *units = 2, dlrate /= (1024.0 * 1024.0);
644   else
645     /* Maybe someone will need this, one day. */
646     *units = 3, dlrate /= (1024.0 * 1024.0 * 1024.0);
647
648   return dlrate;
649 }
650 \f
651
652 #define SUSPEND_POST_DATA do {                  \
653   post_data_suspended = true;                   \
654   saved_post_data = opt.post_data;              \
655   saved_post_file_name = opt.post_file_name;    \
656   opt.post_data = NULL;                         \
657   opt.post_file_name = NULL;                    \
658 } while (0)
659
660 #define RESTORE_POST_DATA do {                          \
661   if (post_data_suspended)                              \
662     {                                                   \
663       opt.post_data = saved_post_data;                  \
664       opt.post_file_name = saved_post_file_name;        \
665       post_data_suspended = false;                      \
666     }                                                   \
667 } while (0)
668
669 static char *getproxy (struct url *);
670
671 /* Retrieve the given URL.  Decides which loop to call -- HTTP, FTP,
672    FTP, proxy, etc.  */
673
674 /* #### This function should be rewritten so it doesn't return from
675    multiple points. */
676
677 uerr_t
678 retrieve_url (struct url * orig_parsed, const char *origurl, char **file,
679               char **newloc, const char *refurl, int *dt, bool recursive,
680               struct iri *iri)
681 {
682   uerr_t result;
683   char *url;
684   bool location_changed;
685   bool iri_fallbacked = 0;
686   int dummy;
687   char *mynewloc, *proxy;
688   struct url *u = orig_parsed, *proxy_url;
689   int up_error_code;            /* url parse error code */
690   char *local_file;
691   int redirection_count = 0;
692
693   bool post_data_suspended = false;
694   char *saved_post_data = NULL;
695   char *saved_post_file_name = NULL;
696
697   /* If dt is NULL, use local storage.  */
698   if (!dt)
699     {
700       dt = &dummy;
701       dummy = 0;
702     }
703   url = xstrdup (origurl);
704   if (newloc)
705     *newloc = NULL;
706   if (file)
707     *file = NULL;
708
709   if (!refurl)
710     refurl = opt.referer;
711
712  redirected:
713   /* (also for IRI fallbacking) */
714
715   result = NOCONERROR;
716   mynewloc = NULL;
717   local_file = NULL;
718   proxy_url = NULL;
719
720   proxy = getproxy (u);
721   if (proxy)
722     {
723       struct iri *pi = iri_new ();
724       set_uri_encoding (pi, opt.locale, true);
725       pi->utf8_encode = false;
726
727       /* Parse the proxy URL.  */
728       proxy_url = url_parse (proxy, &up_error_code, NULL, true);
729       if (!proxy_url)
730         {
731           char *error = url_error (proxy, up_error_code);
732           logprintf (LOG_NOTQUIET, _("Error parsing proxy URL %s: %s.\n"),
733                      proxy, error);
734           xfree (url);
735           xfree (error);
736           RESTORE_POST_DATA;
737           return PROXERR;
738         }
739       if (proxy_url->scheme != SCHEME_HTTP && proxy_url->scheme != u->scheme)
740         {
741           logprintf (LOG_NOTQUIET, _("Error in proxy URL %s: Must be HTTP.\n"), proxy);
742           url_free (proxy_url);
743           xfree (url);
744           RESTORE_POST_DATA;
745           return PROXERR;
746         }
747     }
748
749   if (u->scheme == SCHEME_HTTP
750 #ifdef HAVE_SSL
751       || u->scheme == SCHEME_HTTPS
752 #endif
753       || (proxy_url && proxy_url->scheme == SCHEME_HTTP))
754     {
755       result = http_loop (u, &mynewloc, &local_file, refurl, dt, proxy_url, iri);
756     }
757   else if (u->scheme == SCHEME_FTP)
758     {
759       /* If this is a redirection, temporarily turn off opt.ftp_glob
760          and opt.recursive, both being undesirable when following
761          redirects.  */
762       bool oldrec = recursive, glob = opt.ftp_glob;
763       if (redirection_count)
764         oldrec = glob = false;
765
766       result = ftp_loop (u, dt, proxy_url, recursive, glob);
767       recursive = oldrec;
768
769       /* There is a possibility of having HTTP being redirected to
770          FTP.  In these cases we must decide whether the text is HTML
771          according to the suffix.  The HTML suffixes are `.html',
772          `.htm' and a few others, case-insensitive.  */
773       if (redirection_count && local_file && u->scheme == SCHEME_FTP)
774         {
775           if (has_html_suffix_p (local_file))
776             *dt |= TEXTHTML;
777         }
778     }
779
780   if (proxy_url)
781     {
782       url_free (proxy_url);
783       proxy_url = NULL;
784     }
785
786   location_changed = (result == NEWLOCATION);
787   if (location_changed)
788     {
789       char *construced_newloc;
790       struct url *newloc_parsed;
791
792       assert (mynewloc != NULL);
793
794       if (local_file)
795         xfree (local_file);
796
797       /* The HTTP specs only allow absolute URLs to appear in
798          redirects, but a ton of boneheaded webservers and CGIs out
799          there break the rules and use relative URLs, and popular
800          browsers are lenient about this, so wget should be too. */
801       construced_newloc = uri_merge (url, mynewloc);
802       xfree (mynewloc);
803       mynewloc = construced_newloc;
804
805       /* Reset UTF-8 encoding state, keep the URI encoding and reset
806          the content encoding. */
807       iri->utf8_encode = opt.enable_iri;
808       set_content_encoding (iri, NULL);
809       xfree_null (iri->orig_url);
810
811       /* Now, see if this new location makes sense. */
812       newloc_parsed = url_parse (mynewloc, &up_error_code, iri, true);
813       if (!newloc_parsed)
814         {
815           char *error = url_error (mynewloc, up_error_code);
816           logprintf (LOG_NOTQUIET, "%s: %s.\n", escnonprint_uri (mynewloc),
817                      error);
818           if (orig_parsed != u)
819             {
820               url_free (u);
821             }
822           xfree (url);
823           xfree (mynewloc);
824           xfree (error);
825           RESTORE_POST_DATA;
826           return result;
827         }
828
829       /* Now mynewloc will become newloc_parsed->url, because if the
830          Location contained relative paths like .././something, we
831          don't want that propagating as url.  */
832       xfree (mynewloc);
833       mynewloc = xstrdup (newloc_parsed->url);
834
835       /* Check for max. number of redirections.  */
836       if (++redirection_count > opt.max_redirect)
837         {
838           logprintf (LOG_NOTQUIET, _("%d redirections exceeded.\n"),
839                      opt.max_redirect);
840           url_free (newloc_parsed);
841           if (orig_parsed != u)
842             {
843               url_free (u);
844             }
845           xfree (url);
846           xfree (mynewloc);
847           RESTORE_POST_DATA;
848           return WRONGCODE;
849         }
850
851       xfree (url);
852       url = mynewloc;
853       if (orig_parsed != u)
854         {
855           url_free (u);
856         }
857       u = newloc_parsed;
858
859       /* If we're being redirected from POST, we don't want to POST
860          again.  Many requests answer POST with a redirection to an
861          index page; that redirection is clearly a GET.  We "suspend"
862          POST data for the duration of the redirections, and restore
863          it when we're done. */
864       if (!post_data_suspended)
865         SUSPEND_POST_DATA;
866
867       goto redirected;
868     }
869
870   /* Try to not encode in UTF-8 if fetching failed */
871   if (!(*dt & RETROKF) && iri->utf8_encode)
872     {
873       iri->utf8_encode = false;
874       if (orig_parsed != u)
875         {
876           url_free (u);
877         }
878       u = url_parse (origurl, NULL, iri, true);
879       if (u)
880         {
881           DEBUGP (("[IRI fallbacking to non-utf8 for %s\n", quote (url)));
882           url = xstrdup (u->url);
883           iri_fallbacked = 1;
884           goto redirected;
885         }
886       else
887           DEBUGP (("[Couldn't fallback to non-utf8 for %s\n", quote (url)));
888     }
889
890   if (local_file && *dt & RETROKF)
891     {
892       register_download (u->url, local_file);
893       if (redirection_count && 0 != strcmp (origurl, u->url))
894         register_redirection (origurl, u->url);
895       if (*dt & TEXTHTML)
896         register_html (u->url, local_file);
897       if (*dt & RETROKF)
898         {
899           register_download (u->url, local_file);
900           if (redirection_count && 0 != strcmp (origurl, u->url))
901             register_redirection (origurl, u->url);
902           if (*dt & TEXTHTML)
903             register_html (u->url, local_file);
904           if (*dt & TEXTCSS)
905             register_css (u->url, local_file);
906         }
907     }
908
909   if (file)
910     *file = local_file ? local_file : NULL;
911   else
912     xfree_null (local_file);
913
914   if (orig_parsed != u)
915     {
916       url_free (u);
917     }
918
919   if (redirection_count || iri_fallbacked)
920     {
921       if (newloc)
922         *newloc = url;
923       else
924         xfree (url);
925     }
926   else
927     {
928       if (newloc)
929         *newloc = NULL;
930       xfree (url);
931     }
932
933   RESTORE_POST_DATA;
934
935   return result;
936 }
937
938 /* Find the URLs in the file and call retrieve_url() for each of them.
939    If HTML is true, treat the file as HTML, and construct the URLs
940    accordingly.
941
942    If opt.recursive is set, call retrieve_tree() for each file.  */
943
944 uerr_t
945 retrieve_from_file (const char *file, bool html, int *count)
946 {
947   uerr_t status;
948   struct urlpos *url_list, *cur_url;
949   struct iri *iri = iri_new();
950
951   char *input_file = NULL;
952   const char *url = file;
953
954   status = RETROK;             /* Suppose everything is OK.  */
955   *count = 0;                  /* Reset the URL count.  */
956
957   /* sXXXav : Assume filename and links in the file are in the locale */
958   set_uri_encoding (iri, opt.locale, true);
959   set_content_encoding (iri, opt.locale);
960
961   if (url_has_scheme (url))
962     {
963       int dt,url_err;
964       uerr_t status;
965       struct url * url_parsed = url_parse(url, &url_err, iri, true);
966
967       if (!url_parsed)
968         {
969           char *error = url_error (url, url_err);
970           logprintf (LOG_NOTQUIET, "%s: %s.\n", url, error);
971           xfree (error);
972           return URLERROR;
973         }
974
975       if (!opt.base_href)
976         opt.base_href = xstrdup (url);
977
978       status = retrieve_url (url_parsed, url, &input_file, NULL, NULL, &dt,
979                              false, iri);
980       if (status != RETROK)
981         return status;
982
983       if (dt & TEXTHTML)
984         html = true;
985
986       /* If we have a found a content encoding, use it.
987        * ( == is okay, because we're checking for identical object) */
988       if (iri->content_encoding != opt.locale)
989           set_uri_encoding (iri, iri->content_encoding, false);
990
991       /* Reset UTF-8 encode status */
992       iri->utf8_encode = opt.enable_iri;
993       xfree_null (iri->orig_url);
994       iri->orig_url = NULL;
995     }
996   else
997     input_file = (char *) file;
998
999   url_list = (html ? get_urls_html (input_file, NULL, NULL, iri)
1000               : get_urls_file (input_file));
1001
1002   for (cur_url = url_list; cur_url; cur_url = cur_url->next, ++*count)
1003     {
1004       char *filename = NULL, *new_file = NULL;
1005       int dt;
1006       struct iri *tmpiri = iri_dup (iri);
1007       struct url *parsed_url = NULL;
1008
1009       if (cur_url->ignore_when_downloading)
1010         continue;
1011
1012       if (opt.quota && total_downloaded_bytes > opt.quota)
1013         {
1014           status = QUOTEXC;
1015           break;
1016         }
1017
1018       /* Need to reparse the url, since it didn't have iri information. */
1019       if (opt.enable_iri)
1020           parsed_url = url_parse (cur_url->url->url, NULL, tmpiri, true);
1021
1022       if ((opt.recursive || opt.page_requisites)
1023           && (cur_url->url->scheme != SCHEME_FTP || getproxy (cur_url->url)))
1024         {
1025           int old_follow_ftp = opt.follow_ftp;
1026
1027           /* Turn opt.follow_ftp on in case of recursive FTP retrieval */
1028           if (cur_url->url->scheme == SCHEME_FTP)
1029             opt.follow_ftp = 1;
1030
1031           status = retrieve_tree (parsed_url ? parsed_url : cur_url->url,
1032                                   tmpiri);
1033
1034           opt.follow_ftp = old_follow_ftp;
1035         }
1036       else
1037         status = retrieve_url (parsed_url ? parsed_url : cur_url->url,
1038                                cur_url->url->url, &filename,
1039                                &new_file, NULL, &dt, opt.recursive, tmpiri);
1040
1041       if (parsed_url)
1042           url_free (parsed_url);
1043
1044       if (filename && opt.delete_after && file_exists_p (filename))
1045         {
1046           DEBUGP (("\
1047 Removing file due to --delete-after in retrieve_from_file():\n"));
1048           logprintf (LOG_VERBOSE, _("Removing %s.\n"), filename);
1049           if (unlink (filename))
1050             logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
1051           dt &= ~RETROKF;
1052         }
1053
1054       xfree_null (new_file);
1055       xfree_null (filename);
1056       iri_free (tmpiri);
1057     }
1058
1059   /* Free the linked list of URL-s.  */
1060   free_urlpos (url_list);
1061
1062   iri_free (iri);
1063
1064   return status;
1065 }
1066
1067 /* Print `giving up', or `retrying', depending on the impending
1068    action.  N1 and N2 are the attempt number and the attempt limit.  */
1069 void
1070 printwhat (int n1, int n2)
1071 {
1072   logputs (LOG_VERBOSE, (n1 == n2) ? _("Giving up.\n\n") : _("Retrying.\n\n"));
1073 }
1074
1075 /* If opt.wait or opt.waitretry are specified, and if certain
1076    conditions are met, sleep the appropriate number of seconds.  See
1077    the documentation of --wait and --waitretry for more information.
1078
1079    COUNT is the count of current retrieval, beginning with 1. */
1080
1081 void
1082 sleep_between_retrievals (int count)
1083 {
1084   static bool first_retrieval = true;
1085
1086   if (first_retrieval)
1087     {
1088       /* Don't sleep before the very first retrieval. */
1089       first_retrieval = false;
1090       return;
1091     }
1092
1093   if (opt.waitretry && count > 1)
1094     {
1095       /* If opt.waitretry is specified and this is a retry, wait for
1096          COUNT-1 number of seconds, or for opt.waitretry seconds.  */
1097       if (count <= opt.waitretry)
1098         xsleep (count - 1);
1099       else
1100         xsleep (opt.waitretry);
1101     }
1102   else if (opt.wait)
1103     {
1104       if (!opt.random_wait || count > 1)
1105         /* If random-wait is not specified, or if we are sleeping
1106            between retries of the same download, sleep the fixed
1107            interval.  */
1108         xsleep (opt.wait);
1109       else
1110         {
1111           /* Sleep a random amount of time averaging in opt.wait
1112              seconds.  The sleeping amount ranges from 0.5*opt.wait to
1113              1.5*opt.wait.  */
1114           double waitsecs = (0.5 + random_float ()) * opt.wait;
1115           DEBUGP (("sleep_between_retrievals: avg=%f,sleep=%f\n",
1116                    opt.wait, waitsecs));
1117           xsleep (waitsecs);
1118         }
1119     }
1120 }
1121
1122 /* Free the linked list of urlpos.  */
1123 void
1124 free_urlpos (struct urlpos *l)
1125 {
1126   while (l)
1127     {
1128       struct urlpos *next = l->next;
1129       if (l->url)
1130         url_free (l->url);
1131       xfree_null (l->local_name);
1132       xfree (l);
1133       l = next;
1134     }
1135 }
1136
1137 /* Rotate FNAME opt.backups times */
1138 void
1139 rotate_backups(const char *fname)
1140 {
1141   int maxlen = strlen (fname) + 1 + numdigit (opt.backups) + 1;
1142   char *from = (char *)alloca (maxlen);
1143   char *to = (char *)alloca (maxlen);
1144   struct_stat sb;
1145   int i;
1146
1147   if (stat (fname, &sb) == 0)
1148     if (S_ISREG (sb.st_mode) == 0)
1149       return;
1150
1151   for (i = opt.backups; i > 1; i--)
1152     {
1153       sprintf (from, "%s.%d", fname, i - 1);
1154       sprintf (to, "%s.%d", fname, i);
1155       rename (from, to);
1156     }
1157
1158   sprintf (to, "%s.%d", fname, 1);
1159   rename(fname, to);
1160 }
1161
1162 static bool no_proxy_match (const char *, const char **);
1163
1164 /* Return the URL of the proxy appropriate for url U.  */
1165
1166 static char *
1167 getproxy (struct url *u)
1168 {
1169   char *proxy = NULL;
1170   char *rewritten_url;
1171   static char rewritten_storage[1024];
1172
1173   if (!opt.use_proxy)
1174     return NULL;
1175   if (no_proxy_match (u->host, (const char **)opt.no_proxy))
1176     return NULL;
1177
1178   switch (u->scheme)
1179     {
1180     case SCHEME_HTTP:
1181       proxy = opt.http_proxy ? opt.http_proxy : getenv ("http_proxy");
1182       break;
1183 #ifdef HAVE_SSL
1184     case SCHEME_HTTPS:
1185       proxy = opt.https_proxy ? opt.https_proxy : getenv ("https_proxy");
1186       break;
1187 #endif
1188     case SCHEME_FTP:
1189       proxy = opt.ftp_proxy ? opt.ftp_proxy : getenv ("ftp_proxy");
1190       break;
1191     case SCHEME_INVALID:
1192       break;
1193     }
1194   if (!proxy || !*proxy)
1195     return NULL;
1196
1197   /* Handle shorthands.  `rewritten_storage' is a kludge to allow
1198      getproxy() to return static storage. */
1199   rewritten_url = rewrite_shorthand_url (proxy);
1200   if (rewritten_url)
1201     {
1202       strncpy (rewritten_storage, rewritten_url, sizeof (rewritten_storage));
1203       rewritten_storage[sizeof (rewritten_storage) - 1] = '\0';
1204       proxy = rewritten_storage;
1205     }
1206
1207   return proxy;
1208 }
1209
1210 /* Returns true if URL would be downloaded through a proxy. */
1211
1212 bool
1213 url_uses_proxy (struct url * u)
1214 {
1215   bool ret;
1216   if (!u)
1217     return false;
1218   ret = getproxy (u) != NULL;
1219   return ret;
1220 }
1221
1222 /* Should a host be accessed through proxy, concerning no_proxy?  */
1223 static bool
1224 no_proxy_match (const char *host, const char **no_proxy)
1225 {
1226   if (!no_proxy)
1227     return false;
1228   else
1229     return sufmatch (no_proxy, host);
1230 }
1231
1232 /* Set the file parameter to point to the local file string.  */
1233 void
1234 set_local_file (const char **file, const char *default_file)
1235 {
1236   if (opt.output_document)
1237     {
1238       if (output_stream_regular)
1239         *file = opt.output_document;
1240     }
1241   else
1242     *file = default_file;
1243 }