1 /* $NetBSD: http.c,v 1.29 2010/01/24 19:10:35 joerg Exp $ */
3 * Copyright (c) 2000-2004 Dag-Erling Coïdan Smørgrav
4 * Copyright (c) 2003 Thomas Klausner <wiz@NetBSD.org>
5 * Copyright (c) 2008, 2009 Joerg Sonnenberger <joerg@NetBSD.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer
13 * in this position and unchanged.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * $FreeBSD: http.c,v 1.83 2008/02/06 11:39:55 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 #if defined(__linux__) || defined(__MINT__)
67 /* Keep this down to Linux or MiNT, it can create surprises elsewhere. */
72 /* Needed for gmtime_r on Interix */
79 #if !defined(NETBSD) && !defined(__minix)
83 #include <sys/types.h>
84 #include <sys/socket.h>
90 #if !defined(NETBSD) && !defined(__minix)
91 #include <nbcompat/stdio.h>
100 #include <netinet/in.h>
101 #include <netinet/tcp.h>
103 #if !defined(NETBSD) && !defined(__minix)
104 #include <nbcompat/netdb.h>
109 #include <arpa/inet.h>
114 /* Maximum number of redirects to follow */
115 #define MAX_REDIRECT 5
117 /* Symbolic names for reply codes we care about */
119 #define HTTP_PARTIAL 206
120 #define HTTP_MOVED_PERM 301
121 #define HTTP_MOVED_TEMP 302
122 #define HTTP_SEE_OTHER 303
123 #define HTTP_NOT_MODIFIED 304
124 #define HTTP_TEMP_REDIRECT 307
125 #define HTTP_NEED_AUTH 401
126 #define HTTP_NEED_PROXY_AUTH 407
127 #define HTTP_BAD_RANGE 416
128 #define HTTP_PROTOCOL_ERROR 999
130 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
131 || (xyz) == HTTP_MOVED_TEMP \
132 || (xyz) == HTTP_TEMP_REDIRECT \
133 || (xyz) == HTTP_SEE_OTHER)
135 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
137 #define MINBUFSIZE 4096
139 /*****************************************************************************
140 * I/O functions for decoding chunked streams
145 conn_t
*conn
; /* connection */
146 int chunked
; /* chunked mode */
147 int keep_alive
; /* keep-alive mode */
148 char *buf
; /* chunk buffer */
149 size_t bufsize
; /* size of chunk buffer */
150 ssize_t buflen
; /* amount of data currently in buffer */
151 int bufpos
; /* current read offset in buffer */
152 int eof
; /* end-of-file flag */
153 int error
; /* error flag */
154 size_t chunksize
; /* remaining size of current chunk */
155 off_t contentlength
; /* remaining size of the content */
159 * Get next chunk header
162 http_new_chunk(struct httpio
*io
)
166 if (fetch_getln(io
->conn
) == -1)
169 if (io
->conn
->buflen
< 2 || !isxdigit((unsigned char)*io
->conn
->buf
))
172 for (p
= io
->conn
->buf
; *p
&& !isspace((unsigned char)*p
); ++p
) {
175 if (!isxdigit((unsigned char)*p
))
177 if (isdigit((unsigned char)*p
)) {
178 io
->chunksize
= io
->chunksize
* 16 +
181 io
->chunksize
= io
->chunksize
* 16 +
182 10 + tolower((unsigned char)*p
) - 'a';
186 return (io
->chunksize
);
190 * Grow the input buffer to at least len bytes
193 http_growbuf(struct httpio
*io
, size_t len
)
197 if (io
->bufsize
>= len
)
200 if ((tmp
= realloc(io
->buf
, len
)) == NULL
)
208 * Fill the input buffer, do chunk decoding on the fly
211 http_fillbuf(struct httpio
*io
, size_t len
)
218 if (io
->contentlength
>= 0 && (off_t
)len
> io
->contentlength
)
219 len
= io
->contentlength
;
221 if (io
->chunked
== 0) {
222 if (http_growbuf(io
, len
) == -1)
224 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
228 if (io
->contentlength
)
229 io
->contentlength
-= io
->buflen
;
234 if (io
->chunksize
== 0) {
235 switch (http_new_chunk(io
)) {
241 if (fetch_getln(io
->conn
) == -1)
247 if (len
> io
->chunksize
)
249 if (http_growbuf(io
, len
) == -1)
251 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
255 io
->chunksize
-= io
->buflen
;
256 if (io
->contentlength
>= 0)
257 io
->contentlength
-= io
->buflen
;
259 if (io
->chunksize
== 0) {
263 len2
= fetch_read(io
->conn
, endl
, 2);
264 if (len2
== 1 && fetch_read(io
->conn
, endl
+ 1, 1) != 1)
266 if (len2
== -1 || endl
[0] != '\r' || endl
[1] != '\n')
279 http_readfn(void *v
, void *buf
, size_t len
)
281 struct httpio
*io
= (struct httpio
*)v
;
289 for (pos
= 0; len
> 0; pos
+= l
, len
-= l
) {
291 if (!io
->buf
|| io
->bufpos
== io
->buflen
)
292 if (http_fillbuf(io
, len
) < 1)
294 l
= io
->buflen
- io
->bufpos
;
297 memcpy((char *)buf
+ pos
, io
->buf
+ io
->bufpos
, l
);
301 if (!pos
&& io
->error
)
310 http_writefn(void *v
, const void *buf
, size_t len
)
312 struct httpio
*io
= (struct httpio
*)v
;
314 return (fetch_write(io
->conn
, buf
, len
));
321 http_closefn(void *v
)
323 struct httpio
*io
= (struct httpio
*)v
;
325 if (io
->keep_alive
) {
329 setsockopt(io
->conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &val
,
331 fetch_cache_put(io
->conn
, fetch_close
);
334 setsockopt(io
->conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
,
338 fetch_close(io
->conn
);
346 * Wrap a file descriptor up
349 http_funopen(conn_t
*conn
, int chunked
, int keep_alive
, off_t clength
)
354 if ((io
= calloc(1, sizeof(*io
))) == NULL
) {
359 io
->chunked
= chunked
;
360 io
->contentlength
= clength
;
361 io
->keep_alive
= keep_alive
;
362 f
= fetchIO_unopen(io
, http_readfn
, http_writefn
, http_closefn
);
372 /*****************************************************************************
373 * Helper functions for talking to the server and parsing its replies
387 hdr_transfer_encoding
,
391 /* Names of interesting headers */
396 { hdr_connection
, "Connection" },
397 { hdr_content_length
, "Content-Length" },
398 { hdr_content_range
, "Content-Range" },
399 { hdr_last_modified
, "Last-Modified" },
400 { hdr_location
, "Location" },
401 { hdr_transfer_encoding
, "Transfer-Encoding" },
402 { hdr_www_authenticate
, "WWW-Authenticate" },
403 { hdr_unknown
, NULL
},
407 * Send a formatted line; optionally echo to terminal
411 http_cmd(conn_t
*conn
, const char *fmt
, ...)
419 len
= vasprintf(&msg
, fmt
, ap
);
428 r
= fetch_write(conn
, msg
, len
);
440 http_cmd(conn_t
*conn
, const char *fmt
, ...)
444 char msg
[MINBUFSIZE
];
448 len
= vsnprintf(&msg
[0], MINBUFSIZE
, fmt
, ap
);
451 if (len
>= MINBUFSIZE
) {
457 r
= fetch_write(conn
, &msg
[0], len
);
468 * Get and parse status line
471 http_get_reply(conn_t
*conn
)
475 if (fetch_getln(conn
) == -1)
478 * A valid status line looks like "HTTP/m.n xyz reason" where m
479 * and n are the major and minor protocol version numbers and xyz
481 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
482 * just one) that do not send a version number, so we can't rely
483 * on finding one, but if we do, insist on it being 1.0 or 1.1.
484 * We don't care about the reason phrase.
486 if (strncmp(conn
->buf
, "HTTP", 4) != 0)
487 return (HTTP_PROTOCOL_ERROR
);
490 if (p
[1] != '1' || p
[2] != '.' || (p
[3] != '0' && p
[3] != '1'))
491 return (HTTP_PROTOCOL_ERROR
);
495 !isdigit((unsigned char)p
[1]) ||
496 !isdigit((unsigned char)p
[2]) ||
497 !isdigit((unsigned char)p
[3]))
498 return (HTTP_PROTOCOL_ERROR
);
500 conn
->err
= (p
[1] - '0') * 100 + (p
[2] - '0') * 10 + (p
[3] - '0');
505 * Check a header; if the type matches the given string, return a pointer
506 * to the beginning of the value.
509 http_match(const char *str
, const char *hdr
)
511 while (*str
&& *hdr
&&
512 tolower((unsigned char)*str
++) == tolower((unsigned char)*hdr
++))
514 if (*str
|| *hdr
!= ':')
516 while (*hdr
&& isspace((unsigned char)*++hdr
))
522 * Get the next header and return the appropriate symbolic code.
525 http_next_header(conn_t
*conn
, const char **p
)
529 if (fetch_getln(conn
) == -1)
530 return (hdr_syserror
);
531 while (conn
->buflen
&& isspace((unsigned char)conn
->buf
[conn
->buflen
- 1]))
533 conn
->buf
[conn
->buflen
] = '\0';
534 if (conn
->buflen
== 0)
537 * We could check for malformed headers but we don't really care.
538 * A valid header starts with a token immediately followed by a
539 * colon; a token is any sequence of non-control, non-whitespace
540 * characters except "()<>@,;:\\\"{}".
542 for (i
= 0; hdr_names
[i
].num
!= hdr_unknown
; i
++)
543 if ((*p
= http_match(hdr_names
[i
].name
, conn
->buf
)) != NULL
)
544 return (hdr_names
[i
].num
);
545 return (hdr_unknown
);
549 * Parse a last-modified header
552 http_parse_mtime(const char *p
, time_t *mtime
)
557 strncpy(locale
, setlocale(LC_TIME
, NULL
), sizeof(locale
));
558 setlocale(LC_TIME
, "C");
559 r
= strptime(p
, "%a, %d %b %Y %H:%M:%S GMT", &tm
);
560 /* XXX should add support for date-2 and date-3 */
561 setlocale(LC_TIME
, locale
);
564 *mtime
= timegm(&tm
);
569 * Parse a content-length header
572 http_parse_length(const char *p
, off_t
*length
)
576 for (len
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
577 len
= len
* 10 + (*p
- '0');
585 * Parse a content-range header
588 http_parse_range(const char *p
, off_t
*offset
, off_t
*length
, off_t
*size
)
590 off_t first
, last
, len
;
592 if (strncasecmp(p
, "bytes ", 6) != 0)
599 for (first
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
600 first
= first
* 10 + *p
- '0';
603 for (last
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
604 last
= last
* 10 + *p
- '0';
606 if (first
> last
|| *p
!= '/')
608 for (len
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
609 len
= len
* 10 + *p
- '0';
610 if (*p
|| len
< last
- first
+ 1)
615 *length
= last
- first
+ 1;
622 /*****************************************************************************
623 * Helper functions for authorization
630 http_base64(const char *src
)
632 static const char base64
[] =
633 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
634 "abcdefghijklmnopqrstuvwxyz"
641 if ((str
= malloc(((l
+ 2) / 3) * 4 + 1)) == NULL
)
647 t
= (src
[0] << 16) | (src
[1] << 8) | src
[2];
648 dst
[0] = base64
[(t
>> 18) & 0x3f];
649 dst
[1] = base64
[(t
>> 12) & 0x3f];
650 dst
[2] = base64
[(t
>> 6) & 0x3f];
651 dst
[3] = base64
[(t
>> 0) & 0x3f];
658 t
= (src
[0] << 16) | (src
[1] << 8);
659 dst
[0] = base64
[(t
>> 18) & 0x3f];
660 dst
[1] = base64
[(t
>> 12) & 0x3f];
661 dst
[2] = base64
[(t
>> 6) & 0x3f];
668 dst
[0] = base64
[(t
>> 18) & 0x3f];
669 dst
[1] = base64
[(t
>> 12) & 0x3f];
670 dst
[2] = dst
[3] = '=';
683 * Encode username and password
687 http_basic_auth(conn_t
*conn
, const char *hdr
, const char *usr
, const char *pwd
)
692 if (asprintf(&upw
, "%s:%s", usr
, pwd
) == -1)
694 auth
= http_base64(upw
);
698 r
= http_cmd(conn
, "%s: Basic %s\r\n", hdr
, auth
);
704 http_basic_auth(conn_t
*conn
, const char *hdr
, const char *usr
, const char *pwd
)
706 char upw
[MINBUFSIZE
], *auth
;
709 len
= snprintf(&upw
[0], MINBUFSIZE
, "%s:%s", usr
, pwd
);
710 if (len
>= MINBUFSIZE
)
712 auth
= http_base64(&upw
[0]);
715 r
= http_cmd(conn
, "%s: Basic %s\r\n", hdr
, auth
);
721 * Send an authorization header
724 http_authorize(conn_t
*conn
, const char *hdr
, const char *p
)
726 /* basic authorization */
727 if (strncasecmp(p
, "basic:", 6) == 0) {
728 char *user
, *pwd
, *str
;
732 for (p
+= 6; *p
&& *p
!= ':'; ++p
)
734 if (!*p
|| strchr(++p
, ':') == NULL
)
736 if ((str
= strdup(p
)) == NULL
)
737 return (-1); /* XXX */
739 pwd
= strchr(str
, ':');
741 r
= http_basic_auth(conn
, hdr
, user
, pwd
);
749 /*****************************************************************************
750 * Helper functions for connecting to a server or proxy
754 * Connect to the correct HTTP server or proxy.
757 http_connect(struct url
*URL
, struct url
*purl
, const char *flags
, int *cached
)
773 verbose
= CHECK_FLAG('v');
777 else if (CHECK_FLAG('6'))
781 if (purl
&& strcasecmp(URL
->scheme
, SCHEME_HTTPS
) != 0) {
783 } else if (strcasecmp(URL
->scheme
, SCHEME_FTP
) == 0) {
784 /* can't talk http to an ftp server */
785 /* XXX should set an error code */
789 if ((conn
= fetch_cache_get(URL
, af
)) != NULL
) {
794 if ((conn
= fetch_connect(URL
, af
, verbose
)) == NULL
)
795 /* fetch_connect() has already set an error code */
797 if (strcasecmp(URL
->scheme
, SCHEME_HTTPS
) == 0 &&
798 fetch_ssl(conn
, verbose
) == -1) {
812 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
, sizeof(val
));
819 http_get_proxy(struct url
* url
, const char *flags
)
824 if (flags
!= NULL
&& strchr(flags
, 'd') != NULL
)
826 if (fetch_no_proxy_match(url
->host
))
828 if (((p
= getenv("HTTP_PROXY")) || (p
= getenv("http_proxy"))) &&
829 *p
&& (purl
= fetchParseURL(p
))) {
831 strcpy(purl
->scheme
, SCHEME_HTTP
);
833 purl
->port
= fetch_default_proxy_port(purl
->scheme
);
834 if (strcasecmp(purl
->scheme
, SCHEME_HTTP
) == 0)
842 set_if_modified_since(conn_t
*conn
, time_t last_modified
)
844 static const char weekdays
[] = "SunMonTueWedThuFriSat";
845 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
848 gmtime_r(&last_modified
, &tm
);
849 snprintf(buf
, sizeof(buf
), "%.3s, %02d %.3s %4d %02d:%02d:%02d GMT",
850 weekdays
+ tm
.tm_wday
* 3, tm
.tm_mday
, months
+ tm
.tm_mon
* 3,
851 tm
.tm_year
+ 1900, tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
852 http_cmd(conn
, "If-Modified-Since: %s\r\n", buf
);
856 /*****************************************************************************
861 * Send a request and process the reply
863 * XXX This function is way too long, the do..while loop should be split
864 * XXX off into a separate function.
867 http_request(struct url
*URL
, const char *op
, struct url_stat
*us
,
868 struct url
*purl
, const char *flags
)
871 struct url
*url
, *new;
872 int chunked
, direct
, if_modified_since
, need_auth
, noredirect
;
873 int keep_alive
, verbose
, cached
;
875 off_t offset
, clength
, length
, size
;
880 char hbuf
[URL_HOSTLEN
+ 7], *host
;
882 direct
= CHECK_FLAG('d');
883 noredirect
= CHECK_FLAG('A');
884 verbose
= CHECK_FLAG('v');
885 if_modified_since
= CHECK_FLAG('i');
888 if (direct
&& purl
) {
893 /* try the provided URL first */
896 /* if the A flag is set, we only get one try */
897 n
= noredirect
? 1 : MAX_REDIRECT
;
900 e
= HTTP_PROTOCOL_ERROR
;
913 url
->port
= fetch_default_port(url
->scheme
);
915 /* were we redirected to an FTP URL? */
916 if (purl
== NULL
&& strcmp(url
->scheme
, SCHEME_FTP
) == 0) {
917 if (strcmp(op
, "GET") == 0)
918 return (ftp_request(url
, "RETR", NULL
, us
, purl
, flags
));
919 else if (strcmp(op
, "HEAD") == 0)
920 return (ftp_request(url
, "STAT", NULL
, us
, purl
, flags
));
923 /* connect to server or proxy */
924 if ((conn
= http_connect(url
, purl
, flags
, &cached
)) == NULL
)
929 if (strchr(url
->host
, ':')) {
930 snprintf(hbuf
, sizeof(hbuf
), "[%s]", url
->host
);
934 if (url
->port
!= fetch_default_port(url
->scheme
)) {
939 snprintf(hbuf
+ strlen(hbuf
),
940 sizeof(hbuf
) - strlen(hbuf
), ":%d", url
->port
);
945 fetch_info("requesting %s://%s%s",
946 url
->scheme
, host
, url
->doc
);
948 http_cmd(conn
, "%s %s://%s%s HTTP/1.1\r\n",
949 op
, url
->scheme
, host
, url
->doc
);
951 http_cmd(conn
, "%s %s HTTP/1.1\r\n",
955 if (if_modified_since
&& url
->last_modified
> 0)
956 set_if_modified_since(conn
, url
->last_modified
);
959 http_cmd(conn
, "Host: %s\r\n", host
);
961 /* proxy authorization */
963 if (*purl
->user
|| *purl
->pwd
)
964 http_basic_auth(conn
, "Proxy-Authorization",
965 purl
->user
, purl
->pwd
);
966 else if ((p
= getenv("HTTP_PROXY_AUTH")) != NULL
&& *p
!= '\0')
967 http_authorize(conn
, "Proxy-Authorization", p
);
970 /* server authorization */
971 if (need_auth
|| *url
->user
|| *url
->pwd
) {
972 if (*url
->user
|| *url
->pwd
)
973 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
974 else if ((p
= getenv("HTTP_AUTH")) != NULL
&& *p
!= '\0')
975 http_authorize(conn
, "Authorization", p
);
976 else if (fetchAuthMethod
&& fetchAuthMethod(url
) == 0) {
977 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
979 http_seterr(HTTP_NEED_AUTH
);
985 if ((p
= getenv("HTTP_REFERER")) != NULL
&& *p
!= '\0') {
986 if (strcasecmp(p
, "auto") == 0)
987 http_cmd(conn
, "Referer: %s://%s%s\r\n",
988 url
->scheme
, host
, url
->doc
);
990 http_cmd(conn
, "Referer: %s\r\n", p
);
992 if ((p
= getenv("HTTP_USER_AGENT")) != NULL
&& *p
!= '\0')
993 http_cmd(conn
, "User-Agent: %s\r\n", p
);
995 http_cmd(conn
, "User-Agent: %s\r\n", _LIBFETCH_VER
);
998 http_cmd(conn
, "Range: bytes=%lld-\r\n", (long long)url
->offset
);
1000 if (url
->offset
> 0)
1001 http_cmd(conn
, "Range: bytes=%ld-\r\n", (long)url
->offset
);
1003 http_cmd(conn
, "\r\n");
1006 * Force the queued request to be dispatched. Normally, one
1007 * would do this with shutdown(2) but squid proxies can be
1008 * configured to disallow such half-closed connections. To
1009 * be compatible with such configurations, fiddle with socket
1010 * options to force the pending data to be written.
1014 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
,
1018 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &val
,
1022 switch (http_get_reply(conn
)) {
1025 case HTTP_NOT_MODIFIED
:
1028 case HTTP_MOVED_PERM
:
1029 case HTTP_MOVED_TEMP
:
1030 case HTTP_SEE_OTHER
:
1032 * Not so fine, but we still have to read the
1033 * headers to get the new location.
1036 case HTTP_NEED_AUTH
:
1039 * We already sent out authorization code,
1040 * so there's nothing more we can do.
1042 http_seterr(conn
->err
);
1045 /* try again, but send the password this time */
1047 fetch_info("server requires authorization");
1049 case HTTP_NEED_PROXY_AUTH
:
1051 * If we're talking to a proxy, we already sent
1052 * our proxy authorization code, so there's
1053 * nothing more we can do.
1055 http_seterr(conn
->err
);
1057 case HTTP_BAD_RANGE
:
1059 * This can happen if we ask for 0 bytes because
1060 * we already have the whole file. Consider this
1061 * a success for now, and check sizes later.
1064 case HTTP_PROTOCOL_ERROR
:
1073 http_seterr(conn
->err
);
1076 /* fall through so we can get the full error message */
1081 switch ((h
= http_next_header(conn
, &p
))) {
1086 http_seterr(HTTP_PROTOCOL_ERROR
);
1088 case hdr_connection
:
1090 keep_alive
= (strcasecmp(p
, "keep-alive") == 0);
1092 case hdr_content_length
:
1093 http_parse_length(p
, &clength
);
1095 case hdr_content_range
:
1096 http_parse_range(p
, &offset
, &length
, &size
);
1098 case hdr_last_modified
:
1099 http_parse_mtime(p
, &mtime
);
1102 if (!HTTP_REDIRECT(conn
->err
))
1107 fetch_info("%d redirect to %s", conn
->err
, p
);
1110 new = fetchMakeURL(url
->scheme
, url
->host
, url
->port
, p
,
1111 url
->user
, url
->pwd
);
1113 new = fetchParseURL(p
);
1115 /* XXX should set an error code */
1118 if (!*new->user
&& !*new->pwd
) {
1119 strcpy(new->user
, url
->user
);
1120 strcpy(new->pwd
, url
->pwd
);
1122 new->offset
= url
->offset
;
1123 new->length
= url
->length
;
1125 case hdr_transfer_encoding
:
1127 chunked
= (strcasecmp(p
, "chunked") == 0);
1129 case hdr_www_authenticate
:
1130 if (conn
->err
!= HTTP_NEED_AUTH
)
1132 /* if we were smarter, we'd check the method and realm */
1140 } while (h
> hdr_end
);
1142 /* we need to provide authentication */
1143 if (conn
->err
== HTTP_NEED_AUTH
) {
1151 /* requested range not satisfiable */
1152 if (conn
->err
== HTTP_BAD_RANGE
) {
1153 if (url
->offset
== size
&& url
->length
== 0) {
1154 /* asked for 0 bytes; fake it */
1155 offset
= url
->offset
;
1156 conn
->err
= HTTP_OK
;
1159 http_seterr(conn
->err
);
1164 /* we have a hit or an error */
1165 if (conn
->err
== HTTP_OK
||
1166 conn
->err
== HTTP_PARTIAL
||
1167 conn
->err
== HTTP_NOT_MODIFIED
||
1168 HTTP_ERROR(conn
->err
))
1171 /* all other cases: we got a redirect */
1183 /* we failed, or ran out of retries */
1189 /* check for inconsistencies */
1190 if (clength
!= -1 && length
!= -1 && clength
!= length
) {
1191 http_seterr(HTTP_PROTOCOL_ERROR
);
1197 length
= offset
+ clength
;
1198 if (length
!= -1 && size
!= -1 && length
!= size
) {
1199 http_seterr(HTTP_PROTOCOL_ERROR
);
1208 us
->atime
= us
->mtime
= mtime
;
1212 if (URL
->offset
> 0 && offset
> URL
->offset
) {
1213 http_seterr(HTTP_PROTOCOL_ERROR
);
1217 /* report back real offset and size */
1218 URL
->offset
= offset
;
1219 URL
->length
= clength
;
1221 if (clength
== -1 && !chunked
)
1224 if (conn
->err
== HTTP_NOT_MODIFIED
) {
1225 http_seterr(HTTP_NOT_MODIFIED
);
1227 fetch_cache_put(conn
, fetch_close
);
1233 /* wrap it up in a fetchIO */
1234 if ((f
= http_funopen(conn
, chunked
, keep_alive
, clength
)) == NULL
) {
1244 if (HTTP_ERROR(conn
->err
)) {
1249 } while (fetchIO_read(f
, buf
, sizeof(buf
)) > 0);
1269 /*****************************************************************************
1274 * Retrieve and stat a file by HTTP
1277 fetchXGetHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1279 return (http_request(URL
, "GET", us
, http_get_proxy(URL
, flags
), flags
));
1283 * Retrieve a file by HTTP
1286 fetchGetHTTP(struct url
*URL
, const char *flags
)
1288 return (fetchXGetHTTP(URL
, NULL
, flags
));
1292 * Store a file by HTTP
1295 fetchPutHTTP(struct url
*URL
, const char *flags
)
1297 fprintf(stderr
, "fetchPutHTTP(): not implemented\n");
1302 * Get an HTTP document's metadata
1305 fetchStatHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1309 f
= http_request(URL
, "HEAD", us
, http_get_proxy(URL
, flags
), flags
);
1332 struct index_parser
{
1333 struct url_list
*ue
;
1335 enum http_states state
;
1339 parse_index(struct index_parser
*parser
, const char *buf
, size_t len
)
1341 char *end_attr
, p
= *buf
;
1343 switch (parser
->state
) {
1345 /* Plain text, not in markup */
1347 parser
->state
= ST_LT
;
1350 /* In tag -- "<" already found */
1352 parser
->state
= ST_NONE
;
1353 else if (p
== 'a' || p
== 'A')
1354 parser
->state
= ST_LTA
;
1355 else if (!isspace((unsigned char)p
))
1356 parser
->state
= ST_TAG
;
1359 /* In tag -- "<a" already found */
1361 parser
->state
= ST_NONE
;
1363 parser
->state
= ST_TAGAQ
;
1364 else if (isspace((unsigned char)p
))
1365 parser
->state
= ST_TAGA
;
1367 parser
->state
= ST_TAG
;
1370 /* In tag, but not "<a" -- disregard */
1372 parser
->state
= ST_NONE
;
1375 /* In a-tag -- "<a " already found */
1377 parser
->state
= ST_NONE
;
1379 parser
->state
= ST_TAGAQ
;
1380 else if (p
== 'h' || p
== 'H')
1381 parser
->state
= ST_H
;
1382 else if (!isspace((unsigned char)p
))
1383 parser
->state
= ST_TAGAX
;
1386 /* In unknown keyword in a-tag */
1388 parser
->state
= ST_NONE
;
1390 parser
->state
= ST_TAGAQ
;
1391 else if (isspace((unsigned char)p
))
1392 parser
->state
= ST_TAGA
;
1395 /* In a-tag, unknown argument for keys. */
1397 parser
->state
= ST_NONE
;
1399 parser
->state
= ST_TAGA
;
1402 /* In a-tag -- "<a h" already found */
1404 parser
->state
= ST_NONE
;
1406 parser
->state
= ST_TAGAQ
;
1407 else if (p
== 'r' || p
== 'R')
1408 parser
->state
= ST_R
;
1409 else if (isspace((unsigned char)p
))
1410 parser
->state
= ST_TAGA
;
1412 parser
->state
= ST_TAGAX
;
1415 /* In a-tag -- "<a hr" already found */
1417 parser
->state
= ST_NONE
;
1419 parser
->state
= ST_TAGAQ
;
1420 else if (p
== 'e' || p
== 'E')
1421 parser
->state
= ST_E
;
1422 else if (isspace((unsigned char)p
))
1423 parser
->state
= ST_TAGA
;
1425 parser
->state
= ST_TAGAX
;
1428 /* In a-tag -- "<a hre" already found */
1430 parser
->state
= ST_NONE
;
1432 parser
->state
= ST_TAGAQ
;
1433 else if (p
== 'f' || p
== 'F')
1434 parser
->state
= ST_F
;
1435 else if (isspace((unsigned char)p
))
1436 parser
->state
= ST_TAGA
;
1438 parser
->state
= ST_TAGAX
;
1441 /* In a-tag -- "<a href" already found */
1443 parser
->state
= ST_NONE
;
1445 parser
->state
= ST_TAGAQ
;
1447 parser
->state
= ST_HREF
;
1448 else if (!isspace((unsigned char)p
))
1449 parser
->state
= ST_TAGAX
;
1452 /* In a-tag -- "<a href=" already found */
1454 parser
->state
= ST_NONE
;
1456 parser
->state
= ST_HREFQ
;
1457 else if (!isspace((unsigned char)p
))
1458 parser
->state
= ST_TAGA
;
1461 /* In href of the a-tag */
1462 end_attr
= memchr(buf
, '"', len
);
1463 if (end_attr
== NULL
)
1466 parser
->state
= ST_TAGA
;
1467 if (fetch_add_entry(parser
->ue
, parser
->url
, buf
, 1))
1469 return end_attr
+ 1 - buf
;
1475 struct http_index_cache
{
1476 struct http_index_cache
*next
;
1477 struct url
*location
;
1481 static struct http_index_cache
*index_cache
;
1487 fetchListHTTP(struct url_list
*ue
, struct url
*url
, const char *pattern
, const char *flags
)
1490 char buf
[2 * PATH_MAX
];
1491 size_t buf_len
, sum_processed
;
1492 ssize_t read_len
, processed
;
1493 struct index_parser state
;
1494 struct http_index_cache
*cache
= NULL
;
1497 do_cache
= CHECK_FLAG('c');
1500 for (cache
= index_cache
; cache
!= NULL
; cache
= cache
->next
) {
1501 if (strcmp(cache
->location
->scheme
, url
->scheme
))
1503 if (strcmp(cache
->location
->user
, url
->user
))
1505 if (strcmp(cache
->location
->pwd
, url
->pwd
))
1507 if (strcmp(cache
->location
->host
, url
->host
))
1509 if (cache
->location
->port
!= url
->port
)
1511 if (strcmp(cache
->location
->doc
, url
->doc
))
1513 return fetchAppendURLList(ue
, &cache
->ue
);
1516 cache
= malloc(sizeof(*cache
));
1517 fetchInitURLList(&cache
->ue
);
1518 cache
->location
= fetchCopyURL(url
);
1521 f
= fetchGetHTTP(url
, flags
);
1524 fetchFreeURLList(&cache
->ue
);
1525 fetchFreeURL(cache
->location
);
1532 state
.state
= ST_NONE
;
1534 state
.ue
= &cache
->ue
;
1541 while ((read_len
= fetchIO_read(f
, buf
+ buf_len
, sizeof(buf
) - buf_len
)) > 0) {
1542 buf_len
+= read_len
;
1545 processed
= parse_index(&state
, buf
+ sum_processed
, buf_len
);
1546 if (processed
== -1)
1548 buf_len
-= processed
;
1549 sum_processed
+= processed
;
1550 } while (processed
!= 0 && buf_len
> 0);
1551 if (processed
== -1) {
1555 memmove(buf
, buf
+ sum_processed
, buf_len
);
1560 ret
= read_len
< 0 ? -1 : 0;
1564 cache
->next
= index_cache
;
1565 index_cache
= cache
;
1568 if (fetchAppendURLList(ue
, &cache
->ue
))