Since rangecoder is just a bunch of C functions, move it into the one user
[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 <stdio.h>
10 #include <errno.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <ctype.h>
14 #include <string.h>
15 #include <strings.h>
16 #include <unistd.h>
17 #include <signal.h>
18 #include <sys/ioctl.h>
19
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
25 #include <netdb.h>
26
27 #include <getopt.h>
28
29 #include "busybox.h"
30
31 struct host_info {
32         char *host;
33         int port;
34         char *path;
35         int is_ftp;
36         char *user;
37 };
38
39 static void parse_url(char *url, struct host_info *h);
40 static FILE *open_socket(struct sockaddr_in *s_in);
41 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
42 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf);
43
44 /* Globals (can be accessed from signal handlers */
45 static off_t filesize;          /* content-length of the file */
46 static int chunked;             /* chunked transfer encoding */
47 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
48 static void progressmeter(int flag);
49 static char *curfile;           /* Name of current file being transferred. */
50 static struct timeval start;    /* Time a transfer started. */
51 static off_t transferred;       /* Number of bytes transferred so far. */
52 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
53 enum {
54         STALLTIME = 5
55 };
56 #else
57 static inline void progressmeter(int flag) {}
58 #endif
59
60 static void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
61 {
62         if (output != stdout && do_continue==0) {
63                 fclose(output);
64                 unlink(fname_out);
65         }
66 }
67
68 /* Read NMEMB elements of SIZE bytes into PTR from STREAM.  Returns the
69  * number of elements read, and a short count if an eof or non-interrupt
70  * error is encountered.  */
71 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
72 {
73         size_t ret = 0;
74
75         do {
76                 clearerr(stream);
77                 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
78         } while (ret < nmemb && ferror(stream) && errno == EINTR);
79
80         return ret;
81 }
82
83 /* Write NMEMB elements of SIZE bytes from PTR to STREAM.  Returns the
84  * number of elements written, and a short count if an eof or non-interrupt
85  * error is encountered.  */
86 static size_t safe_fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)
87 {
88         size_t ret = 0;
89
90         do {
91                 clearerr(stream);
92                 ret += fwrite((char *)ptr + (ret * size), size, nmemb - ret, stream);
93         } while (ret < nmemb && ferror(stream) && errno == EINTR);
94
95         return ret;
96 }
97
98 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
99  * Returns S, or NULL if an eof or non-interrupt error is encountered.  */
100 static char *safe_fgets(char *s, int size, FILE *stream)
101 {
102         char *ret;
103
104         do {
105                 clearerr(stream);
106                 ret = fgets(s, size, stream);
107         } while (ret == NULL && ferror(stream) && errno == EINTR);
108
109         return ret;
110 }
111
112 #define close_delete_and_die(s...) { \
113         close_and_delete_outfile(output, fname_out, do_continue); \
114         bb_error_msg_and_die(s); }
115
116
117 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
118 /*
119  *  Base64-encode character string
120  *  oops... isn't something similar in uuencode.c?
121  *  XXX: It would be better to use already existing code
122  */
123 static char *base64enc(unsigned char *p, char *buf, int len) {
124
125         char al[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
126                     "0123456789+/";
127         char *s = buf;
128
129         while(*p) {
130                 if (s >= buf+len-4)
131                         bb_error_msg_and_die("buffer overflow");
132                 *(s++) = al[(*p >> 2) & 0x3F];
133                 *(s++) = al[((*p << 4) & 0x30) | ((*(p+1) >> 4) & 0x0F)];
134                 *s = *(s+1) = '=';
135                 *(s+2) = 0;
136                 if (! *(++p)) break;
137                 *(s++) = al[((*p << 2) & 0x3C) | ((*(p+1) >> 6) & 0x03)];
138                 if (! *(++p)) break;
139                 *(s++) = al[*(p++) & 0x3F];
140         }
141
142         return buf;
143 }
144 #endif
145
146 #define WGET_OPT_CONTINUE       1
147 #define WGET_OPT_QUIET  2
148 #define WGET_OPT_PASSIVE        4
149 #define WGET_OPT_OUTNAME        8
150 #define WGET_OPT_HEADER 16
151 #define WGET_OPT_PREFIX 32
152 #define WGET_OPT_PROXY  64
153
154 #if ENABLE_WGET_LONG_OPTIONS
155 static const struct option wget_long_options[] = {
156         { "continue",        0, NULL, 'c' },
157         { "quiet",           0, NULL, 'q' },
158         { "passive-ftp",     0, NULL, 139 },
159         { "output-document", 1, NULL, 'O' },
160         { "header",          1, NULL, 131 },
161         { "directory-prefix",1, NULL, 'P' },
162         { "proxy",           1, NULL, 'Y' },
163         { 0,                 0, 0, 0 }
164 };
165 #endif
166
167 int wget_main(int argc, char **argv)
168 {
169         int n, try=5, status;
170         unsigned long opt;
171         int port;
172         char *proxy = 0;
173         char *dir_prefix=NULL;
174         char *s, buf[512];
175         struct stat sbuf;
176         char extra_headers[1024];
177         char *extra_headers_ptr = extra_headers;
178         int extra_headers_left = sizeof(extra_headers);
179         struct host_info server, target;
180         struct sockaddr_in s_in;
181         llist_t *headers_llist = NULL;
182
183         FILE *sfp = NULL;               /* socket to web/ftp server         */
184         FILE *dfp = NULL;               /* socket to ftp server (data)      */
185         char *fname_out = NULL;         /* where to direct output (-O)      */
186         int do_continue = 0;            /* continue a prev transfer (-c)    */
187         long beg_range = 0L;            /*   range at which continue begins */
188         int got_clen = 0;               /* got content-length: from server  */
189         FILE *output;                   /* socket to web server             */
190         int quiet_flag = FALSE;         /* Be verry, verry quiet...         */
191         int use_proxy = 1;              /* Use proxies if env vars are set  */
192         char *proxy_flag = "on";        /* Use proxies if env vars are set  */
193
194         /*
195          * Crack command line.
196          */
197         bb_opt_complementally = "-1:\203::";
198 #if ENABLE_WGET_LONG_OPTIONS
199         bb_applet_long_options = wget_long_options;
200 #endif
201         opt = bb_getopt_ulflags(argc, argv, "cq\213O:\203:P:Y:",
202                                         &fname_out, &headers_llist,
203                                         &dir_prefix, &proxy_flag);
204         if (opt & WGET_OPT_CONTINUE) {
205                 ++do_continue;
206         }
207         if (opt & WGET_OPT_QUIET) {
208                 quiet_flag = TRUE;
209         }
210         if (strcmp(proxy_flag, "off") == 0) {
211                 /* Use the proxy if necessary. */
212                 use_proxy = 0;
213         }
214         if (opt & WGET_OPT_HEADER) {
215                 while (headers_llist) {
216                         int arglen = strlen(headers_llist->data);
217                         if (extra_headers_left - arglen - 2 <= 0)
218                                 bb_error_msg_and_die("extra_headers buffer too small(need %i)", extra_headers_left - arglen);
219                         strcpy(extra_headers_ptr, headers_llist->data);
220                         extra_headers_ptr += arglen;
221                         extra_headers_left -= ( arglen + 2 );
222                         *extra_headers_ptr++ = '\r';
223                         *extra_headers_ptr++ = '\n';
224                         *(extra_headers_ptr + 1) = 0;
225                         headers_llist = headers_llist->link;
226                 }
227         }
228
229         parse_url(argv[optind], &target);
230         server.host = target.host;
231         server.port = target.port;
232
233         /*
234          * Use the proxy if necessary.
235          */
236         if (use_proxy) {
237                 proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
238                 if (proxy && *proxy) {
239                         parse_url(bb_xstrdup(proxy), &server);
240                 } else {
241                         use_proxy = 0;
242                 }
243         }
244
245         /* Guess an output filename */
246         if (!fname_out) {
247                 // Dirty hack. Needed because bb_get_last_path_component
248                 // will destroy trailing / by storing '\0' in last byte!
249                 if(*target.path && target.path[strlen(target.path)-1]!='/') {
250                         fname_out =
251 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
252                                 curfile =
253 #endif
254                                 bb_get_last_path_component(target.path);
255                 }
256                 if (fname_out==NULL || strlen(fname_out)<1) {
257                         fname_out =
258 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
259                                 curfile =
260 #endif
261                                 "index.html";
262                 }
263                 if (dir_prefix != NULL)
264                         fname_out = concat_path_file(dir_prefix, fname_out);
265 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
266         } else {
267                 curfile = bb_get_last_path_component(fname_out);
268 #endif
269         }
270         if (do_continue && !fname_out)
271                 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)");
272
273
274         /*
275          * Open the output file stream.
276          */
277         if (strcmp(fname_out, "-") == 0) {
278                 output = stdout;
279                 quiet_flag = TRUE;
280         } else {
281                 output = bb_xfopen(fname_out, (do_continue ? "a" : "w"));
282         }
283
284         /*
285          * Determine where to start transfer.
286          */
287         if (do_continue) {
288                 if (fstat(fileno(output), &sbuf) < 0)
289                         bb_perror_msg_and_die("fstat()");
290                 if (sbuf.st_size > 0)
291                         beg_range = sbuf.st_size;
292                 else
293                         do_continue = 0;
294         }
295
296         /* We want to do exactly _one_ DNS lookup, since some
297          * sites (i.e. ftp.us.debian.org) use round-robin DNS
298          * and we want to connect to only one IP... */
299         bb_lookup_host(&s_in, server.host);
300         s_in.sin_port = server.port;
301         if (quiet_flag==FALSE) {
302                 fprintf(stdout, "Connecting to %s[%s]:%d\n",
303                                 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
304         }
305
306         if (use_proxy || !target.is_ftp) {
307                 /*
308                  *  HTTP session
309                  */
310                 do {
311                         got_clen = chunked = 0;
312
313                         if (! --try)
314                                 close_delete_and_die("too many redirections");
315
316                         /*
317                          * Open socket to http server
318                          */
319                         if (sfp) fclose(sfp);
320                         sfp = open_socket(&s_in);
321
322                         /*
323                          * Send HTTP request.
324                          */
325                         if (use_proxy) {
326                                 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
327 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
328                                 if (strchr(target.host, ':'))
329                                         format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
330 #endif
331                                 fprintf(sfp, format,
332                                         target.is_ftp ? "f" : "ht", target.host,
333                                         ntohs(target.port), target.path);
334                         } else {
335                                 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
336                         }
337
338                         fprintf(sfp, "Host: %s\r\nUser-Agent: Wget\r\n", target.host);
339
340 #ifdef CONFIG_FEATURE_WGET_AUTHENTICATION
341                         if (target.user) {
342                                 fprintf(sfp, "Authorization: Basic %s\r\n",
343                                         base64enc((unsigned char*)target.user, buf, sizeof(buf)));
344                         }
345                         if (use_proxy && server.user) {
346                                 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
347                                         base64enc((unsigned char*)server.user, buf, sizeof(buf)));
348                         }
349 #endif
350
351                         if (do_continue)
352                                 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
353                         if(extra_headers_left < sizeof(extra_headers))
354                                 fputs(extra_headers,sfp);
355                         fprintf(sfp,"Connection: close\r\n\r\n");
356
357                         /*
358                         * Retrieve HTTP response line and check for "200" status code.
359                         */
360 read_response:
361                         if (fgets(buf, sizeof(buf), sfp) == NULL)
362                                 close_delete_and_die("no response from server");
363
364                         for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
365                                 ;
366                         for ( ; isspace(*s) ; ++s)
367                                 ;
368                         switch (status = atoi(s)) {
369                                 case 0:
370                                 case 100:
371                                         while (gethdr(buf, sizeof(buf), sfp, &n) != NULL);
372                                         goto read_response;
373                                 case 200:
374                                         if (do_continue && output != stdout)
375                                                 output = freopen(fname_out, "w", output);
376                                         do_continue = 0;
377                                         break;
378                                 case 300:       /* redirection */
379                                 case 301:
380                                 case 302:
381                                 case 303:
382                                         break;
383                                 case 206:
384                                         if (do_continue)
385                                                 break;
386                                         /*FALLTHRU*/
387                                 default:
388                                         chomp(buf);
389                                         close_delete_and_die("server returned error %d: %s", atoi(s), buf);
390                         }
391
392                         /*
393                          * Retrieve HTTP headers.
394                          */
395                         while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
396                                 if (strcasecmp(buf, "content-length") == 0) {
397                                         unsigned long value;
398                                         if (safe_strtoul(s, &value)) {
399                                                 close_delete_and_die("content-length %s is garbage", s);
400                                         }
401                                         filesize = value;
402                                         got_clen = 1;
403                                         continue;
404                                 }
405                                 if (strcasecmp(buf, "transfer-encoding") == 0) {
406                                         if (strcasecmp(s, "chunked") == 0) {
407                                                 chunked = got_clen = 1;
408                                         } else {
409                                                 close_delete_and_die("server wants to do %s transfer encoding", s);
410                                         }
411                                 }
412                                 if (strcasecmp(buf, "location") == 0) {
413                                         if (s[0] == '/')
414                                                 target.path = bb_xstrdup(s+1);
415                                         else {
416                                                 parse_url(bb_xstrdup(s), &target);
417                                                 if (use_proxy == 0) {
418                                                         server.host = target.host;
419                                                         server.port = target.port;
420                                                 }
421                                                 bb_lookup_host(&s_in, server.host);
422                                                 s_in.sin_port = server.port;
423                                                 break;
424                                         }
425                                 }
426                         }
427                 } while(status >= 300);
428
429                 dfp = sfp;
430         }
431         else
432         {
433                 /*
434                  *  FTP session
435                  */
436                 if (! target.user)
437                         target.user = bb_xstrdup("anonymous:busybox@");
438
439                 sfp = open_socket(&s_in);
440                 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
441                         close_delete_and_die("%s", buf+4);
442
443                 /*
444                  * Splitting username:password pair,
445                  * trying to log in
446                  */
447                 s = strchr(target.user, ':');
448                 if (s)
449                         *(s++) = '\0';
450                 switch(ftpcmd("USER ", target.user, sfp, buf)) {
451                         case 230:
452                                 break;
453                         case 331:
454                                 if (ftpcmd("PASS ", s, sfp, buf) == 230)
455                                         break;
456                                 /* FALLTHRU (failed login) */
457                         default:
458                                 close_delete_and_die("ftp login: %s", buf+4);
459                 }
460
461                 ftpcmd("CDUP", NULL, sfp, buf);
462                 ftpcmd("TYPE I", NULL, sfp, buf);
463
464                 /*
465                  * Querying file size
466                  */
467                 if (ftpcmd("SIZE /", target.path, sfp, buf) == 213) {
468                         unsigned long value;
469                         if (safe_strtoul(buf+4, &value)) {
470                                 close_delete_and_die("SIZE value is garbage");
471                         }
472                         filesize = value;
473                         got_clen = 1;
474                 }
475
476                 /*
477                  * Entering passive mode
478                  */
479                 if (ftpcmd("PASV", NULL, sfp, buf) !=  227)
480                         close_delete_and_die("PASV: %s", buf+4);
481                 s = strrchr(buf, ',');
482                 *s = 0;
483                 port = atoi(s+1);
484                 s = strrchr(buf, ',');
485                 port += atoi(s+1) * 256;
486                 s_in.sin_port = htons(port);
487                 dfp = open_socket(&s_in);
488
489                 if (do_continue) {
490                         sprintf(buf, "REST %ld", beg_range);
491                         if (ftpcmd(buf, NULL, sfp, buf) != 350) {
492                                 if (output != stdout)
493                                         output = freopen(fname_out, "w", output);
494                                 do_continue = 0;
495                         } else
496                                 filesize -= beg_range;
497                 }
498
499                 if (ftpcmd("RETR /", target.path, sfp, buf) > 150)
500                         close_delete_and_die("RETR: %s", buf+4);
501         }
502
503
504         /*
505          * Retrieve file
506          */
507         if (chunked) {
508                 fgets(buf, sizeof(buf), dfp);
509                 filesize = strtol(buf, (char **) NULL, 16);
510         }
511
512         if (quiet_flag==FALSE)
513                 progressmeter(-1);
514
515         do {
516                 while ((filesize > 0 || !got_clen) && (n = safe_fread(buf, 1, ((chunked || got_clen) && (filesize < sizeof(buf)) ? filesize : sizeof(buf)), dfp)) > 0) {
517                         if (safe_fwrite(buf, 1, n, output) != n) {
518                                 bb_perror_msg_and_die(bb_msg_write_error);
519                         }
520 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
521                         transferred += n;
522 #endif
523                         if (got_clen) {
524                                 filesize -= n;
525                         }
526                 }
527
528                 if (chunked) {
529                         safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
530                         safe_fgets(buf, sizeof(buf), dfp);
531                         filesize = strtol(buf, (char **) NULL, 16);
532                         if (filesize==0) {
533                                 chunked = 0; /* all done! */
534                         }
535                 }
536
537                 if (n == 0 && ferror(dfp)) {
538                         bb_perror_msg_and_die(bb_msg_read_error);
539                 }
540         } while (chunked);
541
542         if (quiet_flag==FALSE)
543                 progressmeter(1);
544
545         if ((use_proxy == 0) && target.is_ftp) {
546                 fclose(dfp);
547                 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
548                         bb_error_msg_and_die("ftp error: %s", buf+4);
549                 ftpcmd("QUIT", NULL, sfp, buf);
550         }
551         exit(EXIT_SUCCESS);
552 }
553
554
555 void parse_url(char *url, struct host_info *h)
556 {
557         char *cp, *sp, *up, *pp;
558
559         if (strncmp(url, "http://", 7) == 0) {
560                 h->port = bb_lookup_port("http", "tcp", 80);
561                 h->host = url + 7;
562                 h->is_ftp = 0;
563         } else if (strncmp(url, "ftp://", 6) == 0) {
564                 h->port = bb_lookup_port("ftp", "tfp", 21);
565                 h->host = url + 6;
566                 h->is_ftp = 1;
567         } else
568                 bb_error_msg_and_die("not an http or ftp url: %s", url);
569
570         sp = strchr(h->host, '/');
571         if (sp) {
572                 *sp++ = '\0';
573                 h->path = sp;
574         } else
575                 h->path = bb_xstrdup("");
576
577         up = strrchr(h->host, '@');
578         if (up != NULL) {
579                 h->user = h->host;
580                 *up++ = '\0';
581                 h->host = up;
582         } else
583                 h->user = NULL;
584
585         pp = h->host;
586
587 #ifdef CONFIG_FEATURE_WGET_IP6_LITERAL
588         if (h->host[0] == '[') {
589                 char *ep;
590
591                 ep = h->host + 1;
592                 while (*ep == ':' || isxdigit (*ep))
593                         ep++;
594                 if (*ep == ']') {
595                         h->host++;
596                         *ep = '\0';
597                         pp = ep + 1;
598                 }
599         }
600 #endif
601
602         cp = strchr(pp, ':');
603         if (cp != NULL) {
604                 *cp++ = '\0';
605                 h->port = htons(atoi(cp));
606         }
607 }
608
609
610 FILE *open_socket(struct sockaddr_in *s_in)
611 {
612         FILE *fp;
613
614         fp = fdopen(xconnect(s_in), "r+");
615         if (fp == NULL)
616                 bb_perror_msg_and_die("fdopen()");
617
618         return fp;
619 }
620
621
622 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
623 {
624         char *s, *hdrval;
625         int c;
626
627         *istrunc = 0;
628
629         /* retrieve header line */
630         if (fgets(buf, bufsiz, fp) == NULL)
631                 return NULL;
632
633         /* see if we are at the end of the headers */
634         for (s = buf ; *s == '\r' ; ++s)
635                 ;
636         if (s[0] == '\n')
637                 return NULL;
638
639         /* convert the header name to lower case */
640         for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
641                 *s = tolower(*s);
642
643         /* verify we are at the end of the header name */
644         if (*s != ':')
645                 bb_error_msg_and_die("bad header line: %s", buf);
646
647         /* locate the start of the header value */
648         for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
649                 ;
650         hdrval = s;
651
652         /* locate the end of header */
653         while (*s != '\0' && *s != '\r' && *s != '\n')
654                 ++s;
655
656         /* end of header found */
657         if (*s != '\0') {
658                 *s = '\0';
659                 return hdrval;
660         }
661
662         /* Rats!  The buffer isn't big enough to hold the entire header value. */
663         while (c = getc(fp), c != EOF && c != '\n')
664                 ;
665         *istrunc = 1;
666         return hdrval;
667 }
668
669 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
670 {
671         if (s1) {
672                 if (!s2) s2="";
673                 fprintf(fp, "%s%s\r\n", s1, s2);
674                 fflush(fp);
675         }
676
677         do {
678                 char *buf_ptr;
679
680                 if (fgets(buf, 510, fp) == NULL) {
681                         bb_perror_msg_and_die("fgets()");
682                 }
683                 buf_ptr = strstr(buf, "\r\n");
684                 if (buf_ptr) {
685                         *buf_ptr = '\0';
686                 }
687         } while (! isdigit(buf[0]) || buf[3] != ' ');
688
689         return atoi(buf);
690 }
691
692 #ifdef CONFIG_FEATURE_WGET_STATUSBAR
693 /* Stuff below is from BSD rcp util.c, as added to openshh.
694  * Original copyright notice is retained at the end of this file.
695  *
696  */
697
698
699 static int
700 getttywidth(void)
701 {
702         int width=0;
703         get_terminal_width_height(0, &width, NULL);
704         return (width);
705 }
706
707 static void
708 updateprogressmeter(int ignore)
709 {
710         int save_errno = errno;
711
712         progressmeter(0);
713         errno = save_errno;
714 }
715
716 static void
717 alarmtimer(int wait)
718 {
719         struct itimerval itv;
720
721         itv.it_value.tv_sec = wait;
722         itv.it_value.tv_usec = 0;
723         itv.it_interval = itv.it_value;
724         setitimer(ITIMER_REAL, &itv, NULL);
725 }
726
727
728 static void
729 progressmeter(int flag)
730 {
731         static struct timeval lastupdate;
732         static off_t lastsize, totalsize;
733
734         struct timeval now, td, wait;
735         off_t abbrevsize;
736         int elapsed, ratio, barlength, i;
737         char buf[256];
738
739         if (flag == -1) {
740                 (void) gettimeofday(&start, (struct timezone *) 0);
741                 lastupdate = start;
742                 lastsize = 0;
743                 totalsize = filesize; /* as filesize changes.. */
744         }
745
746         (void) gettimeofday(&now, (struct timezone *) 0);
747         ratio = 100;
748         if (totalsize != 0 && !chunked) {
749                 ratio = (int) (100 * transferred / totalsize);
750                 ratio = MIN(ratio, 100);
751         }
752
753         fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
754
755         barlength = getttywidth() - 51;
756         if (barlength > 0 && barlength < sizeof(buf)) {
757                 i = barlength * ratio / 100;
758                 memset(buf, '*', i);
759                 memset(buf + i, ' ', barlength - i);
760                 buf[barlength] = '\0';
761                 fprintf(stderr, "|%s|", buf);
762         }
763         i = 0;
764         abbrevsize = transferred;
765         while (abbrevsize >= 100000) {
766                 i++;
767                 abbrevsize >>= 10;
768         }
769         /* See http://en.wikipedia.org/wiki/Tera */
770         fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
771
772         timersub(&now, &lastupdate, &wait);
773         if (transferred > lastsize) {
774                 lastupdate = now;
775                 lastsize = transferred;
776                 if (wait.tv_sec >= STALLTIME)
777                         timeradd(&start, &wait, &start);
778                 wait.tv_sec = 0;
779         }
780         timersub(&now, &start, &td);
781         elapsed = td.tv_sec;
782
783         if (wait.tv_sec >= STALLTIME) {
784                 fprintf(stderr, " - stalled -");
785         } else if (transferred <= 0 || elapsed <= 0 || transferred > totalsize || chunked) {
786                 fprintf(stderr, "--:--:-- ETA");
787         } else {
788                 /* totalsize / (transferred/elapsed) - elapsed: */
789                 int eta = (int) (totalsize*elapsed/transferred - elapsed);
790                 i = eta % 3600;
791                 fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
792         }
793
794         if (flag == -1) {
795                 struct sigaction sa;
796                 sa.sa_handler = updateprogressmeter;
797                 sigemptyset(&sa.sa_mask);
798                 sa.sa_flags = SA_RESTART;
799                 sigaction(SIGALRM, &sa, NULL);
800                 alarmtimer(1);
801         } else if (flag == 1) {
802                 alarmtimer(0);
803                 transferred = 0;
804                 putc('\n', stderr);
805         }
806 }
807 #endif
808
809 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
810  * much of which was blatantly stolen from openssh.  */
811
812 /*-
813  * Copyright (c) 1992, 1993
814  *      The Regents of the University of California.  All rights reserved.
815  *
816  * Redistribution and use in source and binary forms, with or without
817  * modification, are permitted provided that the following conditions
818  * are met:
819  * 1. Redistributions of source code must retain the above copyright
820  *    notice, this list of conditions and the following disclaimer.
821  * 2. Redistributions in binary form must reproduce the above copyright
822  *    notice, this list of conditions and the following disclaimer in the
823  *    documentation and/or other materials provided with the distribution.
824  *
825  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
826  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
827  *
828  * 4. Neither the name of the University nor the names of its contributors
829  *    may be used to endorse or promote products derived from this software
830  *    without specific prior written permission.
831  *
832  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
833  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
834  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
835  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
836  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
837  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
838  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
839  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
840  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
841  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
842  * SUCH DAMAGE.
843  *
844  *      $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $
845  */