1 /* vi: set sw=4 ts=4: */
3 * wget - retrieve a file using HTTP or FTP
5 * Chip Rosenthal Covad Communications <chip@laserlink.net>
20 static void parse_url(char *url, struct host_info *h);
21 static FILE *open_socket(struct sockaddr_in *s_in);
22 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
23 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf);
25 /* Globals (can be accessed from signal handlers */
26 static off_t filesize; /* content-length of the file */
27 static int chunked; /* chunked transfer encoding */
28 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
29 static void progressmeter(int flag);
30 static char *curfile; /* Name of current file being transferred. */
31 static struct timeval start; /* Time a transfer started. */
32 static off_t transferred; /* Number of bytes transferred so far. */
33 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
38 static void progressmeter(int flag) {}
41 /* Read NMEMB elements of SIZE bytes into PTR from STREAM. Returns the
42 * number of elements read, and a short count if an eof or non-interrupt
43 * error is encountered. */
44 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
50 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
51 } while (ret < nmemb && ferror(stream) && errno == EINTR);
56 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
57 * Returns S, or NULL if an eof or non-interrupt error is encountered. */
58 static char *safe_fgets(char *s, int size, FILE *stream)
64 ret = fgets(s, size, stream);
65 } while (ret == NULL && ferror(stream) && errno == EINTR);
70 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
72 * Base64-encode character string and return the string.
74 static char *base64enc(unsigned char *p, char *buf, int len)
76 bb_uuencode(p, buf, len, bb_uuenc_tbl_base64);
81 #define WGET_OPT_CONTINUE 1
82 #define WGET_OPT_QUIET 2
83 #define WGET_OPT_PASSIVE 4
84 #define WGET_OPT_OUTNAME 8
85 #define WGET_OPT_HEADER 16
86 #define WGET_OPT_PREFIX 32
87 #define WGET_OPT_PROXY 64
88 #define WGET_OPT_USER_AGENT 128
90 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
91 static const struct option wget_long_options[] = {
92 { "continue", 0, NULL, 'c' },
93 { "quiet", 0, NULL, 'q' },
94 { "passive-ftp", 0, NULL, 139 },
95 { "output-document", 1, NULL, 'O' },
96 { "header", 1, NULL, 131 },
97 { "directory-prefix",1, NULL, 'P' },
98 { "proxy", 1, NULL, 'Y' },
99 { "user-agent", 1, NULL, 'U' },
104 int wget_main(int argc, char **argv)
106 int n, try=5, status;
110 char *dir_prefix=NULL;
112 char extra_headers[1024];
113 char *extra_headers_ptr = extra_headers;
114 int extra_headers_left = sizeof(extra_headers);
115 struct host_info server, target;
116 struct sockaddr_in s_in;
117 llist_t *headers_llist = NULL;
119 FILE *sfp = NULL; /* socket to web/ftp server */
120 FILE *dfp = NULL; /* socket to ftp server (data) */
121 char *fname_out = NULL; /* where to direct output (-O) */
122 int do_continue = 0; /* continue a prev transfer (-c) */
123 off64_t beg_range = 0; /* range at which continue begins */
124 int got_clen = 0; /* got content-length: from server */
126 int quiet_flag = FALSE; /* Be verry, verry quiet... */
127 int use_proxy = 1; /* Use proxies if env vars are set */
128 char *proxy_flag = "on"; /* Use proxies if env vars are set */
129 char *user_agent = "Wget"; /* Content of the "User-Agent" header field */
132 * Crack command line.
134 bb_opt_complementally = "-1:\203::";
135 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
136 bb_applet_long_options = wget_long_options;
138 opt = bb_getopt_ulflags(argc, argv, "cq\213O:\203:P:Y:U:",
139 &fname_out, &headers_llist,
140 &dir_prefix, &proxy_flag, &user_agent);
141 if (opt & WGET_OPT_CONTINUE) {
144 if (opt & WGET_OPT_QUIET) {
147 if (strcmp(proxy_flag, "off") == 0) {
148 /* Use the proxy if necessary. */
151 if (opt & WGET_OPT_HEADER) {
152 while (headers_llist) {
153 int arglen = strlen(headers_llist->data);
154 if (extra_headers_left - arglen - 2 <= 0)
155 bb_error_msg_and_die("extra_headers buffer too small "
156 "(need %i)", extra_headers_left - arglen);
157 strcpy(extra_headers_ptr, headers_llist->data);
158 extra_headers_ptr += arglen;
159 extra_headers_left -= ( arglen + 2 );
160 *extra_headers_ptr++ = '\r';
161 *extra_headers_ptr++ = '\n';
162 *(extra_headers_ptr + 1) = 0;
163 headers_llist = headers_llist->link;
167 parse_url(argv[optind], &target);
168 server.host = target.host;
169 server.port = target.port;
172 * Use the proxy if necessary.
175 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
176 if (proxy && *proxy) {
177 parse_url(xstrdup(proxy), &server);
183 /* Guess an output filename */
185 // Dirty hack. Needed because bb_get_last_path_component
186 // will destroy trailing / by storing '\0' in last byte!
187 if (*target.path && target.path[strlen(target.path)-1] != '/') {
189 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
192 bb_get_last_path_component(target.path);
194 if (!fname_out || !fname_out[0]) {
196 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
201 if (dir_prefix != NULL)
202 fname_out = concat_path_file(dir_prefix, fname_out);
203 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
205 curfile = bb_get_last_path_component(fname_out);
208 if (do_continue && !fname_out)
209 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
212 * Determine where to start transfer.
214 if (!strcmp(fname_out, "-")) {
218 } else if (do_continue) {
219 output_fd = open(fname_out, O_WRONLY|O_LARGEFILE);
220 if (output_fd >= 0) {
221 beg_range = lseek64(output_fd, 0, SEEK_END);
222 if (beg_range == (off64_t)-1)
223 bb_perror_msg_and_die("lseek64");
225 /* File doesn't exist. We do not create file here yet.
226 We are not sure it exists on remove side */
229 /* We want to do exactly _one_ DNS lookup, since some
230 * sites (i.e. ftp.us.debian.org) use round-robin DNS
231 * and we want to connect to only one IP... */
232 bb_lookup_host(&s_in, server.host);
233 s_in.sin_port = server.port;
234 if (quiet_flag == FALSE) {
235 printf("Connecting to %s[%s]:%d\n",
236 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
239 if (use_proxy || !target.is_ftp) {
244 got_clen = chunked = 0;
247 bb_error_msg_and_die("too many redirections");
250 * Open socket to http server
252 if (sfp) fclose(sfp);
253 sfp = open_socket(&s_in);
259 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
260 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
261 if (strchr(target.host, ':'))
262 format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
265 target.is_ftp ? "f" : "ht", target.host,
266 ntohs(target.port), target.path);
268 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
271 fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n", target.host,
274 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
276 fprintf(sfp, "Authorization: Basic %s\r\n",
277 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
279 if (use_proxy && server.user) {
280 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
281 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
286 fprintf(sfp, "Range: bytes=%lld-\r\n", (long long)beg_range);
287 if(extra_headers_left < sizeof(extra_headers))
288 fputs(extra_headers,sfp);
289 fprintf(sfp,"Connection: close\r\n\r\n");
292 * Retrieve HTTP response line and check for "200" status code.
295 if (fgets(buf, sizeof(buf), sfp) == NULL)
296 bb_error_msg_and_die("no response from server");
298 for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
300 for ( ; isspace(*s) ; ++s)
302 switch (status = atoi(s)) {
305 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
309 case 300: /* redirection */
320 bb_error_msg_and_die("server returned error %d: %s", atoi(s), buf);
324 * Retrieve HTTP headers.
326 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
327 if (strcasecmp(buf, "content-length") == 0) {
329 if (safe_strtoul(s, &value)) {
330 bb_error_msg_and_die("content-length %s is garbage", s);
336 if (strcasecmp(buf, "transfer-encoding") == 0) {
337 if (strcasecmp(s, "chunked") == 0) {
338 chunked = got_clen = 1;
340 bb_error_msg_and_die("server wants to do %s transfer encoding", s);
343 if (strcasecmp(buf, "location") == 0) {
345 target.path = xstrdup(s+1);
347 parse_url(xstrdup(s), &target);
348 if (use_proxy == 0) {
349 server.host = target.host;
350 server.port = target.port;
352 bb_lookup_host(&s_in, server.host);
353 s_in.sin_port = server.port;
358 } while(status >= 300);
368 target.user = xstrdup("anonymous:busybox@");
370 sfp = open_socket(&s_in);
371 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
372 bb_error_msg_and_die("%s", buf+4);
375 * Splitting username:password pair,
378 s = strchr(target.user, ':');
381 switch(ftpcmd("USER ", target.user, sfp, buf)) {
385 if (ftpcmd("PASS ", s, sfp, buf) == 230)
387 /* FALLTHRU (failed login) */
389 bb_error_msg_and_die("ftp login: %s", buf+4);
392 ftpcmd("TYPE I", NULL, sfp, buf);
397 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
399 if (safe_strtoul(buf+4, &value)) {
400 bb_error_msg_and_die("SIZE value is garbage");
407 * Entering passive mode
409 if (ftpcmd("PASV", NULL, sfp, buf) != 227)
410 bb_error_msg_and_die("PASV: %s", buf+4);
411 s = strrchr(buf, ',');
414 s = strrchr(buf, ',');
415 port += atoi(s+1) * 256;
416 s_in.sin_port = htons(port);
417 dfp = open_socket(&s_in);
420 sprintf(buf, "REST %lld", (long long)beg_range);
421 if (ftpcmd(buf, NULL, sfp, buf) == 350)
422 filesize -= beg_range;
425 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
426 bb_error_msg_and_die("RETR: %s", buf+4);
434 fgets(buf, sizeof(buf), dfp);
435 filesize = strtol(buf, (char **) NULL, 16);
438 if (quiet_flag == FALSE)
442 while (filesize > 0 || !got_clen) {
443 unsigned rdsz = sizeof(buf);
444 if (filesize < sizeof(buf) && (chunked || got_clen))
446 n = safe_fread(buf, 1, rdsz, dfp);
450 output_fd = xopen3(fname_out, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC|O_LARGEFILE, 0666);
451 if (full_write(output_fd, buf, n) != n) {
452 bb_perror_msg_and_die(bb_msg_write_error);
454 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
463 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
464 safe_fgets(buf, sizeof(buf), dfp);
465 filesize = strtol(buf, (char **) NULL, 16);
467 chunked = 0; /* all done! */
471 if (n == 0 && ferror(dfp)) {
472 bb_perror_msg_and_die(bb_msg_read_error);
476 if (quiet_flag == FALSE)
479 if ((use_proxy == 0) && target.is_ftp) {
481 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
482 bb_error_msg_and_die("ftp error: %s", buf+4);
483 ftpcmd("QUIT", NULL, sfp, buf);
489 static void parse_url(char *url, struct host_info *h)
491 char *cp, *sp, *up, *pp;
493 if (strncmp(url, "http://", 7) == 0) {
494 h->port = bb_lookup_port("http", "tcp", 80);
497 } else if (strncmp(url, "ftp://", 6) == 0) {
498 h->port = bb_lookup_port("ftp", "tfp", 21);
502 bb_error_msg_and_die("not an http or ftp url: %s", url);
504 sp = strchr(h->host, '/');
509 h->path = xstrdup("");
511 up = strrchr(h->host, '@');
521 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
522 if (h->host[0] == '[') {
526 while (*ep == ':' || isxdigit (*ep))
536 cp = strchr(pp, ':');
539 h->port = htons(atoi(cp));
544 static FILE *open_socket(struct sockaddr_in *s_in)
548 fp = fdopen(xconnect(s_in), "r+");
550 bb_perror_msg_and_die("fdopen");
556 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
563 /* retrieve header line */
564 if (fgets(buf, bufsiz, fp) == NULL)
567 /* see if we are at the end of the headers */
568 for (s = buf ; *s == '\r' ; ++s)
573 /* convert the header name to lower case */
574 for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
577 /* verify we are at the end of the header name */
579 bb_error_msg_and_die("bad header line: %s", buf);
581 /* locate the start of the header value */
582 for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
586 /* locate the end of header */
587 while (*s != '\0' && *s != '\r' && *s != '\n')
590 /* end of header found */
596 /* Rats! The buffer isn't big enough to hold the entire header value. */
597 while (c = getc(fp), c != EOF && c != '\n')
603 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
607 fprintf(fp, "%s%s\r\n", s1, s2);
614 if (fgets(buf, 510, fp) == NULL) {
615 bb_perror_msg_and_die("fgets");
617 buf_ptr = strstr(buf, "\r\n");
621 } while (!isdigit(buf[0]) || buf[3] != ' ');
626 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
627 /* Stuff below is from BSD rcp util.c, as added to openshh.
628 * Original copyright notice is retained at the end of this file.
637 get_terminal_width_height(0, &width, NULL);
642 updateprogressmeter(int ignore)
644 int save_errno = errno;
650 static void alarmtimer(int iwait)
652 struct itimerval itv;
654 itv.it_value.tv_sec = iwait;
655 itv.it_value.tv_usec = 0;
656 itv.it_interval = itv.it_value;
657 setitimer(ITIMER_REAL, &itv, NULL);
662 progressmeter(int flag)
664 static struct timeval lastupdate;
665 static off_t lastsize, totalsize;
667 struct timeval now, td, tvwait;
669 int elapsed, ratio, barlength, i;
673 (void) gettimeofday(&start, (struct timezone *) 0);
676 totalsize = filesize; /* as filesize changes.. */
679 (void) gettimeofday(&now, (struct timezone *) 0);
681 if (totalsize != 0 && !chunked) {
682 ratio = (int) (100 * transferred / totalsize);
683 ratio = MIN(ratio, 100);
686 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
688 barlength = getttywidth() - 51;
689 if (barlength > 0 && barlength < sizeof(buf)) {
690 i = barlength * ratio / 100;
692 memset(buf + i, ' ', barlength - i);
693 buf[barlength] = '\0';
694 fprintf(stderr, "|%s|", buf);
697 abbrevsize = transferred;
698 while (abbrevsize >= 100000) {
702 /* See http://en.wikipedia.org/wiki/Tera */
703 fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
705 timersub(&now, &lastupdate, &tvwait);
706 if (transferred > lastsize) {
708 lastsize = transferred;
709 if (tvwait.tv_sec >= STALLTIME)
710 timeradd(&start, &tvwait, &start);
713 timersub(&now, &start, &td);
716 if (tvwait.tv_sec >= STALLTIME) {
717 fprintf(stderr, " - stalled -");
718 } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
719 fprintf(stderr, "--:--:-- ETA");
721 /* totalsize / (transferred/elapsed) - elapsed: */
722 int eta = (int) (totalsize*elapsed/transferred - elapsed);
724 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
729 sa.sa_handler = updateprogressmeter;
730 sigemptyset(&sa.sa_mask);
731 sa.sa_flags = SA_RESTART;
732 sigaction(SIGALRM, &sa, NULL);
734 } else if (flag == 1) {
742 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
743 * much of which was blatantly stolen from openssh. */
746 * Copyright (c) 1992, 1993
747 * The Regents of the University of California. All rights reserved.
749 * Redistribution and use in source and binary forms, with or without
750 * modification, are permitted provided that the following conditions
752 * 1. Redistributions of source code must retain the above copyright
753 * notice, this list of conditions and the following disclaimer.
754 * 2. Redistributions in binary form must reproduce the above copyright
755 * notice, this list of conditions and the following disclaimer in the
756 * documentation and/or other materials provided with the distribution.
758 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
759 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
761 * 4. Neither the name of the University nor the names of its contributors
762 * may be used to endorse or promote products derived from this software
763 * without specific prior written permission.
765 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
766 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
767 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
768 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
769 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
770 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
771 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
772 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
773 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
774 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
777 * $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $