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(struct sockaddr_in *s_in);
28 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
29 static int ftpcmd(char *s1, 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 int chunked; /* chunked transfer encoding */
38 #if ENABLE_FEATURE_WGET_STATUSBAR
39 static void progressmeter(int flag);
40 static 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
80 * Base64-encode character string and return the string.
82 static char *base64enc(unsigned char *p, char *buf, int len)
84 bb_uuencode(p, buf, len, bb_uuenc_tbl_base64);
89 int wget_main(int argc, char **argv)
92 struct host_info server, target;
93 struct sockaddr_in s_in;
100 char *dir_prefix = NULL;
101 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
102 char *extra_headers = NULL;
103 llist_t *headers_llist = NULL;
106 /* server.allocated = target.allocated = NULL; */
108 FILE *sfp = NULL; /* socket to web/ftp server */
109 FILE *dfp = NULL; /* socket to ftp server (data) */
110 char *fname_out = NULL; /* where to direct output (-O) */
111 int got_clen = 0; /* got content-length: from server */
113 int use_proxy = 1; /* Use proxies if env vars are set */
114 const char *proxy_flag = "on"; /* Use proxies if env vars are set */
115 const char *user_agent = "Wget";/* Content of the "User-Agent" header field */
118 * Crack command line.
121 WGET_OPT_CONTINUE = 0x1,
122 WGET_OPT_QUIET = 0x2,
123 WGET_OPT_OUTNAME = 0x4,
124 WGET_OPT_PREFIX = 0x8,
125 WGET_OPT_PROXY = 0x10,
126 WGET_OPT_USER_AGENT = 0x20,
127 WGET_OPT_PASSIVE = 0x40,
128 WGET_OPT_HEADER = 0x80,
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 { "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 opt_complementary = "-1" USE_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
146 opt = getopt32(argc, argv, "cqO:P:Y:U:",
147 &fname_out, &dir_prefix,
148 &proxy_flag, &user_agent
149 USE_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
151 if (strcmp(proxy_flag, "off") == 0) {
152 /* Use the proxy if necessary. */
155 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
159 llist_t *ll = headers_llist = rev_llist(headers_llist);
161 size += strlen(ll->data) + 2;
164 extra_headers = cp = xmalloc(size);
165 while (headers_llist) {
166 cp += sprintf(cp, "%s\r\n", headers_llist->data);
167 headers_llist = headers_llist->link;
172 parse_url(argv[optind], &target);
173 server.host = target.host;
174 server.port = target.port;
177 * 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 (*target.path && target.path[strlen(target.path)-1] != '/') {
194 #if ENABLE_FEATURE_WGET_STATUSBAR
197 bb_get_last_path_component(target.path);
199 if (!fname_out || !fname_out[0]) {
201 #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);
213 if ((opt & WGET_OPT_CONTINUE) && !fname_out)
214 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
217 * Determine where to start transfer.
219 if (!strcmp(fname_out, "-")) {
221 opt |= WGET_OPT_QUIET;
222 opt &= ~WGET_OPT_CONTINUE;
223 } else if (opt & WGET_OPT_CONTINUE) {
224 output_fd = open(fname_out, O_WRONLY);
225 if (output_fd >= 0) {
226 beg_range = xlseek(output_fd, 0, SEEK_END);
228 /* File doesn't exist. We do not create file here yet.
229 We are not sure it exists on remove side */
232 /* We want to do exactly _one_ DNS lookup, since some
233 * sites (i.e. ftp.us.debian.org) use round-robin DNS
234 * and we want to connect to only one IP... */
235 bb_lookup_host(&s_in, server.host);
236 s_in.sin_port = server.port;
237 if (!(opt & WGET_OPT_QUIET)) {
238 printf("Connecting to %s[%s]:%d\n",
239 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
242 if (use_proxy || !target.is_ftp) {
247 got_clen = chunked = 0;
250 bb_error_msg_and_die("too many redirections");
253 * Open socket to http server
255 if (sfp) fclose(sfp);
256 sfp = open_socket(&s_in);
262 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
263 #if ENABLE_FEATURE_WGET_IP6_LITERAL
264 if (strchr(target.host, ':'))
265 format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
268 target.is_ftp ? "f" : "ht", target.host,
269 ntohs(target.port), target.path);
271 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
274 fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n", target.host,
277 #if ENABLE_FEATURE_WGET_AUTHENTICATION
279 fprintf(sfp, "Authorization: Basic %s\r\n",
280 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
282 if (use_proxy && server.user) {
283 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
284 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
289 fprintf(sfp, "Range: bytes=%"OFF_FMT"-\r\n", beg_range);
290 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
292 fputs(extra_headers, sfp);
294 fprintf(sfp, "Connection: close\r\n\r\n");
297 * Retrieve HTTP response line and check for "200" status code.
300 if (fgets(buf, sizeof(buf), sfp) == NULL)
301 bb_error_msg_and_die("no response from server");
304 while (*s != '\0' && !isspace(*s)) ++s;
305 s = skip_whitespace(s);
306 // FIXME: no error check
307 // xatou wouldn't work: "200 OK"
312 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL)
313 /* eat all remaining headers */;
317 case 300: /* redirection */
327 /* Show first line only and kill any ESC tricks */
328 buf[strcspn(buf, "\n\r\x1b")] = '\0';
329 bb_error_msg_and_die("server returned error: %s", buf);
333 * Retrieve HTTP headers.
335 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
336 if (strcasecmp(buf, "content-length") == 0) {
337 if (SAFE_STRTOOFF(s, &content_len) || content_len < 0) {
338 bb_error_msg_and_die("content-length %s is garbage", s);
343 if (strcasecmp(buf, "transfer-encoding") == 0) {
344 if (strcasecmp(s, "chunked") != 0)
345 bb_error_msg_and_die("server wants to do %s transfer encoding", s);
346 chunked = got_clen = 1;
348 if (strcasecmp(buf, "location") == 0) {
350 /* free(target.allocated); */
351 target.path = /* target.allocated = */ xstrdup(s+1);
353 parse_url(s, &target);
354 if (use_proxy == 0) {
355 server.host = target.host;
356 server.port = target.port;
358 bb_lookup_host(&s_in, server.host);
359 s_in.sin_port = server.port;
364 } while(status >= 300);
374 target.user = xstrdup("anonymous:busybox@");
376 sfp = open_socket(&s_in);
377 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
378 bb_error_msg_and_die("%s", buf+4);
381 * Splitting username:password pair,
384 s = strchr(target.user, ':');
387 switch (ftpcmd("USER ", target.user, sfp, buf)) {
391 if (ftpcmd("PASS ", s, sfp, buf) == 230)
393 /* FALLTHRU (failed login) */
395 bb_error_msg_and_die("ftp login: %s", buf+4);
398 ftpcmd("TYPE I", NULL, sfp, buf);
403 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
404 if (SAFE_STRTOOFF(buf+4, &content_len) || content_len < 0) {
405 bb_error_msg_and_die("SIZE value is garbage");
411 * Entering passive mode
413 if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
415 bb_error_msg_and_die("bad response to %s: %s", "PASV", buf);
417 // Response is "227 garbageN1,N2,N3,N4,P1,P2[)]
418 // Server's IP is N1.N2.N3.N4 (we ignore it)
419 // Server's port for data connection is P1*256+P2
420 s = strrchr(buf, ')');
421 if (s && !s[1]) s[0] = '\0';
422 s = strrchr(buf, ',');
423 if (!s) goto pasv_error;
424 port = xatol_range(s+1, 0, 255);
426 s = strrchr(buf, ',');
427 if (!s) goto pasv_error;
428 port += xatol_range(s+1, 0, 255) * 256;
429 s_in.sin_port = htons(port);
430 dfp = open_socket(&s_in);
433 sprintf(buf, "REST %"OFF_FMT, beg_range);
434 if (ftpcmd(buf, NULL, sfp, buf) == 350)
435 content_len -= beg_range;
438 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
439 bb_error_msg_and_die("bad response to %s: %s", "RETR", buf);
447 fgets(buf, sizeof(buf), dfp);
448 content_len = STRTOOFF(buf, (char **) NULL, 16);
449 /* FIXME: error check?? */
452 /* Do it before progressmeter (want to have nice error message) */
454 output_fd = xopen3(fname_out,
455 O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0666);
457 if (!(opt & WGET_OPT_QUIET))
461 while (content_len > 0 || !got_clen) {
462 unsigned rdsz = sizeof(buf);
463 if (content_len < sizeof(buf) && (chunked || got_clen))
464 rdsz = (unsigned)content_len;
465 n = safe_fread(buf, 1, rdsz, dfp);
468 if (full_write(output_fd, buf, n) != n) {
469 bb_perror_msg_and_die(bb_msg_write_error);
471 #if ENABLE_FEATURE_WGET_STATUSBAR
480 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
481 safe_fgets(buf, sizeof(buf), dfp);
482 content_len = STRTOOFF(buf, (char **) NULL, 16);
483 /* FIXME: error check? */
484 if (content_len == 0) {
485 chunked = 0; /* all done! */
489 if (n == 0 && ferror(dfp)) {
490 bb_perror_msg_and_die(bb_msg_read_error);
494 if (!(opt & WGET_OPT_QUIET))
497 if ((use_proxy == 0) && target.is_ftp) {
499 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
500 bb_error_msg_and_die("ftp error: %s", buf+4);
501 ftpcmd("QUIT", NULL, sfp, buf);
507 static void parse_url(char *src_url, struct host_info *h)
509 char *url, *p, *cp, *sp, *up, *pp;
511 /* h->allocated = */ url = xstrdup(src_url);
513 if (strncmp(url, "http://", 7) == 0) {
514 h->port = bb_lookup_port("http", "tcp", 80);
517 } else if (strncmp(url, "ftp://", 6) == 0) {
518 h->port = bb_lookup_port("ftp", "tcp", 21);
522 bb_error_msg_and_die("not an http or ftp url: %s", url);
525 // "Real" wget 'http://busybox.net?var=a/b' sends this request:
526 // 'GET /?var=a/b HTTP 1.0'
527 // and saves 'index.html?var=a%2Fb' (we save 'b')
528 // wget 'http://busybox.net?login=john@doe':
529 // request: 'GET /?login=john@doe HTTP/1.0'
530 // saves: 'index.html?login=john@doe' (we save '?login=john@doe')
531 // wget 'http://busybox.net#test/test':
532 // request: 'GET / HTTP/1.0'
533 // saves: 'index.html' (we save 'test')
535 // We also don't add unique .N suffix if file exists...
536 sp = strchr(h->host, '/');
537 p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
538 p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
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 up = strrchr(h->host, '@');
564 #if ENABLE_FEATURE_WGET_IP6_LITERAL
565 if (h->host[0] == '[') {
569 while (*ep == ':' || isxdigit(*ep))
579 cp = strchr(pp, ':');
582 h->port = htons(xatou16(cp));
587 static FILE *open_socket(struct sockaddr_in *s_in)
591 /* glibc 2.4 seems to try seeking on it - ??! */
592 /* hopefully it understands what ESPIPE means... */
593 fp = fdopen(xconnect_tcp_v4(s_in), "r+");
595 bb_perror_msg_and_die("fdopen");
601 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
608 /* retrieve header line */
609 if (fgets(buf, bufsiz, fp) == NULL)
612 /* see if we are at the end of the headers */
613 for (s = buf; *s == '\r'; ++s)
618 /* convert the header name to lower case */
619 for (s = buf; isalnum(*s) || *s == '-'; ++s)
622 /* verify we are at the end of the header name */
624 bb_error_msg_and_die("bad header line: %s", buf);
626 /* locate the start of the header value */
627 for (*s++ = '\0'; *s == ' ' || *s == '\t'; ++s)
631 /* locate the end of header */
632 while (*s != '\0' && *s != '\r' && *s != '\n')
635 /* end of header found */
641 /* Rats! The buffer isn't big enough to hold the entire header value. */
642 while (c = getc(fp), c != EOF && c != '\n')
648 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
653 fprintf(fp, "%s%s\r\n", s1, s2);
660 if (fgets(buf, 510, fp) == NULL) {
661 bb_perror_msg_and_die("error getting response");
663 buf_ptr = strstr(buf, "\r\n");
667 } while (!isdigit(buf[0]) || buf[3] != ' ');
670 result = xatoi_u(buf);
675 #if ENABLE_FEATURE_WGET_STATUSBAR
676 /* Stuff below is from BSD rcp util.c, as added to openshh.
677 * Original copyright notice is retained at the end of this file.
683 get_terminal_width_height(0, &width, NULL);
688 updateprogressmeter(int ignore)
690 int save_errno = errno;
696 static void alarmtimer(int iwait)
698 struct itimerval itv;
700 itv.it_value.tv_sec = iwait;
701 itv.it_value.tv_usec = 0;
702 itv.it_interval = itv.it_value;
703 setitimer(ITIMER_REAL, &itv, NULL);
708 progressmeter(int flag)
710 static struct timeval lastupdate;
711 static off_t lastsize, totalsize;
713 struct timeval now, td, tvwait;
715 int elapsed, ratio, barlength, i;
718 if (flag == -1) { /* first call to progressmeter */
719 gettimeofday(&start, (struct timezone *) 0);
722 totalsize = content_len + beg_range; /* as content_len changes.. */
725 gettimeofday(&now, (struct timezone *) 0);
727 if (totalsize != 0 && !chunked) {
728 /* long long helps to have working ETA even if !LFS */
729 ratio = (int) (100 * (unsigned long long)(transferred+beg_range) / totalsize);
730 ratio = MIN(ratio, 100);
733 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
735 barlength = getttywidth() - 51;
736 if (barlength > 0 && barlength < sizeof(buf)) {
737 i = barlength * ratio / 100;
739 memset(buf + i, ' ', barlength - i);
740 buf[barlength] = '\0';
741 fprintf(stderr, "|%s|", buf);
744 abbrevsize = transferred + beg_range;
745 while (abbrevsize >= 100000) {
749 /* see http://en.wikipedia.org/wiki/Tera */
750 fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
752 timersub(&now, &lastupdate, &tvwait);
753 if (transferred > lastsize) {
755 lastsize = transferred;
756 if (tvwait.tv_sec >= STALLTIME)
757 timeradd(&start, &tvwait, &start);
760 timersub(&now, &start, &td);
763 if (tvwait.tv_sec >= STALLTIME) {
764 fprintf(stderr, " - stalled -");
766 off_t to_download = totalsize - beg_range;
767 if (transferred <= 0 || elapsed <= 0 || transferred > to_download || chunked) {
768 fprintf(stderr, "--:--:-- ETA");
770 /* to_download / (transferred/elapsed) - elapsed: */
771 int eta = (int) ((unsigned long long)to_download*elapsed/transferred - elapsed);
772 /* (long long helps to have working ETA even if !LFS) */
774 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
778 if (flag == -1) { /* first call to progressmeter */
780 sa.sa_handler = updateprogressmeter;
781 sigemptyset(&sa.sa_mask);
782 sa.sa_flags = SA_RESTART;
783 sigaction(SIGALRM, &sa, NULL);
785 } else if (flag == 1) { /* last call to progressmeter */
793 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
794 * much of which was blatantly stolen from openssh. */
797 * Copyright (c) 1992, 1993
798 * The Regents of the University of California. All rights reserved.
800 * Redistribution and use in source and binary forms, with or without
801 * modification, are permitted provided that the following conditions
803 * 1. Redistributions of source code must retain the above copyright
804 * notice, this list of conditions and the following disclaimer.
805 * 2. Redistributions in binary form must reproduce the above copyright
806 * notice, this list of conditions and the following disclaimer in the
807 * documentation and/or other materials provided with the distribution.
809 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
810 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
812 * 4. Neither the name of the University nor the names of its contributors
813 * may be used to endorse or promote products derived from this software
814 * without specific prior written permission.
816 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
817 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
818 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
819 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
820 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
821 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
822 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
823 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
824 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
825 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
828 * $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $