2 * Copyright (c) 2000-2004 Dag-Erling Coïdan Smørgrav
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD: src/lib/libfetch/http.c,v 1.76.2.2 2007/05/29 12:35:26 des Exp $");
35 * The following copyright applies to the base64 code:
38 * Copyright 1997 Massachusetts Institute of Technology
40 * Permission to use, copy, modify, and distribute this software and
41 * its documentation for any purpose and without fee is hereby
42 * granted, provided that both the above copyright notice and this
43 * permission notice appear in all copies, that both the above
44 * copyright notice and this permission notice appear in all
45 * supporting documentation, and that the name of M.I.T. not be used
46 * in advertising or publicity pertaining to distribution of the
47 * software without specific, written prior permission. M.I.T. makes
48 * no representations about the suitability of this software for any
49 * purpose. It is provided "as is" without express or implied
52 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
53 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
54 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
55 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
56 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
57 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
58 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
59 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
60 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
61 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
62 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 #include <sys/param.h>
67 #include <sys/socket.h>
81 #include <netinet/in.h>
82 #include <netinet/tcp.h>
90 /* Maximum number of redirects to follow */
91 #define MAX_REDIRECT 5
93 /* Symbolic names for reply codes we care about */
95 #define HTTP_PARTIAL 206
96 #define HTTP_MOVED_PERM 301
97 #define HTTP_MOVED_TEMP 302
98 #define HTTP_SEE_OTHER 303
99 #define HTTP_TEMP_REDIRECT 307
100 #define HTTP_NEED_AUTH 401
101 #define HTTP_NEED_PROXY_AUTH 407
102 #define HTTP_BAD_RANGE 416
103 #define HTTP_PROTOCOL_ERROR 999
105 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
106 || (xyz) == HTTP_MOVED_TEMP \
107 || (xyz) == HTTP_TEMP_REDIRECT \
108 || (xyz) == HTTP_SEE_OTHER)
110 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
113 /*****************************************************************************
114 * I/O functions for decoding chunked streams
119 conn_t
*conn
; /* connection */
120 int chunked
; /* chunked mode */
121 char *buf
; /* chunk buffer */
122 size_t bufsize
; /* size of chunk buffer */
123 ssize_t buflen
; /* amount of data currently in buffer */
124 int bufpos
; /* current read offset in buffer */
125 int eof
; /* end-of-file flag */
126 int error
; /* error flag */
127 size_t chunksize
; /* remaining size of current chunk */
135 * Get next chunk header
138 _http_new_chunk(struct httpio
*io
)
142 if (_fetch_getln(io
->conn
) == -1)
145 if (io
->conn
->buflen
< 2 || !ishexnumber((unsigned)*io
->conn
->buf
))
148 for (p
= io
->conn
->buf
; *p
&& !isspace((unsigned)*p
); ++p
) {
151 if (!ishexnumber((unsigned)*p
))
153 if (isdigit((unsigned)*p
)) {
154 io
->chunksize
= io
->chunksize
* 16 +
157 io
->chunksize
= io
->chunksize
* 16 +
158 10 + tolower((unsigned)*p
) - 'a';
164 io
->total
+= io
->chunksize
;
165 if (io
->chunksize
== 0)
166 fprintf(stderr
, "%s(): end of last chunk\n", __func__
);
168 fprintf(stderr
, "%s(): new chunk: %lu (%lu)\n",
169 __func__
, (unsigned long)io
->chunksize
,
170 (unsigned long)io
->total
);
174 return (io
->chunksize
);
178 * Grow the input buffer to at least len bytes
181 _http_growbuf(struct httpio
*io
, size_t len
)
185 if (io
->bufsize
>= len
)
188 if ((tmp
= realloc(io
->buf
, len
)) == NULL
)
196 * Fill the input buffer, do chunk decoding on the fly
199 _http_fillbuf(struct httpio
*io
, size_t len
)
206 if (io
->chunked
== 0) {
207 if (_http_growbuf(io
, len
) == -1)
209 if ((io
->buflen
= _fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
217 if (io
->chunksize
== 0) {
218 switch (_http_new_chunk(io
)) {
228 if (len
> io
->chunksize
)
230 if (_http_growbuf(io
, len
) == -1)
232 if ((io
->buflen
= _fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
236 io
->chunksize
-= io
->buflen
;
238 if (io
->chunksize
== 0) {
241 if (_fetch_read(io
->conn
, endl
, 2) != 2 ||
242 endl
[0] != '\r' || endl
[1] != '\n')
255 _http_readfn(void *v
, char *buf
, int len
)
257 struct httpio
*io
= (struct httpio
*)v
;
265 for (pos
= 0; len
> 0; pos
+= l
, len
-= l
) {
267 if (!io
->buf
|| io
->bufpos
== io
->buflen
)
268 if (_http_fillbuf(io
, (unsigned) len
) < 1)
270 l
= io
->buflen
- io
->bufpos
;
273 bcopy(io
->buf
+ io
->bufpos
, buf
+ pos
, (unsigned) l
);
277 if (!pos
&& io
->error
)
286 _http_writefn(void *v
, const char *buf
, int len
)
288 struct httpio
*io
= (struct httpio
*)v
;
290 return (_fetch_write(io
->conn
, buf
, (unsigned) len
));
297 _http_closefn(void *v
)
299 struct httpio
*io
= (struct httpio
*)v
;
302 r
= _fetch_close(io
->conn
);
310 * Wrap a file descriptor up
313 _http_funopen(conn_t
*conn
, int chunked
)
318 if ((io
= calloc(1, sizeof(*io
))) == NULL
) {
323 io
->chunked
= chunked
;
324 f
= funopen(io
, _http_readfn
, _http_writefn
, NULL
, _http_closefn
);
334 /*****************************************************************************
335 * Helper functions for talking to the server and parsing its replies
348 hdr_transfer_encoding
,
352 /* Names of interesting headers */
357 { hdr_content_length
, "Content-Length" },
358 { hdr_content_range
, "Content-Range" },
359 { hdr_last_modified
, "Last-Modified" },
360 { hdr_location
, "Location" },
361 { hdr_transfer_encoding
, "Transfer-Encoding" },
362 { hdr_www_authenticate
, "WWW-Authenticate" },
363 { hdr_unknown
, NULL
},
367 * Send a formatted line; optionally echo to terminal
370 _http_cmd(conn_t
*conn
, const char *fmt
, ...)
378 len
= vasprintf(&msg
, fmt
, ap
);
387 r
= _fetch_putln(conn
, msg
, len
);
399 * Get and parse status line
402 _http_get_reply(conn_t
*conn
)
406 if (_fetch_getln(conn
) == -1)
409 * A valid status line looks like "HTTP/m.n xyz reason" where m
410 * and n are the major and minor protocol version numbers and xyz
412 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
413 * just one) that do not send a version number, so we can't rely
414 * on finding one, but if we do, insist on it being 1.0 or 1.1.
415 * We don't care about the reason phrase.
417 if (strncmp(conn
->buf
, "HTTP", 4) != 0)
418 return (HTTP_PROTOCOL_ERROR
);
421 if (p
[1] != '1' || p
[2] != '.' || (p
[3] != '0' && p
[3] != '1'))
422 return (HTTP_PROTOCOL_ERROR
);
425 if (*p
!= ' ' || !isdigit((unsigned)p
[1]) || !isdigit((unsigned)p
[2]) || !isdigit((unsigned)p
[3]))
426 return (HTTP_PROTOCOL_ERROR
);
428 conn
->err
= (p
[1] - '0') * 100 + (p
[2] - '0') * 10 + (p
[3] - '0');
433 * Check a header; if the type matches the given string, return a pointer
434 * to the beginning of the value.
437 _http_match(const char *str
, const char *hdr
)
439 while (*str
&& *hdr
&& tolower((unsigned)*str
++) == tolower((unsigned)*hdr
++))
441 if (*str
|| *hdr
!= ':')
443 while (*hdr
&& isspace((unsigned)*++hdr
))
449 * Get the next header and return the appropriate symbolic code.
452 _http_next_header(conn_t
*conn
, const char **p
)
456 if (_fetch_getln(conn
) == -1)
457 return (hdr_syserror
);
458 while (conn
->buflen
&& isspace((unsigned)conn
->buf
[conn
->buflen
- 1]))
460 conn
->buf
[conn
->buflen
] = '\0';
461 if (conn
->buflen
== 0)
464 * We could check for malformed headers but we don't really care.
465 * A valid header starts with a token immediately followed by a
466 * colon; a token is any sequence of non-control, non-whitespace
467 * characters except "()<>@,;:\\\"{}".
469 for (i
= 0; hdr_names
[i
].num
!= hdr_unknown
; i
++)
470 if ((*p
= _http_match(hdr_names
[i
].name
, conn
->buf
)) != NULL
)
471 return (hdr_names
[i
].num
);
472 return (hdr_unknown
);
476 * Parse a last-modified header
479 _http_parse_mtime(const char *p
, time_t *mtime
)
484 strncpy(locale
, setlocale(LC_TIME
, NULL
), sizeof(locale
));
485 setlocale(LC_TIME
, "C");
486 r
= strptime(p
, "%a, %d %b %Y %H:%M:%S GMT", &tm
);
487 /* XXX should add support for date-2 and date-3 */
488 setlocale(LC_TIME
, locale
);
491 DEBUG(fprintf(stderr
, "last modified: [%04d-%02d-%02d "
493 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
,
494 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
));
495 *mtime
= timegm(&tm
);
500 * Parse a content-length header
503 _http_parse_length(const char *p
, off_t
*length
)
507 for (len
= 0; *p
&& isdigit((unsigned)*p
); ++p
)
508 len
= len
* 10 + (*p
- '0');
511 DEBUG(fprintf(stderr
, "content length: [%lld]\n",
518 * Parse a content-range header
521 _http_parse_range(const char *p
, off_t
*offset
, off_t
*length
, off_t
*size
)
523 off_t first
, last
, len
;
525 if (strncasecmp(p
, "bytes ", 6) != 0)
532 for (first
= 0; *p
&& isdigit((unsigned)*p
); ++p
)
533 first
= first
* 10 + *p
- '0';
536 for (last
= 0, ++p
; *p
&& isdigit((unsigned)*p
); ++p
)
537 last
= last
* 10 + *p
- '0';
539 if (first
> last
|| *p
!= '/')
541 for (len
= 0, ++p
; *p
&& isdigit((unsigned)*p
); ++p
)
542 len
= len
* 10 + *p
- '0';
543 if (*p
|| len
< last
- first
+ 1)
546 DEBUG(fprintf(stderr
, "content range: [*/%lld]\n",
550 DEBUG(fprintf(stderr
, "content range: [%lld-%lld/%lld]\n",
551 (long long)first
, (long long)last
, (long long)len
));
552 *length
= last
- first
+ 1;
560 /*****************************************************************************
561 * Helper functions for authorization
568 _http_base64(const char *src
)
570 static const char base64
[] =
571 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
572 "abcdefghijklmnopqrstuvwxyz"
580 if ((str
= malloc(((l
+ 2) / 3) * 4 + 1)) == NULL
)
586 t
= (src
[0] << 16) | (src
[1] << 8) | src
[2];
587 dst
[0] = base64
[(t
>> 18) & 0x3f];
588 dst
[1] = base64
[(t
>> 12) & 0x3f];
589 dst
[2] = base64
[(t
>> 6) & 0x3f];
590 dst
[3] = base64
[(t
>> 0) & 0x3f];
597 t
= (src
[0] << 16) | (src
[1] << 8);
598 dst
[0] = base64
[(t
>> 18) & 0x3f];
599 dst
[1] = base64
[(t
>> 12) & 0x3f];
600 dst
[2] = base64
[(t
>> 6) & 0x3f];
607 dst
[0] = base64
[(t
>> 18) & 0x3f];
608 dst
[1] = base64
[(t
>> 12) & 0x3f];
609 dst
[2] = dst
[3] = '=';
622 * Encode username and password
625 _http_basic_auth(conn_t
*conn
, const char *hdr
, const char *usr
, const char *pwd
)
630 DEBUG(fprintf(stderr
, "usr: [%s]\n", usr
));
631 DEBUG(fprintf(stderr
, "pwd: [%s]\n", pwd
));
632 if (asprintf(&upw
, "%s:%s", usr
, pwd
) == -1)
634 auth
= _http_base64(upw
);
638 r
= _http_cmd(conn
, "%s: Basic %s", hdr
, auth
);
644 * Send an authorization header
647 _http_authorize(conn_t
*conn
, const char *hdr
, const char *p
)
649 /* basic authorization */
650 if (strncasecmp(p
, "basic:", 6) == 0) {
651 char *user
, *pwd
, *str
;
655 for (p
+= 6; *p
&& *p
!= ':'; ++p
)
657 if (!*p
|| strchr(++p
, ':') == NULL
)
659 if ((str
= strdup(p
)) == NULL
)
660 return (-1); /* XXX */
662 pwd
= strchr(str
, ':');
664 r
= _http_basic_auth(conn
, hdr
, user
, pwd
);
672 /*****************************************************************************
673 * Helper functions for connecting to a server or proxy
677 * Connect to the correct HTTP server or proxy.
680 _http_connect(struct url
*URL
, struct url
*purl
, const char *flags
)
692 verbose
= CHECK_FLAG('v');
696 else if (CHECK_FLAG('6'))
700 if (purl
&& strcasecmp(URL
->scheme
, SCHEME_HTTPS
) != 0) {
702 } else if (strcasecmp(URL
->scheme
, SCHEME_FTP
) == 0) {
703 /* can't talk http to an ftp server */
704 /* XXX should set an error code */
708 if ((conn
= _fetch_connect(URL
->host
, URL
->port
, af
, verbose
)) == NULL
)
709 /* _fetch_connect() has already set an error code */
711 if (strcasecmp(URL
->scheme
, SCHEME_HTTPS
) == 0 &&
712 _fetch_ssl(conn
, verbose
) == -1) {
725 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
, sizeof(val
));
733 _http_get_proxy(const char *flags
)
738 if (flags
!= NULL
&& strchr(flags
, 'd') != NULL
)
740 if (((p
= getenv("HTTP_PROXY")) || (p
= getenv("http_proxy"))) &&
741 *p
&& (purl
= fetchParseURL(p
))) {
743 strcpy(purl
->scheme
, SCHEME_HTTP
);
745 purl
->port
= _fetch_default_proxy_port(purl
->scheme
);
746 if (strcasecmp(purl
->scheme
, SCHEME_HTTP
) == 0)
754 _http_print_html(FILE *out
, FILE *in
)
761 while ((line
= fgetln(in
, &len
)) != NULL
) {
762 while (len
&& isspace((unsigned)line
[len
- 1]))
764 for (p
= q
= line
; q
< line
+ len
; ++q
) {
765 if (comment
&& *q
== '-') {
766 if (q
+ 2 < line
+ len
&&
767 strcmp(q
, "-->") == 0) {
771 } else if (tag
&& !comment
&& *q
== '>') {
774 } else if (!tag
&& *q
== '<') {
776 fwrite(p
, (unsigned)(q
- p
), 1, out
);
778 if (q
+ 3 < line
+ len
&&
779 strcmp(q
, "<!--") == 0) {
786 fwrite(p
, (unsigned)(q
- p
), 1, out
);
792 /*****************************************************************************
797 * Send a request and process the reply
799 * XXX This function is way too long, the do..while loop should be split
800 * XXX off into a separate function.
803 _http_request(struct url
*URL
, const char *op
, struct url_stat
*us
,
804 struct url
*purl
, const char *flags
)
807 struct url
*url
, *new;
808 int chunked
, direct
, need_auth
, noredirect
, verbose
;
810 off_t offset
, clength
, length
, size
;
815 char hbuf
[MAXHOSTNAMELEN
+ 7], *host
;
817 direct
= CHECK_FLAG('d');
818 noredirect
= CHECK_FLAG('A');
819 verbose
= CHECK_FLAG('v');
821 if (direct
&& purl
) {
826 /* try the provided URL first */
829 /* if the A flag is set, we only get one try */
830 n
= noredirect
? 1 : MAX_REDIRECT
;
833 e
= HTTP_PROTOCOL_ERROR
;
846 url
->port
= _fetch_default_port(url
->scheme
);
848 /* were we redirected to an FTP URL? */
849 if (purl
== NULL
&& strcmp(url
->scheme
, SCHEME_FTP
) == 0) {
850 if (strcmp(op
, "GET") == 0)
851 return (_ftp_request(url
, "RETR", us
, purl
, flags
));
852 else if (strcmp(op
, "HEAD") == 0)
853 return (_ftp_request(url
, "STAT", us
, purl
, flags
));
856 /* connect to server or proxy */
857 if ((conn
= _http_connect(url
, purl
, flags
)) == NULL
)
862 if (strchr(url
->host
, ':')) {
863 snprintf(hbuf
, sizeof(hbuf
), "[%s]", url
->host
);
867 if (url
->port
!= _fetch_default_port(url
->scheme
)) {
872 snprintf(hbuf
+ strlen(hbuf
),
873 sizeof(hbuf
) - strlen(hbuf
), ":%d", url
->port
);
878 _fetch_info("requesting %s://%s%s",
879 url
->scheme
, host
, url
->doc
);
881 _http_cmd(conn
, "%s %s://%s%s HTTP/1.1",
882 op
, url
->scheme
, host
, url
->doc
);
884 _http_cmd(conn
, "%s %s HTTP/1.1",
889 _http_cmd(conn
, "Host: %s", host
);
891 /* proxy authorization */
893 if (*purl
->user
|| *purl
->pwd
)
894 _http_basic_auth(conn
, "Proxy-Authorization",
895 purl
->user
, purl
->pwd
);
896 else if ((p
= getenv("HTTP_PROXY_AUTH")) != NULL
&& *p
!= '\0')
897 _http_authorize(conn
, "Proxy-Authorization", p
);
900 /* server authorization */
901 if (need_auth
|| *url
->user
|| *url
->pwd
) {
902 if (*url
->user
|| *url
->pwd
)
903 _http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
904 else if ((p
= getenv("HTTP_AUTH")) != NULL
&& *p
!= '\0')
905 _http_authorize(conn
, "Authorization", p
);
906 else if (fetchAuthMethod
&& fetchAuthMethod(url
) == 0) {
907 _http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
909 _http_seterr(HTTP_NEED_AUTH
);
915 if ((p
= getenv("HTTP_REFERER")) != NULL
&& *p
!= '\0') {
916 if (strcasecmp(p
, "auto") == 0)
917 _http_cmd(conn
, "Referer: %s://%s%s",
918 url
->scheme
, host
, url
->doc
);
920 _http_cmd(conn
, "Referer: %s", p
);
922 if ((p
= getenv("HTTP_USER_AGENT")) != NULL
&& *p
!= '\0')
923 _http_cmd(conn
, "User-Agent: %s", p
);
925 _http_cmd(conn
, "User-Agent: %s " _LIBFETCH_VER
, getprogname());
927 _http_cmd(conn
, "Range: bytes=%lld-", (long long)url
->offset
);
928 _http_cmd(conn
, "Connection: close");
932 * Force the queued request to be dispatched. Normally, one
933 * would do this with shutdown(2) but squid proxies can be
934 * configured to disallow such half-closed connections. To
935 * be compatible with such configurations, fiddle with socket
936 * options to force the pending data to be written.
940 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
,
944 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &val
,
948 switch (_http_get_reply(conn
)) {
953 case HTTP_MOVED_PERM
:
954 case HTTP_MOVED_TEMP
:
957 * Not so fine, but we still have to read the
958 * headers to get the new location.
964 * We already sent out authorization code,
965 * so there's nothing more we can do.
967 _http_seterr(conn
->err
);
970 /* try again, but send the password this time */
972 _fetch_info("server requires authorization");
974 case HTTP_NEED_PROXY_AUTH
:
976 * If we're talking to a proxy, we already sent
977 * our proxy authorization code, so there's
978 * nothing more we can do.
980 _http_seterr(conn
->err
);
984 * This can happen if we ask for 0 bytes because
985 * we already have the whole file. Consider this
986 * a success for now, and check sizes later.
989 case HTTP_PROTOCOL_ERROR
:
995 _http_seterr(conn
->err
);
998 /* fall through so we can get the full error message */
1003 switch ((h
= _http_next_header(conn
, &p
))) {
1008 _http_seterr(HTTP_PROTOCOL_ERROR
);
1010 case hdr_content_length
:
1011 _http_parse_length(p
, &clength
);
1013 case hdr_content_range
:
1014 _http_parse_range(p
, &offset
, &length
, &size
);
1016 case hdr_last_modified
:
1017 _http_parse_mtime(p
, &mtime
);
1020 if (!HTTP_REDIRECT(conn
->err
))
1025 _fetch_info("%d redirect to %s", conn
->err
, p
);
1028 new = fetchMakeURL(url
->scheme
, url
->host
, url
->port
, p
,
1029 url
->user
, url
->pwd
);
1031 new = fetchParseURL(p
);
1033 /* XXX should set an error code */
1034 DEBUG(fprintf(stderr
, "failed to parse new URL\n"));
1037 if (!*new->user
&& !*new->pwd
) {
1038 strcpy(new->user
, url
->user
);
1039 strcpy(new->pwd
, url
->pwd
);
1041 new->offset
= url
->offset
;
1042 new->length
= url
->length
;
1044 case hdr_transfer_encoding
:
1046 chunked
= (strcasecmp(p
, "chunked") == 0);
1048 case hdr_www_authenticate
:
1049 if (conn
->err
!= HTTP_NEED_AUTH
)
1051 /* if we were smarter, we'd check the method and realm */
1059 } while (h
> hdr_end
);
1061 /* we need to provide authentication */
1062 if (conn
->err
== HTTP_NEED_AUTH
) {
1070 /* requested range not satisfiable */
1071 if (conn
->err
== HTTP_BAD_RANGE
) {
1072 if (url
->offset
== size
&& url
->length
== 0) {
1073 /* asked for 0 bytes; fake it */
1074 offset
= url
->offset
;
1075 conn
->err
= HTTP_OK
;
1078 _http_seterr(conn
->err
);
1083 /* we have a hit or an error */
1084 if (conn
->err
== HTTP_OK
|| conn
->err
== HTTP_PARTIAL
|| HTTP_ERROR(conn
->err
))
1087 /* all other cases: we got a redirect */
1093 DEBUG(fprintf(stderr
, "redirect with no new location\n"));
1101 /* we failed, or ran out of retries */
1107 DEBUG(fprintf(stderr
, "offset %lld, length %lld,"
1108 " size %lld, clength %lld\n",
1109 (long long)offset
, (long long)length
,
1110 (long long)size
, (long long)clength
));
1112 /* check for inconsistencies */
1113 if (clength
!= -1 && length
!= -1 && clength
!= length
) {
1114 _http_seterr(HTTP_PROTOCOL_ERROR
);
1120 length
= offset
+ clength
;
1121 if (length
!= -1 && size
!= -1 && length
!= size
) {
1122 _http_seterr(HTTP_PROTOCOL_ERROR
);
1131 us
->atime
= us
->mtime
= mtime
;
1135 if (URL
->offset
> 0 && offset
> URL
->offset
) {
1136 _http_seterr(HTTP_PROTOCOL_ERROR
);
1140 /* report back real offset and size */
1141 URL
->offset
= offset
;
1142 URL
->length
= (unsigned) clength
;
1144 /* wrap it up in a FILE */
1145 if ((f
= _http_funopen(conn
, chunked
)) == NULL
) {
1155 if (HTTP_ERROR(conn
->err
)) {
1156 _http_print_html(stderr
, f
);
1174 /*****************************************************************************
1179 * Retrieve and stat a file by HTTP
1182 fetchXGetHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1184 return (_http_request(URL
, "GET", us
, _http_get_proxy(flags
), flags
));
1188 * Retrieve a file by HTTP
1191 fetchGetHTTP(struct url
*URL
, const char *flags
)
1193 return (fetchXGetHTTP(URL
, NULL
, flags
));
1197 * Store a file by HTTP
1201 fetchPutHTTP(struct url
*URL __unused
, const char *flags __unused
)
1203 warnx("fetchPutHTTP(): not implemented");
1208 * Get an HTTP document's metadata
1211 fetchStatHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1215 f
= _http_request(URL
, "HEAD", us
, _http_get_proxy(flags
), flags
);
1227 fetchListHTTP(struct url
*url __unused
, const char *flags __unused
)
1229 warnx("fetchListHTTP(): not implemented");