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
13 #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 */
42 STALLTIME = 5 /* Seconds when xfer considered "stalled" */
45 static void progressmeter(int flag) {}
48 /* Read NMEMB elements of SIZE bytes into PTR from STREAM. Returns the
49 * number of elements read, and a short count if an eof or non-interrupt
50 * error is encountered. */
51 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
57 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
58 } while (ret < nmemb && ferror(stream) && errno == EINTR);
63 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
64 * Returns S, or NULL if an eof or non-interrupt error is encountered. */
65 static char *safe_fgets(char *s, int size, FILE *stream)
71 ret = fgets(s, size, stream);
72 } while (ret == NULL && ferror(stream) && errno == EINTR);
77 #if ENABLE_FEATURE_WGET_AUTHENTICATION
78 /* Base64-encode character string and return the string. */
79 static char *base64enc(unsigned char *p, char *buf, int len)
81 bb_uuencode(p, buf, len, bb_uuenc_tbl_base64);
86 int wget_main(int argc, char **argv);
87 int wget_main(int argc, char **argv)
90 struct host_info server, target;
91 len_and_sockaddr *lsa;
98 char *dir_prefix = NULL;
99 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
100 char *extra_headers = NULL;
101 llist_t *headers_llist = NULL;
104 FILE *sfp = NULL; /* socket to web/ftp server */
105 FILE *dfp = NULL; /* socket to ftp server (data) */
106 char *fname_out = NULL; /* where to direct output (-O) */
107 bool got_clen = 0; /* got content-length: from server */
109 bool use_proxy = 1; /* Use proxies if env vars are set */
110 const char *proxy_flag = "on"; /* Use proxies if env vars are set */
111 const char *user_agent = "Wget";/* "User-Agent" header field */
112 static const char * const keywords[] = {
113 "content-length", "transfer-encoding", "chunked", "location", NULL
116 KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
119 WGET_OPT_CONTINUE = 0x1,
120 WGET_OPT_SPIDER = 0x2,
121 WGET_OPT_QUIET = 0x4,
122 WGET_OPT_OUTNAME = 0x8,
123 WGET_OPT_PREFIX = 0x10,
124 WGET_OPT_PROXY = 0x20,
125 WGET_OPT_USER_AGENT = 0x40,
126 WGET_OPT_PASSIVE = 0x80,
127 WGET_OPT_HEADER = 0x100,
129 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
130 static const struct option wget_long_options[] = {
131 /* name, has_arg, flag, val */
132 { "continue", no_argument, NULL, 'c' },
133 { "spider", no_argument, NULL, 's' },
134 { "quiet", no_argument, NULL, 'q' },
135 { "output-document", required_argument, NULL, 'O' },
136 { "directory-prefix", required_argument, NULL, 'P' },
137 { "proxy", required_argument, NULL, 'Y' },
138 { "user-agent", required_argument, NULL, 'U' },
139 { "passive-ftp", no_argument, NULL, 0xff },
140 { "header", required_argument, NULL, 0xfe },
143 applet_long_options = wget_long_options;
145 /* server.allocated = target.allocated = NULL; */
146 opt_complementary = "-1" USE_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
147 opt = getopt32(argc, argv, "csqO:P:Y:U:",
148 &fname_out, &dir_prefix,
149 &proxy_flag, &user_agent
150 USE_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
152 if (strcmp(proxy_flag, "off") == 0) {
153 /* Use the proxy if necessary */
156 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
160 llist_t *ll = headers_llist;
162 size += strlen(ll->data) + 2;
165 extra_headers = cp = xmalloc(size);
166 while (headers_llist) {
167 cp += sprintf(cp, "%s\r\n", headers_llist->data);
168 headers_llist = headers_llist->link;
173 parse_url(argv[optind], &target);
174 server.host = target.host;
175 server.port = target.port;
177 /* Use the proxy if necessary */
179 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
180 if (proxy && *proxy) {
181 parse_url(proxy, &server);
187 /* Guess an output filename */
189 // Dirty hack. Needed because bb_get_last_path_component
190 // will destroy trailing / by storing '\0' in last byte!
191 if (!last_char_is(target.path, '/')) {
192 fname_out = bb_get_last_path_component(target.path);
193 #if ENABLE_FEATURE_WGET_STATUSBAR
197 if (!fname_out || !fname_out[0]) {
198 /* bb_get_last_path_component writes
199 * to last '/' only. We don't have one here... */
200 fname_out = (char*)"index.html";
201 #if ENABLE_FEATURE_WGET_STATUSBAR
205 if (dir_prefix != NULL)
206 fname_out = concat_path_file(dir_prefix, fname_out);
207 #if ENABLE_FEATURE_WGET_STATUSBAR
209 curfile = bb_get_last_path_component(fname_out);
213 if ((opt & WGET_OPT_CONTINUE) && !fname_out)
214 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)"); */
216 /* Determine where to start transfer */
217 if (LONE_DASH(fname_out)) {
219 opt &= ~WGET_OPT_CONTINUE;
221 if (opt & WGET_OPT_CONTINUE) {
222 output_fd = open(fname_out, O_WRONLY);
223 if (output_fd >= 0) {
224 beg_range = xlseek(output_fd, 0, SEEK_END);
226 /* File doesn't exist. We do not create file here yet.
227 We are not sure it exists on remove side */
230 /* We want to do exactly _one_ DNS lookup, since some
231 * sites (i.e. ftp.us.debian.org) use round-robin DNS
232 * and we want to connect to only one IP... */
233 lsa = xhost2sockaddr(server.host, server.port);
234 if (!(opt & WGET_OPT_QUIET)) {
235 fprintf(stderr, "Connecting to %s (%s)\n", server.host,
236 xmalloc_sockaddr2dotted(&lsa->sa, lsa->len));
237 /* We leak result of xmalloc_sockaddr2dotted */
240 if (use_proxy || !target.is_ftp) {
245 got_clen = chunked = 0;
248 bb_error_msg_and_die("too many redirections");
250 /* Open socket to http server */
251 if (sfp) fclose(sfp);
252 sfp = open_socket(lsa);
254 /* Send HTTP request. */
256 fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
257 target.is_ftp ? "f" : "ht", target.host,
260 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
263 fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
264 target.host, user_agent);
266 #if ENABLE_FEATURE_WGET_AUTHENTICATION
268 fprintf(sfp, "Authorization: Basic %s\r\n",
269 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
271 if (use_proxy && server.user) {
272 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
273 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
278 fprintf(sfp, "Range: bytes=%"OFF_FMT"d-\r\n", beg_range);
279 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
281 fputs(extra_headers, sfp);
283 fprintf(sfp, "Connection: close\r\n\r\n");
286 * Retrieve HTTP response line and check for "200" status code.
289 if (fgets(buf, sizeof(buf), sfp) == NULL)
290 bb_error_msg_and_die("no response from server");
293 str = skip_non_whitespace(str);
294 str = skip_whitespace(str);
295 // FIXME: no error check
296 // xatou wouldn't work: "200 OK"
301 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL)
302 /* eat all remaining headers */;
306 case 300: /* redirection */
316 /* Show first line only and kill any ESC tricks */
317 buf[strcspn(buf, "\n\r\x1b")] = '\0';
318 bb_error_msg_and_die("server returned error: %s", buf);
322 * Retrieve HTTP headers.
324 while ((str = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
325 /* gethdr did already convert the "FOO:" string to lowercase */
326 smalluint key = index_in_str_array(keywords, *&buf) + 1;
327 if (key == KEY_content_length) {
328 content_len = BB_STRTOOFF(str, NULL, 10);
329 if (errno || content_len < 0) {
330 bb_error_msg_and_die("content-length %s is garbage", str);
335 if (key == KEY_transfer_encoding) {
336 if (index_in_str_array(keywords, str_tolower(str)) + 1 != KEY_chunked)
337 bb_error_msg_and_die("server wants to do %s transfer encoding", str);
338 chunked = got_clen = 1;
340 if (key == KEY_location) {
342 /* free(target.allocated); */
343 target.path = /* target.allocated = */ xstrdup(str+1);
345 parse_url(str, &target);
346 if (use_proxy == 0) {
347 server.host = target.host;
348 server.port = target.port;
351 lsa = xhost2sockaddr(server.host, server.port);
356 } while (status >= 300);
366 target.user = xstrdup("anonymous:busybox@");
368 sfp = open_socket(lsa);
369 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
370 bb_error_msg_and_die("%s", buf+4);
373 * Splitting username:password pair,
376 str = strchr(target.user, ':');
379 switch (ftpcmd("USER ", target.user, sfp, buf)) {
383 if (ftpcmd("PASS ", str, sfp, buf) == 230)
385 /* FALLTHRU (failed login) */
387 bb_error_msg_and_die("ftp login: %s", buf+4);
390 ftpcmd("TYPE I", NULL, sfp, buf);
395 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
396 content_len = BB_STRTOOFF(buf+4, NULL, 10);
397 if (errno || content_len < 0) {
398 bb_error_msg_and_die("SIZE value is garbage");
404 * Entering passive mode
406 if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
408 bb_error_msg_and_die("bad response to %s: %s", "PASV", buf);
410 // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
411 // Server's IP is N1.N2.N3.N4 (we ignore it)
412 // Server's port for data connection is P1*256+P2
413 str = strrchr(buf, ')');
414 if (str) str[0] = '\0';
415 str = strrchr(buf, ',');
416 if (!str) goto pasv_error;
417 port = xatou_range(str+1, 0, 255);
419 str = strrchr(buf, ',');
420 if (!str) goto pasv_error;
421 port += xatou_range(str+1, 0, 255) * 256;
422 set_nport(lsa, htons(port));
423 dfp = open_socket(lsa);
426 sprintf(buf, "REST %"OFF_FMT"d", beg_range);
427 if (ftpcmd(buf, NULL, sfp, buf) == 350)
428 content_len -= beg_range;
431 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
432 bb_error_msg_and_die("bad response to RETR: %s", buf);
434 if (opt & WGET_OPT_SPIDER) {
435 if (ENABLE_FEATURE_CLEAN_UP)
444 fgets(buf, sizeof(buf), dfp);
445 content_len = STRTOOFF(buf, NULL, 16);
446 /* FIXME: error check?? */
449 /* Do it before progressmeter (want to have nice error message) */
451 output_fd = xopen(fname_out,
452 O_WRONLY|O_CREAT|O_EXCL|O_TRUNC);
454 if (!(opt & WGET_OPT_QUIET))
458 while (content_len > 0 || !got_clen) {
459 unsigned rdsz = sizeof(buf);
460 if (content_len < sizeof(buf) && (chunked || got_clen))
461 rdsz = (unsigned)content_len;
462 n = safe_fread(buf, 1, rdsz, dfp);
465 if (full_write(output_fd, buf, n) != n) {
466 bb_perror_msg_and_die(bb_msg_write_error);
468 #if ENABLE_FEATURE_WGET_STATUSBAR
477 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
478 safe_fgets(buf, sizeof(buf), dfp);
479 content_len = STRTOOFF(buf, NULL, 16);
480 /* FIXME: error check? */
481 if (content_len == 0) {
482 chunked = 0; /* all done! */
486 if (n == 0 && ferror(dfp)) {
487 bb_perror_msg_and_die(bb_msg_read_error);
491 if (!(opt & WGET_OPT_QUIET))
494 if ((use_proxy == 0) && target.is_ftp) {
496 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
497 bb_error_msg_and_die("ftp error: %s", buf+4);
498 ftpcmd("QUIT", NULL, sfp, buf);
505 static void parse_url(char *src_url, struct host_info *h)
509 /* h->allocated = */ url = xstrdup(src_url);
511 if (strncmp(url, "http://", 7) == 0) {
512 h->port = bb_lookup_port("http", "tcp", 80);
515 } else if (strncmp(url, "ftp://", 6) == 0) {
516 h->port = bb_lookup_port("ftp", "tcp", 21);
520 bb_error_msg_and_die("not an http or ftp url: %s", url);
523 // "Real" wget 'http://busybox.net?var=a/b' sends this request:
524 // 'GET /?var=a/b HTTP 1.0'
525 // and saves 'index.html?var=a%2Fb' (we save 'b')
526 // wget 'http://busybox.net?login=john@doe':
527 // request: 'GET /?login=john@doe HTTP/1.0'
528 // saves: 'index.html?login=john@doe' (we save '?login=john@doe')
529 // wget 'http://busybox.net#test/test':
530 // request: 'GET / HTTP/1.0'
531 // saves: 'index.html' (we save 'test')
533 // We also don't add unique .N suffix if file exists...
534 sp = strchr(h->host, '/');
535 p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
536 p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
538 /* must be writable because of bb_get_last_path_component() */
539 static char nullstr[] = "";
541 } else if (*sp == '/') {
544 } else { // '#' or '?'
545 // http://busybox.net?login=john@doe is a valid URL
546 // memmove converts to:
547 // http:/busybox.nett?login=john@doe...
548 memmove(h->host-1, h->host, sp - h->host);
554 sp = strrchr(h->host, '@');
566 static FILE *open_socket(len_and_sockaddr *lsa)
570 /* glibc 2.4 seems to try seeking on it - ??! */
571 /* hopefully it understands what ESPIPE means... */
572 fp = fdopen(xconnect_stream(lsa), "r+");
574 bb_perror_msg_and_die("fdopen");
580 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
587 /* retrieve header line */
588 if (fgets(buf, bufsiz, fp) == NULL)
591 /* see if we are at the end of the headers */
592 for (s = buf; *s == '\r'; ++s)
597 /* convert the header name to lower case */
598 for (s = buf; isalnum(*s) || *s == '-'; ++s)
601 /* verify we are at the end of the header name */
603 bb_error_msg_and_die("bad header line: %s", buf);
605 /* locate the start of the header value */
606 for (*s++ = '\0'; *s == ' ' || *s == '\t'; ++s)
610 /* locate the end of header */
611 while (*s != '\0' && *s != '\r' && *s != '\n')
614 /* end of header found */
620 /* Rats! The buffer isn't big enough to hold the entire header value. */
621 while (c = getc(fp), c != EOF && c != '\n')
627 static int ftpcmd(const char *s1, const char *s2, FILE *fp, char *buf)
632 fprintf(fp, "%s%s\r\n", s1, s2);
639 if (fgets(buf, 510, fp) == NULL) {
640 bb_perror_msg_and_die("error getting response");
642 buf_ptr = strstr(buf, "\r\n");
646 } while (!isdigit(buf[0]) || buf[3] != ' ');
649 result = xatoi_u(buf);
654 #if ENABLE_FEATURE_WGET_STATUSBAR
655 /* Stuff below is from BSD rcp util.c, as added to openshh.
656 * Original copyright notice is retained at the end of this file.
662 get_terminal_width_height(0, &width, NULL);
667 updateprogressmeter(int ignore)
669 int save_errno = errno;
675 static void alarmtimer(int iwait)
677 struct itimerval itv;
679 itv.it_value.tv_sec = iwait;
680 itv.it_value.tv_usec = 0;
681 itv.it_interval = itv.it_value;
682 setitimer(ITIMER_REAL, &itv, NULL);
686 progressmeter(int flag)
688 static unsigned lastupdate_sec;
689 static unsigned start_sec;
690 static off_t lastsize, totalsize;
693 unsigned since_last_update, elapsed;
697 if (flag == -1) { /* first call to progressmeter */
698 start_sec = monotonic_sec();
699 lastupdate_sec = start_sec;
701 totalsize = content_len + beg_range; /* as content_len changes.. */
705 if (totalsize != 0 && !chunked) {
706 /* long long helps to have it working even if !LFS */
707 ratio = (unsigned) (100ULL * (transferred+beg_range) / totalsize);
708 if (ratio > 100) ratio = 100;
711 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
713 barlength = getttywidth() - 49;
715 /* god bless gcc for variable arrays :) */
716 i = barlength * ratio / 100;
721 fprintf(stderr, "|%s%*s|", buf, barlength - i, "");
725 abbrevsize = transferred + beg_range;
726 while (abbrevsize >= 100000) {
730 /* see http://en.wikipedia.org/wiki/Tera */
731 fprintf(stderr, "%6d%c ", (int)abbrevsize, " kMGTPEZY"[i]);
733 // Nuts! Ain't it easier to update progress meter ONLY when we transferred++?
734 // FIXME: get rid of alarmtimer + updateprogressmeter mess
736 elapsed = monotonic_sec();
737 since_last_update = elapsed - lastupdate_sec;
738 if (transferred > lastsize) {
739 lastupdate_sec = elapsed;
740 lastsize = transferred;
741 if (since_last_update >= STALLTIME) {
742 /* We "cut off" these seconds from elapsed time
743 * by adjusting start time */
744 start_sec += since_last_update;
746 since_last_update = 0; /* we are un-stalled now */
748 elapsed -= start_sec; /* now it's "elapsed since start" */
750 if (since_last_update >= STALLTIME) {
751 fprintf(stderr, " - stalled -");
753 off_t to_download = totalsize - beg_range;
754 if (transferred <= 0 || (int)elapsed <= 0 || transferred > to_download || chunked) {
755 fprintf(stderr, "--:--:-- ETA");
757 /* to_download / (transferred/elapsed) - elapsed: */
758 int eta = (int) ((unsigned long long)to_download*elapsed/transferred - elapsed);
759 /* (long long helps to have working ETA even if !LFS) */
761 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
765 if (flag == -1) { /* first call to progressmeter */
767 sa.sa_handler = updateprogressmeter;
768 sigemptyset(&sa.sa_mask);
769 sa.sa_flags = SA_RESTART;
770 sigaction(SIGALRM, &sa, NULL);
772 } else if (flag == 1) { /* last call to progressmeter */
780 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
781 * much of which was blatantly stolen from openssh. */
784 * Copyright (c) 1992, 1993
785 * The Regents of the University of California. All rights reserved.
787 * Redistribution and use in source and binary forms, with or without
788 * modification, are permitted provided that the following conditions
790 * 1. Redistributions of source code must retain the above copyright
791 * notice, this list of conditions and the following disclaimer.
792 * 2. Redistributions in binary form must reproduce the above copyright
793 * notice, this list of conditions and the following disclaimer in the
794 * documentation and/or other materials provided with the distribution.
796 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
797 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
799 * 4. Neither the name of the University nor the names of its contributors
800 * may be used to endorse or promote products derived from this software
801 * without specific prior written permission.
803 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
804 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
805 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
806 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
807 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
808 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
809 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
810 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
811 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
812 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF