phttpget.c revision 171120
1148871Scperciva/*-
2148871Scperciva * Copyright 2005 Colin Percival
3148871Scperciva * All rights reserved
4148871Scperciva *
5148871Scperciva * Redistribution and use in source and binary forms, with or without
6148871Scperciva * modification, are permitted providing that the following conditions
7148871Scperciva * are met:
8148871Scperciva * 1. Redistributions of source code must retain the above copyright
9148871Scperciva *    notice, this list of conditions and the following disclaimer.
10148871Scperciva * 2. Redistributions in binary form must reproduce the above copyright
11148871Scperciva *    notice, this list of conditions and the following disclaimer in the
12148871Scperciva *    documentation and/or other materials provided with the distribution.
13148871Scperciva *
14148871Scperciva * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15148871Scperciva * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16148871Scperciva * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17148871Scperciva * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18148871Scperciva * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19148871Scperciva * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20148871Scperciva * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21148871Scperciva * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
22148871Scperciva * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
23148871Scperciva * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24148871Scperciva * POSSIBILITY OF SUCH DAMAGE.
25148871Scperciva */
26148871Scperciva
27148871Scperciva#include <sys/cdefs.h>
28148871Scperciva__FBSDID("$FreeBSD: head/usr.sbin/portsnap/phttpget/phttpget.c 171120 2007-06-30 19:48:28Z cperciva $");
29148871Scperciva
30148871Scperciva#include <sys/types.h>
31148871Scperciva#include <sys/time.h>
32148871Scperciva#include <sys/socket.h>
33148871Scperciva
34148871Scperciva#include <ctype.h>
35148871Scperciva#include <err.h>
36148871Scperciva#include <errno.h>
37148871Scperciva#include <fcntl.h>
38148871Scperciva#include <limits.h>
39148871Scperciva#include <netdb.h>
40150461Scperciva#include <stdint.h>
41148871Scperciva#include <stdio.h>
42148871Scperciva#include <stdlib.h>
43148871Scperciva#include <string.h>
44148871Scperciva#include <sysexits.h>
45148871Scperciva#include <unistd.h>
46148871Scperciva
47148871Scpercivastatic const char *	env_HTTP_PROXY;
48150461Scpercivastatic char *		env_HTTP_PROXY_AUTH;
49148871Scpercivastatic const char *	env_HTTP_USER_AGENT;
50164057Scpercivastatic char *		env_HTTP_TIMEOUT;
51148871Scpercivastatic const char *	proxyport;
52150461Scpercivastatic char *		proxyauth;
53148871Scperciva
54148871Scpercivastatic struct timeval	timo = { 15, 0};
55148871Scperciva
56148871Scpercivastatic void
57148871Scpercivausage(void)
58148871Scperciva{
59148871Scperciva
60148871Scperciva	fprintf(stderr, "usage: phttpget server [file ...]\n");
61148871Scperciva	exit(EX_USAGE);
62148871Scperciva}
63148871Scperciva
64150461Scperciva/*
65150461Scperciva * Base64 encode a string; the string returned, if non-NULL, is
66150461Scperciva * allocated using malloc() and must be freed by the caller.
67150461Scperciva */
68150461Scpercivastatic char *
69150461Scpercivab64enc(const char *ptext)
70150461Scperciva{
71150461Scperciva	static const char base64[] =
72150461Scperciva	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
73150461Scperciva	    "abcdefghijklmnopqrstuvwxyz"
74150461Scperciva	    "0123456789+/";
75150461Scperciva	const char *pt;
76150461Scperciva	char *ctext, *pc;
77150461Scperciva	size_t ptlen, ctlen;
78150461Scperciva	uint32_t t;
79150461Scperciva	unsigned int j;
80150461Scperciva
81150461Scperciva	/*
82150461Scperciva	 * Encoded length is 4 characters per 3-byte block or partial
83150461Scperciva	 * block of plaintext, plus one byte for the terminating NUL
84150461Scperciva	 */
85150461Scperciva	ptlen = strlen(ptext);
86150461Scperciva	if (ptlen > ((SIZE_MAX - 1) / 4) * 3 - 2)
87150461Scperciva		return NULL;	/* Possible integer overflow */
88150461Scperciva	ctlen = 4 * ((ptlen + 2) / 3) + 1;
89150461Scperciva	if ((ctext = malloc(ctlen)) == NULL)
90150461Scperciva		return NULL;
91150461Scperciva	ctext[ctlen - 1] = 0;
92150461Scperciva
93150461Scperciva	/*
94150461Scperciva	 * Scan through ptext, reading up to 3 bytes from ptext and
95150461Scperciva	 * writing 4 bytes to ctext, until we run out of input.
96150461Scperciva	 */
97150461Scperciva	for (pt = ptext, pc = ctext; ptlen; ptlen -= 3, pc += 4) {
98150461Scperciva		/* Read 3 bytes */
99150461Scperciva		for (t = j = 0; j < 3; j++) {
100150461Scperciva			t <<= 8;
101150461Scperciva			if (j < ptlen)
102150461Scperciva				t += *pt++;
103150461Scperciva		}
104150461Scperciva
105150461Scperciva		/* Write 4 bytes */
106150461Scperciva		for (j = 0; j < 4; j++) {
107150461Scperciva			if (j <= ptlen + 1)
108150461Scperciva				pc[j] = base64[(t >> 18) & 0x3f];
109150461Scperciva			else
110150461Scperciva				pc[j] = '=';
111150461Scperciva			t <<= 6;
112150461Scperciva		}
113150461Scperciva
114150461Scperciva		/* If we're done, exit the loop */
115150461Scperciva		if (ptlen <= 3)
116150461Scperciva			break;
117150461Scperciva	}
118150461Scperciva
119150461Scperciva	return (ctext);
120150461Scperciva}
121150461Scperciva
122148871Scpercivastatic void
123148871Scpercivareadenv(void)
124148871Scperciva{
125150461Scperciva	char *proxy_auth_userpass, *proxy_auth_userpass64, *p;
126150461Scperciva	char *proxy_auth_user = NULL;
127150461Scperciva	char *proxy_auth_pass = NULL;
128164057Scperciva	long http_timeout;
129148871Scperciva
130148871Scperciva	env_HTTP_PROXY = getenv("HTTP_PROXY");
131158301Scperciva	if (env_HTTP_PROXY == NULL)
132158301Scperciva		env_HTTP_PROXY = getenv("http_proxy");
133150427Scperciva	if (env_HTTP_PROXY != NULL) {
134148871Scperciva		if (strncmp(env_HTTP_PROXY, "http://", 7) == 0)
135148871Scperciva			env_HTTP_PROXY += 7;
136148880Scperciva		p = strchr(env_HTTP_PROXY, '/');
137148880Scperciva		if (p != NULL)
138148880Scperciva			*p = 0;
139148871Scperciva		p = strchr(env_HTTP_PROXY, ':');
140148871Scperciva		if (p != NULL) {
141148871Scperciva			*p = 0;
142148871Scperciva			proxyport = p + 1;
143148871Scperciva		} else
144148871Scperciva			proxyport = "3128";
145148871Scperciva	}
146148871Scperciva
147150461Scperciva	env_HTTP_PROXY_AUTH = getenv("HTTP_PROXY_AUTH");
148150461Scperciva	if ((env_HTTP_PROXY != NULL) &&
149150461Scperciva	    (env_HTTP_PROXY_AUTH != NULL) &&
150150461Scperciva	    (strncasecmp(env_HTTP_PROXY_AUTH, "basic:" , 6) == 0)) {
151150461Scperciva		/* Ignore authentication scheme */
152150461Scperciva		(void) strsep(&env_HTTP_PROXY_AUTH, ":");
153150461Scperciva
154150461Scperciva		/* Ignore realm */
155150461Scperciva		(void) strsep(&env_HTTP_PROXY_AUTH, ":");
156150461Scperciva
157150461Scperciva		/* Obtain username and password */
158150461Scperciva		proxy_auth_user = strsep(&env_HTTP_PROXY_AUTH, ":");
159156405Sume		proxy_auth_pass = env_HTTP_PROXY_AUTH;
160150461Scperciva	}
161150461Scperciva
162150461Scperciva	if ((proxy_auth_user != NULL) && (proxy_auth_pass != NULL)) {
163150461Scperciva		asprintf(&proxy_auth_userpass, "%s:%s",
164150461Scperciva		    proxy_auth_user, proxy_auth_pass);
165150461Scperciva		if (proxy_auth_userpass == NULL)
166150461Scperciva			err(1, "asprintf");
167150461Scperciva
168150461Scperciva		proxy_auth_userpass64 = b64enc(proxy_auth_userpass);
169150461Scperciva		if (proxy_auth_userpass64 == NULL)
170150461Scperciva			err(1, "malloc");
171150461Scperciva
172150461Scperciva		asprintf(&proxyauth, "Proxy-Authorization: Basic %s\r\n",
173150461Scperciva		    proxy_auth_userpass64);
174150461Scperciva		if (proxyauth == NULL)
175150461Scperciva			err(1, "asprintf");
176150461Scperciva
177150461Scperciva		free(proxy_auth_userpass);
178150461Scperciva		free(proxy_auth_userpass64);
179150461Scperciva	} else
180150461Scperciva		proxyauth = NULL;
181150461Scperciva
182148871Scperciva	env_HTTP_USER_AGENT = getenv("HTTP_USER_AGENT");
183148871Scperciva	if (env_HTTP_USER_AGENT == NULL)
184148871Scperciva		env_HTTP_USER_AGENT = "phttpget/0.1";
185164057Scperciva
186164057Scperciva	env_HTTP_TIMEOUT = getenv("HTTP_TIMEOUT");
187164057Scperciva	if (env_HTTP_TIMEOUT != NULL) {
188164057Scperciva		http_timeout = strtol(env_HTTP_TIMEOUT, &p, 10);
189164057Scperciva		if ((*env_HTTP_TIMEOUT == '\0') || (*p != '\0') ||
190164057Scperciva		    (http_timeout < 0))
191164057Scperciva			warnx("HTTP_TIMEOUT (%s) is not a positive integer",
192164057Scperciva			    env_HTTP_TIMEOUT);
193164057Scperciva		else
194164057Scperciva			timo.tv_sec = http_timeout;
195164057Scperciva	}
196148871Scperciva}
197148871Scperciva
198148871Scpercivastatic int
199148871Scpercivamakerequest(char ** buf, char * path, char * server, int connclose)
200148871Scperciva{
201148871Scperciva	int buflen;
202148871Scperciva
203148871Scperciva	buflen = asprintf(buf,
204148871Scperciva	    "GET %s%s/%s HTTP/1.1\r\n"
205148871Scperciva	    "Host: %s\r\n"
206148871Scperciva	    "User-Agent: %s\r\n"
207148871Scperciva	    "%s"
208150461Scperciva	    "%s"
209148871Scperciva	    "\r\n",
210148871Scperciva	    env_HTTP_PROXY ? "http://" : "",
211148871Scperciva	    env_HTTP_PROXY ? server : "",
212148871Scperciva	    path, server, env_HTTP_USER_AGENT,
213150461Scperciva	    proxyauth ? proxyauth : "",
214171120Scperciva	    connclose ? "Connection: Close\r\n" : "Connection: Keep-Alive\r\n");
215148871Scperciva	if (buflen == -1)
216148871Scperciva		err(1, "asprintf");
217148871Scperciva	return(buflen);
218148871Scperciva}
219148871Scperciva
220148871Scpercivastatic int
221148871Scpercivareadln(int sd, char * resbuf, int * resbuflen, int * resbufpos)
222148871Scperciva{
223148871Scperciva	ssize_t len;
224148871Scperciva
225148871Scperciva	while (strnstr(resbuf + *resbufpos, "\r\n",
226148871Scperciva	    *resbuflen - *resbufpos) == NULL) {
227148871Scperciva		/* Move buffered data to the start of the buffer */
228148871Scperciva		if (*resbufpos != 0) {
229148871Scperciva			memmove(resbuf, resbuf + *resbufpos,
230148871Scperciva			    *resbuflen - *resbufpos);
231148871Scperciva			*resbuflen -= *resbufpos;
232148871Scperciva			*resbufpos = 0;
233148871Scperciva		}
234148871Scperciva
235148871Scperciva		/* If the buffer is full, complain */
236148871Scperciva		if (*resbuflen == BUFSIZ)
237148871Scperciva			return -1;
238148871Scperciva
239148871Scperciva		/* Read more data into the buffer */
240148871Scperciva		len = recv(sd, resbuf + *resbuflen, BUFSIZ - *resbuflen, 0);
241152546Scperciva		if ((len == 0) ||
242152546Scperciva		    ((len == -1) && (errno != EINTR)))
243148871Scperciva			return -1;
244148871Scperciva
245148871Scperciva		if (len != -1)
246148871Scperciva			*resbuflen += len;
247148871Scperciva	}
248148871Scperciva
249148871Scperciva	return 0;
250148871Scperciva}
251148871Scperciva
252148871Scpercivastatic int
253148871Scpercivacopybytes(int sd, int fd, off_t copylen, char * resbuf, int * resbuflen,
254148871Scperciva    int * resbufpos)
255148871Scperciva{
256148871Scperciva	ssize_t len;
257148871Scperciva
258148871Scperciva	while (copylen) {
259148871Scperciva		/* Write data from resbuf to fd */
260148871Scperciva		len = *resbuflen - *resbufpos;
261148871Scperciva		if (copylen < len)
262148871Scperciva			len = copylen;
263148871Scperciva		if (len > 0) {
264148871Scperciva			if (fd != -1)
265148871Scperciva				len = write(fd, resbuf + *resbufpos, len);
266148871Scperciva			if (len == -1)
267148871Scperciva				err(1, "write");
268148871Scperciva			*resbufpos += len;
269148871Scperciva			copylen -= len;
270148871Scperciva			continue;
271148871Scperciva		}
272148871Scperciva
273148871Scperciva		/* Read more data into buffer */
274148871Scperciva		len = recv(sd, resbuf, BUFSIZ, 0);
275148871Scperciva		if (len == -1) {
276148871Scperciva			if (errno == EINTR)
277148871Scperciva				continue;
278148871Scperciva			return -1;
279148871Scperciva		} else if (len == 0) {
280148871Scperciva			return -2;
281148871Scperciva		} else {
282148871Scperciva			*resbuflen = len;
283148871Scperciva			*resbufpos = 0;
284148871Scperciva		}
285148871Scperciva	}
286148871Scperciva
287148871Scperciva	return 0;
288148871Scperciva}
289148871Scperciva
290148871Scpercivaint
291148871Scpercivamain(int argc, char *argv[])
292148871Scperciva{
293148871Scperciva	struct addrinfo hints;	/* Hints to getaddrinfo */
294148871Scperciva	struct addrinfo *res;	/* Pointer to server address being used */
295148871Scperciva	struct addrinfo *res0;	/* Pointer to server addresses */
296148871Scperciva	char * resbuf = NULL;	/* Response buffer */
297148871Scperciva	int resbufpos = 0;	/* Response buffer position */
298148871Scperciva	int resbuflen = 0;	/* Response buffer length */
299148871Scperciva	char * eolp;		/* Pointer to "\r\n" within resbuf */
300148871Scperciva	char * hln;		/* Pointer within header line */
301148871Scperciva	char * servername;	/* Name of server */
302148871Scperciva	char * fname = NULL;	/* Name of downloaded file */
303148871Scperciva	char * reqbuf = NULL;	/* Request buffer */
304148871Scperciva	int reqbufpos = 0;	/* Request buffer position */
305148871Scperciva	int reqbuflen = 0;	/* Request buffer length */
306148871Scperciva	ssize_t len;		/* Length sent or received */
307148871Scperciva	int nreq = 0;		/* Number of next request to send */
308148871Scperciva	int nres = 0;		/* Number of next reply to receive */
309148871Scperciva	int pipelined = 0;	/* != 0 if connection in pipelined mode. */
310171120Scperciva	int keepalive;		/* != 0 if HTTP/1.0 keep-alive rcvd. */
311148871Scperciva	int sd = -1;		/* Socket descriptor */
312148871Scperciva	int sdflags = 0;	/* Flags on the socket sd */
313148871Scperciva	int fd = -1;		/* Descriptor for download target file */
314148871Scperciva	int error;		/* Error code */
315148871Scperciva	int statuscode;		/* HTTP Status code */
316148871Scperciva	off_t contentlength;	/* Value from Content-Length header */
317148871Scperciva	int chunked;		/* != if transfer-encoding is chunked */
318148871Scperciva	off_t clen;		/* Chunk length */
319148871Scperciva	int firstreq = 0;	/* # of first request for this connection */
320148871Scperciva
321148871Scperciva	/* Check that the arguments are sensible */
322148871Scperciva	if (argc < 2)
323148871Scperciva		usage();
324148871Scperciva
325148871Scperciva	/* Read important environment variables */
326148871Scperciva	readenv();
327148871Scperciva
328148871Scperciva	/* Get server name and adjust arg[cv] to point at file names */
329148871Scperciva	servername = argv[1];
330148871Scperciva	argv += 2;
331148871Scperciva	argc -= 2;
332148871Scperciva
333148871Scperciva	/* Allocate response buffer */
334148871Scperciva	resbuf = malloc(BUFSIZ);
335148871Scperciva	if (resbuf == NULL)
336148871Scperciva		err(1, "malloc");
337148871Scperciva
338148871Scperciva	/* Look up server */
339148871Scperciva	memset(&hints, 0, sizeof(hints));
340148871Scperciva	hints.ai_family = PF_UNSPEC;
341148871Scperciva	hints.ai_socktype = SOCK_STREAM;
342148871Scperciva	error = getaddrinfo(env_HTTP_PROXY ? env_HTTP_PROXY : servername,
343148871Scperciva	    env_HTTP_PROXY ? proxyport : "http", &hints, &res0);
344148871Scperciva	if (error)
345154909Scperciva		errx(1, "host = %s, port = %s: %s",
346148871Scperciva		    env_HTTP_PROXY ? env_HTTP_PROXY : servername,
347148880Scperciva		    env_HTTP_PROXY ? proxyport : "http",
348148871Scperciva		    gai_strerror(error));
349148871Scperciva	if (res0 == NULL)
350148871Scperciva		errx(1, "could not look up %s", servername);
351148871Scperciva	res = res0;
352148871Scperciva
353148871Scperciva	/* Do the fetching */
354148871Scperciva	while (nres < argc) {
355148871Scperciva		/* Make sure we have a connected socket */
356148871Scperciva		for (; sd == -1; res = res->ai_next) {
357148871Scperciva			/* No addresses left to try :-( */
358148871Scperciva			if (res == NULL)
359148871Scperciva				errx(1, "Could not connect to %s", servername);
360148871Scperciva
361148871Scperciva			/* Create a socket... */
362148871Scperciva			sd = socket(res->ai_family, res->ai_socktype,
363148871Scperciva			    res->ai_protocol);
364148871Scperciva			if (sd == -1)
365148871Scperciva				continue;
366148871Scperciva
367148871Scperciva			/* ... set 15-second timeouts ... */
368148871Scperciva			setsockopt(sd, SOL_SOCKET, SO_SNDTIMEO,
369148871Scperciva			    (void *)&timo, (socklen_t)sizeof(timo));
370148871Scperciva			setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO,
371148871Scperciva			    (void *)&timo, (socklen_t)sizeof(timo));
372148871Scperciva
373148871Scperciva			/* ... and connect to the server. */
374148871Scperciva			if(connect(sd, res->ai_addr, res->ai_addrlen)) {
375148871Scperciva				close(sd);
376148871Scperciva				sd = -1;
377148871Scperciva				continue;
378148871Scperciva			}
379148871Scperciva
380148871Scperciva			firstreq = nres;
381148871Scperciva		}
382148871Scperciva
383148871Scperciva		/*
384148871Scperciva		 * If in pipelined HTTP mode, put socket into non-blocking
385148871Scperciva		 * mode, since we're probably going to want to try to send
386148871Scperciva		 * several HTTP requests.
387148871Scperciva		 */
388148871Scperciva		if (pipelined) {
389148871Scperciva			sdflags = fcntl(sd, F_GETFL);
390148871Scperciva			if (fcntl(sd, F_SETFL, sdflags | O_NONBLOCK) == -1)
391148871Scperciva				err(1, "fcntl");
392148871Scperciva		}
393148871Scperciva
394148871Scperciva		/* Construct requests and/or send them without blocking */
395148871Scperciva		while ((nreq < argc) && ((reqbuf == NULL) || pipelined)) {
396148871Scperciva			/* If not in the middle of a request, make one */
397148871Scperciva			if (reqbuf == NULL) {
398148871Scperciva				reqbuflen = makerequest(&reqbuf, argv[nreq],
399148871Scperciva				    servername, (nreq == argc - 1));
400148871Scperciva				reqbufpos = 0;
401148871Scperciva			}
402148871Scperciva
403148871Scperciva			/* If in pipelined mode, try to send the request */
404148871Scperciva			if (pipelined) {
405148871Scperciva				while (reqbufpos < reqbuflen) {
406148871Scperciva					len = send(sd, reqbuf + reqbufpos,
407148871Scperciva					    reqbuflen - reqbufpos, 0);
408148871Scperciva					if (len == -1)
409148871Scperciva						break;
410148871Scperciva					reqbufpos += len;
411148871Scperciva				}
412148871Scperciva				if (reqbufpos < reqbuflen) {
413148871Scperciva					if (errno != EAGAIN)
414148871Scperciva						goto conndied;
415148871Scperciva					break;
416148871Scperciva				} else {
417148871Scperciva					free(reqbuf);
418148871Scperciva					reqbuf = NULL;
419148871Scperciva					nreq++;
420148871Scperciva				}
421148871Scperciva			}
422148871Scperciva		}
423148871Scperciva
424148871Scperciva		/* Put connection back into blocking mode */
425148871Scperciva		if (pipelined) {
426148871Scperciva			if (fcntl(sd, F_SETFL, sdflags) == -1)
427148871Scperciva				err(1, "fcntl");
428148871Scperciva		}
429148871Scperciva
430148871Scperciva		/* Do we need to blocking-send a request? */
431148871Scperciva		if (nres == nreq) {
432148871Scperciva			while (reqbufpos < reqbuflen) {
433148871Scperciva				len = send(sd, reqbuf + reqbufpos,
434148871Scperciva				    reqbuflen - reqbufpos, 0);
435148871Scperciva				if (len == -1)
436148871Scperciva					goto conndied;
437148871Scperciva				reqbufpos += len;
438148871Scperciva			}
439148871Scperciva			free(reqbuf);
440148871Scperciva			reqbuf = NULL;
441148871Scperciva			nreq++;
442148871Scperciva		}
443148871Scperciva
444148871Scperciva		/* Scan through the response processing headers. */
445148871Scperciva		statuscode = 0;
446148871Scperciva		contentlength = -1;
447148871Scperciva		chunked = 0;
448171120Scperciva		keepalive = 0;
449148871Scperciva		do {
450148871Scperciva			/* Get a header line */
451148871Scperciva			error = readln(sd, resbuf, &resbuflen, &resbufpos);
452148871Scperciva			if (error)
453148871Scperciva				goto conndied;
454148925Scperciva			hln = resbuf + resbufpos;
455148871Scperciva			eolp = strnstr(hln, "\r\n", resbuflen - resbufpos);
456148871Scperciva			resbufpos = (eolp - resbuf) + 2;
457148871Scperciva			*eolp = '\0';
458148871Scperciva
459148871Scperciva			/* Make sure it doesn't contain a NUL character */
460148871Scperciva			if (strchr(hln, '\0') != eolp)
461148871Scperciva				goto conndied;
462148871Scperciva
463148871Scperciva			if (statuscode == 0) {
464148871Scperciva				/* The first line MUST be HTTP/1.x xxx ... */
465148871Scperciva				if ((strncmp(hln, "HTTP/1.", 7) != 0) ||
466148871Scperciva				    ! isdigit(hln[7]))
467148871Scperciva					goto conndied;
468148871Scperciva
469148871Scperciva				/*
470148871Scperciva				 * If the minor version number isn't zero,
471148871Scperciva				 * then we can assume that pipelining our
472148871Scperciva				 * requests is OK -- as long as we don't
473148871Scperciva				 * see a "Connection: close" line later
474148871Scperciva				 * and we either have a Content-Length or
475148871Scperciva				 * Transfer-Encoding: chunked header to
476148871Scperciva				 * tell us the length.
477148871Scperciva				 */
478148871Scperciva				if (hln[7] != '0')
479148871Scperciva					pipelined = 1;
480148871Scperciva
481148871Scperciva				/* Skip over the minor version number */
482148871Scperciva				hln = strchr(hln + 7, ' ');
483148871Scperciva				if (hln == NULL)
484148871Scperciva					goto conndied;
485148871Scperciva				else
486148871Scperciva					hln++;
487148871Scperciva
488148871Scperciva				/* Read the status code */
489148871Scperciva				while (isdigit(*hln)) {
490148871Scperciva					statuscode = statuscode * 10 +
491148871Scperciva					    *hln - '0';
492148871Scperciva					hln++;
493148871Scperciva				}
494148871Scperciva
495148871Scperciva				if (statuscode < 100 || statuscode > 599)
496148871Scperciva					goto conndied;
497148871Scperciva
498148871Scperciva				/* Ignore the rest of the line */
499148871Scperciva				continue;
500148871Scperciva			}
501148871Scperciva
502171120Scperciva			/*
503171120Scperciva			 * Check for "Connection: close" or
504171120Scperciva			 * "Connection: Keep-Alive" header
505171120Scperciva			 */
506148871Scperciva			if (strncmp(hln, "Connection:", 11) == 0) {
507148871Scperciva				hln += 11;
508148871Scperciva				if (strstr(hln, "close") != NULL)
509148871Scperciva					pipelined = 0;
510171120Scperciva				if (strstr(hln, "Keep-Alive") != NULL)
511171120Scperciva					keepalive = 1;
512148871Scperciva
513148871Scperciva				/* Next header... */
514148871Scperciva				continue;
515148871Scperciva			}
516148871Scperciva
517148871Scperciva			/* Check for "Content-Length:" header */
518148871Scperciva			if (strncmp(hln, "Content-Length:", 15) == 0) {
519148871Scperciva				hln += 15;
520148871Scperciva				contentlength = 0;
521148871Scperciva
522148871Scperciva				/* Find the start of the length */
523148871Scperciva				while (!isdigit(*hln) && (*hln != '\0'))
524148871Scperciva					hln++;
525148871Scperciva
526148871Scperciva				/* Compute the length */
527148871Scperciva				while (isdigit(*hln)) {
528148881Scperciva					if (contentlength >= OFF_MAX / 10) {
529148871Scperciva						/* Nasty people... */
530148871Scperciva						goto conndied;
531148871Scperciva					}
532148871Scperciva					contentlength = contentlength * 10 +
533148871Scperciva					    *hln - '0';
534148871Scperciva					hln++;
535148871Scperciva				}
536148871Scperciva
537148871Scperciva				/* Next header... */
538148871Scperciva				continue;
539148871Scperciva			}
540148871Scperciva
541148871Scperciva			/* Check for "Transfer-Encoding: chunked" header */
542148871Scperciva			if (strncmp(hln, "Transfer-Encoding:", 18) == 0) {
543148871Scperciva				hln += 18;
544148871Scperciva				if (strstr(hln, "chunked") != NULL)
545148871Scperciva					chunked = 1;
546148871Scperciva
547148871Scperciva				/* Next header... */
548148871Scperciva				continue;
549148871Scperciva			}
550148871Scperciva
551148871Scperciva			/* We blithely ignore any other header lines */
552148871Scperciva
553148871Scperciva			/* No more header lines */
554148871Scperciva			if (strlen(hln) == 0) {
555148871Scperciva				/*
556148871Scperciva				 * If the status code was 1xx, then there will
557148871Scperciva				 * be a real header later.  Servers may emit
558148871Scperciva				 * 1xx header blocks at will, but since we
559148871Scperciva				 * don't expect one, we should just ignore it.
560148871Scperciva				 */
561148871Scperciva				if (100 <= statuscode && statuscode <= 199) {
562148871Scperciva					statuscode = 0;
563148871Scperciva					continue;
564148871Scperciva				}
565148871Scperciva
566148871Scperciva				/* End of header; message body follows */
567148871Scperciva				break;
568148871Scperciva			}
569148871Scperciva		} while (1);
570148871Scperciva
571148871Scperciva		/* No message body for 204 or 304 */
572148871Scperciva		if (statuscode == 204 || statuscode == 304) {
573148871Scperciva			nres++;
574148871Scperciva			continue;
575148871Scperciva		}
576148871Scperciva
577148871Scperciva		/*
578148871Scperciva		 * There should be a message body coming, but we only want
579148871Scperciva		 * to send it to a file if the status code is 200
580148871Scperciva		 */
581148871Scperciva		if (statuscode == 200) {
582148871Scperciva			/* Generate a file name for the download */
583148871Scperciva			fname = strrchr(argv[nres], '/');
584148871Scperciva			if (fname == NULL)
585148871Scperciva				fname = argv[nres];
586148871Scperciva			else
587148871Scperciva				fname++;
588148871Scperciva			if (strlen(fname) == 0)
589148871Scperciva				errx(1, "Cannot obtain file name from %s\n",
590148871Scperciva				    argv[nres]);
591148871Scperciva
592148871Scperciva			fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY, 0644);
593148871Scperciva			if (fd == -1)
594148871Scperciva				errx(1, "open(%s)", fname);
595148871Scperciva		};
596148871Scperciva
597148871Scperciva		/* Read the message and send data to fd if appropriate */
598148871Scperciva		if (chunked) {
599148871Scperciva			/* Handle a chunked-encoded entity */
600148871Scperciva
601148871Scperciva			/* Read chunks */
602148871Scperciva			do {
603148871Scperciva				error = readln(sd, resbuf, &resbuflen,
604148871Scperciva				    &resbufpos);
605148871Scperciva				if (error)
606148871Scperciva					goto conndied;
607148871Scperciva				hln = resbuf + resbufpos;
608148871Scperciva				eolp = strstr(hln, "\r\n");
609148871Scperciva				resbufpos = (eolp - resbuf) + 2;
610148871Scperciva
611148871Scperciva				clen = 0;
612148871Scperciva				while (isxdigit(*hln)) {
613148881Scperciva					if (clen >= OFF_MAX / 16) {
614148871Scperciva						/* Nasty people... */
615148871Scperciva						goto conndied;
616148871Scperciva					}
617148871Scperciva					if (isdigit(*hln))
618148871Scperciva						clen = clen * 16 + *hln - '0';
619148871Scperciva					else
620148871Scperciva						clen = clen * 16 + 10 +
621148871Scperciva						    tolower(*hln) - 'a';
622148871Scperciva					hln++;
623148871Scperciva				}
624148871Scperciva
625148871Scperciva				error = copybytes(sd, fd, clen, resbuf,
626148871Scperciva				    &resbuflen, &resbufpos);
627148871Scperciva				if (error) {
628148871Scperciva					goto conndied;
629148871Scperciva				}
630148871Scperciva			} while (clen != 0);
631148871Scperciva
632148871Scperciva			/* Read trailer and final CRLF */
633148871Scperciva			do {
634148871Scperciva				error = readln(sd, resbuf, &resbuflen,
635148871Scperciva				    &resbufpos);
636148871Scperciva				if (error)
637148871Scperciva					goto conndied;
638148871Scperciva				hln = resbuf + resbufpos;
639148871Scperciva				eolp = strstr(hln, "\r\n");
640148871Scperciva				resbufpos = (eolp - resbuf) + 2;
641148871Scperciva			} while (hln != eolp);
642148871Scperciva		} else if (contentlength != -1) {
643148871Scperciva			error = copybytes(sd, fd, contentlength, resbuf,
644148871Scperciva			    &resbuflen, &resbufpos);
645148871Scperciva			if (error)
646148871Scperciva				goto conndied;
647148871Scperciva		} else {
648148871Scperciva			/*
649148871Scperciva			 * Not chunked, and no content length header.
650148871Scperciva			 * Read everything until the server closes the
651148871Scperciva			 * socket.
652148871Scperciva			 */
653148881Scperciva			error = copybytes(sd, fd, OFF_MAX, resbuf,
654148871Scperciva			    &resbuflen, &resbufpos);
655148871Scperciva			if (error == -1)
656148871Scperciva				goto conndied;
657148871Scperciva			pipelined = 0;
658148871Scperciva		}
659148871Scperciva
660148871Scperciva		if (fd != -1) {
661148871Scperciva			close(fd);
662148871Scperciva			fd = -1;
663148871Scperciva		}
664148871Scperciva
665148871Scperciva		fprintf(stderr, "http://%s/%s: %d ", servername, argv[nres],
666148871Scperciva		    statuscode);
667148871Scperciva		if (statuscode == 200)
668148871Scperciva			fprintf(stderr, "OK\n");
669148871Scperciva		else if (statuscode < 300)
670148871Scperciva			fprintf(stderr, "Successful (ignored)\n");
671148871Scperciva		else if (statuscode < 400)
672148871Scperciva			fprintf(stderr, "Redirection (ignored)\n");
673148871Scperciva		else
674148871Scperciva			fprintf(stderr, "Error (ignored)\n");
675148871Scperciva
676148871Scperciva		/* We've finished this file! */
677148871Scperciva		nres++;
678148871Scperciva
679148871Scperciva		/*
680148871Scperciva		 * If necessary, clean up this connection so that we
681148871Scperciva		 * can start a new one.
682148871Scperciva		 */
683171120Scperciva		if (pipelined == 0 && keepalive == 0)
684148871Scperciva			goto cleanupconn;
685148871Scperciva		continue;
686148871Scperciva
687148871Scpercivaconndied:
688148871Scperciva		/*
689148871Scperciva		 * Something went wrong -- our connection died, the server
690148871Scperciva		 * sent us garbage, etc.  If this happened on the first
691148871Scperciva		 * request we sent over this connection, give up.  Otherwise,
692148871Scperciva		 * close this connection, open a new one, and reissue the
693148871Scperciva		 * request.
694148871Scperciva		 */
695148871Scperciva		if (nres == firstreq)
696148871Scperciva			errx(1, "Connection failure");
697148871Scperciva
698148871Scpercivacleanupconn:
699148871Scperciva		/*
700148871Scperciva		 * Clean up our connection and keep on going
701148871Scperciva		 */
702148871Scperciva		shutdown(sd, SHUT_RDWR);
703148871Scperciva		close(sd);
704148871Scperciva		sd = -1;
705148871Scperciva		if (fd != -1) {
706148871Scperciva			close(fd);
707148871Scperciva			fd = -1;
708148871Scperciva		}
709148871Scperciva		if (reqbuf != NULL) {
710148871Scperciva			free(reqbuf);
711148871Scperciva			reqbuf = NULL;
712148871Scperciva		}
713148871Scperciva		nreq = nres;
714148871Scperciva		res = res0;
715148871Scperciva		pipelined = 0;
716148871Scperciva		resbufpos = resbuflen = 0;
717148871Scperciva		continue;
718148871Scperciva	}
719148871Scperciva
720148871Scperciva	free(resbuf);
721148871Scperciva	freeaddrinfo(res0);
722148871Scperciva
723148871Scperciva	return 0;
724148871Scperciva}
725