1b7555abcfa1491dc91aa34e6608b837b3527e97
[oweals/busybox.git] / networking / wget.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * wget - retrieve a file using HTTP or FTP
4  *
5  * Chip Rosenthal Covad Communications <chip@laserlink.net>
6  *
7  */
8
9 #include "busybox.h"
10 #include <getopt.h>
11
12
13 struct host_info {
14         char *host;
15         int port;
16         char *path;
17         int is_ftp;
18         char *user;
19 };
20
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);
25
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" */
35 enum {
36         STALLTIME = 5
37 };
38 #else
39 static inline void progressmeter(int flag) {}
40 #endif
41
42 static void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
43 {
44         if (output != stdout && do_continue==0) {
45                 fclose(output);
46                 unlink(fname_out);
47         }
48 }
49
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)
54 {
55         size_t ret = 0;
56
57         do {
58                 clearerr(stream);
59                 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
60         } while (ret < nmemb && ferror(stream) && errno == EINTR);
61
62         return ret;
63 }
64
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)
69 {
70         size_t ret = 0;
71
72         do {
73                 clearerr(stream);
74                 ret += fwrite((char *)ptr + (ret * size), size, nmemb - ret, stream);
75         } while (ret < nmemb && ferror(stream) && errno == EINTR);
76
77         return ret;
78 }
79
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)
83 {
84         char *ret;
85
86         do {
87                 clearerr(stream);
88                 ret = fgets(s, size, stream);
89         } while (ret == NULL && ferror(stream) && errno == EINTR);
90
91         return ret;
92 }
93
94 #define close_delete_and_die(s...) { \
95         close_and_delete_outfile(output, fname_out, do_continue); \
96         bb_error_msg_and_die(s); }
97
98
99 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
100 /*
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
104  */
105 static char *base64enc(unsigned char *p, char *buf, int len) {
106
107         char al[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
108                     "0123456789+/";
109         char *s = buf;
110
111         while(*p) {
112                 if (s >= buf+len-4)
113                         bb_error_msg_and_die("buffer overflow");
114                 *(s++) = al[(*p >> 2) & 0x3F];
115                 *(s++) = al[((*p << 4) & 0x30) | ((*(p+1) >> 4) & 0x0F)];
116                 *s = *(s+1) = '=';
117                 *(s+2) = 0;
118                 if (! *(++p)) break;
119                 *(s++) = al[((*p << 2) & 0x3C) | ((*(p+1) >> 6) & 0x03)];
120                 if (! *(++p)) break;
121                 *(s++) = al[*(p++) & 0x3F];
122         }
123
124         return buf;
125 }
126 #endif
127
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
135
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' },
145         { 0,                 0, 0, 0 }
146 };
147 #endif
148
149 int wget_main(int argc, char **argv)
150 {
151         int n, try=5, status;
152         unsigned long opt;
153         int port;
154         char *proxy = 0;
155         char *dir_prefix=NULL;
156         char *s, buf[512];
157         struct stat sbuf;
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;
164
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  */
175
176         /*
177          * Crack command line.
178          */
179         bb_opt_complementally = "-1:\203::";
180 #if ENABLE_WGET_LONG_OPTIONS
181         bb_applet_long_options = wget_long_options;
182 #endif
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) {
187                 ++do_continue;
188         }
189         if (opt & WGET_OPT_QUIET) {
190                 quiet_flag = TRUE;
191         }
192         if (strcmp(proxy_flag, "off") == 0) {
193                 /* Use the proxy if necessary. */
194                 use_proxy = 0;
195         }
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;
208                 }
209         }
210
211         parse_url(argv[optind], &target);
212         server.host = target.host;
213         server.port = target.port;
214
215         /*
216          * Use the proxy if necessary.
217          */
218         if (use_proxy) {
219                 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
220                 if (proxy && *proxy) {
221                         parse_url(xstrdup(proxy), &server);
222                 } else {
223                         use_proxy = 0;
224                 }
225         }
226
227         /* Guess an output filename */
228         if (!fname_out) {
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]!='/') {
232                         fname_out =
233 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
234                                 curfile =
235 #endif
236                                 bb_get_last_path_component(target.path);
237                 }
238                 if (fname_out==NULL || strlen(fname_out)<1) {
239                         fname_out =
240 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
241                                 curfile =
242 #endif
243                                 "index.html";
244                 }
245                 if (dir_prefix != NULL)
246                         fname_out = concat_path_file(dir_prefix, fname_out);
247 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
248         } else {
249                 curfile = bb_get_last_path_component(fname_out);
250 #endif
251         }
252         if (do_continue && !fname_out)
253                 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
254
255
256         /*
257          * Open the output file stream.
258          */
259         if (strcmp(fname_out, "-") == 0) {
260                 output = stdout;
261                 quiet_flag = TRUE;
262         } else {
263                 output = xfopen(fname_out, (do_continue ? "a" : "w"));
264         }
265
266         /*
267          * Determine where to start transfer.
268          */
269         if (do_continue) {
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;
274                 else
275                         do_continue = 0;
276         }
277
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));
286         }
287
288         if (use_proxy || !target.is_ftp) {
289                 /*
290                  *  HTTP session
291                  */
292                 do {
293                         got_clen = chunked = 0;
294
295                         if (! --try)
296                                 close_delete_and_die("too many redirections");
297
298                         /*
299                          * Open socket to http server
300                          */
301                         if (sfp) fclose(sfp);
302                         sfp = open_socket(&s_in);
303
304                         /*
305                          * Send HTTP request.
306                          */
307                         if (use_proxy) {
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";
312 #endif
313                                 fprintf(sfp, format,
314                                         target.is_ftp ? "f" : "ht", target.host,
315                                         ntohs(target.port), target.path);
316                         } else {
317                                 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
318                         }
319
320                         fprintf(sfp, "Host: %s\r\nUser-Agent: Wget\r\n", target.host);
321
322 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
323                         if (target.user) {
324                                 fprintf(sfp, "Authorization: Basic %s\r\n",
325                                         base64enc((unsigned char*)target.user, buf, sizeof(buf)));
326                         }
327                         if (use_proxy && server.user) {
328                                 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
329                                         base64enc((unsigned char*)server.user, buf, sizeof(buf)));
330                         }
331 #endif
332
333                         if (do_continue)
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");
338
339                         /*
340                         * Retrieve HTTP response line and check for "200" status code.
341                         */
342 read_response:
343                         if (fgets(buf, sizeof(buf), sfp) == NULL)
344                                 close_delete_and_die("no response from server");
345
346                         for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
347                                 ;
348                         for ( ; isspace(*s) ; ++s)
349                                 ;
350                         switch (status = atoi(s)) {
351                                 case 0:
352                                 case 100:
353                                         while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
354                                         goto read_response;
355                                 case 200:
356                                         if (do_continue && output != stdout)
357                                                 output = freopen(fname_out, "w", output);
358                                         do_continue = 0;
359                                         break;
360                                 case 300:       /* redirection */
361                                 case 301:
362                                 case 302:
363                                 case 303:
364                                         break;
365                                 case 206:
366                                         if (do_continue)
367                                                 break;
368                                         /*FALLTHRU*/
369                                 default:
370                                         chomp(buf);
371                                         close_delete_and_die("server returned error %d: %s", atoi(s), buf);
372                         }
373
374                         /*
375                          * Retrieve HTTP headers.
376                          */
377                         while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
378                                 if (strcasecmp(buf, "content-length") == 0) {
379                                         unsigned long value;
380                                         if (safe_strtoul(s, &value)) {
381                                                 close_delete_and_die("content-length %s is garbage", s);
382                                         }
383                                         filesize = value;
384                                         got_clen = 1;
385                                         continue;
386                                 }
387                                 if (strcasecmp(buf, "transfer-encoding") == 0) {
388                                         if (strcasecmp(s, "chunked") == 0) {
389                                                 chunked = got_clen = 1;
390                                         } else {
391                                                 close_delete_and_die("server wants to do %s transfer encoding", s);
392                                         }
393                                 }
394                                 if (strcasecmp(buf, "location") == 0) {
395                                         if (s[0] == '/')
396                                                 target.path = xstrdup(s+1);
397                                         else {
398                                                 parse_url(xstrdup(s), &target);
399                                                 if (use_proxy == 0) {
400                                                         server.host = target.host;
401                                                         server.port = target.port;
402                                                 }
403                                                 bb_lookup_host(&s_in, server.host);
404                                                 s_in.sin_port = server.port;
405                                                 break;
406                                         }
407                                 }
408                         }
409                 } while(status >= 300);
410
411                 dfp = sfp;
412         }
413         else
414         {
415                 /*
416                  *  FTP session
417                  */
418                 if (! target.user)
419                         target.user = xstrdup("anonymous:busybox@");
420
421                 sfp = open_socket(&s_in);
422                 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
423                         close_delete_and_die("%s", buf+4);
424
425                 /*
426                  * Splitting username:password pair,
427                  * trying to log in
428                  */
429                 s = strchr(target.user, ':');
430                 if (s)
431                         *(s++) = '\0';
432                 switch(ftpcmd("USER ", target.user, sfp, buf)) {
433                         case 230:
434                                 break;
435                         case 331:
436                                 if (ftpcmd("PASS ", s, sfp, buf) == 230)
437                                         break;
438                                 /* FALLTHRU (failed login) */
439                         default:
440                                 close_delete_and_die("ftp login: %s", buf+4);
441                 }
442
443                 ftpcmd("TYPE I", NULL, sfp, buf);
444
445                 /*
446                  * Querying file size
447                  */
448                 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
449                         unsigned long value;
450                         if (safe_strtoul(buf+4, &value)) {
451                                 close_delete_and_die("SIZE value is garbage");
452                         }
453                         filesize = value;
454                         got_clen = 1;
455                 }
456
457                 /*
458                  * Entering passive mode
459                  */
460                 if (ftpcmd("PASV", NULL, sfp, buf) !=  227)
461                         close_delete_and_die("PASV: %s", buf+4);
462                 s = strrchr(buf, ',');
463                 *s = 0;
464                 port = atoi(s+1);
465                 s = strrchr(buf, ',');
466                 port += atoi(s+1) * 256;
467                 s_in.sin_port = htons(port);
468                 dfp = open_socket(&s_in);
469
470                 if (do_continue) {
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);
475                                 do_continue = 0;
476                         } else
477                                 filesize -= beg_range;
478                 }
479
480                 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
481                         close_delete_and_die("RETR: %s", buf+4);
482         }
483
484
485         /*
486          * Retrieve file
487          */
488         if (chunked) {
489                 fgets(buf, sizeof(buf), dfp);
490                 filesize = strtol(buf, (char **) NULL, 16);
491         }
492
493         if (quiet_flag==FALSE)
494                 progressmeter(-1);
495
496         do {
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);
500                         }
501 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
502                         transferred += n;
503 #endif
504                         if (got_clen) {
505                                 filesize -= n;
506                         }
507                 }
508
509                 if (chunked) {
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);
513                         if (filesize==0) {
514                                 chunked = 0; /* all done! */
515                         }
516                 }
517
518                 if (n == 0 && ferror(dfp)) {
519                         bb_perror_msg_and_die(bb_msg_read_error);
520                 }
521         } while (chunked);
522
523         if (quiet_flag==FALSE)
524                 progressmeter(1);
525
526         if ((use_proxy == 0) && target.is_ftp) {
527                 fclose(dfp);
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);
531         }
532         exit(EXIT_SUCCESS);
533 }
534
535
536 void parse_url(char *url, struct host_info *h)
537 {
538         char *cp, *sp, *up, *pp;
539
540         if (strncmp(url, "http://", 7) == 0) {
541                 h->port = bb_lookup_port("http", "tcp", 80);
542                 h->host = url + 7;
543                 h->is_ftp = 0;
544         } else if (strncmp(url, "ftp://", 6) == 0) {
545                 h->port = bb_lookup_port("ftp", "tfp", 21);
546                 h->host = url + 6;
547                 h->is_ftp = 1;
548         } else
549                 bb_error_msg_and_die("not an http or ftp url: %s", url);
550
551         sp = strchr(h->host, '/');
552         if (sp) {
553                 *sp++ = '\0';
554                 h->path = sp;
555         } else
556                 h->path = xstrdup("");
557
558         up = strrchr(h->host, '@');
559         if (up != NULL) {
560                 h->user = h->host;
561                 *up++ = '\0';
562                 h->host = up;
563         } else
564                 h->user = NULL;
565
566         pp = h->host;
567
568 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
569         if (h->host[0] == '[') {
570                 char *ep;
571
572                 ep = h->host + 1;
573                 while (*ep == ':' || isxdigit (*ep))
574                         ep++;
575                 if (*ep == ']') {
576                         h->host++;
577                         *ep = '\0';
578                         pp = ep + 1;
579                 }
580         }
581 #endif
582
583         cp = strchr(pp, ':');
584         if (cp != NULL) {
585                 *cp++ = '\0';
586                 h->port = htons(atoi(cp));
587         }
588 }
589
590
591 FILE *open_socket(struct sockaddr_in *s_in)
592 {
593         FILE *fp;
594
595         fp = fdopen(xconnect(s_in), "r+");
596         if (fp == NULL)
597                 bb_perror_msg_and_die("fdopen()");
598
599         return fp;
600 }
601
602
603 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
604 {
605         char *s, *hdrval;
606         int c;
607
608         *istrunc = 0;
609
610         /* retrieve header line */
611         if (fgets(buf, bufsiz, fp) == NULL)
612                 return NULL;
613
614         /* see if we are at the end of the headers */
615         for (s = buf ; *s == '\r' ; ++s)
616                 ;
617         if (s[0] == '\n')
618                 return NULL;
619
620         /* convert the header name to lower case */
621         for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
622                 *s = tolower(*s);
623
624         /* verify we are at the end of the header name */
625         if (*s != ':')
626                 bb_error_msg_and_die("bad header line: %s", buf);
627
628         /* locate the start of the header value */
629         for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
630                 ;
631         hdrval = s;
632
633         /* locate the end of header */
634         while (*s != '\0' && *s != '\r' && *s != '\n')
635                 ++s;
636
637         /* end of header found */
638         if (*s != '\0') {
639                 *s = '\0';
640                 return hdrval;
641         }
642
643         /* Rats!  The buffer isn't big enough to hold the entire header value. */
644         while (c = getc(fp), c != EOF && c != '\n')
645                 ;
646         *istrunc = 1;
647         return hdrval;
648 }
649
650 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
651 {
652         if (s1) {
653                 if (!s2) s2="";
654                 fprintf(fp, "%s%s\r\n", s1, s2);
655                 fflush(fp);
656         }
657
658         do {
659                 char *buf_ptr;
660
661                 if (fgets(buf, 510, fp) == NULL) {
662                         bb_perror_msg_and_die("fgets()");
663                 }
664                 buf_ptr = strstr(buf, "\r\n");
665                 if (buf_ptr) {
666                         *buf_ptr = '\0';
667                 }
668         } while (! isdigit(buf[0]) || buf[3] != ' ');
669
670         return atoi(buf);
671 }
672
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.
676  *
677  */
678
679
680 static int
681 getttywidth(void)
682 {
683         int width=0;
684         get_terminal_width_height(0, &width, NULL);
685         return (width);
686 }
687
688 static void
689 updateprogressmeter(int ignore)
690 {
691         int save_errno = errno;
692
693         progressmeter(0);
694         errno = save_errno;
695 }
696
697 static void alarmtimer(int iwait)
698 {
699         struct itimerval itv;
700
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);
705 }
706
707
708 static void
709 progressmeter(int flag)
710 {
711         static struct timeval lastupdate;
712         static off_t lastsize, totalsize;
713
714         struct timeval now, td, tvwait;
715         off_t abbrevsize;
716         int elapsed, ratio, barlength, i;
717         char buf[256];
718
719         if (flag == -1) {
720                 (void) gettimeofday(&start, (struct timezone *) 0);
721                 lastupdate = start;
722                 lastsize = 0;
723                 totalsize = filesize; /* as filesize changes.. */
724         }
725
726         (void) gettimeofday(&now, (struct timezone *) 0);
727         ratio = 100;
728         if (totalsize != 0 && !chunked) {
729                 ratio = (int) (100 * transferred / totalsize);
730                 ratio = MIN(ratio, 100);
731         }
732
733         fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
734
735         barlength = getttywidth() - 51;
736         if (barlength > 0 && barlength < sizeof(buf)) {
737                 i = barlength * ratio / 100;
738                 memset(buf, '*', i);
739                 memset(buf + i, ' ', barlength - i);
740                 buf[barlength] = '\0';
741                 fprintf(stderr, "|%s|", buf);
742         }
743         i = 0;
744         abbrevsize = transferred;
745         while (abbrevsize >= 100000) {
746                 i++;
747                 abbrevsize >>= 10;
748         }
749         /* See http://en.wikipedia.org/wiki/Tera */
750         fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
751
752         timersub(&now, &lastupdate, &tvwait);
753         if (transferred > lastsize) {
754                 lastupdate = now;
755                 lastsize = transferred;
756                 if (tvwait.tv_sec >= STALLTIME)
757                         timeradd(&start, &tvwait, &start);
758                 tvwait.tv_sec = 0;
759         }
760         timersub(&now, &start, &td);
761         elapsed = td.tv_sec;
762
763         if (tvwait.tv_sec >= STALLTIME) {
764                 fprintf(stderr, " - stalled -");
765         } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
766                 fprintf(stderr, "--:--:-- ETA");
767         } else {
768                 /* totalsize / (transferred/elapsed) - elapsed: */
769                 int eta = (int) (totalsize*elapsed/transferred - elapsed);
770                 i = eta % 3600;
771                 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
772         }
773
774         if (flag == -1) {
775                 struct sigaction sa;
776                 sa.sa_handler = updateprogressmeter;
777                 sigemptyset(&sa.sa_mask);
778                 sa.sa_flags = SA_RESTART;
779                 sigaction(SIGALRM, &sa, NULL);
780                 alarmtimer(1);
781         } else if (flag == 1) {
782                 alarmtimer(0);
783                 transferred = 0;
784                 putc('\n', stderr);
785         }
786 }
787 #endif
788
789 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
790  * much of which was blatantly stolen from openssh.  */
791
792 /*-
793  * Copyright (c) 1992, 1993
794  *      The Regents of the University of California.  All rights reserved.
795  *
796  * Redistribution and use in source and binary forms, with or without
797  * modification, are permitted provided that the following conditions
798  * are met:
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.
804  *
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>
807  *
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.
811  *
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
822  * SUCH DAMAGE.
823  *
824  *      $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $
825  */