1 /* vi: set sw=4 ts=4: */
3 * wget - retrieve a file using HTTP or FTP
5 * Chip Rosenthal Covad Communications <chip@laserlink.net>
18 #include <sys/ioctl.h>
20 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
39 static void parse_url(char *url, struct host_info *h);
40 static FILE *open_socket(struct sockaddr_in *s_in);
41 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
42 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf);
44 /* Globals (can be accessed from signal handlers */
45 static off_t filesize; /* content-length of the file */
46 static int chunked; /* chunked transfer encoding */
47 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
48 static void progressmeter(int flag);
49 static char *curfile; /* Name of current file being transferred. */
50 static struct timeval start; /* Time a transfer started. */
51 static off_t transferred; /* Number of bytes transferred so far. */
52 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
57 static inline void progressmeter(int flag) {}
60 static void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
62 if (output != stdout && do_continue==0) {
68 /* Read NMEMB elements of SIZE bytes into PTR from STREAM. Returns the
69 * number of elements read, and a short count if an eof or non-interrupt
70 * error is encountered. */
71 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
77 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
78 } while (ret < nmemb && ferror(stream) && errno == EINTR);
83 /* Write NMEMB elements of SIZE bytes from PTR to STREAM. Returns the
84 * number of elements written, and a short count if an eof or non-interrupt
85 * error is encountered. */
86 static size_t safe_fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)
92 ret += fwrite((char *)ptr + (ret * size), size, nmemb - ret, stream);
93 } while (ret < nmemb && ferror(stream) && errno == EINTR);
98 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
99 * Returns S, or NULL if an eof or non-interrupt error is encountered. */
100 static char *safe_fgets(char *s, int size, FILE *stream)
106 ret = fgets(s, size, stream);
107 } while (ret == NULL && ferror(stream) && errno == EINTR);
112 #define close_delete_and_die(s...) { \
113 close_and_delete_outfile(output, fname_out, do_continue); \
114 bb_error_msg_and_die(s); }
117 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
119 * Base64-encode character string
120 * oops... isn't something similar in uuencode.c?
121 * XXX: It would be better to use already existing code
123 static char *base64enc(unsigned char *p, char *buf, int len) {
125 char al[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
131 bb_error_msg_and_die("buffer overflow");
132 *(s++) = al[(*p >> 2) & 0x3F];
133 *(s++) = al[((*p << 4) & 0x30) | ((*(p+1) >> 4) & 0x0F)];
137 *(s++) = al[((*p << 2) & 0x3C) | ((*(p+1) >> 6) & 0x03)];
139 *(s++) = al[*(p++) & 0x3F];
146 #define WGET_OPT_CONTINUE 1
147 #define WGET_OPT_QUIET 2
148 #define WGET_OPT_PASSIVE 4
149 #define WGET_OPT_OUTNAME 8
150 #define WGET_OPT_HEADER 16
151 #define WGET_OPT_PREFIX 32
152 #define WGET_OPT_PROXY 64
154 #if ENABLE_WGET_LONG_OPTIONS
155 static const struct option wget_long_options[] = {
156 { "continue", 0, NULL, 'c' },
157 { "quiet", 0, NULL, 'q' },
158 { "passive-ftp", 0, NULL, 139 },
159 { "output-document", 1, NULL, 'O' },
160 { "header", 1, NULL, 131 },
161 { "directory-prefix",1, NULL, 'P' },
162 { "proxy", 1, NULL, 'Y' },
167 int wget_main(int argc, char **argv)
169 int n, try=5, status;
173 char *dir_prefix=NULL;
176 char extra_headers[1024];
177 char *extra_headers_ptr = extra_headers;
178 int extra_headers_left = sizeof(extra_headers);
179 struct host_info server, target;
180 struct sockaddr_in s_in;
181 llist_t *headers_llist = NULL;
183 FILE *sfp = NULL; /* socket to web/ftp server */
184 FILE *dfp = NULL; /* socket to ftp server (data) */
185 char *fname_out = NULL; /* where to direct output (-O) */
186 int do_continue = 0; /* continue a prev transfer (-c) */
187 long beg_range = 0L; /* range at which continue begins */
188 int got_clen = 0; /* got content-length: from server */
189 FILE *output; /* socket to web server */
190 int quiet_flag = FALSE; /* Be verry, verry quiet... */
191 int use_proxy = 1; /* Use proxies if env vars are set */
192 char *proxy_flag = "on"; /* Use proxies if env vars are set */
195 * Crack command line.
197 bb_opt_complementally = "-1:\203::";
198 #if ENABLE_WGET_LONG_OPTIONS
199 bb_applet_long_options = wget_long_options;
201 opt = bb_getopt_ulflags(argc, argv, "cq\213O:\203:P:Y:",
202 &fname_out, &headers_llist,
203 &dir_prefix, &proxy_flag);
204 if (opt & WGET_OPT_CONTINUE) {
207 if (opt & WGET_OPT_QUIET) {
210 if (strcmp(proxy_flag, "off") == 0) {
211 /* Use the proxy if necessary. */
214 if (opt & WGET_OPT_HEADER) {
215 while (headers_llist) {
216 int arglen = strlen(headers_llist->data);
217 if (extra_headers_left - arglen - 2 <= 0)
218 bb_error_msg_and_die("extra_headers buffer too small(need %i)", extra_headers_left - arglen);
219 strcpy(extra_headers_ptr, headers_llist->data);
220 extra_headers_ptr += arglen;
221 extra_headers_left -= ( arglen + 2 );
222 *extra_headers_ptr++ = '\r';
223 *extra_headers_ptr++ = '\n';
224 *(extra_headers_ptr + 1) = 0;
225 headers_llist = headers_llist->link;
229 parse_url(argv[optind], &target);
230 server.host = target.host;
231 server.port = target.port;
234 * Use the proxy if necessary.
237 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
238 if (proxy && *proxy) {
239 parse_url(bb_xstrdup(proxy), &server);
245 /* Guess an output filename */
247 // Dirty hack. Needed because bb_get_last_path_component
248 // will destroy trailing / by storing '\0' in last byte!
249 if(*target.path && target.path[strlen(target.path)-1]!='/') {
251 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
254 bb_get_last_path_component(target.path);
256 if (fname_out==NULL || strlen(fname_out)<1) {
258 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
263 if (dir_prefix != NULL)
264 fname_out = concat_path_file(dir_prefix, fname_out);
265 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
267 curfile = bb_get_last_path_component(fname_out);
270 if (do_continue && !fname_out)
271 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
275 * Open the output file stream.
277 if (strcmp(fname_out, "-") == 0) {
281 output = bb_xfopen(fname_out, (do_continue ? "a" : "w"));
285 * Determine where to start transfer.
288 if (fstat(fileno(output), &sbuf) < 0)
289 bb_perror_msg_and_die("fstat()");
290 if (sbuf.st_size > 0)
291 beg_range = sbuf.st_size;
296 /* We want to do exactly _one_ DNS lookup, since some
297 * sites (i.e. ftp.us.debian.org) use round-robin DNS
298 * and we want to connect to only one IP... */
299 bb_lookup_host(&s_in, server.host);
300 s_in.sin_port = server.port;
301 if (quiet_flag==FALSE) {
302 fprintf(stdout, "Connecting to %s[%s]:%d\n",
303 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
306 if (use_proxy || !target.is_ftp) {
311 got_clen = chunked = 0;
314 close_delete_and_die("too many redirections");
317 * Open socket to http server
319 if (sfp) fclose(sfp);
320 sfp = open_socket(&s_in);
326 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
327 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
328 if (strchr(target.host, ':'))
329 format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
332 target.is_ftp ? "f" : "ht", target.host,
333 ntohs(target.port), target.path);
335 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
338 fprintf(sfp, "Host: %s\r\nUser-Agent: Wget\r\n", target.host);
340 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
342 fprintf(sfp, "Authorization: Basic %s\r\n",
343 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
345 if (use_proxy && server.user) {
346 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
347 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
352 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
353 if(extra_headers_left < sizeof(extra_headers))
354 fputs(extra_headers,sfp);
355 fprintf(sfp,"Connection: close\r\n\r\n");
358 * Retrieve HTTP response line and check for "200" status code.
361 if (fgets(buf, sizeof(buf), sfp) == NULL)
362 close_delete_and_die("no response from server");
364 for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
366 for ( ; isspace(*s) ; ++s)
368 switch (status = atoi(s)) {
371 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
374 if (do_continue && output != stdout)
375 output = freopen(fname_out, "w", output);
378 case 300: /* redirection */
389 close_delete_and_die("server returned error %d: %s", atoi(s), buf);
393 * Retrieve HTTP headers.
395 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
396 if (strcasecmp(buf, "content-length") == 0) {
398 if (safe_strtoul(s, &value)) {
399 close_delete_and_die("content-length %s is garbage", s);
405 if (strcasecmp(buf, "transfer-encoding") == 0) {
406 if (strcasecmp(s, "chunked") == 0) {
407 chunked = got_clen = 1;
409 close_delete_and_die("server wants to do %s transfer encoding", s);
412 if (strcasecmp(buf, "location") == 0) {
414 target.path = bb_xstrdup(s+1);
416 parse_url(bb_xstrdup(s), &target);
417 if (use_proxy == 0) {
418 server.host = target.host;
419 server.port = target.port;
421 bb_lookup_host(&s_in, server.host);
422 s_in.sin_port = server.port;
427 } while(status >= 300);
437 target.user = bb_xstrdup("anonymous:busybox@");
439 sfp = open_socket(&s_in);
440 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
441 close_delete_and_die("%s", buf+4);
444 * Splitting username:password pair,
447 s = strchr(target.user, ':');
450 switch(ftpcmd("USER ", target.user, sfp, buf)) {
454 if (ftpcmd("PASS ", s, sfp, buf) == 230)
456 /* FALLTHRU (failed login) */
458 close_delete_and_die("ftp login: %s", buf+4);
461 ftpcmd("CDUP", NULL, sfp, buf);
462 ftpcmd("TYPE I", NULL, sfp, buf);
467 if (ftpcmd("SIZE /", target.path, sfp, buf) == 213) {
469 if (safe_strtoul(buf+4, &value)) {
470 close_delete_and_die("SIZE value is garbage");
477 * Entering passive mode
479 if (ftpcmd("PASV", NULL, sfp, buf) != 227)
480 close_delete_and_die("PASV: %s", buf+4);
481 s = strrchr(buf, ',');
484 s = strrchr(buf, ',');
485 port += atoi(s+1) * 256;
486 s_in.sin_port = htons(port);
487 dfp = open_socket(&s_in);
490 sprintf(buf, "REST %ld", beg_range);
491 if (ftpcmd(buf, NULL, sfp, buf) != 350) {
492 if (output != stdout)
493 output = freopen(fname_out, "w", output);
496 filesize -= beg_range;
499 if (ftpcmd("RETR /", target.path, sfp, buf) > 150)
500 close_delete_and_die("RETR: %s", buf+4);
508 fgets(buf, sizeof(buf), dfp);
509 filesize = strtol(buf, (char **) NULL, 16);
512 if (quiet_flag==FALSE)
516 while ((filesize > 0 || !got_clen) && (n = safe_fread(buf, 1, ((chunked || got_clen) && (filesize < sizeof(buf)) ? filesize : sizeof(buf)), dfp)) > 0) {
517 if (safe_fwrite(buf, 1, n, output) != n) {
518 bb_perror_msg_and_die(bb_msg_write_error);
520 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
529 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
530 safe_fgets(buf, sizeof(buf), dfp);
531 filesize = strtol(buf, (char **) NULL, 16);
533 chunked = 0; /* all done! */
537 if (n == 0 && ferror(dfp)) {
538 bb_perror_msg_and_die(bb_msg_read_error);
542 if (quiet_flag==FALSE)
545 if ((use_proxy == 0) && target.is_ftp) {
547 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
548 bb_error_msg_and_die("ftp error: %s", buf+4);
549 ftpcmd("QUIT", NULL, sfp, buf);
555 void parse_url(char *url, struct host_info *h)
557 char *cp, *sp, *up, *pp;
559 if (strncmp(url, "http://", 7) == 0) {
560 h->port = bb_lookup_port("http", "tcp", 80);
563 } else if (strncmp(url, "ftp://", 6) == 0) {
564 h->port = bb_lookup_port("ftp", "tfp", 21);
568 bb_error_msg_and_die("not an http or ftp url: %s", url);
570 sp = strchr(h->host, '/');
575 h->path = bb_xstrdup("");
577 up = strrchr(h->host, '@');
587 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
588 if (h->host[0] == '[') {
592 while (*ep == ':' || isxdigit (*ep))
602 cp = strchr(pp, ':');
605 h->port = htons(atoi(cp));
610 FILE *open_socket(struct sockaddr_in *s_in)
614 fp = fdopen(xconnect(s_in), "r+");
616 bb_perror_msg_and_die("fdopen()");
622 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
629 /* retrieve header line */
630 if (fgets(buf, bufsiz, fp) == NULL)
633 /* see if we are at the end of the headers */
634 for (s = buf ; *s == '\r' ; ++s)
639 /* convert the header name to lower case */
640 for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
643 /* verify we are at the end of the header name */
645 bb_error_msg_and_die("bad header line: %s", buf);
647 /* locate the start of the header value */
648 for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
652 /* locate the end of header */
653 while (*s != '\0' && *s != '\r' && *s != '\n')
656 /* end of header found */
662 /* Rats! The buffer isn't big enough to hold the entire header value. */
663 while (c = getc(fp), c != EOF && c != '\n')
669 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
673 fprintf(fp, "%s%s\r\n", s1, s2);
680 if (fgets(buf, 510, fp) == NULL) {
681 bb_perror_msg_and_die("fgets()");
683 buf_ptr = strstr(buf, "\r\n");
687 } while (! isdigit(buf[0]) || buf[3] != ' ');
692 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
693 /* Stuff below is from BSD rcp util.c, as added to openshh.
694 * Original copyright notice is retained at the end of this file.
703 get_terminal_width_height(0, &width, NULL);
708 updateprogressmeter(int ignore)
710 int save_errno = errno;
719 struct itimerval itv;
721 itv.it_value.tv_sec = wait;
722 itv.it_value.tv_usec = 0;
723 itv.it_interval = itv.it_value;
724 setitimer(ITIMER_REAL, &itv, NULL);
729 progressmeter(int flag)
731 static struct timeval lastupdate;
732 static off_t lastsize, totalsize;
734 struct timeval now, td, wait;
736 int elapsed, ratio, barlength, i;
740 (void) gettimeofday(&start, (struct timezone *) 0);
743 totalsize = filesize; /* as filesize changes.. */
746 (void) gettimeofday(&now, (struct timezone *) 0);
748 if (totalsize != 0 && !chunked) {
749 ratio = (int) (100 * transferred / totalsize);
750 ratio = MIN(ratio, 100);
753 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
755 barlength = getttywidth() - 51;
756 if (barlength > 0 && barlength < sizeof(buf)) {
757 i = barlength * ratio / 100;
759 memset(buf + i, ' ', barlength - i);
760 buf[barlength] = '\0';
761 fprintf(stderr, "|%s|", buf);
764 abbrevsize = transferred;
765 while (abbrevsize >= 100000) {
769 /* See http://en.wikipedia.org/wiki/Tera */
770 fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
772 timersub(&now, &lastupdate, &wait);
773 if (transferred > lastsize) {
775 lastsize = transferred;
776 if (wait.tv_sec >= STALLTIME)
777 timeradd(&start, &wait, &start);
780 timersub(&now, &start, &td);
783 if (wait.tv_sec >= STALLTIME) {
784 fprintf(stderr, " - stalled -");
785 } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
786 fprintf(stderr, "--:--:-- ETA");
788 /* totalsize / (transferred/elapsed) - elapsed: */
789 int eta = (int) (totalsize*elapsed/transferred - elapsed);
791 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
796 sa.sa_handler = updateprogressmeter;
797 sigemptyset(&sa.sa_mask);
798 sa.sa_flags = SA_RESTART;
799 sigaction(SIGALRM, &sa, NULL);
801 } else if (flag == 1) {
809 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
810 * much of which was blatantly stolen from openssh. */
813 * Copyright (c) 1992, 1993
814 * The Regents of the University of California. All rights reserved.
816 * Redistribution and use in source and binary forms, with or without
817 * modification, are permitted provided that the following conditions
819 * 1. Redistributions of source code must retain the above copyright
820 * notice, this list of conditions and the following disclaimer.
821 * 2. Redistributions in binary form must reproduce the above copyright
822 * notice, this list of conditions and the following disclaimer in the
823 * documentation and/or other materials provided with the distribution.
825 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
826 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
828 * 4. Neither the name of the University nor the names of its contributors
829 * may be used to endorse or promote products derived from this software
830 * without specific prior written permission.
832 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
833 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
834 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
835 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
836 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
837 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
838 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
839 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
840 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
841 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
844 * $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $