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