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