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