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