1 /* vi: set sw=4 ts=4: */
3 * wget - retrieve a file using HTTP or FTP
5 * Chip Rosenthal Covad Communications <chip@laserlink.net>
21 static void parse_url(char *url, struct host_info *h);
22 static FILE *open_socket(struct sockaddr_in *s_in);
23 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
24 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf);
26 /* Globals (can be accessed from signal handlers */
27 static off_t filesize; /* content-length of the file */
28 static int chunked; /* chunked transfer encoding */
29 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
30 static void progressmeter(int flag);
31 static char *curfile; /* Name of current file being transferred. */
32 static struct timeval start; /* Time a transfer started. */
33 static off_t transferred; /* Number of bytes transferred so far. */
34 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
39 static void progressmeter(int flag) {}
42 static void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
44 if (output != stdout && do_continue == 0) {
50 /* Read NMEMB elements of SIZE bytes into PTR from STREAM. Returns the
51 * number of elements read, and a short count if an eof or non-interrupt
52 * error is encountered. */
53 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
59 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
60 } while (ret < nmemb && ferror(stream) && errno == EINTR);
65 /* Write NMEMB elements of SIZE bytes from PTR to STREAM. Returns the
66 * number of elements written, and a short count if an eof or non-interrupt
67 * error is encountered. */
68 static size_t safe_fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)
74 ret += fwrite((char *)ptr + (ret * size), size, nmemb - ret, stream);
75 } while (ret < nmemb && ferror(stream) && errno == EINTR);
80 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
81 * Returns S, or NULL if an eof or non-interrupt error is encountered. */
82 static char *safe_fgets(char *s, int size, FILE *stream)
88 ret = fgets(s, size, stream);
89 } while (ret == NULL && ferror(stream) && errno == EINTR);
94 #define close_delete_and_die(s...) { \
95 close_and_delete_outfile(output, fname_out, do_continue); \
96 bb_error_msg_and_die(s); }
99 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
101 * Base64-encode character string and return the string.
103 static char *base64enc(unsigned char *p, char *buf, int len)
105 bb_uuencode(p, buf, len, bb_uuenc_tbl_base64);
110 #define WGET_OPT_CONTINUE 1
111 #define WGET_OPT_QUIET 2
112 #define WGET_OPT_PASSIVE 4
113 #define WGET_OPT_OUTNAME 8
114 #define WGET_OPT_HEADER 16
115 #define WGET_OPT_PREFIX 32
116 #define WGET_OPT_PROXY 64
117 #define WGET_OPT_USER_AGENT 128
119 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
120 static const struct option wget_long_options[] = {
121 { "continue", 0, NULL, 'c' },
122 { "quiet", 0, NULL, 'q' },
123 { "passive-ftp", 0, NULL, 139 },
124 { "output-document", 1, NULL, 'O' },
125 { "header", 1, NULL, 131 },
126 { "directory-prefix",1, NULL, 'P' },
127 { "proxy", 1, NULL, 'Y' },
128 { "user-agent", 1, NULL, 'U' },
133 int wget_main(int argc, char **argv)
135 int n, try=5, status;
139 char *dir_prefix=NULL;
142 char extra_headers[1024];
143 char *extra_headers_ptr = extra_headers;
144 int extra_headers_left = sizeof(extra_headers);
145 struct host_info server, target;
146 struct sockaddr_in s_in;
147 llist_t *headers_llist = NULL;
149 FILE *sfp = NULL; /* socket to web/ftp server */
150 FILE *dfp = NULL; /* socket to ftp server (data) */
151 char *fname_out = NULL; /* where to direct output (-O) */
152 int do_continue = 0; /* continue a prev transfer (-c) */
153 long beg_range = 0L; /* range at which continue begins */
154 int got_clen = 0; /* got content-length: from server */
155 FILE *output; /* socket to web server */
156 int quiet_flag = FALSE; /* Be verry, verry quiet... */
157 int use_proxy = 1; /* Use proxies if env vars are set */
158 char *proxy_flag = "on"; /* Use proxies if env vars are set */
159 char *user_agent = "Wget"; /* Content of the "User-Agent" header field */
162 * Crack command line.
164 bb_opt_complementally = "-1:\203::";
165 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
166 bb_applet_long_options = wget_long_options;
168 opt = bb_getopt_ulflags(argc, argv, "cq\213O:\203:P:Y:U:",
169 &fname_out, &headers_llist,
170 &dir_prefix, &proxy_flag, &user_agent);
171 if (opt & WGET_OPT_CONTINUE) {
174 if (opt & WGET_OPT_QUIET) {
177 if (strcmp(proxy_flag, "off") == 0) {
178 /* Use the proxy if necessary. */
181 if (opt & WGET_OPT_HEADER) {
182 while (headers_llist) {
183 int arglen = strlen(headers_llist->data);
184 if (extra_headers_left - arglen - 2 <= 0)
185 bb_error_msg_and_die("extra_headers buffer too small "
186 "(need %i)", extra_headers_left - arglen);
187 strcpy(extra_headers_ptr, headers_llist->data);
188 extra_headers_ptr += arglen;
189 extra_headers_left -= ( arglen + 2 );
190 *extra_headers_ptr++ = '\r';
191 *extra_headers_ptr++ = '\n';
192 *(extra_headers_ptr + 1) = 0;
193 headers_llist = headers_llist->link;
197 parse_url(argv[optind], &target);
198 server.host = target.host;
199 server.port = target.port;
202 * Use the proxy if necessary.
205 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
206 if (proxy && *proxy) {
207 parse_url(xstrdup(proxy), &server);
213 /* Guess an output filename */
215 // Dirty hack. Needed because bb_get_last_path_component
216 // will destroy trailing / by storing '\0' in last byte!
217 if (*target.path && target.path[strlen(target.path)-1] != '/') {
219 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
222 bb_get_last_path_component(target.path);
224 if (fname_out == NULL || strlen(fname_out) < 1) {
226 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
231 if (dir_prefix != NULL)
232 fname_out = concat_path_file(dir_prefix, fname_out);
233 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
235 curfile = bb_get_last_path_component(fname_out);
238 if (do_continue && !fname_out)
239 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
243 * Open the output file stream.
245 if (strcmp(fname_out, "-") == 0) {
249 output = xfopen(fname_out, (do_continue ? "a" : "w"));
253 * Determine where to start transfer.
256 if (fstat(fileno(output), &sbuf) < 0)
257 bb_perror_msg_and_die("fstat");
258 if (sbuf.st_size > 0)
259 beg_range = sbuf.st_size;
264 /* We want to do exactly _one_ DNS lookup, since some
265 * sites (i.e. ftp.us.debian.org) use round-robin DNS
266 * and we want to connect to only one IP... */
267 bb_lookup_host(&s_in, server.host);
268 s_in.sin_port = server.port;
269 if (quiet_flag == FALSE) {
270 printf("Connecting to %s[%s]:%d\n",
271 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
274 if (use_proxy || !target.is_ftp) {
279 got_clen = chunked = 0;
282 close_delete_and_die("too many redirections");
285 * Open socket to http server
287 if (sfp) fclose(sfp);
288 sfp = open_socket(&s_in);
294 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
295 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
296 if (strchr(target.host, ':'))
297 format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
300 target.is_ftp ? "f" : "ht", target.host,
301 ntohs(target.port), target.path);
303 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
306 fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n", target.host,
309 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
311 fprintf(sfp, "Authorization: Basic %s\r\n",
312 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
314 if (use_proxy && server.user) {
315 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
316 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
321 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
322 if(extra_headers_left < sizeof(extra_headers))
323 fputs(extra_headers,sfp);
324 fprintf(sfp,"Connection: close\r\n\r\n");
327 * Retrieve HTTP response line and check for "200" status code.
330 if (fgets(buf, sizeof(buf), sfp) == NULL)
331 close_delete_and_die("no response from server");
333 for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
335 for ( ; isspace(*s) ; ++s)
337 switch (status = atoi(s)) {
340 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
343 if (do_continue && output != stdout)
344 output = freopen(fname_out, "w", output);
347 case 300: /* redirection */
358 close_delete_and_die("server returned error %d: %s", atoi(s), buf);
362 * Retrieve HTTP headers.
364 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
365 if (strcasecmp(buf, "content-length") == 0) {
367 if (safe_strtoul(s, &value)) {
368 close_delete_and_die("content-length %s is garbage", s);
374 if (strcasecmp(buf, "transfer-encoding") == 0) {
375 if (strcasecmp(s, "chunked") == 0) {
376 chunked = got_clen = 1;
378 close_delete_and_die("server wants to do %s transfer encoding", s);
381 if (strcasecmp(buf, "location") == 0) {
383 target.path = xstrdup(s+1);
385 parse_url(xstrdup(s), &target);
386 if (use_proxy == 0) {
387 server.host = target.host;
388 server.port = target.port;
390 bb_lookup_host(&s_in, server.host);
391 s_in.sin_port = server.port;
396 } while(status >= 300);
406 target.user = xstrdup("anonymous:busybox@");
408 sfp = open_socket(&s_in);
409 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
410 close_delete_and_die("%s", buf+4);
413 * Splitting username:password pair,
416 s = strchr(target.user, ':');
419 switch(ftpcmd("USER ", target.user, sfp, buf)) {
423 if (ftpcmd("PASS ", s, sfp, buf) == 230)
425 /* FALLTHRU (failed login) */
427 close_delete_and_die("ftp login: %s", buf+4);
430 ftpcmd("TYPE I", NULL, sfp, buf);
435 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
437 if (safe_strtoul(buf+4, &value)) {
438 close_delete_and_die("SIZE value is garbage");
445 * Entering passive mode
447 if (ftpcmd("PASV", NULL, sfp, buf) != 227)
448 close_delete_and_die("PASV: %s", buf+4);
449 s = strrchr(buf, ',');
452 s = strrchr(buf, ',');
453 port += atoi(s+1) * 256;
454 s_in.sin_port = htons(port);
455 dfp = open_socket(&s_in);
458 sprintf(buf, "REST %ld", beg_range);
459 if (ftpcmd(buf, NULL, sfp, buf) != 350) {
460 if (output != stdout)
461 output = freopen(fname_out, "w", output);
464 filesize -= beg_range;
467 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
468 close_delete_and_die("RETR: %s", buf+4);
476 fgets(buf, sizeof(buf), dfp);
477 filesize = strtol(buf, (char **) NULL, 16);
480 if (quiet_flag == FALSE)
484 while (filesize > 0 || !got_clen) {
485 unsigned rdsz = sizeof(buf);
486 if (filesize < sizeof(buf) && (chunked || got_clen))
488 n = safe_fread(buf, 1, rdsz, dfp);
491 if (safe_fwrite(buf, 1, n, output) != n) {
492 bb_perror_msg_and_die(bb_msg_write_error);
494 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
503 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
504 safe_fgets(buf, sizeof(buf), dfp);
505 filesize = strtol(buf, (char **) NULL, 16);
507 chunked = 0; /* all done! */
511 if (n == 0 && ferror(dfp)) {
512 bb_perror_msg_and_die(bb_msg_read_error);
516 if (quiet_flag == FALSE)
519 if ((use_proxy == 0) && target.is_ftp) {
521 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
522 bb_error_msg_and_die("ftp error: %s", buf+4);
523 ftpcmd("QUIT", NULL, sfp, buf);
529 void parse_url(char *url, struct host_info *h)
531 char *cp, *sp, *up, *pp;
533 if (strncmp(url, "http://", 7) == 0) {
534 h->port = bb_lookup_port("http", "tcp", 80);
537 } else if (strncmp(url, "ftp://", 6) == 0) {
538 h->port = bb_lookup_port("ftp", "tfp", 21);
542 bb_error_msg_and_die("not an http or ftp url: %s", url);
544 sp = strchr(h->host, '/');
549 h->path = xstrdup("");
551 up = strrchr(h->host, '@');
561 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
562 if (h->host[0] == '[') {
566 while (*ep == ':' || isxdigit (*ep))
576 cp = strchr(pp, ':');
579 h->port = htons(atoi(cp));
584 FILE *open_socket(struct sockaddr_in *s_in)
588 fp = fdopen(xconnect(s_in), "r+");
590 bb_perror_msg_and_die("fdopen");
596 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
603 /* retrieve header line */
604 if (fgets(buf, bufsiz, fp) == NULL)
607 /* see if we are at the end of the headers */
608 for (s = buf ; *s == '\r' ; ++s)
613 /* convert the header name to lower case */
614 for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
617 /* verify we are at the end of the header name */
619 bb_error_msg_and_die("bad header line: %s", buf);
621 /* locate the start of the header value */
622 for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
626 /* locate the end of header */
627 while (*s != '\0' && *s != '\r' && *s != '\n')
630 /* end of header found */
636 /* Rats! The buffer isn't big enough to hold the entire header value. */
637 while (c = getc(fp), c != EOF && c != '\n')
643 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
647 fprintf(fp, "%s%s\r\n", s1, s2);
654 if (fgets(buf, 510, fp) == NULL) {
655 bb_perror_msg_and_die("fgets");
657 buf_ptr = strstr(buf, "\r\n");
661 } while (!isdigit(buf[0]) || buf[3] != ' ');
666 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
667 /* Stuff below is from BSD rcp util.c, as added to openshh.
668 * Original copyright notice is retained at the end of this file.
677 get_terminal_width_height(0, &width, NULL);
682 updateprogressmeter(int ignore)
684 int save_errno = errno;
690 static void alarmtimer(int iwait)
692 struct itimerval itv;
694 itv.it_value.tv_sec = iwait;
695 itv.it_value.tv_usec = 0;
696 itv.it_interval = itv.it_value;
697 setitimer(ITIMER_REAL, &itv, NULL);
702 progressmeter(int flag)
704 static struct timeval lastupdate;
705 static off_t lastsize, totalsize;
707 struct timeval now, td, tvwait;
709 int elapsed, ratio, barlength, i;
713 (void) gettimeofday(&start, (struct timezone *) 0);
716 totalsize = filesize; /* as filesize changes.. */
719 (void) gettimeofday(&now, (struct timezone *) 0);
721 if (totalsize != 0 && !chunked) {
722 ratio = (int) (100 * transferred / totalsize);
723 ratio = MIN(ratio, 100);
726 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
728 barlength = getttywidth() - 51;
729 if (barlength > 0 && barlength < sizeof(buf)) {
730 i = barlength * ratio / 100;
732 memset(buf + i, ' ', barlength - i);
733 buf[barlength] = '\0';
734 fprintf(stderr, "|%s|", buf);
737 abbrevsize = transferred;
738 while (abbrevsize >= 100000) {
742 /* See http://en.wikipedia.org/wiki/Tera */
743 fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
745 timersub(&now, &lastupdate, &tvwait);
746 if (transferred > lastsize) {
748 lastsize = transferred;
749 if (tvwait.tv_sec >= STALLTIME)
750 timeradd(&start, &tvwait, &start);
753 timersub(&now, &start, &td);
756 if (tvwait.tv_sec >= STALLTIME) {
757 fprintf(stderr, " - stalled -");
758 } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
759 fprintf(stderr, "--:--:-- ETA");
761 /* totalsize / (transferred/elapsed) - elapsed: */
762 int eta = (int) (totalsize*elapsed/transferred - elapsed);
764 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
769 sa.sa_handler = updateprogressmeter;
770 sigemptyset(&sa.sa_mask);
771 sa.sa_flags = SA_RESTART;
772 sigaction(SIGALRM, &sa, NULL);
774 } else if (flag == 1) {
782 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
783 * much of which was blatantly stolen from openssh. */
786 * Copyright (c) 1992, 1993
787 * The Regents of the University of California. All rights reserved.
789 * Redistribution and use in source and binary forms, with or without
790 * modification, are permitted provided that the following conditions
792 * 1. Redistributions of source code must retain the above copyright
793 * notice, this list of conditions and the following disclaimer.
794 * 2. Redistributions in binary form must reproduce the above copyright
795 * notice, this list of conditions and the following disclaimer in the
796 * documentation and/or other materials provided with the distribution.
798 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
799 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
801 * 4. Neither the name of the University nor the names of its contributors
802 * may be used to endorse or promote products derived from this software
803 * without specific prior written permission.
805 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
806 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
807 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
808 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
809 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
810 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
811 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
812 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
813 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
814 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
817 * $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $