~ubuntu-branches/ubuntu/precise/wget/precise-proposed

« back to all changes in this revision

Viewing changes to src/http.c

  • Committer: Bazaar Package Importer
  • Author(s): Steve Langasek
  • Date: 2011-10-19 00:00:09 UTC
  • mfrom: (2.1.13 sid)
  • Revision ID: james.westby@ubuntu.com-20111019000009-8p33w3wz4b1rdri0
Tags: 1.13-1ubuntu1
* Merge from Debian unstable, remaining changes:
  - Add wget-udeb to ship wget.gnu as alternative to busybox wget
    implementation.
  - Depend on libssl-dev 0.9.8k-7ubuntu4 (LP: #503339)
* Dropped changes, superseded in Debian:
  - Keep build dependencies in main:
    + debian/control: remove info2man build-dep
    + debian/patches/series: disable wget-infopod_generated_manpage
  - Mark wget Multi-Arch: foreign, so packages that aren't of the same arch
    can depend on it.
* Pass --with-ssl=openssl; we don't want to use gnutls, there's no udeb for
  it.
* Add a second build pass for the udeb, so we can build without libidn.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* HTTP support.
2
 
   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3
 
   2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
 
2
   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
 
3
   2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation,
 
4
   Inc.
4
5
 
5
6
This file is part of GNU Wget.
6
7
 
33
34
#include <stdio.h>
34
35
#include <stdlib.h>
35
36
#include <string.h>
36
 
#ifdef HAVE_UNISTD_H
37
 
# include <unistd.h>
38
 
#endif
 
37
#include <unistd.h>
39
38
#include <assert.h>
40
39
#include <errno.h>
41
40
#include <time.h>
56
55
# include "http-ntlm.h"
57
56
#endif
58
57
#include "cookies.h"
59
 
#ifdef ENABLE_DIGEST
60
 
# include "gen-md5.h"
61
 
#endif
 
58
#include "md5.h"
62
59
#include "convert.h"
63
60
#include "spider.h"
64
61
 
95
92
#define TEXTCSS_S "text/css"
96
93
 
97
94
/* Some status code validation macros: */
 
95
#define H_10X(x)        (((x) >= 100) && ((x) < 200))
98
96
#define H_20X(x)        (((x) >= 200) && ((x) < 300))
99
97
#define H_PARTIAL(x)    ((x) == HTTP_STATUS_PARTIAL_CONTENTS)
100
98
#define H_REDIRECTED(x) ((x) == HTTP_STATUS_MOVED_PERMANENTLY          \
352
350
 
353
351
  APPEND (p, req->method); *p++ = ' ';
354
352
  APPEND (p, req->arg);    *p++ = ' ';
355
 
  memcpy (p, "HTTP/1.0\r\n", 10); p += 10;
 
353
  memcpy (p, "HTTP/1.1\r\n", 10); p += 10;
356
354
 
357
355
  for (i = 0; i < req->hcount; i++)
358
356
    {
406
404
 
407
405
  if (opt.auth_without_challenge)
408
406
    {
409
 
      DEBUGP(("Auth-without-challenge set, sending Basic credentials.\n"));
 
407
      DEBUGP (("Auth-without-challenge set, sending Basic credentials.\n"));
410
408
      do_challenge = true;
411
409
    }
412
410
  else if (basic_authed_hosts
413
411
      && hash_table_contains(basic_authed_hosts, hostname))
414
412
    {
415
 
      DEBUGP(("Found %s in basic_authed_hosts.\n", quote (hostname)));
 
413
      DEBUGP (("Found %s in basic_authed_hosts.\n", quote (hostname)));
416
414
      do_challenge = true;
417
415
    }
418
416
  else
419
417
    {
420
 
      DEBUGP(("Host %s has not issued a general basic challenge.\n",
 
418
      DEBUGP (("Host %s has not issued a general basic challenge.\n",
421
419
              quote (hostname)));
422
420
    }
423
421
  if (do_challenge)
439
437
  if (!hash_table_contains(basic_authed_hosts, hostname))
440
438
    {
441
439
      hash_table_put (basic_authed_hosts, xstrdup(hostname), NULL);
442
 
      DEBUGP(("Inserted %s into basic_authed_hosts\n", quote (hostname)));
 
440
      DEBUGP (("Inserted %s into basic_authed_hosts\n", quote (hostname)));
443
441
    }
444
442
}
445
443
 
901
899
   mode, the body is displayed for debugging purposes.  */
902
900
 
903
901
static bool
904
 
skip_short_body (int fd, wgint contlen)
 
902
skip_short_body (int fd, wgint contlen, bool chunked)
905
903
{
906
904
  enum {
907
905
    SKIP_SIZE = 512,                /* size of the download buffer */
908
906
    SKIP_THRESHOLD = 4096        /* the largest size we read */
909
907
  };
 
908
  wgint remaining_chunk_size = 0;
910
909
  char dlbuf[SKIP_SIZE + 1];
911
910
  dlbuf[SKIP_SIZE] = '\0';        /* so DEBUGP can safely print it */
912
911
 
913
 
  /* We shouldn't get here with unknown contlen.  (This will change
914
 
     with HTTP/1.1, which supports "chunked" transfer.)  */
915
 
  assert (contlen != -1);
 
912
  assert (contlen != -1 || contlen);
916
913
 
917
914
  /* If the body is too large, it makes more sense to simply close the
918
915
     connection than to try to read the body.  */
919
916
  if (contlen > SKIP_THRESHOLD)
920
917
    return false;
921
918
 
922
 
  DEBUGP (("Skipping %s bytes of body: [", number_to_static_string (contlen)));
923
 
 
924
 
  while (contlen > 0)
 
919
  while (contlen > 0 || chunked)
925
920
    {
926
 
      int ret = fd_read (fd, dlbuf, MIN (contlen, SKIP_SIZE), -1);
 
921
      int ret;
 
922
      if (chunked)
 
923
        {
 
924
          if (remaining_chunk_size == 0)
 
925
            {
 
926
              char *line = fd_read_line (fd);
 
927
              char *endl;
 
928
              if (line == NULL)
 
929
                break;
 
930
 
 
931
              remaining_chunk_size = strtol (line, &endl, 16);
 
932
              if (remaining_chunk_size == 0)
 
933
                {
 
934
                  fd_read_line (fd);
 
935
                  break;
 
936
                }
 
937
            }
 
938
 
 
939
          contlen = MIN (remaining_chunk_size, SKIP_SIZE);
 
940
        }
 
941
 
 
942
      DEBUGP (("Skipping %s bytes of body: [", number_to_static_string (contlen)));
 
943
 
 
944
      ret = fd_read (fd, dlbuf, MIN (contlen, SKIP_SIZE), -1);
927
945
      if (ret <= 0)
928
946
        {
929
947
          /* Don't normally report the error since this is an
933
951
          return false;
934
952
        }
935
953
      contlen -= ret;
 
954
 
 
955
      if (chunked)
 
956
        {
 
957
          remaining_chunk_size -= ret;
 
958
          if (remaining_chunk_size == 0)
 
959
            if (fd_read_line (fd) == NULL)
 
960
              return false;
 
961
        }
 
962
 
936
963
      /* Safe even if %.*s bogusly expects terminating \0 because
937
964
         we've zero-terminated dlbuf above.  */
938
965
      DEBUGP (("%.*s", ret, dlbuf));
942
969
  return true;
943
970
}
944
971
 
 
972
#define NOT_RFC2231 0
 
973
#define RFC2231_NOENCODING 1
 
974
#define RFC2231_ENCODING 2
 
975
 
 
976
/* extract_param extracts the parameter name into NAME.
 
977
   However, if the parameter name is in RFC2231 format then
 
978
   this function adjusts NAME by stripping of the trailing
 
979
   characters that are not part of the name but are present to
 
980
   indicate the presence of encoding information in the value
 
981
   or a fragment of a long parameter value
 
982
*/
 
983
static int
 
984
modify_param_name(param_token *name)
 
985
{
 
986
  const char *delim1 = memchr (name->b, '*', name->e - name->b);
 
987
  const char *delim2 = memrchr (name->b, '*', name->e - name->b);
 
988
 
 
989
  int result;
 
990
 
 
991
  if(delim1 == NULL)
 
992
    {
 
993
      result = NOT_RFC2231;
 
994
    }
 
995
  else if(delim1 == delim2)
 
996
    {
 
997
      if ((name->e - 1) == delim1)
 
998
        {
 
999
          result = RFC2231_ENCODING;
 
1000
        }
 
1001
      else
 
1002
        {
 
1003
          result = RFC2231_NOENCODING;
 
1004
        }
 
1005
      name->e = delim1;
 
1006
    }
 
1007
  else
 
1008
    {
 
1009
      name->e = delim1;
 
1010
      result = RFC2231_ENCODING;
 
1011
    }
 
1012
  return result;
 
1013
}
 
1014
 
 
1015
/* extract_param extract the paramater value into VALUE.
 
1016
   Like modify_param_name this function modifies VALUE by
 
1017
   stripping off the encoding information from the actual value
 
1018
*/
 
1019
static void
 
1020
modify_param_value (param_token *value, int encoding_type )
 
1021
{
 
1022
  if (RFC2231_ENCODING == encoding_type)
 
1023
    {
 
1024
      const char *delim = memrchr (value->b, '\'', value->e - value->b);
 
1025
      if ( delim != NULL )
 
1026
        {
 
1027
          value->b = (delim+1);
 
1028
        }
 
1029
    }
 
1030
}
 
1031
 
945
1032
/* Extract a parameter from the string (typically an HTTP header) at
946
1033
   **SOURCE and advance SOURCE to the next parameter.  Return false
947
1034
   when there are no more parameters to extract.  The name of the
1013
1100
      if (*p == separator) ++p;
1014
1101
    }
1015
1102
  *source = p;
 
1103
 
 
1104
  int param_type = modify_param_name(name);
 
1105
  if (NOT_RFC2231 != param_type)
 
1106
    {
 
1107
      modify_param_value(value, param_type);
 
1108
    }
1016
1109
  return true;
1017
1110
}
1018
1111
 
 
1112
#undef NOT_RFC2231
 
1113
#undef RFC2231_NOENCODING
 
1114
#undef RFC2231_ENCODING
 
1115
 
 
1116
/* Appends the string represented by VALUE to FILENAME */
 
1117
 
 
1118
static void
 
1119
append_value_to_filename (char **filename, param_token const * const value)
 
1120
{
 
1121
  int original_length = strlen(*filename);
 
1122
  int new_length = strlen(*filename) + (value->e - value->b);
 
1123
  *filename = xrealloc (*filename, new_length+1);
 
1124
  memcpy (*filename + original_length, value->b, (value->e - value->b)); 
 
1125
  (*filename)[new_length] = '\0';
 
1126
}
 
1127
 
1019
1128
#undef MAX
1020
1129
#define MAX(p, q) ((p) > (q) ? (p) : (q))
1021
1130
 
1034
1143
   false.
1035
1144
 
1036
1145
   The file name is stripped of directory components and must not be
1037
 
   empty.  */
1038
 
 
 
1146
   empty.
 
1147
 
 
1148
   Historically, this function returned filename prefixed with opt.dir_prefix,
 
1149
   now that logic is handled by the caller, new code should pay attention,
 
1150
   changed by crq, Sep 2010.
 
1151
 
 
1152
*/
1039
1153
static bool
1040
1154
parse_content_disposition (const char *hdr, char **filename)
1041
1155
{
1042
1156
  param_token name, value;
 
1157
  *filename = NULL;
1043
1158
  while (extract_param (&hdr, &name, &value, ';'))
1044
 
    if (BOUNDED_EQUAL_NO_CASE (name.b, name.e, "filename") && value.b != NULL)
1045
 
      {
1046
 
        /* Make the file name begin at the last slash or backslash. */
1047
 
        const char *last_slash = memrchr (value.b, '/', value.e - value.b);
1048
 
        const char *last_bs = memrchr (value.b, '\\', value.e - value.b);
1049
 
        if (last_slash && last_bs)
1050
 
          value.b = 1 + MAX (last_slash, last_bs);
1051
 
        else if (last_slash || last_bs)
1052
 
          value.b = 1 + (last_slash ? last_slash : last_bs);
1053
 
        if (value.b == value.e)
1054
 
          continue;
1055
 
        /* Start with the directory prefix, if specified. */
1056
 
        if (opt.dir_prefix)
1057
 
          {
1058
 
            int prefix_length = strlen (opt.dir_prefix);
1059
 
            bool add_slash = (opt.dir_prefix[prefix_length - 1] != '/');
1060
 
            int total_length;
1061
 
 
1062
 
            if (add_slash)
1063
 
              ++prefix_length;
1064
 
            total_length = prefix_length + (value.e - value.b);
1065
 
            *filename = xmalloc (total_length + 1);
1066
 
            strcpy (*filename, opt.dir_prefix);
1067
 
            if (add_slash)
1068
 
              (*filename)[prefix_length - 1] = '/';
1069
 
            memcpy (*filename + prefix_length, value.b, (value.e - value.b));
1070
 
            (*filename)[total_length] = '\0';
1071
 
          }
1072
 
        else
1073
 
          *filename = strdupdelim (value.b, value.e);
1074
 
        return true;
1075
 
      }
1076
 
  return false;
 
1159
    {
 
1160
      int isFilename = BOUNDED_EQUAL_NO_CASE ( name.b, name.e, "filename" );
 
1161
      if ( isFilename && value.b != NULL)
 
1162
        {
 
1163
          /* Make the file name begin at the last slash or backslash. */
 
1164
          const char *last_slash = memrchr (value.b, '/', value.e - value.b);
 
1165
          const char *last_bs = memrchr (value.b, '\\', value.e - value.b);
 
1166
          if (last_slash && last_bs)
 
1167
            value.b = 1 + MAX (last_slash, last_bs);
 
1168
          else if (last_slash || last_bs)
 
1169
            value.b = 1 + (last_slash ? last_slash : last_bs);
 
1170
          if (value.b == value.e)
 
1171
            continue;
 
1172
 
 
1173
          if (*filename)
 
1174
            append_value_to_filename (filename, &value);
 
1175
          else
 
1176
            *filename = strdupdelim (value.b, value.e);
 
1177
        }
 
1178
    }
 
1179
 
 
1180
  if (*filename)
 
1181
    return true;
 
1182
  else
 
1183
    return false;
1077
1184
}
 
1185
 
1078
1186
 
1079
1187
/* Persistent connections.  Currently, we cache the most recently used
1080
1188
   connection as persistent, provided that the HTTP server agrees to
1340
1448
  hs->error = NULL;
1341
1449
}
1342
1450
 
 
1451
static void
 
1452
get_file_flags (const char *filename, int *dt)
 
1453
{
 
1454
  logprintf (LOG_VERBOSE, _("\
 
1455
File %s already there; not retrieving.\n\n"), quote (filename));
 
1456
  /* If the file is there, we suppose it's retrieved OK.  */
 
1457
  *dt |= RETROKF;
 
1458
 
 
1459
  /* #### Bogusness alert.  */
 
1460
  /* If its suffix is "html" or "htm" or similar, assume text/html.  */
 
1461
  if (has_html_suffix_p (filename))
 
1462
    *dt |= TEXTHTML;
 
1463
}
 
1464
 
1343
1465
#define BEGINS_WITH(line, string_constant)                               \
1344
1466
  (!strncasecmp (line, string_constant, sizeof (string_constant) - 1)    \
1345
1467
   && (c_isspace (line[sizeof (string_constant) - 1])                      \
1385
1507
   server, and u->url will be requested.  */
1386
1508
static uerr_t
1387
1509
gethttp (struct url *u, struct http_stat *hs, int *dt, struct url *proxy,
1388
 
         struct iri *iri)
 
1510
         struct iri *iri, int count)
1389
1511
{
1390
1512
  struct request *req;
1391
1513
 
1429
1551
     is done. */
1430
1552
  bool keep_alive;
1431
1553
 
1432
 
  /* Whether keep-alive should be inhibited.
 
1554
  /* Is the server using the chunked transfer encoding?  */
 
1555
  bool chunked_transfer_encoding = false;
1433
1556
 
1434
 
     RFC 2068 requests that 1.0 clients not send keep-alive requests
1435
 
     to proxies.  This is because many 1.0 proxies do not interpret
1436
 
     the Connection header and transfer it to the remote server,
1437
 
     causing it to not close the connection and leave both the proxy
1438
 
     and the client hanging.  */
 
1557
  /* Whether keep-alive should be inhibited.  */
1439
1558
  bool inhibit_keep_alive =
1440
 
    !opt.http_keep_alive || opt.ignore_length || proxy != NULL;
 
1559
    !opt.http_keep_alive || opt.ignore_length;
1441
1560
 
1442
1561
  /* Headers sent when using POST. */
1443
1562
  wgint post_data_size = 0;
1500
1619
 
1501
1620
  request_set_header (req, "Referer", (char *) hs->referer, rel_none);
1502
1621
  if (*dt & SEND_NOCACHE)
1503
 
    request_set_header (req, "Pragma", "no-cache", rel_none);
1504
 
  if (hs->restval)
 
1622
    {
 
1623
      /* Cache-Control MUST be obeyed by all HTTP/1.1 caching mechanisms...  */
 
1624
      request_set_header (req, "Cache-Control", "no-cache, must-revalidate", rel_none);
 
1625
 
 
1626
      /* ... but some HTTP/1.0 caches doesn't implement Cache-Control.  */
 
1627
      request_set_header (req, "Pragma", "no-cache", rel_none);
 
1628
    }
 
1629
  if (hs->restval && !opt.timestamping)
1505
1630
    request_set_header (req, "Range",
1506
1631
                        aprintf ("bytes=%s-",
1507
1632
                                 number_to_static_string (hs->restval)),
1547
1672
                        rel_value);
1548
1673
  }
1549
1674
 
1550
 
  if (!inhibit_keep_alive)
1551
 
    request_set_header (req, "Connection", "Keep-Alive", rel_none);
1552
 
 
1553
 
  if (opt.cookies)
1554
 
    request_set_header (req, "Cookie",
1555
 
                        cookie_header (wget_cookie_jar,
1556
 
                                       u->host, u->port, u->path,
1557
 
#ifdef HAVE_SSL
1558
 
                                       u->scheme == SCHEME_HTTPS
1559
 
#else
1560
 
                                       0
1561
 
#endif
1562
 
                                       ),
1563
 
                        rel_value);
 
1675
  if (inhibit_keep_alive)
 
1676
    request_set_header (req, "Connection", "Close", rel_none);
 
1677
  else
 
1678
    {
 
1679
      if (proxy == NULL)
 
1680
        request_set_header (req, "Connection", "Keep-Alive", rel_none);
 
1681
      else
 
1682
        {
 
1683
          request_set_header (req, "Connection", "Close", rel_none);
 
1684
          request_set_header (req, "Proxy-Connection", "Keep-Alive", rel_none);
 
1685
        }
 
1686
    }
1564
1687
 
1565
1688
  if (opt.post_data || opt.post_file_name)
1566
1689
    {
1583
1706
                          rel_value);
1584
1707
    }
1585
1708
 
 
1709
 retry_with_auth:
 
1710
  /* We need to come back here when the initial attempt to retrieve
 
1711
     without authorization header fails.  (Expected to happen at least
 
1712
     for the Digest authorization scheme.)  */
 
1713
 
 
1714
  if (opt.cookies)
 
1715
    request_set_header (req, "Cookie",
 
1716
                        cookie_header (wget_cookie_jar,
 
1717
                                       u->host, u->port, u->path,
 
1718
#ifdef HAVE_SSL
 
1719
                                       u->scheme == SCHEME_HTTPS
 
1720
#else
 
1721
                                       0
 
1722
#endif
 
1723
                                       ),
 
1724
                        rel_value);
 
1725
 
1586
1726
  /* Add the user headers. */
1587
1727
  if (opt.user_headers)
1588
1728
    {
1591
1731
        request_set_user_header (req, opt.user_headers[i]);
1592
1732
    }
1593
1733
 
1594
 
 retry_with_auth:
1595
 
  /* We need to come back here when the initial attempt to retrieve
1596
 
     without authorization header fails.  (Expected to happen at least
1597
 
     for the Digest authorization scheme.)  */
1598
 
 
1599
1734
  proxyauth = NULL;
1600
1735
  if (proxy)
1601
1736
    {
1631
1766
        request_set_header (req, "Proxy-Authorization", proxyauth, rel_value);
1632
1767
    }
1633
1768
 
1634
 
  keep_alive = false;
 
1769
  keep_alive = true;
1635
1770
 
1636
1771
  /* Establish the connection.  */
1637
1772
 
1638
 
  if (!inhibit_keep_alive)
 
1773
  if (inhibit_keep_alive)
 
1774
    keep_alive = false;
 
1775
  else
1639
1776
    {
1640
1777
      /* Look for a persistent connection to target host, unless a
1641
1778
         proxy is used.  The exception is when SSL is in use, in which
1741
1878
 
1742
1879
          resp = resp_new (head);
1743
1880
          statcode = resp_status (resp, &message);
 
1881
          if (statcode < 0)
 
1882
            {
 
1883
              char *tms = datetime_str (time (NULL));
 
1884
              logprintf (LOG_VERBOSE, "%d\n", statcode);
 
1885
              logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode,
 
1886
                         quotearg_style (escape_quoting_style,
 
1887
                                         _("Malformed status line")));
 
1888
              xfree (head);
 
1889
              return HERR;
 
1890
            }
1744
1891
          hs->message = xstrdup (message);
1745
1892
          resp_free (resp);
1746
1893
          xfree (head);
1803
1950
  contrange = 0;
1804
1951
  *dt &= ~RETROKF;
1805
1952
 
 
1953
read_header:
1806
1954
  head = read_http_response_head (sock);
1807
1955
  if (!head)
1808
1956
    {
1829
1977
  /* Check for status line.  */
1830
1978
  message = NULL;
1831
1979
  statcode = resp_status (resp, &message);
 
1980
  if (statcode < 0)
 
1981
    {
 
1982
      char *tms = datetime_str (time (NULL));
 
1983
      logprintf (LOG_VERBOSE, "%d\n", statcode);
 
1984
      logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode,
 
1985
                 quotearg_style (escape_quoting_style,
 
1986
                                 _("Malformed status line")));
 
1987
      CLOSE_INVALIDATE (sock);
 
1988
      request_free (req);
 
1989
      return HERR;
 
1990
    }
 
1991
 
 
1992
  if (H_10X (statcode))
 
1993
    {
 
1994
      DEBUGP (("Ignoring response\n"));
 
1995
      goto read_header;
 
1996
    }
 
1997
 
1832
1998
  hs->message = xstrdup (message);
1833
1999
  if (!opt.server_response)
1834
2000
    logprintf (LOG_VERBOSE, "%2d %s\n", statcode,
1867
2033
  /* Check for keep-alive related responses. */
1868
2034
  if (!inhibit_keep_alive && contlen != -1)
1869
2035
    {
1870
 
      if (resp_header_copy (resp, "Keep-Alive", NULL, 0))
1871
 
        keep_alive = true;
1872
 
      else if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval)))
 
2036
      if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval)))
1873
2037
        {
1874
 
          if (0 == strcasecmp (hdrval, "Keep-Alive"))
1875
 
            keep_alive = true;
 
2038
          if (0 == strcasecmp (hdrval, "Close"))
 
2039
            keep_alive = false;
1876
2040
        }
1877
2041
    }
1878
2042
 
 
2043
  resp_header_copy (resp, "Transfer-Encoding", hdrval, sizeof (hdrval));
 
2044
  if (0 == strcasecmp (hdrval, "chunked"))
 
2045
    chunked_transfer_encoding = true;
 
2046
 
1879
2047
  /* Handle (possibly multiple instances of) the Set-Cookie header. */
1880
2048
  if (opt.cookies)
1881
2049
    {
1902
2070
  if (statcode == HTTP_STATUS_UNAUTHORIZED)
1903
2071
    {
1904
2072
      /* Authorization is required.  */
1905
 
      if (keep_alive && !head_only && skip_short_body (sock, contlen))
 
2073
      if (keep_alive && !head_only
 
2074
          && skip_short_body (sock, contlen, chunked_transfer_encoding))
1906
2075
        CLOSE_FINISH (sock);
1907
2076
      else
1908
2077
        CLOSE_INVALIDATE (sock);
1981
2150
   * hstat.local_file is set by http_loop to the argument of -O. */
1982
2151
  if (!hs->local_file)
1983
2152
    {
 
2153
      char *local_file = NULL;
 
2154
 
1984
2155
      /* Honor Content-Disposition whether possible. */
1985
2156
      if (!opt.content_disposition
1986
2157
          || !resp_header_copy (resp, "Content-Disposition",
1987
2158
                                hdrval, sizeof (hdrval))
1988
 
          || !parse_content_disposition (hdrval, &hs->local_file))
 
2159
          || !parse_content_disposition (hdrval, &local_file))
1989
2160
        {
1990
2161
          /* The Content-Disposition header is missing or broken.
1991
2162
           * Choose unique file name according to given URL. */
1992
 
          hs->local_file = url_file_name (u);
 
2163
          hs->local_file = url_file_name (u, NULL);
 
2164
        }
 
2165
      else
 
2166
        {
 
2167
          DEBUGP (("Parsed filename from Content-Disposition: %s\n",
 
2168
                  local_file));
 
2169
          hs->local_file = url_file_name (u, local_file);
1993
2170
        }
1994
2171
    }
1995
2172
 
2001
2178
          /* If opt.noclobber is turned on and file already exists, do not
2002
2179
             retrieve the file. But if the output_document was given, then this
2003
2180
             test was already done and the file didn't exist. Hence the !opt.output_document */
2004
 
          logprintf (LOG_VERBOSE, _("\
2005
 
File %s already there; not retrieving.\n\n"), quote (hs->local_file));
2006
 
          /* If the file is there, we suppose it's retrieved OK.  */
2007
 
          *dt |= RETROKF;
2008
 
 
2009
 
          /* #### Bogusness alert.  */
2010
 
          /* If its suffix is "html" or "htm" or similar, assume text/html.  */
2011
 
          if (has_html_suffix_p (hs->local_file))
2012
 
            *dt |= TEXTHTML;
2013
 
 
 
2181
          get_file_flags (hs->local_file, dt);
2014
2182
          xfree (head);
2015
2183
          xfree_null (message);
2016
2184
          return RETRUNNEEDED;
2154
2322
                     _("Location: %s%s\n"),
2155
2323
                     hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
2156
2324
                     hs->newloc ? _(" [following]") : "");
2157
 
          if (keep_alive && !head_only && skip_short_body (sock, contlen))
 
2325
          if (keep_alive && !head_only
 
2326
              && skip_short_body (sock, contlen, chunked_transfer_encoding))
2158
2327
            CLOSE_FINISH (sock);
2159
2328
          else
2160
2329
            CLOSE_INVALIDATE (sock);
2161
2330
          xfree_null (type);
2162
2331
          xfree (head);
 
2332
          /* From RFC2616: The status codes 303 and 307 have
 
2333
             been added for servers that wish to make unambiguously
 
2334
             clear which kind of reaction is expected of the client.
 
2335
             
 
2336
             A 307 should be redirected using the same method,
 
2337
             in other words, a POST should be preserved and not
 
2338
             converted to a GET in that case. */
 
2339
          if (statcode == HTTP_STATUS_TEMPORARY_REDIRECT)
 
2340
            return NEWLOCATION_KEEP_POST;
2163
2341
          return NEWLOCATION;
2164
2342
        }
2165
2343
    }
2197
2375
    }
2198
2376
 
2199
2377
  if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE
2200
 
      || (hs->restval > 0 && statcode == HTTP_STATUS_OK
2201
 
          && contrange == 0 && hs->restval >= contlen)
2202
 
     )
 
2378
      || (!opt.timestamping && hs->restval > 0 && statcode == HTTP_STATUS_OK
 
2379
          && contrange == 0 && contlen >= 0 && hs->restval >= contlen))
2203
2380
    {
2204
2381
      /* If `-c' is in use and the file has been fully downloaded (or
2205
2382
         the remote file has shrunk), Wget effectively requests bytes
2284
2461
           If not, they can be worked around using
2285
2462
           `--no-http-keep-alive'.  */
2286
2463
        CLOSE_FINISH (sock);
2287
 
      else if (keep_alive && skip_short_body (sock, contlen))
 
2464
      else if (keep_alive
 
2465
               && skip_short_body (sock, contlen, chunked_transfer_encoding))
2288
2466
        /* Successfully skipped the body; also keep using the socket. */
2289
2467
        CLOSE_FINISH (sock);
2290
2468
      else
2320
2498
          fp = fopen (hs->local_file, "ab");
2321
2499
#endif /* def __VMS [else] */
2322
2500
        }
2323
 
      else if (ALLOW_CLOBBER)
 
2501
      else if (ALLOW_CLOBBER || count > 0)
2324
2502
        {
 
2503
          if (opt.unlink && file_exists_p (hs->local_file))
 
2504
            {
 
2505
              int res = unlink (hs->local_file);
 
2506
              if (res < 0)
 
2507
                {
 
2508
                  logprintf (LOG_NOTQUIET, "%s: %s\n", hs->local_file,
 
2509
                             strerror (errno));
 
2510
                  CLOSE_INVALIDATE (sock);
 
2511
                  xfree (head);
 
2512
                  return UNLINKERR;
 
2513
                }
 
2514
            }
 
2515
 
2325
2516
#ifdef __VMS
2326
2517
          int open_id;
2327
2518
 
2385
2576
    /* If the server ignored our range request, instruct fd_read_body
2386
2577
       to skip the first RESTVAL bytes of body.  */
2387
2578
    flags |= rb_skip_startpos;
 
2579
 
 
2580
  if (chunked_transfer_encoding)
 
2581
    flags |= rb_chunked_transfer_encoding;
 
2582
 
2388
2583
  hs->len = hs->restval;
2389
2584
  hs->rd_size = 0;
2390
2585
  hs->res = fd_read_body (sock, fp, contlen != -1 ? contlen : 0,
2426
2621
  struct_stat st;
2427
2622
  bool send_head_first = true;
2428
2623
  char *file_name;
 
2624
  bool force_full_retrieve = false;
2429
2625
 
2430
2626
  /* Assert that no value for *LOCAL_FILE was passed. */
2431
2627
  assert (local_file == NULL || *local_file == NULL);
2441
2637
     here so that we don't go through the hoops if we're just using
2442
2638
     FTP or whatever. */
2443
2639
  if (opt.cookies)
2444
 
    load_cookies();
 
2640
    load_cookies ();
2445
2641
 
2446
2642
  /* Warn on (likely bogus) wildcard usage in HTTP. */
2447
2643
  if (opt.ftp_glob && has_wildcards_p (u->path))
2459
2655
  else if (!opt.content_disposition)
2460
2656
    {
2461
2657
      hstat.local_file =
2462
 
        url_file_name (opt.trustservernames ? u : original_url);
 
2658
        url_file_name (opt.trustservernames ? u : original_url, NULL);
2463
2659
      got_name = true;
2464
2660
    }
2465
2661
 
2466
 
  /* TODO: Ick! This code is now in both gethttp and http_loop, and is
2467
 
   * screaming for some refactoring. */
2468
2662
  if (got_name && file_exists_p (hstat.local_file) && opt.noclobber && !opt.output_document)
2469
2663
    {
2470
2664
      /* If opt.noclobber is turned on and file already exists, do not
2471
2665
         retrieve the file. But if the output_document was given, then this
2472
2666
         test was already done and the file didn't exist. Hence the !opt.output_document */
2473
 
      logprintf (LOG_VERBOSE, _("\
2474
 
File %s already there; not retrieving.\n\n"),
2475
 
                 quote (hstat.local_file));
2476
 
      /* If the file is there, we suppose it's retrieved OK.  */
2477
 
      *dt |= RETROKF;
2478
 
 
2479
 
      /* #### Bogusness alert.  */
2480
 
      /* If its suffix is "html" or "htm" or similar, assume text/html.  */
2481
 
      if (has_html_suffix_p (hstat.local_file))
2482
 
        *dt |= TEXTHTML;
2483
 
 
 
2667
      get_file_flags (hstat.local_file, dt);
2484
2668
      ret = RETROK;
2485
2669
      goto exit;
2486
2670
    }
2491
2675
  /* Reset the document type. */
2492
2676
  *dt = 0;
2493
2677
 
2494
 
  /* Skip preliminary HEAD request if we're not in spider mode AND
2495
 
   * if -O was given or HTTP Content-Disposition support is disabled. */
2496
 
  if (!opt.spider
2497
 
      && (got_name || !opt.content_disposition))
 
2678
  /* Skip preliminary HEAD request if we're not in spider mode.  */
 
2679
  if (!opt.spider)
2498
2680
    send_head_first = false;
2499
2681
 
2500
2682
  /* Send preliminary HEAD request if -N is given and we have an existing
2501
2683
   * destination file. */
2502
 
  file_name = url_file_name (opt.trustservernames ? u : original_url);
2503
 
  if (opt.timestamping
2504
 
      && !opt.content_disposition
2505
 
      && file_exists_p (file_name))
 
2684
  file_name = url_file_name (opt.trustservernames ? u : original_url, NULL);
 
2685
  if (opt.timestamping && (file_exists_p (file_name)
 
2686
                           || opt.content_disposition))
2506
2687
    send_head_first = true;
2507
2688
  xfree (file_name);
2508
2689
 
2553
2734
        *dt &= ~HEAD_ONLY;
2554
2735
 
2555
2736
      /* Decide whether or not to restart.  */
2556
 
      if (opt.always_rest
 
2737
      if (force_full_retrieve)
 
2738
        hstat.restval = hstat.len;
 
2739
      else if (opt.always_rest
2557
2740
          && got_name
2558
2741
          && stat (hstat.local_file, &st) == 0
2559
2742
          && S_ISREG (st.st_mode))
2580
2763
        *dt &= ~SEND_NOCACHE;
2581
2764
 
2582
2765
      /* Try fetching the document, or at least its head.  */
2583
 
      err = gethttp (u, &hstat, dt, proxy, iri);
 
2766
      err = gethttp (u, &hstat, dt, proxy, iri, count);
2584
2767
 
2585
2768
      /* Time?  */
2586
2769
      tms = datetime_str (time (NULL));
2614
2797
          logprintf (LOG_NOTQUIET, _("Unable to establish SSL connection.\n"));
2615
2798
          ret = err;
2616
2799
          goto exit;
 
2800
        case UNLINKERR:
 
2801
          /* Another fatal error.  */
 
2802
          logputs (LOG_VERBOSE, "\n");
 
2803
          logprintf (LOG_NOTQUIET, _("Cannot unlink %s (%s).\n"),
 
2804
                     quote (hstat.local_file), strerror (errno));
 
2805
          ret = err;
 
2806
          goto exit;
2617
2807
        case NEWLOCATION:
 
2808
        case NEWLOCATION_KEEP_POST:
2618
2809
          /* Return the new location to the caller.  */
2619
2810
          if (!*newloc)
2620
2811
            {
2625
2816
            }
2626
2817
          else
2627
2818
            {
2628
 
              ret = NEWLOCATION;
 
2819
              ret = err;
2629
2820
            }
2630
2821
          goto exit;
2631
2822
        case RETRUNNEEDED:
2741
2932
                                }
2742
2933
                            }
2743
2934
                          else
2744
 
                            logputs (LOG_VERBOSE,
2745
 
                                     _("Remote file is newer, retrieving.\n"));
 
2935
                            {
 
2936
                              force_full_retrieve = true;
 
2937
                              logputs (LOG_VERBOSE,
 
2938
                                       _("Remote file is newer, retrieving.\n"));
 
2939
                            }
2746
2940
 
2747
2941
                          logputs (LOG_VERBOSE, "\n");
2748
2942
                        }
2803
2997
            } /* send_head_first */
