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