1 /* vi: set sw=4 ts=4: */
3 * wget - retrieve a file using HTTP or FTP
5 * Chip Rosenthal Covad Communications <chip@laserlink.net>
12 #include <sys/ioctl.h>
24 static void parse_url(char *url, struct host_info *h);
25 static FILE *open_socket(struct sockaddr_in *s_in);
26 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
27 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf);
29 /* Globals (can be accessed from signal handlers */
30 static off_t filesize; /* content-length of the file */
31 static int chunked; /* chunked transfer encoding */
32 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
33 static void progressmeter(int flag);
34 static char *curfile; /* Name of current file being transferred. */
35 static struct timeval start; /* Time a transfer started. */
36 static off_t transferred; /* Number of bytes transferred so far. */
37 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
42 static inline void progressmeter(int flag) {}
45 static void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
47 if (output != stdout && do_continue==0) {
53 /* Read NMEMB elements of SIZE bytes into PTR from STREAM. Returns the
54 * number of elements read, and a short count if an eof or non-interrupt
55 * error is encountered. */
56 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
62 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
63 } while (ret < nmemb && ferror(stream) && errno == EINTR);
68 /* Write NMEMB elements of SIZE bytes from PTR to STREAM. Returns the
69 * number of elements written, and a short count if an eof or non-interrupt
70 * error is encountered. */
71 static size_t safe_fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)
77 ret += fwrite((char *)ptr + (ret * size), size, nmemb - ret, stream);
78 } while (ret < nmemb && ferror(stream) && errno == EINTR);
83 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
84 * Returns S, or NULL if an eof or non-interrupt error is encountered. */
85 static char *safe_fgets(char *s, int size, FILE *stream)
91 ret = fgets(s, size, stream);
92 } while (ret == NULL && ferror(stream) && errno == EINTR);
97 #define close_delete_and_die(s...) { \
98 close_and_delete_outfile(output, fname_out, do_continue); \
99 bb_error_msg_and_die(s); }
102 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
104 * Base64-encode character string
105 * oops... isn't something similar in uuencode.c?
106 * XXX: It would be better to use already existing code
108 static char *base64enc(unsigned char *p, char *buf, int len) {
110 char al[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
116 bb_error_msg_and_die("buffer overflow");
117 *(s++) = al[(*p >> 2) & 0x3F];
118 *(s++) = al[((*p << 4) & 0x30) | ((*(p+1) >> 4) & 0x0F)];
122 *(s++) = al[((*p << 2) & 0x3C) | ((*(p+1) >> 6) & 0x03)];
124 *(s++) = al[*(p++) & 0x3F];
131 #define WGET_OPT_CONTINUE 1
132 #define WGET_OPT_QUIET 2
133 #define WGET_OPT_PASSIVE 4
134 #define WGET_OPT_OUTNAME 8
135 #define WGET_OPT_HEADER 16
136 #define WGET_OPT_PREFIX 32
137 #define WGET_OPT_PROXY 64
139 #if ENABLE_WGET_LONG_OPTIONS
140 static const struct option wget_long_options[] = {
141 { "continue", 0, NULL, 'c' },
142 { "quiet", 0, NULL, 'q' },
143 { "passive-ftp", 0, NULL, 139 },
144 { "output-document", 1, NULL, 'O' },
145 { "header", 1, NULL, 131 },
146 { "directory-prefix",1, NULL, 'P' },
147 { "proxy", 1, NULL, 'Y' },
152 int wget_main(int argc, char **argv)
154 int n, try=5, status;
158 char *dir_prefix=NULL;
161 char extra_headers[1024];
162 char *extra_headers_ptr = extra_headers;
163 int extra_headers_left = sizeof(extra_headers);
164 struct host_info server, target;
165 struct sockaddr_in s_in;
166 llist_t *headers_llist = NULL;
168 FILE *sfp = NULL; /* socket to web/ftp server */
169 FILE *dfp = NULL; /* socket to ftp server (data) */
170 char *fname_out = NULL; /* where to direct output (-O) */
171 int do_continue = 0; /* continue a prev transfer (-c) */
172 long beg_range = 0L; /* range at which continue begins */
173 int got_clen = 0; /* got content-length: from server */
174 FILE *output; /* socket to web server */
175 int quiet_flag = FALSE; /* Be verry, verry quiet... */
176 int use_proxy = 1; /* Use proxies if env vars are set */
177 char *proxy_flag = "on"; /* Use proxies if env vars are set */
180 * Crack command line.
182 bb_opt_complementally = "-1:\203::";
183 #if ENABLE_WGET_LONG_OPTIONS
184 bb_applet_long_options = wget_long_options;
186 opt = bb_getopt_ulflags(argc, argv, "cq\213O:\203:P:Y:",
187 &fname_out, &headers_llist,
188 &dir_prefix, &proxy_flag);
189 if (opt & WGET_OPT_CONTINUE) {
192 if (opt & WGET_OPT_QUIET) {
195 if (strcmp(proxy_flag, "off") == 0) {
196 /* Use the proxy if necessary. */
199 if (opt & WGET_OPT_HEADER) {
200 while (headers_llist) {
201 int arglen = strlen(headers_llist->data);
202 if (extra_headers_left - arglen - 2 <= 0)
203 bb_error_msg_and_die("extra_headers buffer too small(need %i)", extra_headers_left - arglen);
204 strcpy(extra_headers_ptr, headers_llist->data);
205 extra_headers_ptr += arglen;
206 extra_headers_left -= ( arglen + 2 );
207 *extra_headers_ptr++ = '\r';
208 *extra_headers_ptr++ = '\n';
209 *(extra_headers_ptr + 1) = 0;
210 headers_llist = headers_llist->link;
214 parse_url(argv[optind], &target);
215 server.host = target.host;
216 server.port = target.port;
219 * Use the proxy if necessary.
222 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
223 if (proxy && *proxy) {
224 parse_url(bb_xstrdup(proxy), &server);
230 /* Guess an output filename */
232 // Dirty hack. Needed because bb_get_last_path_component
233 // will destroy trailing / by storing '\0' in last byte!
234 if(*target.path && target.path[strlen(target.path)-1]!='/') {
236 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
239 bb_get_last_path_component(target.path);
241 if (fname_out==NULL || strlen(fname_out)<1) {
243 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
248 if (dir_prefix != NULL)
249 fname_out = concat_path_file(dir_prefix, fname_out);
250 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
252 curfile = bb_get_last_path_component(fname_out);
255 if (do_continue && !fname_out)
256 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
260 * Open the output file stream.
262 if (strcmp(fname_out, "-") == 0) {
266 output = bb_xfopen(fname_out, (do_continue ? "a" : "w"));
270 * Determine where to start transfer.
273 if (fstat(fileno(output), &sbuf) < 0)
274 bb_perror_msg_and_die("fstat()");
275 if (sbuf.st_size > 0)
276 beg_range = sbuf.st_size;
281 /* We want to do exactly _one_ DNS lookup, since some
282 * sites (i.e. ftp.us.debian.org) use round-robin DNS
283 * and we want to connect to only one IP... */
284 bb_lookup_host(&s_in, server.host);
285 s_in.sin_port = server.port;
286 if (quiet_flag==FALSE) {
287 fprintf(stdout, "Connecting to %s[%s]:%d\n",
288 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
291 if (use_proxy || !target.is_ftp) {
296 got_clen = chunked = 0;
299 close_delete_and_die("too many redirections");
302 * Open socket to http server
304 if (sfp) fclose(sfp);
305 sfp = open_socket(&s_in);
311 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
312 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
313 if (strchr(target.host, ':'))
314 format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
317 target.is_ftp ? "f" : "ht", target.host,
318 ntohs(target.port), target.path);
320 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
323 fprintf(sfp, "Host: %s\r\nUser-Agent: Wget\r\n", target.host);
325 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
327 fprintf(sfp, "Authorization: Basic %s\r\n",
328 base64enc((unsigned char*)target.user, buf, sizeof(buf)));
330 if (use_proxy && server.user) {
331 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
332 base64enc((unsigned char*)server.user, buf, sizeof(buf)));
337 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
338 if(extra_headers_left < sizeof(extra_headers))
339 fputs(extra_headers,sfp);
340 fprintf(sfp,"Connection: close\r\n\r\n");
343 * Retrieve HTTP response line and check for "200" status code.
346 if (fgets(buf, sizeof(buf), sfp) == NULL)
347 close_delete_and_die("no response from server");
349 for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
351 for ( ; isspace(*s) ; ++s)
353 switch (status = atoi(s)) {
356 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
359 if (do_continue && output != stdout)
360 output = freopen(fname_out, "w", output);
363 case 300: /* redirection */
374 close_delete_and_die("server returned error %d: %s", atoi(s), buf);
378 * Retrieve HTTP headers.
380 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
381 if (strcasecmp(buf, "content-length") == 0) {
383 if (safe_strtoul(s, &value)) {
384 close_delete_and_die("content-length %s is garbage", s);
390 if (strcasecmp(buf, "transfer-encoding") == 0) {
391 if (strcasecmp(s, "chunked") == 0) {
392 chunked = got_clen = 1;
394 close_delete_and_die("server wants to do %s transfer encoding", s);
397 if (strcasecmp(buf, "location") == 0) {
399 target.path = bb_xstrdup(s+1);
401 parse_url(bb_xstrdup(s), &target);
402 if (use_proxy == 0) {
403 server.host = target.host;
404 server.port = target.port;
406 bb_lookup_host(&s_in, server.host);
407 s_in.sin_port = server.port;
412 } while(status >= 300);
422 target.user = bb_xstrdup("anonymous:busybox@");
424 sfp = open_socket(&s_in);
425 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
426 close_delete_and_die("%s", buf+4);
429 * Splitting username:password pair,
432 s = strchr(target.user, ':');
435 switch(ftpcmd("USER ", target.user, sfp, buf)) {
439 if (ftpcmd("PASS ", s, sfp, buf) == 230)
441 /* FALLTHRU (failed login) */
443 close_delete_and_die("ftp login: %s", buf+4);
446 ftpcmd("TYPE I", NULL, sfp, buf);
451 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
453 if (safe_strtoul(buf+4, &value)) {
454 close_delete_and_die("SIZE value is garbage");
461 * Entering passive mode
463 if (ftpcmd("PASV", NULL, sfp, buf) != 227)
464 close_delete_and_die("PASV: %s", buf+4);
465 s = strrchr(buf, ',');
468 s = strrchr(buf, ',');
469 port += atoi(s+1) * 256;
470 s_in.sin_port = htons(port);
471 dfp = open_socket(&s_in);
474 sprintf(buf, "REST %ld", beg_range);
475 if (ftpcmd(buf, NULL, sfp, buf) != 350) {
476 if (output != stdout)
477 output = freopen(fname_out, "w", output);
480 filesize -= beg_range;
483 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
484 close_delete_and_die("RETR: %s", buf+4);
492 fgets(buf, sizeof(buf), dfp);
493 filesize = strtol(buf, (char **) NULL, 16);
496 if (quiet_flag==FALSE)
500 while ((filesize > 0 || !got_clen) && (n = safe_fread(buf, 1, ((chunked || got_clen) && (filesize < sizeof(buf)) ? filesize : sizeof(buf)), dfp)) > 0) {
501 if (safe_fwrite(buf, 1, n, output) != n) {
502 bb_perror_msg_and_die(bb_msg_write_error);
504 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
513 safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
514 safe_fgets(buf, sizeof(buf), dfp);
515 filesize = strtol(buf, (char **) NULL, 16);
517 chunked = 0; /* all done! */
521 if (n == 0 && ferror(dfp)) {
522 bb_perror_msg_and_die(bb_msg_read_error);
526 if (quiet_flag==FALSE)
529 if ((use_proxy == 0) && target.is_ftp) {
531 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
532 bb_error_msg_and_die("ftp error: %s", buf+4);
533 ftpcmd("QUIT", NULL, sfp, buf);
539 void parse_url(char *url, struct host_info *h)
541 char *cp, *sp, *up, *pp;
543 if (strncmp(url, "http://", 7) == 0) {
544 h->port = bb_lookup_port("http", "tcp", 80);
547 } else if (strncmp(url, "ftp://", 6) == 0) {
548 h->port = bb_lookup_port("ftp", "tfp", 21);
552 bb_error_msg_and_die("not an http or ftp url: %s", url);
554 sp = strchr(h->host, '/');
559 h->path = bb_xstrdup("");
561 up = strrchr(h->host, '@');
571 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
572 if (h->host[0] == '[') {
576 while (*ep == ':' || isxdigit (*ep))
586 cp = strchr(pp, ':');
589 h->port = htons(atoi(cp));
594 FILE *open_socket(struct sockaddr_in *s_in)
598 fp = fdopen(xconnect(s_in), "r+");
600 bb_perror_msg_and_die("fdopen()");
606 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
613 /* retrieve header line */
614 if (fgets(buf, bufsiz, fp) == NULL)
617 /* see if we are at the end of the headers */
618 for (s = buf ; *s == '\r' ; ++s)
623 /* convert the header name to lower case */
624 for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
627 /* verify we are at the end of the header name */
629 bb_error_msg_and_die("bad header line: %s", buf);
631 /* locate the start of the header value */
632 for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
636 /* locate the end of header */
637 while (*s != '\0' && *s != '\r' && *s != '\n')
640 /* end of header found */
646 /* Rats! The buffer isn't big enough to hold the entire header value. */
647 while (c = getc(fp), c != EOF && c != '\n')
653 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
657 fprintf(fp, "%s%s\r\n", s1, s2);
664 if (fgets(buf, 510, fp) == NULL) {
665 bb_perror_msg_and_die("fgets()");
667 buf_ptr = strstr(buf, "\r\n");
671 } while (! isdigit(buf[0]) || buf[3] != ' ');
676 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
677 /* Stuff below is from BSD rcp util.c, as added to openshh.
678 * Original copyright notice is retained at the end of this file.
687 get_terminal_width_height(0, &width, NULL);
692 updateprogressmeter(int ignore)
694 int save_errno = errno;
703 struct itimerval itv;
705 itv.it_value.tv_sec = wait;
706 itv.it_value.tv_usec = 0;
707 itv.it_interval = itv.it_value;
708 setitimer(ITIMER_REAL, &itv, NULL);
713 progressmeter(int flag)
715 static struct timeval lastupdate;
716 static off_t lastsize, totalsize;
718 struct timeval now, td, wait;
720 int elapsed, ratio, barlength, i;
724 (void) gettimeofday(&start, (struct timezone *) 0);
727 totalsize = filesize; /* as filesize changes.. */
730 (void) gettimeofday(&now, (struct timezone *) 0);
732 if (totalsize != 0 && !chunked) {
733 ratio = (int) (100 * transferred / totalsize);
734 ratio = MIN(ratio, 100);
737 fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
739 barlength = getttywidth() - 51;
740 if (barlength > 0 && barlength < sizeof(buf)) {
741 i = barlength * ratio / 100;
743 memset(buf + i, ' ', barlength - i);
744 buf[barlength] = '\0';
745 fprintf(stderr, "|%s|", buf);
748 abbrevsize = transferred;
749 while (abbrevsize >= 100000) {
753 /* See http://en.wikipedia.org/wiki/Tera */
754 fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
756 timersub(&now, &lastupdate, &wait);
757 if (transferred > lastsize) {
759 lastsize = transferred;
760 if (wait.tv_sec >= STALLTIME)
761 timeradd(&start, &wait, &start);
764 timersub(&now, &start, &td);
767 if (wait.tv_sec >= STALLTIME) {
768 fprintf(stderr, " - stalled -");
769 } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
770 fprintf(stderr, "--:--:-- ETA");
772 /* totalsize / (transferred/elapsed) - elapsed: */
773 int eta = (int) (totalsize*elapsed/transferred - elapsed);
775 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
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) {
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 $