1 /* vi: set sw=4 ts=4: */
3 * wget - retrieve a file using HTTP or FTP
5 * Chip Rosenthal Covad Communications <chip@laserlink.net>
9 /* We want libc to give us xxx64 functions also */
10 /* http://www.unix.org/version2/whatsnew/lfs20mar.html */
11 #define _LARGEFILE64_SOURCE 1
14 #include <getopt.h> /* for struct option */
17 // May be used if we ever will want to free() all xstrdup()s...
18 /* char *allocated; */
26 static void parse_url(char *url, struct host_info *h);
27 static FILE *open_socket(len_and_sockaddr *lsa);
28 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
29 static int ftpcmd(const char *s1, const char *s2, FILE *fp, char *buf);
31 /* Globals (can be accessed from signal handlers */
32 static off_t content_len; /* Content-length of the file */
33 static off_t beg_range; /* Range at which continue begins */
34 #if ENABLE_FEATURE_WGET_STATUSBAR
35 static off_t transferred; /* Number of bytes transferred so far */
37 static bool chunked; /* chunked transfer encoding */
38 #if ENABLE_FEATURE_WGET_STATUSBAR
39 static void progressmeter(int flag);
40 static const char *curfile; /* Name of current file being transferred */
41 static struct timeval start; /* Time a transfer started */
43 STALLTIME = 5 /* Seconds when xfer considered "stalled" */
46 static void progressmeter(int flag) {}
49 /* Read NMEMB elements of SIZE bytes into PTR from STREAM. Returns the
50 * number of elements read, and a short count if an eof or non-interrupt
51 * error is encountered. */
52 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
58 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
59 } while (ret < nmemb && ferror(stream) && errno == EINTR);
64 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
65 * Returns S, or NULL if an eof or non-interrupt error is encountered. */
66 static char *safe_fgets(char *s, int size, FILE *stream)
72 ret = fgets(s, size, stream);
73 } while (ret == NULL && ferror(stream) && errno == EINTR);
78 #if ENABLE_FEATURE_WGET_AUTHENTICATION
79 /* Base64-encode character string and return the string. */
80 static char *base64enc(unsigned char *p, char *buf, int len)
82 bb_uuencode(p, buf, len, bb_uuenc_tbl_base64);
87 int wget_main(int argc, char **argv);
88 int wget_main(int argc, char **argv)
91 struct host_info server, target;
92 len_and_sockaddr *lsa;
99 char *dir_prefix = NULL;
100 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
101 char *extra_headers = NULL;
102 llist_t *headers_llist = NULL;
105 FILE *sfp = NULL; /* socket to web/ftp server */
106 FILE *dfp = NULL; /* socket to ftp server (data) */
107 char *fname_out = NULL; /* where to direct output (-O) */
108 bool got_clen = 0; /* got content-length: from server */
110 bool use_proxy = 1; /* Use proxies if env vars are set */
111 const char *proxy_flag = "on"; /* Use proxies if env vars are set */
112 const char *user_agent = "Wget";/* "User-Agent" header field */
113 static const char * const keywords[] = {
114 "content-length", "transfer-encoding", "chunked", "location", NULL
117 KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
120 WGET_OPT_CONTINUE = 0x1,
121 WGET_OPT_SPIDER = 0x2,
122 WGET_OPT_QUIET = 0x4,
123 WGET_OPT_OUTNAME = 0x8,
124 WGET_OPT_PREFIX = 0x10,
125 WGET_OPT_PROXY = 0x20,
126 WGET_OPT_USER_AGENT = 0x40,
127 WGET_OPT_PASSIVE = 0x80,
128 WGET_OPT_HEADER = 0x100,
130 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
131 static const struct option wget_long_options[] = {
132 /* name, has_arg, flag, val */
133 { "continue", no_argument, NULL, 'c' },
134 { "spider", no_argument, NULL, 's' },
135 { "quiet", no_argument, NULL, 'q' },
136 { "output-document", required_argument, NULL, 'O' },
137 { "directory-prefix", required_argument, NULL, 'P' },
138 { "proxy", required_argument, NULL, 'Y' },
139 { "user-agent", required_argument, NULL, 'U' },
140 { "passive-ftp", no_argument, NULL, 0xff },
141 { "header", required_argument, NULL, 0xfe },
144 applet_long_options = wget_long_options;
146 /* server.allocated = target.allocated = NULL; */
147 opt_complementary = "-1" USE_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
148 opt = getopt32(argc, argv, "csqO:P:Y:U:",
149 &fname_out, &dir_prefix,
150 &proxy_flag, &user_agent
151 USE_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
153 if (strcmp(proxy_flag, "off") == 0) {
154 /* Use the proxy if necessary */
157 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
161 llist_t *ll = headers_llist;
163 size += strlen(ll->data) + 2;
166 extra_headers = cp = xmalloc(size);
167 while (headers_llist) {
168 cp += sprintf(cp, "%s\r\n", headers_llist->data);
169 headers_llist = headers_llist->link;
174 parse_url(argv[optind], &target);
175 server.host = target.host;
176 server.port = target.port;
178 /* Use the proxy if necessary */
180 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
181 if (proxy && *proxy) {
182 parse_url(proxy, &server);
188 /* Guess an output filename */
190 // Dirty hack. Needed because bb_get_last_path_component
191 // will destroy trailing / by storing '\0' in last byte!
192 if (!last_char_is(target.path, '/')) {
193 fname_out = bb_get_last_path_component(target.path);
194 #if ENABLE_FEATURE_WGET_STATUSBAR
198 if (!fname_out || !fname_out[0]) {
199 /* bb_get_last_path_component writes
200 * to last '/' only. We don't have one here... */
201 fname_out = (char*)"index.html";
202 #if ENABLE_FEATURE_WGET_STATUSBAR
206 if (dir_prefix != NULL)
207 fname_out = concat_path_file(dir_prefix, fname_out);
208 #if ENABLE_FEATURE_WGET_STATUSBAR
210 curfile = bb_get_last_path_component(fname_out);
214 if ((opt & WGET_OPT_CONTINUE) && !fname_out)
215 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)"); */
217 /* Determine where to start transfer */
218 if (LONE_DASH(fname_out)) {
220 opt &= ~WGET_OPT_CONTINUE;
222 if (opt & WGET_OPT_CONTINUE) {
223 output_fd = open(fname_out, O_WRONLY);
224 if (output_fd >= 0) {
225 beg_range = xlseek(output_fd, 0, SEEK_END);
227 /* File doesn't exist. We do not create file here yet.
228 We are not sure it exists on remove side */
231 /* We want to do exactly _one_ DNS lookup, since some
232 * sites (i.e. ftp.us.debian.org) use round-robin DNS
233 * and we want to connect to only one IP... */
234 lsa = xhost2sockaddr(server.host, server.port);
235 if (!(opt & WGET_OPT_QUIET)) {
236 fprintf(stderr, "Connecting to %s (%s)\n", server.host,
237 xmalloc_sockaddr2dotted(&lsa->sa, lsa->len));
238 /* We leak result of xmalloc_sockaddr2dotted */
241 if (use_proxy || !target.is_ftp) {
246 got_clen = chunked = 0;
249 bb_error_msg_and_die("too many redirections");
251 /* Open socket to http server */
252 if (sfp) fclose(sfp);
253 sfp = open_socket(lsa);
255 /* Send HTTP request. */
257 fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
258 target.is_ftp ? "f" : "ht", target.host,
261 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
264 fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
265 target.host, user_agent);
267 #if ENABLE_FEATURE_WGET_AUTHENTICATION
269 fprintf(sfp, "Authorization: Basic %s\r\n",
270 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
272 if (use_proxy && server.user) {
273 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
274 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
279 fprintf(sfp, "Range: bytes=%"OFF_FMT"d-\r\n", beg_range);
280 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
282 fputs(extra_headers, sfp);
284 fprintf(sfp, "Connection: close\r\n\r\n");
287 * Retrieve HTTP response line and check for "200" status code.
290 if (fgets(buf, sizeof(buf), sfp) == NULL)
291 bb_error_msg_and_die("no response from server");
294 str = skip_non_whitespace(str);
295 str = skip_whitespace(str);
296 // FIXME: no error check
297 // xatou wouldn't work: "200 OK"
302 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL)
303 /* eat all remaining headers */;
307 case 300: /* redirection */
317 /* Show first line only and kill any ESC tricks */
318 buf[strcspn(buf, "\n\r\x1b")] = '\0';
319 bb_error_msg_and_die("server returned error: %s", buf);
323 * Retrieve HTTP headers.
325 while ((str = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
326 /* gethdr did already convert the "FOO:" string to lowercase */
327 smalluint key = index_in_str_array(keywords, *&buf) + 1;
328 if (key == KEY_content_length) {
329 content_len = BB_STRTOOFF(str, NULL, 10);
330 if (errno || content_len < 0) {
331 bb_error_msg_and_die("content-length %s is garbage", str);
336 if (key == KEY_transfer_encoding) {
337 if (index_in_str_array(keywords, str_tolower(str)) + 1 != KEY_chunked)
338 bb_error_msg_and_die("server wants to do %s transfer encoding", str);
339 chunked = got_clen = 1;
341 if (key == KEY_location) {
343 /* free(target.allocated); */
344 target.path = /* target.allocated = */ xstrdup(str+1);
346 parse_url(str, &target);
347 if (use_proxy == 0) {
348 server.host = target.host;
349 server.port = target.port;
352 lsa = xhost2sockaddr(server.host, server.port);
357 } while (status >= 300);
367 target.user = xstrdup("anonymous:busybox@");
369 sfp = open_socket(lsa);
370 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
371 bb_error_msg_and_die("%s", buf+4);
374 * Splitting username:password pair,
377 str = strchr(target.user, ':');
380 switch (ftpcmd("USER ", target.user, sfp, buf)) {
384 if (ftpcmd("PASS ", str, sfp, buf) == 230)
386 /* FALLTHRU (failed login) */
388 bb_error_msg_and_die("ftp login: %s", buf+4);
391 ftpcmd("TYPE I", NULL, sfp, buf);
396 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
397 content_len = BB_STRTOOFF(buf+4, NULL, 10);
398 if (errno || content_len < 0) {
399 bb_error_msg_and_die("SIZE value is garbage");
405 * Entering passive mode
407 if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
409 bb_error_msg_and_die("bad response to %s: %s", "PASV", buf);
411 // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
412 // Server's IP is N1.N2.N3.N4 (we ignore it)
413 // Server's port for data connection is P1*256+P2
414 str = strrchr(buf, ')');
415 if (str) str[0] = '\0';
416 str = strrchr(buf, ',');
417 if (!str) goto pasv_error;
418 port = xatou_range(str+1, 0, 255);
420 str = strrchr(buf, ',');
421 if (!str) goto pasv_error;
422 port += xatou_range(str+1, 0, 255) * 256;
423 set_nport(lsa, htons(port));
424 dfp = open_socket(lsa);
427 sprintf(buf, "REST %"OFF_FMT"d", beg_range);
428 if (ftpcmd(buf, NULL, sfp, buf) == 350)
429 content_len -= beg_range;
432 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
433 bb_error_msg_and_die("bad response to RETR: %s", buf);
435 if (opt & WGET_OPT_SPIDER) {
436 if (ENABLE_FEATURE_CLEAN_UP)
445 fgets(buf, sizeof(buf), dfp);
446 content_len = STRTOOFF(buf, NULL, 16);
447 /* FIXME: error check?? */
450 /* Do it before progressmeter (want to have nice error message) */
452 output_fd = xopen(fname_out,
453 O_WRONLY|O_CREAT|O_EXCL|O_TRUNC);
455 if (!(opt & WGET_OPT_QUIET))
459 while (content_len > 0 || !got_clen) {
460 unsigned rdsz = sizeof(buf);
461 if (content_len < sizeof(buf) && (chunked || got_clen))
462 rdsz = (unsigned)content_len;
463 n = safe_fread(buf, 1, rdsz, dfp);
466 if (full_write(output_fd, buf, n) != n) {
467 bb_perror_msg_and_die(bb_msg_write_error);
469 #if ENABLE_FEATURE_WGET_STATUSBAR
478 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
479 safe_fgets(buf, sizeof(buf), dfp);
480 content_len = STRTOOFF(buf, NULL, 16);
481 /* FIXME: error check? */
482 if (content_len == 0) {
483 chunked = 0; /* all done! */
487 if (n == 0 && ferror(dfp)) {
488 bb_perror_msg_and_die(bb_msg_read_error);
492 if (!(opt & WGET_OPT_QUIET))
495 if ((use_proxy == 0) && target.is_ftp) {
497 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
498 bb_error_msg_and_die("ftp error: %s", buf+4);
499 ftpcmd("QUIT", NULL, sfp, buf);
506 static void parse_url(char *src_url, struct host_info *h)
510 /* h->allocated = */ url = xstrdup(src_url);
512 if (strncmp(url, "http://", 7) == 0) {
513 h->port = bb_lookup_port("http", "tcp", 80);
516 } else if (strncmp(url, "ftp://", 6) == 0) {
517 h->port = bb_lookup_port("ftp", "tcp", 21);
521 bb_error_msg_and_die("not an http or ftp url: %s", url);
524 // "Real" wget 'http://busybox.net?var=a/b' sends this request:
525 // 'GET /?var=a/b HTTP 1.0'
526 // and saves 'index.html?var=a%2Fb' (we save 'b')
527 // wget 'http://busybox.net?login=john@doe':
528 // request: 'GET /?login=john@doe HTTP/1.0'
529 // saves: 'index.html?login=john@doe' (we save '?login=john@doe')
530 // wget 'http://busybox.net#test/test':
531 // request: 'GET / HTTP/1.0'
532 // saves: 'index.html' (we save 'test')
534 // We also don't add unique .N suffix if file exists...
535 sp = strchr(h->host, '/');
536 p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
537 p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
539 /* must be writable because of bb_get_last_path_component() */
540 static char nullstr[] = "";
542 } else if (*sp == '/') {
545 } else { // '#' or '?'
546 // http://busybox.net?login=john@doe is a valid URL
547 // memmove converts to:
548 // http:/busybox.nett?login=john@doe...
549 memmove(h->host-1, h->host, sp - h->host);
555 sp = strrchr(h->host, '@');
567 static FILE *open_socket(len_and_sockaddr *lsa)
571 /* glibc 2.4 seems to try seeking on it - ??! */
572 /* hopefully it understands what ESPIPE means... */
573 fp = fdopen(xconnect_stream(lsa), "r+");
575 bb_perror_msg_and_die("fdopen");
581 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
588 /* retrieve header line */
589 if (fgets(buf, bufsiz, fp) == NULL)
592 /* see if we are at the end of the headers */
593 for (s = buf; *s == '\r'; ++s)
598 /* convert the header name to lower case */
599 for (s = buf; isalnum(*s) || *s == '-'; ++s)
602 /* verify we are at the end of the header name */
604 bb_error_msg_and_die("bad header line: %s", buf);
606 /* locate the start of the header value */
607 for (*s++ = '\0'; *s == ' ' || *s == '\t'; ++s)
611 /* locate the end of header */
612 while (*s != '\0' && *s != '\r' && *s != '\n')
615 /* end of header found */
621 /* Rats! The buffer isn't big enough to hold the entire header value. */
622 while (c = getc(fp), c != EOF && c != '\n')
628 static int ftpcmd(const char *s1, const char *s2, FILE *fp, char *buf)
633 fprintf(fp, "%s%s\r\n", s1, s2);
640 if (fgets(buf, 510, fp) == NULL) {
641 bb_perror_msg_and_die("error getting response");
643 buf_ptr = strstr(buf, "\r\n");
647 } while (!isdigit(buf[0]) || buf[3] != ' ');
650 result = xatoi_u(buf);
655 #if ENABLE_FEATURE_WGET_STATUSBAR
656 /* Stuff below is from BSD rcp util.c, as added to openshh.
657 * Original copyright notice is retained at the end of this file.
663 get_terminal_width_height(0, &width, NULL);
668 updateprogressmeter(int ignore)
670 int save_errno = errno;
676 static void alarmtimer(int iwait)
678 struct itimerval itv;
680 itv.it_value.tv_sec = iwait;
681 itv.it_value.tv_usec = 0;
682 itv.it_interval = itv.it_value;
683 setitimer(ITIMER_REAL, &itv, NULL);
688 progressmeter(int flag)
690 static struct timeval lastupdate;
691 static off_t lastsize, totalsize;
693 struct timeval now, td, tvwait;
695 int elapsed, ratio, barlength, i;
698 if (flag == -1) { /* first call to progressmeter */
699 gettimeofday(&start, (struct timezone *) 0);
702 totalsize = content_len + beg_range; /* as content_len changes.. */
705 gettimeofday(&now, (struct timezone *) 0);
707 if (totalsize != 0 && !chunked) {
708 /* long long helps to have working ETA even if !LFS */
709 ratio = (int) (100 * (unsigned long long)(transferred+beg_range) / totalsize);
710 ratio = MIN(ratio, 100);
713 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
715 barlength = getttywidth() - 51;
716 if (barlength > 0 && barlength < sizeof(buf)) {
717 i = barlength * ratio / 100;
719 memset(buf + i, ' ', barlength - i);
720 buf[barlength] = '\0';
721 fprintf(stderr, "|%s|", buf);
724 abbrevsize = transferred + beg_range;
725 while (abbrevsize >= 100000) {
729 /* see http://en.wikipedia.org/wiki/Tera */
730 fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
732 timersub(&now, &lastupdate, &tvwait);
733 if (transferred > lastsize) {
735 lastsize = transferred;
736 if (tvwait.tv_sec >= STALLTIME)
737 timeradd(&start, &tvwait, &start);
740 timersub(&now, &start, &td);
743 if (tvwait.tv_sec >= STALLTIME) {
744 fprintf(stderr, " - stalled -");
746 off_t to_download = totalsize - beg_range;
747 if (transferred <= 0 || elapsed <= 0 || transferred > to_download || chunked) {
748 fprintf(stderr, "--:--:-- ETA");
750 /* to_download / (transferred/elapsed) - elapsed: */
751 int eta = (int) ((unsigned long long)to_download*elapsed/transferred - elapsed);
752 /* (long long helps to have working ETA even if !LFS) */
754 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
758 if (flag == -1) { /* first call to progressmeter */
760 sa.sa_handler = updateprogressmeter;
761 sigemptyset(&sa.sa_mask);
762 sa.sa_flags = SA_RESTART;
763 sigaction(SIGALRM, &sa, NULL);
765 } else if (flag == 1) { /* last call to progressmeter */
773 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
774 * much of which was blatantly stolen from openssh. */
777 * Copyright (c) 1992, 1993
778 * The Regents of the University of California. All rights reserved.
780 * Redistribution and use in source and binary forms, with or without
781 * modification, are permitted provided that the following conditions
783 * 1. Redistributions of source code must retain the above copyright
784 * notice, this list of conditions and the following disclaimer.
785 * 2. Redistributions in binary form must reproduce the above copyright
786 * notice, this list of conditions and the following disclaimer in the
787 * documentation and/or other materials provided with the distribution.
789 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
790 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
792 * 4. Neither the name of the University nor the names of its contributors
793 * may be used to endorse or promote products derived from this software
794 * without specific prior written permission.
796 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
797 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
798 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
799 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
800 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
801 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
802 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
803 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
804 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
805 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF