2 * Copyright 2005 Colin Percival
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted providing 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 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
22 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
23 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24 * POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <sys/types.h>
32 #include <sys/socket.h>
47 static const char * env_HTTP_PROXY;
48 static char * env_HTTP_PROXY_AUTH;
49 static const char * env_HTTP_USER_AGENT;
50 static char * env_HTTP_TIMEOUT;
51 static const char * proxyport;
52 static char * proxyauth;
54 static struct timeval timo = { 15, 0};
60 fprintf(stderr, "usage: phttpget server [file ...]\n");
65 * Base64 encode a string; the string returned, if non-NULL, is
66 * allocated using malloc() and must be freed by the caller.
69 b64enc(const char *ptext)
71 static const char base64[] =
72 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
73 "abcdefghijklmnopqrstuvwxyz"
82 * Encoded length is 4 characters per 3-byte block or partial
83 * block of plaintext, plus one byte for the terminating NUL
85 ptlen = strlen(ptext);
86 if (ptlen > ((SIZE_MAX - 1) / 4) * 3 - 2)
87 return NULL; /* Possible integer overflow */
88 ctlen = 4 * ((ptlen + 2) / 3) + 1;
89 if ((ctext = malloc(ctlen)) == NULL)
94 * Scan through ptext, reading up to 3 bytes from ptext and
95 * writing 4 bytes to ctext, until we run out of input.
97 for (pt = ptext, pc = ctext; ptlen; ptlen -= 3, pc += 4) {
99 for (t = j = 0; j < 3; j++) {
106 for (j = 0; j < 4; j++) {
108 pc[j] = base64[(t >> 18) & 0x3f];
114 /* If we're done, exit the loop */
125 char *proxy_auth_userpass, *proxy_auth_userpass64, *p;
126 char *proxy_auth_user = NULL;
127 char *proxy_auth_pass = NULL;
130 env_HTTP_PROXY = getenv("HTTP_PROXY");
131 if (env_HTTP_PROXY == NULL)
132 env_HTTP_PROXY = getenv("http_proxy");
133 if (env_HTTP_PROXY != NULL) {
134 if (strncmp(env_HTTP_PROXY, "http://", 7) == 0)
136 p = strchr(env_HTTP_PROXY, '/');
139 p = strchr(env_HTTP_PROXY, ':');
147 env_HTTP_PROXY_AUTH = getenv("HTTP_PROXY_AUTH");
148 if ((env_HTTP_PROXY != NULL) &&
149 (env_HTTP_PROXY_AUTH != NULL) &&
150 (strncasecmp(env_HTTP_PROXY_AUTH, "basic:" , 6) == 0)) {
151 /* Ignore authentication scheme */
152 (void) strsep(&env_HTTP_PROXY_AUTH, ":");
155 (void) strsep(&env_HTTP_PROXY_AUTH, ":");
157 /* Obtain username and password */
158 proxy_auth_user = strsep(&env_HTTP_PROXY_AUTH, ":");
159 proxy_auth_pass = env_HTTP_PROXY_AUTH;
162 if ((proxy_auth_user != NULL) && (proxy_auth_pass != NULL)) {
163 asprintf(&proxy_auth_userpass, "%s:%s",
164 proxy_auth_user, proxy_auth_pass);
165 if (proxy_auth_userpass == NULL)
168 proxy_auth_userpass64 = b64enc(proxy_auth_userpass);
169 if (proxy_auth_userpass64 == NULL)
172 asprintf(&proxyauth, "Proxy-Authorization: Basic %s\r\n",
173 proxy_auth_userpass64);
174 if (proxyauth == NULL)
177 free(proxy_auth_userpass);
178 free(proxy_auth_userpass64);
182 env_HTTP_USER_AGENT = getenv("HTTP_USER_AGENT");
183 if (env_HTTP_USER_AGENT == NULL)
184 env_HTTP_USER_AGENT = "phttpget/0.1";
186 env_HTTP_TIMEOUT = getenv("HTTP_TIMEOUT");
187 if (env_HTTP_TIMEOUT != NULL) {
188 http_timeout = strtol(env_HTTP_TIMEOUT, &p, 10);
189 if ((*env_HTTP_TIMEOUT == '\0') || (*p != '\0') ||
191 warnx("HTTP_TIMEOUT (%s) is not a positive integer",
194 timo.tv_sec = http_timeout;
199 makerequest(char ** buf, char * path, char * server, int connclose)
203 buflen = asprintf(buf,
204 "GET %s%s/%s HTTP/1.1\r\n"
210 env_HTTP_PROXY ? "http://" : "",
211 env_HTTP_PROXY ? server : "",
212 path, server, env_HTTP_USER_AGENT,
213 proxyauth ? proxyauth : "",
214 connclose ? "Connection: Close\r\n" : "Connection: Keep-Alive\r\n");
221 readln(int sd, char * resbuf, int * resbuflen, int * resbufpos)
225 while (strnstr(resbuf + *resbufpos, "\r\n",
226 *resbuflen - *resbufpos) == NULL) {
227 /* Move buffered data to the start of the buffer */
228 if (*resbufpos != 0) {
229 memmove(resbuf, resbuf + *resbufpos,
230 *resbuflen - *resbufpos);
231 *resbuflen -= *resbufpos;
235 /* If the buffer is full, complain */
236 if (*resbuflen == BUFSIZ)
239 /* Read more data into the buffer */
240 len = recv(sd, resbuf + *resbuflen, BUFSIZ - *resbuflen, 0);
242 ((len == -1) && (errno != EINTR)))
253 copybytes(int sd, int fd, off_t copylen, char * resbuf, int * resbuflen,
259 /* Write data from resbuf to fd */
260 len = *resbuflen - *resbufpos;
265 len = write(fd, resbuf + *resbufpos, len);
273 /* Read more data into buffer */
274 len = recv(sd, resbuf, BUFSIZ, 0);
279 } else if (len == 0) {
291 main(int argc, char *argv[])
293 struct addrinfo hints; /* Hints to getaddrinfo */
294 struct addrinfo *res; /* Pointer to server address being used */
295 struct addrinfo *res0; /* Pointer to server addresses */
296 char * resbuf = NULL; /* Response buffer */
297 int resbufpos = 0; /* Response buffer position */
298 int resbuflen = 0; /* Response buffer length */
299 char * eolp; /* Pointer to "\r\n" within resbuf */
300 char * hln; /* Pointer within header line */
301 char * servername; /* Name of server */
302 char * fname = NULL; /* Name of downloaded file */
303 char * reqbuf = NULL; /* Request buffer */
304 int reqbufpos = 0; /* Request buffer position */
305 int reqbuflen = 0; /* Request buffer length */
306 ssize_t len; /* Length sent or received */
307 int nreq = 0; /* Number of next request to send */
308 int nres = 0; /* Number of next reply to receive */
309 int pipelined = 0; /* != 0 if connection in pipelined mode. */
310 int keepalive; /* != 0 if HTTP/1.0 keep-alive rcvd. */
311 int sd = -1; /* Socket descriptor */
312 int sdflags = 0; /* Flags on the socket sd */
313 int fd = -1; /* Descriptor for download target file */
314 int error; /* Error code */
315 int statuscode; /* HTTP Status code */
316 off_t contentlength; /* Value from Content-Length header */
317 int chunked; /* != if transfer-encoding is chunked */
318 off_t clen; /* Chunk length */
319 int firstreq = 0; /* # of first request for this connection */
320 int val; /* Value used for setsockopt call */
322 /* Check that the arguments are sensible */
326 /* Read important environment variables */
329 /* Get server name and adjust arg[cv] to point at file names */
330 servername = argv[1];
334 /* Allocate response buffer */
335 resbuf = malloc(BUFSIZ);
340 memset(&hints, 0, sizeof(hints));
341 hints.ai_family = PF_UNSPEC;
342 hints.ai_socktype = SOCK_STREAM;
343 error = getaddrinfo(env_HTTP_PROXY ? env_HTTP_PROXY : servername,
344 env_HTTP_PROXY ? proxyport : "http", &hints, &res0);
346 errx(1, "host = %s, port = %s: %s",
347 env_HTTP_PROXY ? env_HTTP_PROXY : servername,
348 env_HTTP_PROXY ? proxyport : "http",
349 gai_strerror(error));
351 errx(1, "could not look up %s", servername);
354 /* Do the fetching */
355 while (nres < argc) {
356 /* Make sure we have a connected socket */
357 for (; sd == -1; res = res->ai_next) {
358 /* No addresses left to try :-( */
360 errx(1, "Could not connect to %s", servername);
362 /* Create a socket... */
363 sd = socket(res->ai_family, res->ai_socktype,
368 /* ... set 15-second timeouts ... */
369 setsockopt(sd, SOL_SOCKET, SO_SNDTIMEO,
370 (void *)&timo, (socklen_t)sizeof(timo));
371 setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO,
372 (void *)&timo, (socklen_t)sizeof(timo));
374 /* ... disable SIGPIPE generation ... */
376 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE,
377 (void *)&val, sizeof(int));
379 /* ... and connect to the server. */
380 if(connect(sd, res->ai_addr, res->ai_addrlen)) {
390 * If in pipelined HTTP mode, put socket into non-blocking
391 * mode, since we're probably going to want to try to send
392 * several HTTP requests.
395 sdflags = fcntl(sd, F_GETFL);
396 if (fcntl(sd, F_SETFL, sdflags | O_NONBLOCK) == -1)
400 /* Construct requests and/or send them without blocking */
401 while ((nreq < argc) && ((reqbuf == NULL) || pipelined)) {
402 /* If not in the middle of a request, make one */
403 if (reqbuf == NULL) {
404 reqbuflen = makerequest(&reqbuf, argv[nreq],
405 servername, (nreq == argc - 1));
409 /* If in pipelined mode, try to send the request */
411 while (reqbufpos < reqbuflen) {
412 len = send(sd, reqbuf + reqbufpos,
413 reqbuflen - reqbufpos, 0);
418 if (reqbufpos < reqbuflen) {
430 /* Put connection back into blocking mode */
432 if (fcntl(sd, F_SETFL, sdflags) == -1)
436 /* Do we need to blocking-send a request? */
438 while (reqbufpos < reqbuflen) {
439 len = send(sd, reqbuf + reqbufpos,
440 reqbuflen - reqbufpos, 0);
450 /* Scan through the response processing headers. */
456 /* Get a header line */
457 error = readln(sd, resbuf, &resbuflen, &resbufpos);
460 hln = resbuf + resbufpos;
461 eolp = strnstr(hln, "\r\n", resbuflen - resbufpos);
462 resbufpos = (eolp - resbuf) + 2;
465 /* Make sure it doesn't contain a NUL character */
466 if (strchr(hln, '\0') != eolp)
469 if (statuscode == 0) {
470 /* The first line MUST be HTTP/1.x xxx ... */
471 if ((strncmp(hln, "HTTP/1.", 7) != 0) ||
476 * If the minor version number isn't zero,
477 * then we can assume that pipelining our
478 * requests is OK -- as long as we don't
479 * see a "Connection: close" line later
480 * and we either have a Content-Length or
481 * Transfer-Encoding: chunked header to
482 * tell us the length.
487 /* Skip over the minor version number */
488 hln = strchr(hln + 7, ' ');
494 /* Read the status code */
495 while (isdigit(*hln)) {
496 statuscode = statuscode * 10 +
501 if (statuscode < 100 || statuscode > 599)
504 /* Ignore the rest of the line */
509 * Check for "Connection: close" or
510 * "Connection: Keep-Alive" header
512 if (strncasecmp(hln, "Connection:", 11) == 0) {
514 if (strcasestr(hln, "close") != NULL)
516 if (strcasestr(hln, "Keep-Alive") != NULL)
523 /* Check for "Content-Length:" header */
524 if (strncasecmp(hln, "Content-Length:", 15) == 0) {
528 /* Find the start of the length */
529 while (!isdigit(*hln) && (*hln != '\0'))
532 /* Compute the length */
533 while (isdigit(*hln)) {
534 if (contentlength >= OFF_MAX / 10) {
535 /* Nasty people... */
538 contentlength = contentlength * 10 +
547 /* Check for "Transfer-Encoding: chunked" header */
548 if (strncasecmp(hln, "Transfer-Encoding:", 18) == 0) {
550 if (strcasestr(hln, "chunked") != NULL)
557 /* We blithely ignore any other header lines */
559 /* No more header lines */
560 if (strlen(hln) == 0) {
562 * If the status code was 1xx, then there will
563 * be a real header later. Servers may emit
564 * 1xx header blocks at will, but since we
565 * don't expect one, we should just ignore it.
567 if (100 <= statuscode && statuscode <= 199) {
572 /* End of header; message body follows */
577 /* No message body for 204 or 304 */
578 if (statuscode == 204 || statuscode == 304) {
584 * There should be a message body coming, but we only want
585 * to send it to a file if the status code is 200
587 if (statuscode == 200) {
588 /* Generate a file name for the download */
589 fname = strrchr(argv[nres], '/');
594 if (strlen(fname) == 0)
595 errx(1, "Cannot obtain file name from %s\n",
598 fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY, 0644);
600 errx(1, "open(%s)", fname);
603 /* Read the message and send data to fd if appropriate */
605 /* Handle a chunked-encoded entity */
609 error = readln(sd, resbuf, &resbuflen,
613 hln = resbuf + resbufpos;
614 eolp = strstr(hln, "\r\n");
615 resbufpos = (eolp - resbuf) + 2;
618 while (isxdigit(*hln)) {
619 if (clen >= OFF_MAX / 16) {
620 /* Nasty people... */
624 clen = clen * 16 + *hln - '0';
626 clen = clen * 16 + 10 +
631 error = copybytes(sd, fd, clen, resbuf,
632 &resbuflen, &resbufpos);
638 /* Read trailer and final CRLF */
640 error = readln(sd, resbuf, &resbuflen,
644 hln = resbuf + resbufpos;
645 eolp = strstr(hln, "\r\n");
646 resbufpos = (eolp - resbuf) + 2;
647 } while (hln != eolp);
648 } else if (contentlength != -1) {
649 error = copybytes(sd, fd, contentlength, resbuf,
650 &resbuflen, &resbufpos);
655 * Not chunked, and no content length header.
656 * Read everything until the server closes the
659 error = copybytes(sd, fd, OFF_MAX, resbuf,
660 &resbuflen, &resbufpos);
671 fprintf(stderr, "http://%s/%s: %d ", servername, argv[nres],
673 if (statuscode == 200)
674 fprintf(stderr, "OK\n");
675 else if (statuscode < 300)
676 fprintf(stderr, "Successful (ignored)\n");
677 else if (statuscode < 400)
678 fprintf(stderr, "Redirection (ignored)\n");
680 fprintf(stderr, "Error (ignored)\n");
682 /* We've finished this file! */
686 * If necessary, clean up this connection so that we
687 * can start a new one.
689 if (pipelined == 0 && keepalive == 0)
695 * Something went wrong -- our connection died, the server
696 * sent us garbage, etc. If this happened on the first
697 * request we sent over this connection, give up. Otherwise,
698 * close this connection, open a new one, and reissue the
701 if (nres == firstreq)
702 errx(1, "Connection failure");
706 * Clean up our connection and keep on going
708 shutdown(sd, SHUT_RDWR);
715 if (reqbuf != NULL) {
722 resbufpos = resbuflen = 0;