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