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 #include <getopt.h> /* for struct option */
13 // May be used if we ever will want to free() all xstrdup()s...
14 /* char *allocated; */
23 /* Globals (can be accessed from signal handlers) */
25 off_t content_len; /* Content-length of the file */
26 off_t beg_range; /* Range at which continue begins */
27 #if ENABLE_FEATURE_WGET_STATUSBAR
30 off_t transferred; /* Number of bytes transferred so far */
31 const char *curfile; /* Name of current file being transferred */
32 unsigned lastupdate_sec;
35 bool chunked; /* chunked transfer encoding */
37 #define G (*(struct globals*)&bb_common_bufsiz1)
38 struct BUG_G_too_big {
39 char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
41 #define content_len (G.content_len )
42 #define beg_range (G.beg_range )
43 #define lastsize (G.lastsize )
44 #define totalsize (G.totalsize )
45 #define transferred (G.transferred )
46 #define curfile (G.curfile )
47 #define lastupdate_sec (G.lastupdate_sec )
48 #define start_sec (G.start_sec )
49 #define chunked (G.chunked )
50 #define INIT_G() do { } while (0)
53 static void parse_url(char *url, struct host_info *h);
54 static FILE *open_socket(len_and_sockaddr *lsa);
55 static char *gethdr(char *buf, size_t bufsiz, FILE *fp /*,int *istrunc*/ );
56 static int ftpcmd(const char *s1, const char *s2, FILE *fp, char *buf);
58 #if ENABLE_FEATURE_WGET_STATUSBAR
59 static void progressmeter(int flag);
61 STALLTIME = 5 /* Seconds when xfer considered "stalled" */
64 static ALWAYS_INLINE void progressmeter(int flag) {}
67 /* Read NMEMB bytes into PTR from STREAM. Returns the number of bytes read,
68 * and a short count if an eof or non-interrupt error is encountered. */
69 static size_t safe_fread(void *ptr, size_t nmemb, FILE *stream)
76 ret = fread(p, 1, nmemb, stream);
79 } while (nmemb && ferror(stream) && errno == EINTR);
81 return p - (char*)ptr;
84 /* Read a line or SIZE-1 bytes into S, whichever is less, from STREAM.
85 * Returns S, or NULL if an eof or non-interrupt error is encountered. */
86 static char *safe_fgets(char *s, int size, FILE *stream)
92 ret = fgets(s, size, stream);
93 } while (ret == NULL && ferror(stream) && errno == EINTR);
98 #if ENABLE_FEATURE_WGET_AUTHENTICATION
99 /* Base64-encode character string. buf is assumed to be char buf[512]. */
100 static char *base64enc_512(char buf[512], const char *str)
102 unsigned len = strlen(str);
103 if (len > 512/4*3 - 10) /* paranoia */
105 bb_uuencode(buf, str, len, bb_uuenc_tbl_base64);
110 int wget_main(int argc, char **argv);
111 int wget_main(int argc, char **argv)
114 struct host_info server, target;
115 len_and_sockaddr *lsa;
122 char *dir_prefix = NULL;
123 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
124 char *extra_headers = NULL;
125 llist_t *headers_llist = NULL;
127 FILE *sfp = NULL; /* socket to web/ftp server */
128 FILE *dfp = NULL; /* socket to ftp server (data) */
129 char *fname_out = NULL; /* where to direct output (-O) */
130 bool got_clen = 0; /* got content-length: from server */
132 bool use_proxy = 1; /* Use proxies if env vars are set */
133 const char *proxy_flag = "on"; /* Use proxies if env vars are set */
134 const char *user_agent = "Wget";/* "User-Agent" header field */
136 static const char keywords[] ALIGN1 =
137 "content-length\0""transfer-encoding\0""chunked\0""location\0";
139 KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
142 WGET_OPT_CONTINUE = 0x1,
143 WGET_OPT_SPIDER = 0x2,
144 WGET_OPT_QUIET = 0x4,
145 WGET_OPT_OUTNAME = 0x8,
146 WGET_OPT_PREFIX = 0x10,
147 WGET_OPT_PROXY = 0x20,
148 WGET_OPT_USER_AGENT = 0x40,
149 WGET_OPT_PASSIVE = 0x80,
150 WGET_OPT_HEADER = 0x100,
152 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
153 static const char wget_longopts[] ALIGN1 =
154 /* name, has_arg, val */
155 "continue\0" No_argument "c"
156 "spider\0" No_argument "s"
157 "quiet\0" No_argument "q"
158 "output-document\0" Required_argument "O"
159 "directory-prefix\0" Required_argument "P"
160 "proxy\0" Required_argument "Y"
161 "user-agent\0" Required_argument "U"
162 "passive-ftp\0" No_argument "\xff"
163 "header\0" Required_argument "\xfe"
169 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
170 applet_long_options = wget_longopts;
172 /* server.allocated = target.allocated = NULL; */
173 opt_complementary = "-1" USE_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
174 opt = getopt32(argv, "csqO:P:Y:U:",
175 &fname_out, &dir_prefix,
176 &proxy_flag, &user_agent
177 USE_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
179 if (strcmp(proxy_flag, "off") == 0) {
180 /* Use the proxy if necessary */
183 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
187 llist_t *ll = headers_llist;
189 size += strlen(ll->data) + 2;
192 extra_headers = cp = xmalloc(size);
193 while (headers_llist) {
194 cp += sprintf(cp, "%s\r\n", headers_llist->data);
195 headers_llist = headers_llist->link;
200 parse_url(argv[optind], &target);
201 server.host = target.host;
202 server.port = target.port;
204 /* Use the proxy if necessary */
206 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
207 if (proxy && *proxy) {
208 parse_url(proxy, &server);
214 /* Guess an output filename */
216 // Dirty hack. Needed because bb_get_last_path_component
217 // will destroy trailing / by storing '\0' in last byte!
218 if (!last_char_is(target.path, '/')) {
219 fname_out = bb_get_last_path_component(target.path);
220 #if ENABLE_FEATURE_WGET_STATUSBAR
224 if (!fname_out || !fname_out[0]) {
225 /* bb_get_last_path_component writes
226 * to last '/' only. We don't have one here... */
227 fname_out = (char*)"index.html";
228 #if ENABLE_FEATURE_WGET_STATUSBAR
232 if (dir_prefix != NULL)
233 fname_out = concat_path_file(dir_prefix, fname_out);
234 #if ENABLE_FEATURE_WGET_STATUSBAR
236 curfile = bb_get_last_path_component(fname_out);
240 if ((opt & WGET_OPT_CONTINUE) && !fname_out)
241 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)"); */
243 /* Determine where to start transfer */
244 if (LONE_DASH(fname_out)) {
246 opt &= ~WGET_OPT_CONTINUE;
248 if (opt & WGET_OPT_CONTINUE) {
249 output_fd = open(fname_out, O_WRONLY);
250 if (output_fd >= 0) {
251 beg_range = xlseek(output_fd, 0, SEEK_END);
253 /* File doesn't exist. We do not create file here yet.
254 We are not sure it exists on remove side */
257 /* We want to do exactly _one_ DNS lookup, since some
258 * sites (i.e. ftp.us.debian.org) use round-robin DNS
259 * and we want to connect to only one IP... */
260 lsa = xhost2sockaddr(server.host, server.port);
261 if (!(opt & WGET_OPT_QUIET)) {
262 fprintf(stderr, "Connecting to %s (%s)\n", server.host,
263 xmalloc_sockaddr2dotted(&lsa->sa));
264 /* We leak result of xmalloc_sockaddr2dotted */
267 if (use_proxy || !target.is_ftp) {
272 got_clen = chunked = 0;
275 bb_error_msg_and_die("too many redirections");
277 /* Open socket to http server */
278 if (sfp) fclose(sfp);
279 sfp = open_socket(lsa);
281 /* Send HTTP request. */
283 fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
284 target.is_ftp ? "f" : "ht", target.host,
287 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
290 fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
291 target.host, user_agent);
293 #if ENABLE_FEATURE_WGET_AUTHENTICATION
295 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
296 base64enc_512(buf, target.user));
298 if (use_proxy && server.user) {
299 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
300 base64enc_512(buf, server.user));
305 fprintf(sfp, "Range: bytes=%"OFF_FMT"d-\r\n", beg_range);
306 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
308 fputs(extra_headers, sfp);
310 fprintf(sfp, "Connection: close\r\n\r\n");
313 * Retrieve HTTP response line and check for "200" status code.
316 if (fgets(buf, sizeof(buf), sfp) == NULL)
317 bb_error_msg_and_die("no response from server");
320 str = skip_non_whitespace(str);
321 str = skip_whitespace(str);
322 // FIXME: no error check
323 // xatou wouldn't work: "200 OK"
328 while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
329 /* eat all remaining headers */;
333 case 300: /* redirection */
343 /* Show first line only and kill any ESC tricks */
344 buf[strcspn(buf, "\n\r\x1b")] = '\0';
345 bb_error_msg_and_die("server returned error: %s", buf);
349 * Retrieve HTTP headers.
351 while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
352 /* gethdr did already convert the "FOO:" string to lowercase */
353 smalluint key = index_in_strings(keywords, *&buf) + 1;
354 if (key == KEY_content_length) {
355 content_len = BB_STRTOOFF(str, NULL, 10);
356 if (errno || content_len < 0) {
357 bb_error_msg_and_die("content-length %s is garbage", str);
362 if (key == KEY_transfer_encoding) {
363 if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
364 bb_error_msg_and_die("transfer encoding '%s' is not supported", str);
365 chunked = got_clen = 1;
367 if (key == KEY_location) {
369 /* free(target.allocated); */
370 target.path = /* target.allocated = */ xstrdup(str+1);
372 parse_url(str, &target);
373 if (use_proxy == 0) {
374 server.host = target.host;
375 server.port = target.port;
378 lsa = xhost2sockaddr(server.host, server.port);
383 } while (status >= 300);
393 target.user = xstrdup("anonymous:busybox@");
395 sfp = open_socket(lsa);
396 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
397 bb_error_msg_and_die("%s", buf+4);
400 * Splitting username:password pair,
403 str = strchr(target.user, ':');
406 switch (ftpcmd("USER ", target.user, sfp, buf)) {
410 if (ftpcmd("PASS ", str, sfp, buf) == 230)
412 /* FALLTHRU (failed login) */
414 bb_error_msg_and_die("ftp login: %s", buf+4);
417 ftpcmd("TYPE I", NULL, sfp, buf);
422 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
423 content_len = BB_STRTOOFF(buf+4, NULL, 10);
424 if (errno || content_len < 0) {
425 bb_error_msg_and_die("SIZE value is garbage");
431 * Entering passive mode
433 if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
435 bb_error_msg_and_die("bad response to %s: %s", "PASV", buf);
437 // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
438 // Server's IP is N1.N2.N3.N4 (we ignore it)
439 // Server's port for data connection is P1*256+P2
440 str = strrchr(buf, ')');
441 if (str) str[0] = '\0';
442 str = strrchr(buf, ',');
443 if (!str) goto pasv_error;
444 port = xatou_range(str+1, 0, 255);
446 str = strrchr(buf, ',');
447 if (!str) goto pasv_error;
448 port += xatou_range(str+1, 0, 255) * 256;
449 set_nport(lsa, htons(port));
450 dfp = open_socket(lsa);
453 sprintf(buf, "REST %"OFF_FMT"d", beg_range);
454 if (ftpcmd(buf, NULL, sfp, buf) == 350)
455 content_len -= beg_range;
458 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
459 bb_error_msg_and_die("bad response to %s: %s", "RETR", buf);
462 if (opt & WGET_OPT_SPIDER) {
463 if (ENABLE_FEATURE_CLEAN_UP)
472 /* Do it before progressmeter (want to have nice error message) */
474 output_fd = xopen(fname_out,
475 O_WRONLY|O_CREAT|O_EXCL|O_TRUNC);
477 if (!(opt & WGET_OPT_QUIET))
483 /* Loops only if chunked */
485 while (content_len > 0 || !got_clen) {
487 unsigned rdsz = sizeof(buf);
489 if (content_len < sizeof(buf) && (chunked || got_clen))
490 rdsz = (unsigned)content_len;
491 n = safe_fread(buf, rdsz, dfp);
494 /* perror will not work: ferror doesn't set errno */
495 bb_error_msg_and_die(bb_msg_read_error);
499 xwrite(output_fd, buf, n);
500 #if ENABLE_FEATURE_WGET_STATUSBAR
510 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
512 safe_fgets(buf, sizeof(buf), dfp);
513 content_len = STRTOOFF(buf, NULL, 16);
514 /* FIXME: error check? */
515 if (content_len == 0)
516 break; /* all done! */
519 if (!(opt & WGET_OPT_QUIET))
522 if ((use_proxy == 0) && target.is_ftp) {
524 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
525 bb_error_msg_and_die("ftp error: %s", buf+4);
526 ftpcmd("QUIT", NULL, sfp, buf);
533 static void parse_url(char *src_url, struct host_info *h)
537 /* h->allocated = */ url = xstrdup(src_url);
539 if (strncmp(url, "http://", 7) == 0) {
540 h->port = bb_lookup_port("http", "tcp", 80);
543 } else if (strncmp(url, "ftp://", 6) == 0) {
544 h->port = bb_lookup_port("ftp", "tcp", 21);
548 bb_error_msg_and_die("not an http or ftp url: %s", url);
551 // "Real" wget 'http://busybox.net?var=a/b' sends this request:
552 // 'GET /?var=a/b HTTP 1.0'
553 // and saves 'index.html?var=a%2Fb' (we save 'b')
554 // wget 'http://busybox.net?login=john@doe':
555 // request: 'GET /?login=john@doe HTTP/1.0'
556 // saves: 'index.html?login=john@doe' (we save '?login=john@doe')
557 // wget 'http://busybox.net#test/test':
558 // request: 'GET / HTTP/1.0'
559 // saves: 'index.html' (we save 'test')
561 // We also don't add unique .N suffix if file exists...
562 sp = strchr(h->host, '/');
563 p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
564 p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
566 /* must be writable because of bb_get_last_path_component() */
567 static char nullstr[] ALIGN1 = "";
569 } else if (*sp == '/') {
572 } else { // '#' or '?'
573 // http://busybox.net?login=john@doe is a valid URL
574 // memmove converts to:
575 // http:/busybox.nett?login=john@doe...
576 memmove(h->host-1, h->host, sp - h->host);
582 sp = strrchr(h->host, '@');
594 static FILE *open_socket(len_and_sockaddr *lsa)
598 /* glibc 2.4 seems to try seeking on it - ??! */
599 /* hopefully it understands what ESPIPE means... */
600 fp = fdopen(xconnect_stream(lsa), "r+");
602 bb_perror_msg_and_die("fdopen");
608 static char *gethdr(char *buf, size_t bufsiz, FILE *fp /*, int *istrunc*/)
615 /* retrieve header line */
616 if (fgets(buf, bufsiz, fp) == NULL)
619 /* see if we are at the end of the headers */
620 for (s = buf; *s == '\r'; ++s)
625 /* convert the header name to lower case */
626 for (s = buf; isalnum(*s) || *s == '-' || *s == '.'; ++s)
629 /* verify we are at the end of the header name */
631 bb_error_msg_and_die("bad header line: %s", buf);
633 /* locate the start of the header value */
635 hdrval = skip_whitespace(s);
637 /* locate the end of header */
638 while (*s && *s != '\r' && *s != '\n')
641 /* end of header found */
647 /* Rats! The buffer isn't big enough to hold the entire header value. */
648 while (c = getc(fp), c != EOF && c != '\n')
654 static int ftpcmd(const char *s1, const char *s2, FILE *fp, char *buf)
659 fprintf(fp, "%s%s\r\n", s1, s2);
666 if (fgets(buf, 510, fp) == NULL) {
667 bb_perror_msg_and_die("error getting response");
669 buf_ptr = strstr(buf, "\r\n");
673 } while (!isdigit(buf[0]) || buf[3] != ' ');
676 result = xatoi_u(buf);
681 #if ENABLE_FEATURE_WGET_STATUSBAR
682 /* Stuff below is from BSD rcp util.c, as added to openshh.
683 * Original copyright notice is retained at the end of this file.
689 get_terminal_width_height(0, &width, NULL);
694 updateprogressmeter(int ignore)
696 int save_errno = errno;
702 static void alarmtimer(int iwait)
704 struct itimerval itv;
706 itv.it_value.tv_sec = iwait;
707 itv.it_value.tv_usec = 0;
708 itv.it_interval = itv.it_value;
709 setitimer(ITIMER_REAL, &itv, NULL);
713 progressmeter(int flag)
716 unsigned since_last_update, elapsed;
720 if (flag == -1) { /* first call to progressmeter */
721 start_sec = monotonic_sec();
722 lastupdate_sec = start_sec;
724 totalsize = content_len + beg_range; /* as content_len changes.. */
728 if (totalsize != 0 && !chunked) {
729 /* long long helps to have it working even if !LFS */
730 ratio = (unsigned) (100ULL * (transferred+beg_range) / totalsize);
731 if (ratio > 100) ratio = 100;
734 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
736 barlength = getttywidth() - 49;
738 /* god bless gcc for variable arrays :) */
739 i = barlength * ratio / 100;
744 fprintf(stderr, "|%s%*s|", buf, barlength - i, "");
748 abbrevsize = transferred + beg_range;
749 while (abbrevsize >= 100000) {
753 /* see http://en.wikipedia.org/wiki/Tera */
754 fprintf(stderr, "%6d%c ", (int)abbrevsize, " kMGTPEZY"[i]);
756 // Nuts! Ain't it easier to update progress meter ONLY when we transferred++?
757 // FIXME: get rid of alarmtimer + updateprogressmeter mess
759 elapsed = monotonic_sec();
760 since_last_update = elapsed - lastupdate_sec;
761 if (transferred > lastsize) {
762 lastupdate_sec = elapsed;
763 lastsize = transferred;
764 if (since_last_update >= STALLTIME) {
765 /* We "cut off" these seconds from elapsed time
766 * by adjusting start time */
767 start_sec += since_last_update;
769 since_last_update = 0; /* we are un-stalled now */
771 elapsed -= start_sec; /* now it's "elapsed since start" */
773 if (since_last_update >= STALLTIME) {
774 fprintf(stderr, " - stalled -");
776 off_t to_download = totalsize - beg_range;
777 if (transferred <= 0 || (int)elapsed <= 0 || transferred > to_download || chunked) {
778 fprintf(stderr, "--:--:-- ETA");
780 /* to_download / (transferred/elapsed) - elapsed: */
781 int eta = (int) ((unsigned long long)to_download*elapsed/transferred - elapsed);
782 /* (long long helps to have working ETA even if !LFS) */
784 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
788 if (flag == -1) { /* first call to progressmeter */
790 sa.sa_handler = updateprogressmeter;
791 sigemptyset(&sa.sa_mask);
792 sa.sa_flags = SA_RESTART;
793 sigaction(SIGALRM, &sa, NULL);
795 } else if (flag == 1) { /* last call to progressmeter */
801 #endif /* FEATURE_WGET_STATUSBAR */
803 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
804 * much of which was blatantly stolen from openssh. */
807 * Copyright (c) 1992, 1993
808 * The Regents of the University of California. All rights reserved.
810 * Redistribution and use in source and binary forms, with or without
811 * modification, are permitted provided that the following conditions
813 * 1. Redistributions of source code must retain the above copyright
814 * notice, this list of conditions and the following disclaimer.
815 * 2. Redistributions in binary form must reproduce the above copyright
816 * notice, this list of conditions and the following disclaimer in the
817 * documentation and/or other materials provided with the distribution.
819 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
820 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
822 * 4. Neither the name of the University nor the names of its contributors
823 * may be used to endorse or promote products derived from this software
824 * without specific prior written permission.
826 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
827 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
828 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
829 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
830 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
831 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
832 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
833 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
834 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
835 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF