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.
28 * $FreeBSD: src/lib/libfetch/http.c,v 1.86 2008/12/15 08:27:44 murray Exp $
29 * $DragonFly: src/lib/libfetch/http.c,v 1.4 2007/08/05 21:48:12 swildner Exp $
33 * The following copyright applies to the base64 code:
36 * Copyright 1997 Massachusetts Institute of Technology
38 * Permission to use, copy, modify, and distribute this software and
39 * its documentation for any purpose and without fee is hereby
40 * granted, provided that both the above copyright notice and this
41 * permission notice appear in all copies, that both the above
42 * copyright notice and this permission notice appear in all
43 * supporting documentation, and that the name of M.I.T. not be used
44 * in advertising or publicity pertaining to distribution of the
45 * software without specific, written prior permission. M.I.T. makes
46 * no representations about the suitability of this software for any
47 * purpose. It is provided "as is" without express or implied
50 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
51 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
52 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
53 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
54 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
56 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
57 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
58 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
59 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
60 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 #include <sys/param.h>
65 #include <sys/socket.h>
80 #include <netinet/in.h>
81 #include <netinet/tcp.h>
87 /* Maximum number of redirects to follow */
88 #define MAX_REDIRECT 5
90 /* Symbolic names for reply codes we care about */
92 #define HTTP_PARTIAL 206
93 #define HTTP_MOVED_PERM 301
94 #define HTTP_MOVED_TEMP 302
95 #define HTTP_SEE_OTHER 303
96 #define HTTP_NOT_MODIFIED 304
97 #define HTTP_TEMP_REDIRECT 307
98 #define HTTP_NEED_AUTH 401
99 #define HTTP_NEED_PROXY_AUTH 407
100 #define HTTP_BAD_RANGE 416
101 #define HTTP_PROTOCOL_ERROR 999
103 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
104 || (xyz) == HTTP_MOVED_TEMP \
105 || (xyz) == HTTP_TEMP_REDIRECT \
106 || (xyz) == HTTP_SEE_OTHER)
108 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
111 /*****************************************************************************
112 * I/O functions for decoding chunked streams
117 conn_t
*conn
; /* connection */
118 int chunked
; /* chunked mode */
119 char *buf
; /* chunk buffer */
120 size_t bufsize
; /* size of chunk buffer */
121 ssize_t buflen
; /* amount of data currently in buffer */
122 int bufpos
; /* current read offset in buffer */
123 int eof
; /* end-of-file flag */
124 int error
; /* error flag */
125 size_t chunksize
; /* remaining size of current chunk */
132 * Get next chunk header
135 http_new_chunk(struct httpio
*io
)
139 if (fetch_getln(io
->conn
) == -1)
142 if (io
->conn
->buflen
< 2 || !isxdigit((unsigned char)*io
->conn
->buf
))
145 for (p
= io
->conn
->buf
; *p
&& !isspace((unsigned char)*p
); ++p
) {
148 if (!isxdigit((unsigned char)*p
))
150 if (isdigit((unsigned char)*p
)) {
151 io
->chunksize
= io
->chunksize
* 16 +
154 io
->chunksize
= io
->chunksize
* 16 +
155 10 + tolower((unsigned char)*p
) - 'a';
161 io
->total
+= io
->chunksize
;
162 if (io
->chunksize
== 0)
163 fprintf(stderr
, "%s(): end of last chunk\n", __func__
);
165 fprintf(stderr
, "%s(): new chunk: %lu (%lu)\n",
166 __func__
, (unsigned long)io
->chunksize
,
167 (unsigned long)io
->total
);
171 return (io
->chunksize
);
175 * Grow the input buffer to at least len bytes
178 http_growbuf(struct httpio
*io
, size_t len
)
182 if (io
->bufsize
>= len
)
185 if ((tmp
= realloc(io
->buf
, len
)) == NULL
)
193 * Fill the input buffer, do chunk decoding on the fly
196 http_fillbuf(struct httpio
*io
, size_t len
)
203 if (io
->chunked
== 0) {
204 if (http_growbuf(io
, len
) == -1)
206 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
214 if (io
->chunksize
== 0) {
215 switch (http_new_chunk(io
)) {
225 if (len
> io
->chunksize
)
227 if (http_growbuf(io
, len
) == -1)
229 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
233 io
->chunksize
-= io
->buflen
;
235 if (io
->chunksize
== 0) {
238 if (fetch_read(io
->conn
, endl
, 2) != 2 ||
239 endl
[0] != '\r' || endl
[1] != '\n')
252 http_readfn(void *v
, char *buf
, int len
)
254 struct httpio
*io
= (struct httpio
*)v
;
262 for (pos
= 0; len
> 0; pos
+= l
, len
-= l
) {
264 if (!io
->buf
|| io
->bufpos
== io
->buflen
)
265 if (http_fillbuf(io
, len
) < 1)
267 l
= io
->buflen
- io
->bufpos
;
270 memcpy(buf
+ pos
, io
->buf
+ io
->bufpos
, l
);
274 if (!pos
&& io
->error
)
283 http_writefn(void *v
, const char *buf
, int len
)
285 struct httpio
*io
= (struct httpio
*)v
;
287 return (fetch_write(io
->conn
, buf
, len
));
294 http_closefn(void *v
)
296 struct httpio
*io
= (struct httpio
*)v
;
299 r
= fetch_close(io
->conn
);
307 * Wrap a file descriptor up
310 http_funopen(conn_t
*conn
, int chunked
)
315 if ((io
= calloc(1, sizeof(*io
))) == NULL
) {
320 io
->chunked
= chunked
;
321 f
= funopen(io
, http_readfn
, http_writefn
, NULL
, http_closefn
);
331 /*****************************************************************************
332 * Helper functions for talking to the server and parsing its replies
345 hdr_transfer_encoding
,
349 /* Names of interesting headers */
354 { hdr_content_length
, "Content-Length" },
355 { hdr_content_range
, "Content-Range" },
356 { hdr_last_modified
, "Last-Modified" },
357 { hdr_location
, "Location" },
358 { hdr_transfer_encoding
, "Transfer-Encoding" },
359 { hdr_www_authenticate
, "WWW-Authenticate" },
360 { hdr_unknown
, NULL
},
364 * Send a formatted line; optionally echo to terminal
367 http_cmd(conn_t
*conn
, const char *fmt
, ...)
375 len
= vasprintf(&msg
, fmt
, ap
);
384 r
= fetch_putln(conn
, msg
, len
);
396 * Get and parse status line
399 http_get_reply(conn_t
*conn
)
403 if (fetch_getln(conn
) == -1)
406 * A valid status line looks like "HTTP/m.n xyz reason" where m
407 * and n are the major and minor protocol version numbers and xyz
409 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
410 * just one) that do not send a version number, so we can't rely
411 * on finding one, but if we do, insist on it being 1.0 or 1.1.
412 * We don't care about the reason phrase.
414 if (strncmp(conn
->buf
, "HTTP", 4) != 0)
415 return (HTTP_PROTOCOL_ERROR
);
418 if (p
[1] != '1' || p
[2] != '.' || (p
[3] != '0' && p
[3] != '1'))
419 return (HTTP_PROTOCOL_ERROR
);
423 !isdigit((unsigned char)p
[1]) ||
424 !isdigit((unsigned char)p
[2]) ||
425 !isdigit((unsigned char)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
&&
440 tolower((unsigned char)*str
++) == tolower((unsigned char)*hdr
++))
442 if (*str
|| *hdr
!= ':')
444 while (*hdr
&& isspace((unsigned char)*++hdr
))
450 * Get the next header and return the appropriate symbolic code.
453 http_next_header(conn_t
*conn
, const char **p
)
457 if (fetch_getln(conn
) == -1)
458 return (hdr_syserror
);
459 while (conn
->buflen
&& isspace((unsigned char)conn
->buf
[conn
->buflen
- 1]))
461 conn
->buf
[conn
->buflen
] = '\0';
462 if (conn
->buflen
== 0)
465 * We could check for malformed headers but we don't really care.
466 * A valid header starts with a token immediately followed by a
467 * colon; a token is any sequence of non-control, non-whitespace
468 * characters except "()<>@,;:\\\"{}".
470 for (i
= 0; hdr_names
[i
].num
!= hdr_unknown
; i
++)
471 if ((*p
= http_match(hdr_names
[i
].name
, conn
->buf
)) != NULL
)
472 return (hdr_names
[i
].num
);
473 return (hdr_unknown
);
477 * Parse a last-modified header
480 http_parse_mtime(const char *p
, time_t *mtime
)
485 strncpy(locale
, setlocale(LC_TIME
, NULL
), sizeof(locale
));
486 setlocale(LC_TIME
, "C");
487 r
= strptime(p
, "%a, %d %b %Y %H:%M:%S GMT", &tm
);
488 /* XXX should add support for date-2 and date-3 */
489 setlocale(LC_TIME
, locale
);
492 DEBUG(fprintf(stderr
, "last modified: [%04d-%02d-%02d "
494 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
,
495 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
));
496 *mtime
= timegm(&tm
);
501 * Parse a content-length header
504 http_parse_length(const char *p
, off_t
*length
)
508 for (len
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
509 len
= len
* 10 + (*p
- '0');
512 DEBUG(fprintf(stderr
, "content length: [%lld]\n",
519 * Parse a content-range header
522 http_parse_range(const char *p
, off_t
*offset
, off_t
*length
, off_t
*size
)
524 off_t first
, last
, len
;
526 if (strncasecmp(p
, "bytes ", 6) != 0)
533 for (first
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
534 first
= first
* 10 + *p
- '0';
537 for (last
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
538 last
= last
* 10 + *p
- '0';
540 if (first
> last
|| *p
!= '/')
542 for (len
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
543 len
= len
* 10 + *p
- '0';
544 if (*p
|| len
< last
- first
+ 1)
547 DEBUG(fprintf(stderr
, "content range: [*/%lld]\n",
551 DEBUG(fprintf(stderr
, "content range: [%lld-%lld/%lld]\n",
552 (long long)first
, (long long)last
, (long long)len
));
553 *length
= last
- first
+ 1;
561 /*****************************************************************************
562 * Helper functions for authorization
569 http_base64(const char *src
)
571 static const char base64
[] =
572 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
573 "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) {
721 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
, sizeof(val
));
727 http_get_proxy(struct url
* url
, const char *flags
)
732 if (flags
!= NULL
&& strchr(flags
, 'd') != NULL
)
734 if (fetch_no_proxy_match(url
->host
))
736 if (((p
= getenv("HTTP_PROXY")) || (p
= getenv("http_proxy"))) &&
737 *p
&& (purl
= fetchParseURL(p
))) {
739 strcpy(purl
->scheme
, SCHEME_HTTP
);
741 purl
->port
= fetch_default_proxy_port(purl
->scheme
);
742 if (strcasecmp(purl
->scheme
, SCHEME_HTTP
) == 0)
750 http_print_html(FILE *out
, FILE *in
)
757 while ((line
= fgetln(in
, &len
)) != NULL
) {
758 while (len
&& isspace((unsigned char)line
[len
- 1]))
760 for (p
= q
= line
; q
< line
+ len
; ++q
) {
761 if (comment
&& *q
== '-') {
762 if (q
+ 2 < line
+ len
&&
763 strcmp(q
, "-->") == 0) {
767 } else if (tag
&& !comment
&& *q
== '>') {
770 } else if (!tag
&& *q
== '<') {
772 fwrite(p
, q
- p
, 1, out
);
774 if (q
+ 3 < line
+ len
&&
775 strcmp(q
, "<!--") == 0) {
782 fwrite(p
, q
- p
, 1, out
);
788 /*****************************************************************************
793 * Send a request and process the reply
795 * XXX This function is way too long, the do..while loop should be split
796 * XXX off into a separate function.
799 http_request(struct url
*URL
, const char *op
, struct url_stat
*us
,
800 struct url
*purl
, const char *flags
)
803 char hbuf
[MAXHOSTNAMELEN
+ 7], *host
;
805 struct url
*url
, *new;
806 int chunked
, direct
, ims
, need_auth
, noredirect
, verbose
;
808 off_t offset
, clength
, length
, size
;
813 struct tm
*timestruct
;
815 direct
= CHECK_FLAG('d');
816 noredirect
= CHECK_FLAG('A');
817 verbose
= CHECK_FLAG('v');
818 ims
= CHECK_FLAG('i');
820 if (direct
&& purl
) {
825 /* try the provided URL first */
828 /* if the A flag is set, we only get one try */
829 n
= noredirect
? 1 : MAX_REDIRECT
;
832 e
= HTTP_PROTOCOL_ERROR
;
845 url
->port
= fetch_default_port(url
->scheme
);
847 /* were we redirected to an FTP URL? */
848 if (purl
== NULL
&& strcmp(url
->scheme
, SCHEME_FTP
) == 0) {
849 if (strcmp(op
, "GET") == 0)
850 return (ftp_request(url
, "RETR", us
, purl
, flags
));
851 else if (strcmp(op
, "HEAD") == 0)
852 return (ftp_request(url
, "STAT", us
, purl
, flags
));
855 /* connect to server or proxy */
856 if ((conn
= http_connect(url
, purl
, flags
)) == NULL
)
861 if (strchr(url
->host
, ':')) {
862 snprintf(hbuf
, sizeof(hbuf
), "[%s]", url
->host
);
866 if (url
->port
!= fetch_default_port(url
->scheme
)) {
871 snprintf(hbuf
+ strlen(hbuf
),
872 sizeof(hbuf
) - strlen(hbuf
), ":%d", url
->port
);
877 fetch_info("requesting %s://%s%s",
878 url
->scheme
, host
, url
->doc
);
880 http_cmd(conn
, "%s %s://%s%s HTTP/1.1",
881 op
, url
->scheme
, host
, url
->doc
);
883 http_cmd(conn
, "%s %s HTTP/1.1",
887 if (ims
&& url
->ims_time
) {
888 timestruct
= gmtime((time_t *)&url
->ims_time
);
889 (void)strftime(timebuf
, 80, "%a, %d %b %Y %T GMT",
892 fetch_info("If-Modified-Since: %s", timebuf
);
893 http_cmd(conn
, "If-Modified-Since: %s", timebuf
);
896 http_cmd(conn
, "Host: %s", host
);
898 /* proxy authorization */
900 if (*purl
->user
|| *purl
->pwd
)
901 http_basic_auth(conn
, "Proxy-Authorization",
902 purl
->user
, purl
->pwd
);
903 else if ((p
= getenv("HTTP_PROXY_AUTH")) != NULL
&& *p
!= '\0')
904 http_authorize(conn
, "Proxy-Authorization", p
);
907 /* server authorization */
908 if (need_auth
|| *url
->user
|| *url
->pwd
) {
909 if (*url
->user
|| *url
->pwd
)
910 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
911 else if ((p
= getenv("HTTP_AUTH")) != NULL
&& *p
!= '\0')
912 http_authorize(conn
, "Authorization", p
);
913 else if (fetchAuthMethod
&& fetchAuthMethod(url
) == 0) {
914 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
916 http_seterr(HTTP_NEED_AUTH
);
922 if ((p
= getenv("HTTP_REFERER")) != NULL
&& *p
!= '\0') {
923 if (strcasecmp(p
, "auto") == 0)
924 http_cmd(conn
, "Referer: %s://%s%s",
925 url
->scheme
, host
, url
->doc
);
927 http_cmd(conn
, "Referer: %s", p
);
929 if ((p
= getenv("HTTP_USER_AGENT")) != NULL
&& *p
!= '\0')
930 http_cmd(conn
, "User-Agent: %s", p
);
932 http_cmd(conn
, "User-Agent: %s " _LIBFETCH_VER
, getprogname());
934 http_cmd(conn
, "Range: bytes=%lld-", (long long)url
->offset
);
935 http_cmd(conn
, "Connection: close");
939 * Force the queued request to be dispatched. Normally, one
940 * would do this with shutdown(2) but squid proxies can be
941 * configured to disallow such half-closed connections. To
942 * be compatible with such configurations, fiddle with socket
943 * options to force the pending data to be written.
946 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
,
949 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &val
,
953 switch (http_get_reply(conn
)) {
956 case HTTP_NOT_MODIFIED
:
959 case HTTP_MOVED_PERM
:
960 case HTTP_MOVED_TEMP
:
963 * Not so fine, but we still have to read the
964 * headers to get the new location.
970 * We already sent out authorization code,
971 * so there's nothing more we can do.
973 http_seterr(conn
->err
);
976 /* try again, but send the password this time */
978 fetch_info("server requires authorization");
980 case HTTP_NEED_PROXY_AUTH
:
982 * If we're talking to a proxy, we already sent
983 * our proxy authorization code, so there's
984 * nothing more we can do.
986 http_seterr(conn
->err
);
990 * This can happen if we ask for 0 bytes because
991 * we already have the whole file. Consider this
992 * a success for now, and check sizes later.
995 case HTTP_PROTOCOL_ERROR
:
1001 http_seterr(conn
->err
);
1004 /* fall through so we can get the full error message */
1009 switch ((h
= http_next_header(conn
, &p
))) {
1014 http_seterr(HTTP_PROTOCOL_ERROR
);
1016 case hdr_content_length
:
1017 http_parse_length(p
, &clength
);
1019 case hdr_content_range
:
1020 http_parse_range(p
, &offset
, &length
, &size
);
1022 case hdr_last_modified
:
1023 http_parse_mtime(p
, &mtime
);
1026 if (!HTTP_REDIRECT(conn
->err
))
1031 fetch_info("%d redirect to %s", conn
->err
, p
);
1034 new = fetchMakeURL(url
->scheme
, url
->host
, url
->port
, p
,
1035 url
->user
, url
->pwd
);
1037 new = fetchParseURL(p
);
1039 /* XXX should set an error code */
1040 DEBUG(fprintf(stderr
, "failed to parse new URL\n"));
1043 if (!*new->user
&& !*new->pwd
) {
1044 strcpy(new->user
, url
->user
);
1045 strcpy(new->pwd
, url
->pwd
);
1047 new->offset
= url
->offset
;
1048 new->length
= url
->length
;
1050 case hdr_transfer_encoding
:
1052 chunked
= (strcasecmp(p
, "chunked") == 0);
1054 case hdr_www_authenticate
:
1055 if (conn
->err
!= HTTP_NEED_AUTH
)
1057 /* if we were smarter, we'd check the method and realm */
1065 } while (h
> hdr_end
);
1067 /* we need to provide authentication */
1068 if (conn
->err
== HTTP_NEED_AUTH
) {
1076 /* requested range not satisfiable */
1077 if (conn
->err
== HTTP_BAD_RANGE
) {
1078 if (url
->offset
== size
&& url
->length
== 0) {
1079 /* asked for 0 bytes; fake it */
1080 offset
= url
->offset
;
1082 conn
->err
= HTTP_OK
;
1085 http_seterr(conn
->err
);
1090 /* we have a hit or an error */
1091 if (conn
->err
== HTTP_OK
1092 || conn
->err
== HTTP_NOT_MODIFIED
1093 || conn
->err
== HTTP_PARTIAL
1094 || HTTP_ERROR(conn
->err
))
1097 /* all other cases: we got a redirect */
1103 DEBUG(fprintf(stderr
, "redirect with no new location\n"));
1111 /* we failed, or ran out of retries */
1117 DEBUG(fprintf(stderr
, "offset %lld, length %lld,"
1118 " size %lld, clength %lld\n",
1119 (long long)offset
, (long long)length
,
1120 (long long)size
, (long long)clength
));
1122 if (conn
->err
== HTTP_NOT_MODIFIED
) {
1123 http_seterr(HTTP_NOT_MODIFIED
);
1127 /* check for inconsistencies */
1128 if (clength
!= -1 && length
!= -1 && clength
!= length
) {
1129 http_seterr(HTTP_PROTOCOL_ERROR
);
1135 length
= offset
+ clength
;
1136 if (length
!= -1 && size
!= -1 && length
!= size
) {
1137 http_seterr(HTTP_PROTOCOL_ERROR
);
1146 us
->atime
= us
->mtime
= mtime
;
1150 if (URL
->offset
> 0 && offset
> URL
->offset
) {
1151 http_seterr(HTTP_PROTOCOL_ERROR
);
1155 /* report back real offset and size */
1156 URL
->offset
= offset
;
1157 URL
->length
= clength
;
1159 /* wrap it up in a FILE */
1160 if ((f
= http_funopen(conn
, chunked
)) == NULL
) {
1170 if (HTTP_ERROR(conn
->err
)) {
1171 http_print_html(stderr
, f
);
1189 /*****************************************************************************
1194 * Retrieve and stat a file by HTTP
1197 fetchXGetHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1199 return (http_request(URL
, "GET", us
, http_get_proxy(URL
, flags
), flags
));
1203 * Retrieve a file by HTTP
1206 fetchGetHTTP(struct url
*URL
, const char *flags
)
1208 return (fetchXGetHTTP(URL
, NULL
, flags
));
1212 * Store a file by HTTP
1215 fetchPutHTTP(struct url
*URL __unused
, const char *flags __unused
)
1217 warnx("fetchPutHTTP(): not implemented");
1222 * Get an HTTP document's metadata
1225 fetchStatHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1229 f
= http_request(URL
, "HEAD", us
, http_get_proxy(URL
, flags
), flags
);
1240 fetchListHTTP(struct url
*url __unused
, const char *flags __unused
)
1242 warnx("fetchListHTTP(): not implemented");