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