2804
2998
        } /* !got_head */
2805
2999
 
2806
 
      if ((tmr != (time_t) (-1))
 
3000
      if (opt.useservertimestamps
 
3001
          && (tmr != (time_t) (-1))
2807
3002
          && ((hstat.len == hstat.contlen) ||
2808
3003
              ((hstat.res == 0) && (hstat.contlen == -1))))
2809
3004
        {
2850
3045
                         hstat.local_file, count);
2851
3046
            }
2852
3047
          ++numurls;
2853
 
          total_downloaded_bytes += hstat.len;
 
3048
          total_downloaded_bytes += hstat.rd_size;
2854
3049
 
2855
3050
          /* Remember that we downloaded the file for later ".orig" code. */
2856
3051
          if (*dt & ADDED_HTML_EXTENSION)
2883
3078
                             hstat.local_file, count);
2884
3079
                }
2885
3080
              ++numurls;
2886
 
              total_downloaded_bytes += hstat.len;
 
3081
              total_downloaded_bytes += hstat.rd_size;
2887
3082
 
2888
3083
              /* Remember that we downloaded the file for later ".orig" code. */
2889
3084
              if (*dt & ADDED_HTML_EXTENSION)
2944
3139
  while (!opt.ntry || (count < opt.ntry));
2945
3140
 
