1 /* vi: set sw=4 ts=4: */
3 * wget - retrieve a file using HTTP
5 * Chip Rosenthal Covad Communications <chip@laserlink.net>
7 * Note: According to RFC2616 section 3.6.1, "All HTTP/1.1 applications MUST be
8 * able to receive and decode the "chunked" transfer-coding, and MUST ignore
9 * chunk-extension extensions they do not understand."
11 * This prevents this particular wget app from completely RFC compliant, and as
12 * such, prevents it from being used as a general purpose web browser... This
13 * is a design decision, since it makes the code smaller.
26 #include <sys/ioctl.h>
29 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
36 /* Stupid libc5 doesn't define this... */
38 #define timersub(a, b, result) \
40 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
41 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
42 if ((result)->tv_usec < 0) { \
44 (result)->tv_usec += 1000000; \
49 void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path);
50 FILE *open_socket(char *host, int port);
51 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
52 void progressmeter(int flag);
54 /* Globals (can be accessed from signal handlers */
55 static off_t filesize = 0; /* content-length of the file */
56 #ifdef BB_FEATURE_WGET_STATUSBAR
57 static char *curfile; /* Name of current file being transferred. */
58 static struct timeval start; /* Time a transfer started. */
59 volatile unsigned long statbytes; /* Number of bytes transferred so far. */
60 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
61 static const int STALLTIME = 5;
64 void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
66 if (output != stdout && do_continue==0) {
72 int wget_main(int argc, char **argv)
75 char *proxy, *proxy_host;
76 int uri_port, proxy_port;
80 FILE *sfp; /* socket to web server */
81 char *uri_host, *uri_path; /* parsed from command line url */
82 char *fname_out = NULL; /* where to direct output (-O) */
83 int do_continue = 0; /* continue a prev transfer (-c) */
84 long beg_range = 0L; /* range at which continue begins */
85 int got_clen = 0; /* got content-length: from server */
86 FILE *output; /* socket to web server */
87 int quiet_flag = FALSE; /* Be verry, verry quiet... */
92 while ((n = getopt(argc, argv, "cqO:")) != EOF) {
101 /* can't set fname_out to NULL if outputting to stdout, because
102 * this gets interpreted as the auto-gen output filename
103 * case below - tausq@debian.org
105 fname_out = (strcmp(optarg, "-") == 0 ? (char *)1 : optarg);
112 if (argc - optind != 1)
116 * Use the proxy if necessary.
118 if ((proxy = getenv("http_proxy")) != NULL) {
119 proxy = xstrdup(proxy);
120 parse_url(proxy, &proxy_host, &proxy_port, &uri_path);
121 parse_url(argv[optind], &uri_host, &uri_port, &uri_path);
124 * Parse url into components.
126 parse_url(argv[optind], &uri_host, &uri_port, &uri_path);
131 /* Guess an output filename */
134 #ifdef BB_FEATURE_WGET_STATUSBAR
137 get_last_path_component(uri_path);
138 if (fname_out==NULL || strlen(fname_out)<1) {
140 #ifdef BB_FEATURE_WGET_STATUSBAR
145 #ifdef BB_FEATURE_WGET_STATUSBAR
147 curfile=argv[optind];
150 if (do_continue && !fname_out)
151 error_msg_and_die("cannot specify continue (-c) without a filename (-O)\n");
155 * Open socket to server.
157 sfp = open_socket(proxy_host, proxy_port);
159 /* Make the assumption that if the file already exists
160 * on disk that the intention is to continue downloading
161 * a previously aborted download -Erik */
162 if (stat(fname_out, &sbuf) == 0) {
167 * Open the output file stream.
169 if (fname_out != (char *)1) {
170 if ( (output=fopen(fname_out, (do_continue ? "a" : "w"))) == NULL)
171 perror_msg_and_die("fopen(%s)", fname_out);
177 * Determine where to start transfer.
180 if (fstat(fileno(output), &sbuf) < 0)
181 perror_msg_and_die("fstat()");
182 if (sbuf.st_size > 0)
183 beg_range = sbuf.st_size;
191 fprintf(sfp, "GET http://%s:%d/%s HTTP/1.1\r\n",
192 uri_host, uri_port, uri_path);
193 fprintf(sfp, "Host: %s\r\nUser-Agent: Wget\r\n", uri_host);
196 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
197 fprintf(sfp,"Connection: close\r\n\r\n");
200 * Retrieve HTTP response line and check for "200" status code.
202 if (fgets(buf, sizeof(buf), sfp) == NULL) {
203 close_and_delete_outfile(output, fname_out, do_continue);
204 error_msg_and_die("no response from server\n");
206 for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
208 for ( ; isspace(*s) ; ++s)
219 close_and_delete_outfile(output, fname_out, do_continue);
220 error_msg_and_die("server returned error %d: %s", atoi(s), buf);
224 * Retrieve HTTP headers.
226 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
227 if (strcasecmp(buf, "content-length") == 0) {
232 if (strcasecmp(buf, "transfer-encoding") == 0) {
233 close_and_delete_outfile(output, fname_out, do_continue);
234 error_msg_and_die("server wants to do %s transfer encoding\n", s);
240 * Retrieve HTTP body.
242 #ifdef BB_FEATURE_WGET_STATUSBAR
244 if (quiet_flag==FALSE)
247 while (filesize > 0 && (n = fread(buf, 1, sizeof(buf), sfp)) > 0) {
248 fwrite(buf, 1, n, output);
249 #ifdef BB_FEATURE_WGET_STATUSBAR
251 if (quiet_flag==FALSE)
257 if (n == 0 && ferror(sfp))
258 perror_msg_and_die("network read error");
264 void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path)
270 if (strncmp(url, "http://", 7) != 0)
271 error_msg_and_die("not an http url: %s\n", url);
275 cp = strchr(*uri_host, ':');
276 sp = strchr(*uri_host, '/');
278 if (cp != NULL && (sp == NULL || cp < sp)) {
280 *uri_port = atoi(cp);
291 FILE *open_socket(char *host, int port)
293 struct sockaddr_in sin;
298 memset(&sin, 0, sizeof(sin));
299 sin.sin_family = AF_INET;
300 if ((hp = (struct hostent *) gethostbyname(host)) == NULL)
301 error_msg_and_die("cannot resolve %s\n", host);
302 memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
303 sin.sin_port = htons(port);
306 * Get the server onto a stdio stream.
308 if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
309 perror_msg_and_die("socket()");
310 if (connect(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
311 perror_msg_and_die("connect(%s)", host);
312 if ((fp = fdopen(fd, "r+")) == NULL)
313 perror_msg_and_die("fdopen()");
319 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
326 /* retrieve header line */
327 if (fgets(buf, bufsiz, fp) == NULL)
330 /* see if we are at the end of the headers */
331 for (s = buf ; *s == '\r' ; ++s)
336 /* convert the header name to lower case */
337 for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
340 /* verify we are at the end of the header name */
342 error_msg_and_die("bad header line: %s\n", buf);
344 /* locate the start of the header value */
345 for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
349 /* locate the end of header */
350 while (*s != '\0' && *s != '\r' && *s != '\n')
353 /* end of header found */
359 /* Rats! The buffer isn't big enough to hold the entire header value. */
360 while (c = getc(fp), c != EOF && c != '\n')
366 #ifdef BB_FEATURE_WGET_STATUSBAR
367 /* Stuff below is from BSD rcp util.c, as added to openshh.
368 * Original copyright notice is retained at the end of this file.
376 struct winsize winsize;
378 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
379 return (winsize.ws_col ? winsize.ws_col : 80);
385 updateprogressmeter(int ignore)
387 int save_errno = errno;
396 struct itimerval itv;
398 itv.it_value.tv_sec = wait;
399 itv.it_value.tv_usec = 0;
400 itv.it_interval = itv.it_value;
401 setitimer(ITIMER_REAL, &itv, NULL);
406 progressmeter(int flag)
408 static const char prefixes[] = " KMGTP";
409 static struct timeval lastupdate;
410 static off_t lastsize;
411 struct timeval now, td, wait;
412 off_t cursize, abbrevsize;
414 int ratio, barlength, i, remaining;
418 (void) gettimeofday(&start, (struct timezone *) 0);
423 (void) gettimeofday(&now, (struct timezone *) 0);
426 ratio = 100.0 * cursize / filesize;
427 ratio = MAX(ratio, 0);
428 ratio = MIN(ratio, 100);
432 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
434 barlength = getttywidth() - 51;
436 i = barlength * ratio / 100;
437 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
439 "*****************************************************************************"
440 "*****************************************************************************",
444 abbrevsize = cursize;
445 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
449 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
450 (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
453 timersub(&now, &lastupdate, &wait);
454 if (cursize > lastsize) {
457 if (wait.tv_sec >= STALLTIME) {
458 start.tv_sec += wait.tv_sec;
459 start.tv_usec += wait.tv_usec;
463 timersub(&now, &start, &td);
464 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
466 if (statbytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
467 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
469 } else if (wait.tv_sec >= STALLTIME) {
470 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
473 remaining = (int) (filesize / (statbytes / elapsed) - elapsed);
474 i = remaining / 3600;
476 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
479 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
481 i = remaining % 3600;
482 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
483 "%02d:%02d ETA", i / 60, i % 60);
485 write(fileno(stderr), buf, strlen(buf));
489 sa.sa_handler = updateprogressmeter;
490 sigemptyset(&sa.sa_mask);
491 sa.sa_flags = SA_RESTART;
492 sigaction(SIGALRM, &sa, NULL);
494 } else if (flag == 1) {
501 /* Original copyright notice which applies to the BB_FEATURE_WGET_STATUSBAR stuff,
502 * much of which was blatently stolen from openssh. */
505 * Copyright (c) 1992, 1993
506 * The Regents of the University of California. All rights reserved.
508 * Redistribution and use in source and binary forms, with or without
509 * modification, are permitted provided that the following conditions
511 * 1. Redistributions of source code must retain the above copyright
512 * notice, this list of conditions and the following disclaimer.
513 * 2. Redistributions in binary form must reproduce the above copyright
514 * notice, this list of conditions and the following disclaimer in the
515 * documentation and/or other materials provided with the distribution.
517 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
518 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
520 * 4. Neither the name of the University nor the names of its contributors
521 * may be used to endorse or promote products derived from this software
522 * without specific prior written permission.
524 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
525 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
526 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
527 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
528 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
529 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
530 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
531 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
532 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
533 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
536 * $Id: wget.c,v 1.23 2001/01/27 08:24:38 andersen Exp $
543 c-file-style: "linux"