bca66f822f804919bf67d9c31bc77b94d7dd0b1d
[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 #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 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 {
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 #if ENABLE_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 #if ENABLE_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 #if ENABLE_FEATURE_WGET_STATUSBAR
209         } else {
210                 curfile = bb_get_last_path_component(fname_out);
211 #endif
212         }
213         /* Impossible?
214         if ((opt & WGET_OPT_CONTINUE) && !fname_out)
215                 bb_error_msg_and_die("cannot specify continue (-c) without a filename (-O)"); */
216
217         /*
218          * Determine where to start transfer.
219          */
220         if (LONE_DASH(fname_out)) {
221                 output_fd = 1;
222                 opt &= ~WGET_OPT_CONTINUE;
223         }
224         if (opt & WGET_OPT_CONTINUE) {
225                 output_fd = open(fname_out, O_WRONLY);
226                 if (output_fd >= 0) {
227                         beg_range = xlseek(output_fd, 0, SEEK_END);
228                 }
229                 /* File doesn't exist. We do not create file here yet.
230                    We are not sure it exists on remove side */
231         }
232
233         /* We want to do exactly _one_ DNS lookup, since some
234          * sites (i.e. ftp.us.debian.org) use round-robin DNS
235          * and we want to connect to only one IP... */
236         bb_lookup_host(&s_in, server.host);
237         s_in.sin_port = server.port;
238         if (!(opt & WGET_OPT_QUIET)) {
239                 fprintf(stderr, "Connecting to %s[%s]:%d\n",
240                                 server.host, inet_ntoa(s_in.sin_addr), ntohs(server.port));
241         }
242
243         if (use_proxy || !target.is_ftp) {
244                 /*
245                  *  HTTP session
246                  */
247                 do {
248                         got_clen = chunked = 0;
249
250                         if (!--try)
251                                 bb_error_msg_and_die("too many redirections");
252
253                         /*
254                          * Open socket to http server
255                          */
256                         if (sfp) fclose(sfp);
257                         sfp = open_socket(&s_in);
258
259                         /*
260                          * Send HTTP request.
261                          */
262                         if (use_proxy) {
263                                 const char *format = "GET %stp://%s:%d/%s HTTP/1.1\r\n";
264 #if ENABLE_FEATURE_WGET_IP6_LITERAL
265                                 if (strchr(target.host, ':'))
266                                         format = "GET %stp://[%s]:%d/%s HTTP/1.1\r\n";
267 #endif
268                                 fprintf(sfp, format,
269                                         target.is_ftp ? "f" : "ht", target.host,
270                                         ntohs(target.port), target.path);
271                         } else {
272                                 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
273                         }
274
275                         {
276                                 const char *portstr = "";
277                                 if (target.port != 80)
278                                         portstr = xasprintf(":%d", target.port);
279                                 fprintf(sfp, "Host: %s%s\r\nUser-Agent: %s\r\n",
280                                         target.host, portstr, user_agent);
281                                 if (ENABLE_FEATURE_CLEAN_UP && target.port != 80)
282                                         free((char*)portstr);
283                         }
284
285 #if ENABLE_FEATURE_WGET_AUTHENTICATION
286                         if (target.user) {
287                                 fprintf(sfp, "Authorization: Basic %s\r\n",
288                                         base64enc((unsigned char*)target.user, buf, sizeof(buf)));
289                         }
290                         if (use_proxy && server.user) {
291                                 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
292                                         base64enc((unsigned char*)server.user, buf, sizeof(buf)));
293                         }
294 #endif
295
296                         if (beg_range)
297                                 fprintf(sfp, "Range: bytes=%"OFF_FMT"d-\r\n", beg_range);
298 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
299                         if (extra_headers)
300                                 fputs(extra_headers, sfp);
301 #endif
302                         fprintf(sfp, "Connection: close\r\n\r\n");
303
304                         /*
305                         * Retrieve HTTP response line and check for "200" status code.
306                         */
307  read_response:
308                         if (fgets(buf, sizeof(buf), sfp) == NULL)
309                                 bb_error_msg_and_die("no response from server");
310
311                         s = buf;
312                         while (*s != '\0' && !isspace(*s)) ++s;
313                         s = skip_whitespace(s);
314                         // FIXME: no error check
315                         // xatou wouldn't work: "200 OK"
316                         status = atoi(s);
317                         switch (status) {
318                         case 0:
319                         case 100:
320                                 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL)
321                                         /* eat all remaining headers */;
322                                 goto read_response;
323                         case 200:
324                                 break;
325                         case 300:       /* redirection */
326                         case 301:
327                         case 302:
328                         case 303:
329                                 break;
330                         case 206:
331                                 if (beg_range)
332                                         break;
333                                 /*FALLTHRU*/
334                         default:
335                                 /* Show first line only and kill any ESC tricks */
336                                 buf[strcspn(buf, "\n\r\x1b")] = '\0';
337                                 bb_error_msg_and_die("server returned error: %s", buf);
338                         }
339
340                         /*
341                          * Retrieve HTTP headers.
342                          */
343                         while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
344                                 if (strcasecmp(buf, "content-length") == 0) {
345                                         content_len = BB_STRTOOFF(s, NULL, 10);
346                                         if (errno || content_len < 0) {
347                                                 bb_error_msg_and_die("content-length %s is garbage", s);
348                                         }
349                                         got_clen = 1;
350                                         continue;
351                                 }
352                                 if (strcasecmp(buf, "transfer-encoding") == 0) {
353                                         if (strcasecmp(s, "chunked") != 0)
354                                                 bb_error_msg_and_die("server wants to do %s transfer encoding", s);
355                                         chunked = got_clen = 1;
356                                 }
357                                 if (strcasecmp(buf, "location") == 0) {
358                                         if (s[0] == '/')
359                                                 /* free(target.allocated); */
360                                                 target.path = /* target.allocated = */ xstrdup(s+1);
361                                         else {
362                                                 parse_url(s, &target);
363                                                 if (use_proxy == 0) {
364                                                         server.host = target.host;
365                                                         server.port = target.port;
366                                                 }
367                                                 bb_lookup_host(&s_in, server.host);
368                                                 s_in.sin_port = server.port;
369                                                 break;
370                                         }
371                                 }
372                         }
373                 } while (status >= 300);
374
375                 dfp = sfp;
376
377         } else {
378
379                 /*
380                  *  FTP session
381                  */
382                 if (!target.user)
383                         target.user = xstrdup("anonymous:busybox@");
384
385                 sfp = open_socket(&s_in);
386                 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
387                         bb_error_msg_and_die("%s", buf+4);
388
389                 /*
390                  * Splitting username:password pair,
391                  * trying to log in
392                  */
393                 s = strchr(target.user, ':');
394                 if (s)
395                         *(s++) = '\0';
396                 switch (ftpcmd("USER ", target.user, sfp, buf)) {
397                 case 230:
398                         break;
399                 case 331:
400                         if (ftpcmd("PASS ", s, sfp, buf) == 230)
401                                 break;
402                         /* FALLTHRU (failed login) */
403                 default:
404                         bb_error_msg_and_die("ftp login: %s", buf+4);
405                 }
406
407                 ftpcmd("TYPE I", NULL, sfp, buf);
408
409                 /*
410                  * Querying file size
411                  */
412                 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
413                         content_len = BB_STRTOOFF(buf+4, NULL, 10);
414                         if (errno || content_len < 0) {
415                                 bb_error_msg_and_die("SIZE value is garbage");
416                         }
417                         got_clen = 1;
418                 }
419
420                 /*
421                  * Entering passive mode
422                  */
423                 if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
424  pasv_error:
425                         bb_error_msg_and_die("bad response to %s: %s", "PASV", buf);
426                 }
427                 // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
428                 // Server's IP is N1.N2.N3.N4 (we ignore it)
429                 // Server's port for data connection is P1*256+P2
430                 s = strrchr(buf, ')');
431                 if (s) s[0] = '\0';
432                 s = strrchr(buf, ',');
433                 if (!s) goto pasv_error;
434                 port = xatou_range(s+1, 0, 255);
435                 *s = '\0';
436                 s = strrchr(buf, ',');
437                 if (!s) goto pasv_error;
438                 port += xatou_range(s+1, 0, 255) * 256;
439                 s_in.sin_port = htons(port);
440                 dfp = open_socket(&s_in);
441
442                 if (beg_range) {
443                         sprintf(buf, "REST %"OFF_FMT"d", beg_range);
444                         if (ftpcmd(buf, NULL, sfp, buf) == 350)
445                                 content_len -= beg_range;
446                 }
447
448                 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
449                         bb_error_msg_and_die("bad response to RETR: %s", buf);
450         }
451
452
453         /*
454          * Retrieve file
455          */
456         if (chunked) {
457                 fgets(buf, sizeof(buf), dfp);
458                 content_len = STRTOOFF(buf, NULL, 16);
459                 /* FIXME: error check?? */
460         }
461
462         /* Do it before progressmeter (want to have nice error message) */
463         if (output_fd < 0)
464                 output_fd = xopen(fname_out,
465                         O_WRONLY|O_CREAT|O_EXCL|O_TRUNC);
466
467         if (!(opt & WGET_OPT_QUIET))
468                 progressmeter(-1);
469
470         do {
471                 while (content_len > 0 || !got_clen) {
472                         unsigned rdsz = sizeof(buf);
473                         if (content_len < sizeof(buf) && (chunked || got_clen))
474                                 rdsz = (unsigned)content_len;
475                         n = safe_fread(buf, 1, rdsz, dfp);
476                         if (n <= 0)
477                                 break;
478                         if (full_write(output_fd, buf, n) != n) {
479                                 bb_perror_msg_and_die(bb_msg_write_error);
480                         }
481 #if ENABLE_FEATURE_WGET_STATUSBAR
482                         transferred += n;
483 #endif
484                         if (got_clen) {
485                                 content_len -= n;
486                         }
487                 }
488
489                 if (chunked) {
490                         safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
491                         safe_fgets(buf, sizeof(buf), dfp);
492                         content_len = STRTOOFF(buf, NULL, 16);
493                         /* FIXME: error check? */
494                         if (content_len == 0) {
495                                 chunked = 0; /* all done! */
496                         }
497                 }
498
499                 if (n == 0 && ferror(dfp)) {
500                         bb_perror_msg_and_die(bb_msg_read_error);
501                 }
502         } while (chunked);
503
504         if (!(opt & WGET_OPT_QUIET))
505                 progressmeter(1);
506
507         if ((use_proxy == 0) && target.is_ftp) {
508                 fclose(dfp);
509                 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
510                         bb_error_msg_and_die("ftp error: %s", buf+4);
511                 ftpcmd("QUIT", NULL, sfp, buf);
512         }
513         exit(EXIT_SUCCESS);
514 }
515
516
517 static void parse_url(char *src_url, struct host_info *h)
518 {
519         char *url, *p, *sp;
520
521         /* h->allocated = */ url = xstrdup(src_url);
522
523         if (strncmp(url, "http://", 7) == 0) {
524                 h->port = bb_lookup_port("http", "tcp", 80);
525                 h->host = url + 7;
526                 h->is_ftp = 0;
527         } else if (strncmp(url, "ftp://", 6) == 0) {
528                 h->port = bb_lookup_port("ftp", "tcp", 21);
529                 h->host = url + 6;
530                 h->is_ftp = 1;
531         } else
532                 bb_error_msg_and_die("not an http or ftp url: %s", url);
533
534         // FYI:
535         // "Real" wget 'http://busybox.net?var=a/b' sends this request:
536         //   'GET /?var=a/b HTTP 1.0'
537         //   and saves 'index.html?var=a%2Fb' (we save 'b')
538         // wget 'http://busybox.net?login=john@doe':
539         //   request: 'GET /?login=john@doe HTTP/1.0'
540         //   saves: 'index.html?login=john@doe' (we save '?login=john@doe')
541         // wget 'http://busybox.net#test/test':
542         //   request: 'GET / HTTP/1.0'
543         //   saves: 'index.html' (we save 'test')
544         //
545         // We also don't add unique .N suffix if file exists...
546         sp = strchr(h->host, '/');
547         p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
548         p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
549         if (!sp) {
550                 h->path = "";
551         } else if (*sp == '/') {
552                 *sp = '\0';
553                 h->path = sp + 1;
554         } else { // '#' or '?'
555                 // http://busybox.net?login=john@doe is a valid URL
556                 // memmove converts to:
557                 // http:/busybox.nett?login=john@doe...
558                 memmove(h->host-1, h->host, sp - h->host);
559                 h->host--;
560                 sp[-1] = '\0';
561                 h->path = sp;
562         }
563
564         sp = strrchr(h->host, '@');
565         h->user = NULL;
566         if (sp != NULL) {
567                 h->user = h->host;
568                 *sp = '\0';
569                 h->host = sp + 1;
570         }
571
572         sp = h->host;
573
574 #if ENABLE_FEATURE_WGET_IP6_LITERAL
575         if (sp[0] == '[') {
576                 char *ep;
577
578                 ep = sp + 1;
579                 while (*ep == ':' || isxdigit(*ep))
580                         ep++;
581                 if (*ep == ']') {
582                         h->host++;
583                         *ep = '\0';
584                         sp = ep + 1;
585                 }
586         }
587 #endif
588
589         p = strchr(sp, ':');
590         if (p != NULL) {
591                 *p = '\0';
592                 h->port = htons(xatou16(p + 1));
593         }
594 }
595
596
597 static FILE *open_socket(struct sockaddr_in *s_in)
598 {
599         FILE *fp;
600
601         /* glibc 2.4 seems to try seeking on it - ??! */
602         /* hopefully it understands what ESPIPE means... */
603         fp = fdopen(xconnect_tcp_v4(s_in), "r+");
604         if (fp == NULL)
605                 bb_perror_msg_and_die("fdopen");
606
607         return fp;
608 }
609
610
611 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
612 {
613         char *s, *hdrval;
614         int c;
615
616         *istrunc = 0;
617
618         /* retrieve header line */
619         if (fgets(buf, bufsiz, fp) == NULL)
620                 return NULL;
621
622         /* see if we are at the end of the headers */
623         for (s = buf; *s == '\r'; ++s)
624                 ;
625         if (s[0] == '\n')
626                 return NULL;
627
628         /* convert the header name to lower case */
629         for (s = buf; isalnum(*s) || *s == '-'; ++s)
630                 *s = tolower(*s);
631
632         /* verify we are at the end of the header name */
633         if (*s != ':')
634                 bb_error_msg_and_die("bad header line: %s", buf);
635
636         /* locate the start of the header value */
637         for (*s++ = '\0'; *s == ' ' || *s == '\t'; ++s)
638                 ;
639         hdrval = s;
640
641         /* locate the end of header */
642         while (*s != '\0' && *s != '\r' && *s != '\n')
643                 ++s;
644
645         /* end of header found */
646         if (*s != '\0') {
647                 *s = '\0';
648                 return hdrval;
649         }
650
651         /* Rats!  The buffer isn't big enough to hold the entire header value. */
652         while (c = getc(fp), c != EOF && c != '\n')
653                 ;
654         *istrunc = 1;
655         return hdrval;
656 }
657
658 static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf)
659 {
660         int result;
661         if (s1) {
662                 if (!s2) s2 = "";
663                 fprintf(fp, "%s%s\r\n", s1, s2);
664                 fflush(fp);
665         }
666
667         do {
668                 char *buf_ptr;
669
670                 if (fgets(buf, 510, fp) == NULL) {
671                         bb_perror_msg_and_die("error getting response");
672                 }
673                 buf_ptr = strstr(buf, "\r\n");
674                 if (buf_ptr) {
675                         *buf_ptr = '\0';
676                 }
677         } while (!isdigit(buf[0]) || buf[3] != ' ');
678
679         buf[3] = '\0';
680         result = xatoi_u(buf);
681         buf[3] = ' ';
682         return result;
683 }
684
685 #if ENABLE_FEATURE_WGET_STATUSBAR
686 /* Stuff below is from BSD rcp util.c, as added to openshh.
687  * Original copyright notice is retained at the end of this file.
688  */
689 static int
690 getttywidth(void)
691 {
692         int width;
693         get_terminal_width_height(0, &width, NULL);
694         return width;
695 }
696
697 static void
698 updateprogressmeter(int ignore)
699 {
700         int save_errno = errno;
701
702         progressmeter(0);
703         errno = save_errno;
704 }
705
706 static void alarmtimer(int iwait)
707 {
708         struct itimerval itv;
709
710         itv.it_value.tv_sec = iwait;
711         itv.it_value.tv_usec = 0;
712         itv.it_interval = itv.it_value;
713         setitimer(ITIMER_REAL, &itv, NULL);
714 }
715
716
717 static void
718 progressmeter(int flag)
719 {
720         static struct timeval lastupdate;
721         static off_t lastsize, totalsize;
722
723         struct timeval now, td, tvwait;
724         off_t abbrevsize;
725         int elapsed, ratio, barlength, i;
726         char buf[256];
727
728         if (flag == -1) { /* first call to progressmeter */
729                 gettimeofday(&start, (struct timezone *) 0);
730                 lastupdate = start;
731                 lastsize = 0;
732                 totalsize = content_len + beg_range; /* as content_len changes.. */
733         }
734
735         gettimeofday(&now, (struct timezone *) 0);
736         ratio = 100;
737         if (totalsize != 0 && !chunked) {
738                 /* long long helps to have working ETA even if !LFS */
739                 ratio = (int) (100 * (unsigned long long)(transferred+beg_range) / totalsize);
740                 ratio = MIN(ratio, 100);
741         }
742
743         fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
744
745         barlength = getttywidth() - 51;
746         if (barlength > 0 && barlength < sizeof(buf)) {
747                 i = barlength * ratio / 100;
748                 memset(buf, '*', i);
749                 memset(buf + i, ' ', barlength - i);
750                 buf[barlength] = '\0';
751                 fprintf(stderr, "|%s|", buf);
752         }
753         i = 0;
754         abbrevsize = transferred + beg_range;
755         while (abbrevsize >= 100000) {
756                 i++;
757                 abbrevsize >>= 10;
758         }
759         /* see http://en.wikipedia.org/wiki/Tera */
760         fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
761
762         timersub(&now, &lastupdate, &tvwait);
763         if (transferred > lastsize) {
764                 lastupdate = now;
765                 lastsize = transferred;
766                 if (tvwait.tv_sec >= STALLTIME)
767                         timeradd(&start, &tvwait, &start);
768                 tvwait.tv_sec = 0;
769         }
770         timersub(&now, &start, &td);
771         elapsed = td.tv_sec;
772
773         if (tvwait.tv_sec >= STALLTIME) {
774                 fprintf(stderr, " - stalled -");
775         } else {
776                 off_t to_download = totalsize - beg_range;
777                 if (transferred <= 0 || elapsed <= 0 || transferred > to_download || chunked) {
778                         fprintf(stderr, "--:--:-- ETA");
779                 } else {
780                         /* to_download / (transferred/elapsed) - elapsed: */
781                         int eta = (int) ((unsigned long long)to_download*elapsed/transferred - elapsed);
782                         /* (long long helps to have working ETA even if !LFS) */
783                         i = eta % 3600;
784                         fprintf(stderr, "%02d:%02d:%02d ETA", eta / 3600, i / 60, i % 60);
785                 }
786         }
787
788         if (flag == -1) { /* first call to progressmeter */
789                 struct sigaction sa;
790                 sa.sa_handler = updateprogressmeter;
791                 sigemptyset(&sa.sa_mask);
792                 sa.sa_flags = SA_RESTART;
793                 sigaction(SIGALRM, &sa, NULL);
794                 alarmtimer(1);
795         } else if (flag == 1) { /* last call to progressmeter */
796                 alarmtimer(0);
797                 transferred = 0;
798                 putc('\n', stderr);
799         }
800 }
801 #endif
802
803 /* Original copyright notice which applies to the CONFIG_FEATURE_WGET_STATUSBAR stuff,
804  * much of which was blatantly stolen from openssh.  */
805
806 /*-
807  * Copyright (c) 1992, 1993
808  *      The Regents of the University of California.  All rights reserved.
809  *
810  * Redistribution and use in source and binary forms, with or without
811  * modification, are permitted provided that the following conditions
812  * are met:
813  * 1. Redistributions of source code must retain the above copyright
814  *    notice, this list of conditions and the following disclaimer.
815  * 2. Redistributions in binary form must reproduce the above copyright
816  *    notice, this list of conditions and the following disclaimer in the
817  *    documentation and/or other materials provided with the distribution.
818  *
819  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
820  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
821  *
822  * 4. Neither the name of the University nor the names of its contributors
823  *    may be used to endorse or promote products derived from this software
824  *    without specific prior written permission.
825  *
826  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
827  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
828  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
829  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
830  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
831  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
832  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
833  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
834  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
835  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
836  * SUCH DAMAGE.
837  *
838  *      $Id: wget.c,v 1.75 2004/10/08 08:27:40 andersen Exp $
839  */