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