2946
3141
exit:
2947
 
  if (ret == RETROK)
 
3142
  if (ret == RETROK && local_file)
2948
3143
    *local_file = xstrdup (hstat.local_file);
2949
3144
  free_hstat (&hstat);
2950
3145
 
3029
3224
  oldlocale = setlocale (LC_TIME, NULL);
3030
3225
  if (oldlocale)
3031
3226
    {
3032
 
      size_t l = strlen (oldlocale);
 
3227
      size_t l = strlen (oldlocale) + 1;
3033
3228
      if (l >= sizeof savedlocale)
3034
3229
        savedlocale[0] = '\0';
3035
3230
      else
3110
3305
{
3111
3306
  int i;
3112
3307
 
3113
 
  for (i = 0; i < MD5_HASHLEN; i++, hash++)
 
3308
  for (i = 0; i < MD5_DIGEST_SIZE; i++, hash++)
3114
3309
    {
3115
3310
      *buf++ = XNUM_TO_digit (*hash >> 4);
3116
3311
      *buf++ = XNUM_TO_digit (*hash & 0xf);
3163
3358
 
3164
3359
  /* Calculate the digest value.  */
3165
3360
  {
3166
 
    ALLOCA_MD5_CONTEXT (ctx);
3167
 
    unsigned char hash[MD5_HASHLEN];
3168
 
    char a1buf[MD5_HASHLEN * 2 + 1], a2buf[MD5_HASHLEN * 2 + 1];
3169
 
    char response_digest[MD5_HASHLEN * 2 + 1];
 
3361
    struct md5_ctx ctx;
 
3362
    unsigned char hash[MD5_DIGEST_SIZE];
 
3363
    char a1buf[MD5_DIGEST_SIZE * 2 + 1], a2buf[MD5_DIGEST_SIZE * 2 + 1];
 
3364
    char response_digest[MD5_DIGEST_SIZE * 2 + 1];
3170
3365
 
3171
3366
    /* A1BUF = H(user ":" realm ":" password) */
3172
 
    gen_md5_init (ctx);
3173
 
    gen_md5_update ((unsigned char *)user, strlen (user), ctx);
3174
 
    gen_md5_update ((unsigned char *)":", 1, ctx);
3175
 
    gen_md5_update ((unsigned char *)realm, strlen (realm), ctx);
3176
 
    gen_md5_update ((unsigned char *)":", 1, ctx);
3177
 
    gen_md5_update ((unsigned char *)passwd, strlen (passwd), ctx);
3178
 
    gen_md5_finish (ctx, hash);
 
3367
    md5_init_ctx (&ctx);
 
3368
    md5_process_bytes ((unsigned char *)user, strlen (user), &ctx);
 
3369
    md5_process_bytes ((unsigned char *)":", 1, &ctx);
 
3370
    md5_process_bytes ((unsigned char *)realm, strlen (realm), &ctx);
 
3371
    md5_process_bytes ((unsigned char *)":", 1, &ctx);
 
3372
    md5_process_bytes ((unsigned char *)passwd, strlen (passwd), &ctx);
 
3373
    md5_finish_ctx (&ctx, hash);
3179
3374
    dump_hash (a1buf, hash);
3180
3375
 
3181
3376
    /* A2BUF = H(method ":" path) */
3182
 
    gen_md5_init (ctx);
3183
 
    gen_md5_update ((unsigned char *)method, strlen (method), ctx);
3184
 
    gen_md5_update ((unsigned char *)":", 1, ctx);
3185
 
    gen_md5_update ((unsigned char *)path, strlen (path), ctx);
3186
 
    gen_md5_finish (ctx, hash);
 
3377
    md5_init_ctx (&ctx);
 
3378
    md5_process_bytes ((unsigned char *)method, strlen (method), &ctx);
 
3379
    md5_process_bytes ((unsigned char *)":", 1, &ctx);
 
3380
    md5_process_bytes ((unsigned char *)path, strlen (path), &ctx);
 
3381
    md5_finish_ctx (&ctx, hash);
3187
3382
    dump_hash (a2buf, hash);
3188
3383
 
3189
3384
    /* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
3190
 
    gen_md5_init (ctx);
3191
 
    gen_md5_update ((unsigned char *)a1buf, MD5_HASHLEN * 2, ctx);
3192
 
    gen_md5_update ((unsigned char *)":", 1, ctx);
3193
 
    gen_md5_update ((unsigned char *)nonce, strlen (nonce), ctx);
3194
 
    gen_md5_update ((unsigned char *)":", 1, ctx);
3195
 
    gen_md5_update ((unsigned char *)a2buf, MD5_HASHLEN * 2, ctx);
3196
 
    gen_md5_finish (ctx, hash);
 
3385
    md5_init_ctx (&ctx);
 
3386
    md5_process_bytes ((unsigned char *)a1buf, MD5_DIGEST_SIZE * 2, &ctx);
 
3387
    md5_process_bytes ((unsigned char *)":", 1, &ctx);
 
3388
    md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);
 
3389
    md5_process_bytes ((unsigned char *)":", 1, &ctx);
 
3390
    md5_process_bytes ((unsigned char *)a2buf, MD5_DIGEST_SIZE * 2, &ctx);
 
3391
    md5_finish_ctx (&ctx, hash);
3197
3392
    dump_hash (response_digest, hash);
3198
3393
 
3199
3394
    res = xmalloc (strlen (user)
3201
3396
                   + strlen (realm)
3202
3397
                   + strlen (nonce)
3203
3398
                   + strlen (path)
3204
 
                   + 2 * MD5_HASHLEN /*strlen (response_digest)*/
 
3399
                   + 2 * MD5_DIGEST_SIZE /*strlen (response_digest)*/
3205
3400
                   + (opaque ? strlen (opaque) : 0)
3206
3401
                   + 128);
3207
3402
    sprintf (res, "Digest \
3322
3517
  if (len == 5)
3323
3518
    {
3324
3519
      strncpy (shortext, ext, len - 1);
3325
 
      shortext[len - 2] = '\0';
 
3520
      shortext[len - 1] = '\0';
3326
3521
    }
3327
3522
 
3328
3523
  if (last_period_in_local_filename == NULL
3358
3553
  int i;
3359
3554
  struct {
3360
3555
    char *hdrval;
3361
 
    char *opt_dir_prefix;
3362
3556
    char *filename;
3363
3557
    bool result;
3364
3558
  } test_array[] = {
3365
 
    { "filename=\"file.ext\"", NULL, "file.ext", true },
3366
 
    { "filename=\"file.ext\"", "somedir", "somedir/file.ext", true },
3367
 
    { "attachment; filename=\"file.ext\"", NULL, "file.ext", true },
3368
 
    { "attachment; filename=\"file.ext\"", "somedir", "somedir/file.ext", true },
3369
 
    { "attachment; filename=\"file.ext\"; dummy", NULL, "file.ext", true },
3370
 
    { "attachment; filename=\"file.ext\"; dummy", "somedir", "somedir/file.ext", true },
3371
 
    { "attachment", NULL, NULL, false },
3372
 
    { "attachment", "somedir", NULL, false },
 
3559
    { "filename=\"file.ext\"", "file.ext", true },
 
3560
    { "attachment; filename=\"file.ext\"", "file.ext", true },
 
3561
    { "attachment; filename=\"file.ext\"; dummy", "file.ext", true },
 
3562
    { "attachment", NULL, false },
 
3563
    { "attachement; filename*=UTF-8'en-US'hello.txt", "hello.txt", true },
 
3564
    { "attachement; filename*0=\"hello\"; filename*1=\"world.txt\"", "helloworld.txt", true },
3373
3565
  };
3374
3566
 
3375
3567
  for (i = 0; i < sizeof(test_array)/sizeof(test_array[0]); ++i)
3377
3569
      char *filename;
3378
3570
      bool res;
3379
3571
 
3380
 
      opt.dir_prefix = test_array[i].opt_dir_prefix;
3381
3572
      res = parse_content_disposition (test_array[i].hdrval, &filename);
3382
3573
 
3383
3574
      mu_assert ("test_parse_content_disposition: wrong result",