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 inline 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
102 * oops... isn't something similar in uuencode.c?
103 * XXX: It would be better to use already existing code
105 static char *base64enc(unsigned char *p, char *buf, int len) {
107 char al[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
113 bb_error_msg_and_die("buffer overflow");
114 *(s++) = al[(*p >> 2) & 0x3F];
115 *(s++) = al[((*p << 4) & 0x30) | ((*(p+1) >> 4) & 0x0F)];
119 *(s++) = al[((*p << 2) & 0x3C) | ((*(p+1) >> 6) & 0x03)];
121 *(s++) = al[*(p++) & 0x3F];
128 #define WGET_OPT_CONTINUE 1
129 #define WGET_OPT_QUIET 2
130 #define WGET_OPT_PASSIVE 4
131 #define WGET_OPT_OUTNAME 8
132 #define WGET_OPT_HEADER 16
133 #define WGET_OPT_PREFIX 32
134 #define WGET_OPT_PROXY 64
136 #if ENABLE_WGET_LONG_OPTIONS
137 static const struct option wget_long_options[] = {
138 { "continue", 0, NULL, 'c' },
139 { "quiet", 0, NULL, 'q' },
140 { "passive-ftp", 0, NULL, 139 },
141 { "output-document", 1, NULL, 'O' },
142 { "header", 1, NULL, 131 },
143 { "directory-prefix",1, NULL, 'P' },
144 { "proxy", 1, NULL, 'Y' },
149 int wget_main(int argc, char **argv)
151 int n, try=5, status;
155 char *dir_prefix=NULL;
158 char extra_headers[1024];
159 char *extra_headers_ptr = extra_headers;
160 int extra_headers_left = sizeof(extra_headers);
161 struct host_info server, target;
162 struct sockaddr_in s_in;
163 llist_t *headers_llist = NULL;
165 FILE *sfp = NULL; /* socket to web/ftp server */
166 FILE *dfp = NULL; /* socket to ftp server (data) */
167 char *fname_out = NULL; /* where to direct output (-O) */
168 int do_continue = 0; /* continue a prev transfer (-c) */
169 long beg_range = 0L; /* range at which continue begins */
170 int got_clen = 0; /* got content-length: from server */
171 FILE *output; /* socket to web server */
172 int quiet_flag = FALSE; /* Be verry, verry quiet... */
173 int use_proxy = 1; /* Use proxies if env vars are set */
174 char *proxy_flag = "on"; /* Use proxies if env vars are set */
177 * Crack command line.
179 bb_opt_complementally = "-1:\203::";
180 #if ENABLE_WGET_LONG_OPTIONS
181 bb_applet_long_options = wget_long_options;
183 opt = bb_getopt_ulflags(argc, argv, "cq\213O:\203:P:Y:",
184 &fname_out, &headers_llist,
185 &dir_prefix, &proxy_flag);
186 if (opt & WGET_OPT_CONTINUE) {
189 if (opt & WGET_OPT_QUIET) {
192 if (strcmp(proxy_flag, "off") == 0) {
193 /* Use the proxy if necessary. */
196 if (opt & WGET_OPT_HEADER) {
197 while (headers_llist) {
198 int arglen = strlen(headers_llist->data);
199 if (extra_headers_left - arglen - 2 <= 0)
200 bb_error_msg_and_die("extra_headers buffer too small(need %i)", extra_headers_left - arglen);
201 strcpy(extra_headers_ptr, headers_llist->data);
202 extra_headers_ptr += arglen;
203 extra_headers_left -= ( arglen + 2 );
204 *extra_headers_ptr++ = '\r';
205 *extra_headers_ptr++ = '\n';
206 *(extra_headers_ptr + 1) = 0;
207 headers_llist = headers_llist->link;
211 parse_url(argv[optind], &target);
212 server.host = target.host;
213 server.port = target.port;
216 * Use the proxy if necessary.
219 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
220 if (proxy && *proxy) {
221 parse_url(xstrdup(proxy), &server);
227 /* Guess an output filename */
229 // Dirty hack. Needed because bb_get_last_path_component
230 // will destroy trailing / by storing '\0' in last byte!
231 if(*target.path && target.path[strlen(target.path)-1]!='/') {
233 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
236 bb_get_last_path_component(target.path);
238 if (fname_out==NULL || strlen(fname_out)<1) {
240 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
245 if (dir_prefix != NULL)
246 fname_out = concat_path_file(dir_prefix, fname_out);
247 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
249 curfile = bb_get_last_path_component(fname_out);
252 if (do_continue && !fname_out)
253 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
257 * Open the output file stream.
259 if (strcmp(fname_out, "-") == 0) {
263 output = xfopen(fname_out, (do_continue ? "a" : "w"));
267 * Determine where to start transfer.
270 if (fstat(fileno(output), &sbuf) < 0)
271 bb_perror_msg_and_die("fstat()");
272 if (sbuf.st_size > 0)
273 beg_range = sbuf.st_size;
278 /* We want to do exactly _one_ DNS lookup, since some
279 * sites (i.e. ftp.us.debian.org) use round-robin DNS
280 * and we want to connect to only one IP... */
281 bb_lookup_host(&s_in, server.host);
282 s_in.sin_port = server.port;
283 if (quiet_flag==FALSE) {
284 fprintf(stdout, "Connecting to %s[%s]:%d\n",
285 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
288 if (use_proxy || !target.is_ftp) {
293 got_clen = chunked = 0;
296 close_delete_and_die("too many redirections");
299 * Open socket to http server
301 if (sfp) fclose(sfp);
302 sfp = open_socket(&s_in);
308 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
309 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
310 if (strchr(target.host, ':'))
311 format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
314 target.is_ftp ? "f" : "ht", target.host,
315 ntohs(target.port), target.path);
317 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
320 fprintf(sfp, "Host: %s\r\nUser-Agent: Wget\r\n", target.host);
322 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
324 fprintf(sfp, "Authorization: Basic %s\r\n",
325 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
327 if (use_proxy && server.user) {
328 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
329 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
334 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
335 if(extra_headers_left < sizeof(extra_headers))
336 fputs(extra_headers,sfp);
337 fprintf(sfp,"Connection: close\r\n\r\n");
340 * Retrieve HTTP response line and check for "200" status code.
343 if (fgets(buf, sizeof(buf), sfp) == NULL)
344 close_delete_and_die("no response from server");
346 for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
348 for ( ; isspace(*s) ; ++s)
350 switch (status = atoi(s)) {
353 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
356 if (do_continue && output != stdout)
357 output = freopen(fname_out, "w", output);
360 case 300: /* redirection */
371 close_delete_and_die("server returned error %d: %s", atoi(s), buf);
375 * Retrieve HTTP headers.
377 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
378 if (strcasecmp(buf, "content-length") == 0) {
380 if (safe_strtoul(s, &value)) {
381 close_delete_and_die("content-length %s is garbage", s);
387 if (strcasecmp(buf, "transfer-encoding") == 0) {
388 if (strcasecmp(s, "chunked") == 0) {
389 chunked = got_clen = 1;
391 close_delete_and_die("server wants to do %s transfer encoding", s);
394 if (strcasecmp(buf, "location") == 0) {
396 target.path = xstrdup(s+1);
398 parse_url(xstrdup(s), &target);
399 if (use_proxy == 0) {
400 server.host = target.host;
401 server.port = target.port;
403 bb_lookup_host(&s_in, server.host);
404 s_in.sin_port = server.port;
409 } while(status >= 300);
419 target.user = xstrdup("anonymous:busybox@");
421 sfp = open_socket(&s_in);
422 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
423 close_delete_and_die("%s", buf+4);
426 * Splitting username:password pair,
429 s = strchr(target.user, ':');
432 switch(ftpcmd("USER ", target.user, sfp, buf)) {
436 if (ftpcmd("PASS ", s, sfp, buf) == 230)
438 /* FALLTHRU (failed login) */
440 close_delete_and_die("ftp login: %s", buf+4);
443 ftpcmd("TYPE I", NULL, sfp, buf);
448 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
450 if (safe_strtoul(buf+4, &value)) {
451 close_delete_and_die("SIZE value is garbage");
458 * Entering passive mode
460 if (ftpcmd("PASV", NULL, sfp, buf) != 227)
461 close_delete_and_die("PASV: %s", buf+4);
462 s = strrchr(buf, ',');
465 s = strrchr(buf, ',');
466 port += atoi(s+1) * 256;
467 s_in.sin_port = htons(port);
468 dfp = open_socket(&s_in);
471 sprintf(buf, "REST %ld", beg_range);
472 if (ftpcmd(buf, NULL, sfp, buf) != 350) {
473 if (output != stdout)
474 output = freopen(fname_out, "w", output);
477 filesize -= beg_range;
480 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
481 close_delete_and_die("RETR: %s", buf+4);
489 fgets(buf, sizeof(buf), dfp);
490 filesize = strtol(buf, (char **) NULL, 16);
493 if (quiet_flag==FALSE)
497 while ((filesize > 0 || !got_clen) && (n = safe_fread(buf, 1, ((chunked || got_clen) && (filesize < sizeof(buf)) ? filesize : sizeof(buf)), dfp)) > 0) {
498 if (safe_fwrite(buf, 1, n, output) != n) {
499 bb_perror_msg_and_die(bb_msg_write_error);
501 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
510 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
511 safe_fgets(buf, sizeof(buf), dfp);
512 filesize = strtol(buf, (char **) NULL, 16);
514 chunked = 0; /* all done! */
518 if (n == 0 && ferror(dfp)) {
519 bb_perror_msg_and_die(bb_msg_read_error);
523 if (quiet_flag==FALSE)
526 if ((use_proxy == 0) && target.is_ftp) {
528 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
529 bb_error_msg_and_die("ftp error: %s", buf+4);
530 ftpcmd("QUIT", NULL, sfp, buf);
536 void parse_url(char *url, struct host_info *h)
538 char *cp, *sp, *up, *pp;
540 if (strncmp(url, "http://", 7) == 0) {
541 h->port = bb_lookup_port("http", "tcp", 80);
544 } else if (strncmp(url, "ftp://", 6) == 0) {
545 h->port = bb_lookup_port("ftp", "tfp", 21);
549 bb_error_msg_and_die("not an http or ftp url: %s", url);
551 sp = strchr(h->host, '/');
556 h->path = xstrdup("");
558 up = strrchr(h->host, '@');
568 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
569 if (h->host[0] == '[') {
573 while (*ep == ':' || isxdigit (*ep))
583 cp = strchr(pp, ':');
586 h->port = htons(atoi(cp));
591 FILE *open_socket(struct sockaddr_in *s_in)
595 fp = fdopen(xconnect(s_in), "r+");
597 bb_perror_msg_and_die("fdopen()");
603 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
610 /* retrieve header line */
611 if (fgets(buf, bufsiz, fp) == NULL)
614 /* see if we are at the end of the headers */
615 for (s = buf ; *s == '\r' ; ++s)
620 /* convert the header name to lower case */
621 for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
624 /* verify we are at the end of the header name */
626 bb_error_msg_and_die("bad header line: %s", buf);
628 /* locate the start of the header value */
629 for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
633 /* locate the end of header */
634 while (*s != '\0' && *s != '\r' && *s != '\n')
637 /* end of header found */
643 /* Rats! The buffer isn't big enough to hold the entire header value. */
644 while (c = getc(fp), c != EOF && c != '\n')
650 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
654 fprintf(fp, "%s%s\r\n", s1, s2);
661 if (fgets(buf, 510, fp) == NULL) {
662 bb_perror_msg_and_die("fgets()");
664 buf_ptr = strstr(buf, "\r\n");
668 } while (! isdigit(buf[0]) || buf[3] != ' ');
673 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
674 /* Stuff below is from BSD rcp util.c, as added to openshh.
675 * Original copyright notice is retained at the end of this file.
684 get_terminal_width_height(0, &width, NULL);
689 updateprogressmeter(int ignore)
691 int save_errno = errno;
697 static void alarmtimer(int iwait)
699 struct itimerval itv;
701 itv.it_value.tv_sec = iwait;
702 itv.it_value.tv_usec = 0;
703 itv.it_interval = itv.it_value;
704 setitimer(ITIMER_REAL, &itv, NULL);
709 progressmeter(int flag)
711 static struct timeval lastupdate;
712 static off_t lastsize, totalsize;
714 struct timeval now, td, tvwait;
716 int elapsed, ratio, barlength, i;
720 (void) gettimeofday(&start, (struct timezone *) 0);
723 totalsize = filesize; /* as filesize changes.. */
726 (void) gettimeofday(&now, (struct timezone *) 0);
728 if (totalsize != 0 && !chunked) {
729 ratio = (int) (100 * transferred / 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;
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 -");
765 } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
766 fprintf(stderr, "--:--:-- ETA");
768 /* totalsize / (transferred/elapsed) - elapsed: */
769 int eta = (int) (totalsize*elapsed/transferred - elapsed);
771 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
776 sa.sa_handler = updateprogressmeter;
777 sigemptyset(&sa.sa_mask);
778 sa.sa_flags = SA_RESTART;
779 sigaction(SIGALRM, &sa, NULL);
781 } else if (flag == 1) {
789 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
790 * much of which was blatantly stolen from openssh. */
793 * Copyright (c) 1992, 1993
794 * The Regents of the University of California. All rights reserved.
796 * Redistribution and use in source and binary forms, with or without
797 * modification, are permitted provided that the following conditions
799 * 1. Redistributions of source code must retain the above copyright
800 * notice, this list of conditions and the following disclaimer.
801 * 2. Redistributions in binary form must reproduce the above copyright
802 * notice, this list of conditions and the following disclaimer in the
803 * documentation and/or other materials provided with the distribution.
805 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
806 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
808 * 4. Neither the name of the University nor the names of its contributors
809 * may be used to endorse or promote products derived from this software
810 * without specific prior written permission.
812 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
813 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
814 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
815 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
816 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
817 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
818 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
819 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
820 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
821 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
824 * $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $