94b9b6954e5de52f94eed94b9f2b583ac2489226
[oweals/busybox.git] / networking / wget.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * wget - retrieve a file using HTTP or FTP
4  *
5  * Chip Rosenthal Covad Communications <chip@laserlink.net>
6  *
7  */
8
9 /* We want libc to give us xxx64 functions also */
10 /* http://www.unix.org/version2/whatsnew/lfs20mar.html */
11 #define _LARGEFILE64_SOURCE 1
12
13 #include "busybox.h"
14 #include <getopt.h>     /* for struct option */
15
16 struct host_info {
17         // May be used if we ever will want to free() all xstrdup()s...
18         /* char *allocated; */
19         char *host;
20         int port;
21         char *path;
22         int is_ftp;
23         char *user;
24 };
25
26 static void parse_url(char *url, struct host_info *h);
27 static FILE *open_socket(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 int 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 static struct timeval start;            /* Time a transfer started */
42 enum {
43         STALLTIME = 5                   /* Seconds when xfer considered "stalled" */
44 };
45 #else
46 static void progressmeter(int flag) {}
47 #endif
48
49 /* Read NMEMB elements of SIZE bytes into PTR from STREAM.  Returns the
50  * number of elements read, and a short count if an eof or non-interrupt
51  * error is encountered.  */
52 static size_t safe_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
53 {
54         size_t ret = 0;
55
56         do {
57                 clearerr(stream);
58                 ret += fread((char *)ptr + (ret * size), size, nmemb - ret, stream);
59         } while (ret < nmemb && ferror(stream) && errno == EINTR);
60
61         return ret;
62 }
63
64 /* Read a line or SIZE - 1 bytes into S, whichever is less, from STREAM.
65  * Returns S, or NULL if an eof or non-interrupt error is encountered.  */
66 static char *safe_fgets(char *s, int size, FILE *stream)
67 {
68         char *ret;
69
70         do {
71                 clearerr(stream);
72                 ret = fgets(s, size, stream);
73         } while (ret == NULL && ferror(stream) && errno == EINTR);
74
75         return ret;
76 }
77
78 #if ENABLE_FEATURE_WGET_AUTHENTICATION
79 /*
80  *  Base64-encode character string and return the string.
81  */
82 static char *base64enc(unsigned char *p, char *buf, int len)
83 {
84         bb_uuencode(p, buf, len, bb_uuenc_tbl_base64);
85         return buf;
86 }
87 #endif
88
89 int wget_main(int argc, char **argv);
90 int wget_main(int argc, char **argv)
91 {
92         char buf[512];
93         struct host_info server, target;
94         len_and_sockaddr *lsa;
95         int n, status;
96         int port;
97         int try = 5;
98         unsigned opt;
99         char *s;
100         char *proxy = 0;
101         char *dir_prefix = NULL;
102 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
103         char *extra_headers = NULL;
104         llist_t *headers_llist = NULL;
105 #endif
106
107         /* server.allocated = target.allocated = NULL; */
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         int got_clen = 0;               /* got content-length: from server  */
113         int output_fd = -1;
114         int 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";/* Content of the "User-Agent" header field */
117
118         /*
119          * Crack command line.
120          */
121         enum {
122                 WGET_OPT_CONTINUE   = 0x1,
123                 WGET_OPT_SPIDER     = 0x2,
124                 WGET_OPT_QUIET      = 0x4,
125                 WGET_OPT_OUTNAME    = 0x8,
126                 WGET_OPT_PREFIX     = 0x10,
127                 WGET_OPT_PROXY      = 0x20,
128                 WGET_OPT_USER_AGENT = 0x40,
129                 WGET_OPT_PASSIVE    = 0x80,
130                 WGET_OPT_HEADER     = 0x100,
131         };
132 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
133         static const struct option wget_long_options[] = {
134                 // name, has_arg, flag, val
135                 { "continue",         no_argument, NULL, 'c' },
136                 { "spider",           no_argument, NULL, 's' },
137                 { "quiet",            no_argument, NULL, 'q' },
138                 { "output-document",  required_argument, NULL, 'O' },
139                 { "directory-prefix", required_argument, NULL, 'P' },
140                 { "proxy",            required_argument, NULL, 'Y' },
141                 { "user-agent",       required_argument, NULL, 'U' },
142                 { "passive-ftp",      no_argument, NULL, 0xff },
143                 { "header",           required_argument, NULL, 0xfe },
144                 { 0, 0, 0, 0 }
145         };
146         applet_long_options = wget_long_options;
147 #endif
148         opt_complementary = "-1" USE_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
149         opt = getopt32(argc, argv, "csqO:P:Y:U:",
150                                 &fname_out, &dir_prefix,
151                                 &proxy_flag, &user_agent
152                                 USE_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
153                                 );
154         if (strcmp(proxy_flag, "off") == 0) {
155                 /* Use the proxy if necessary. */
156                 use_proxy = 0;
157         }
158 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
159         if (headers_llist) {
160                 int size = 1;
161                 char *cp;
162                 llist_t *ll = headers_llist = llist_rev(headers_llist);
163                 while (ll) {
164                         size += strlen(ll->data) + 2;
165                         ll = ll->link;
166                 }
167                 extra_headers = cp = xmalloc(size);
168                 while (headers_llist) {
169                         cp += sprintf(cp, "%s\r\n", headers_llist->data);
170                         headers_llist = headers_llist->link;
171                 }
172         }
173 #endif
174
175         parse_url(argv[optind], &target);
176         server.host = target.host;
177         server.port = target.port;
178
179         /*
180          * Use the proxy if necessary.
181          */
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         /*
221          * Determine where to start transfer.
222          */
223         if (LONE_DASH(fname_out)) {
224                 output_fd = 1;
225                 opt &= ~WGET_OPT_CONTINUE;
226         }
227         if (opt & WGET_OPT_CONTINUE) {
228                 output_fd = open(fname_out, O_WRONLY);
229                 if (output_fd >= 0) {
230                         beg_range = xlseek(output_fd, 0, SEEK_END);
231                 }
232                 /* File doesn't exist. We do not create file here yet.
233                    We are not sure it exists on remove side */
234         }
235
236         /* We want to do exactly _one_ DNS lookup, since some
237          * sites (i.e. ftp.us.debian.org) use round-robin DNS
238          * and we want to connect to only one IP... */
239         lsa = xhost2sockaddr(server.host, server.port);
240         if (!(opt & WGET_OPT_QUIET)) {
241                 fprintf(stderr, "Connecting to %s (%s)\n", server.host,
242                                 xmalloc_sockaddr2dotted(&lsa->sa, lsa->len));
243                 /* We leak result of xmalloc_sockaddr2dotted */
244         }
245
246         if (use_proxy || !target.is_ftp) {
247                 /*
248                  *  HTTP session
249                  */
250                 do {
251                         got_clen = chunked = 0;
252
253                         if (!--try)
254                                 bb_error_msg_and_die("too many redirections");
255
256                         /*
257                          * Open socket to http server
258                          */
259                         if (sfp) fclose(sfp);
260                         sfp = open_socket(lsa);
261
262                         /*
263                          * Send HTTP request.
264                          */
265                         if (use_proxy) {
266                                 fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
267                                         target.is_ftp ? "f" : "ht", target.host,
268                                         target.path);
269                         } else {
270                                 fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
271                         }
272
273                         fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
274                                 target.host, user_agent);
275
276 #if ENABLE_FEATURE_WGET_AUTHENTICATION
277                         if (target.user) {
278                                 fprintf(sfp, "Authorization: Basic %s\r\n",
279                                         base64enc((unsigned char*)target.user, buf, sizeof(buf)));
280                         }
281                         if (use_proxy && server.user) {
282                                 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
283                                         base64enc((unsigned char*)server.user, buf, sizeof(buf)));
284                         }
285 #endif
286
287                         if (beg_range)
288                                 fprintf(sfp, "Range: bytes=%"OFF_FMT"d-\r\n", beg_range);
289 #if ENABLE_FEATURE_WGET_LONG_OPTIONS
290                         if (extra_headers)
291                                 fputs(extra_headers, sfp);
292 #endif
293                         fprintf(sfp, "Connection: close\r\n\r\n");
294
295                         /*
296                         * Retrieve HTTP response line and check for "200" status code.
297                         */
298  read_response:
299                         if (fgets(buf, sizeof(buf), sfp) == NULL)
300                                 bb_error_msg_and_die("no response from server");
301
302                         s = buf;
303                         while (*s != '\0' && !isspace(*s)) ++s;
304                         s = skip_whitespace(s);
305                         // FIXME: no error check
306                         // xatou wouldn't work: "200 OK"
307                         status = atoi(s);
308                         switch (status) {
309                         case 0:
310                         case 100:
311                                 while (gethdr(buf, sizeof(buf), sfp, &n) != NULL)
312                                         /* eat all remaining headers */;
313                                 goto read_response;
314                         case 200:
315                                 break;
316                         case 300:       /* redirection */
317                         case 301:
318                         case 302:
319                         case 303:
320                                 break;
321                         case 206:
322                                 if (beg_range)
323                                         break;
324                                 /*FALLTHRU*/
325                         default:
326                                 /* Show first line only and kill any ESC tricks */
327                                 buf[strcspn(buf, "\n\r\x1b")] = '\0';
328                                 bb_error_msg_and_die("server returned error: %s", buf);
329                         }
330
331                         /*
332                          * Retrieve HTTP headers.
333                          */
334                         while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
335                                 if (strcasecmp(buf, "content-length") == 0) {
336                                         content_len = BB_STRTOOFF(s, NULL, 10);
337                                         if (errno || content_len < 0) {
338                                                 bb_error_msg_and_die("content-length %s is garbage", s);
339                                         }
340                                         got_clen = 1;
341                                         continue;
342                                 }
343                                 if (strcasecmp(buf, "transfer-encoding") == 0) {
344                                         if (strcasecmp(s, "chunked") != 0)
345                                                 bb_error_msg_and_die("server wants to do %s transfer encoding", s);
346                                         chunked = got_clen = 1;
347                                 }
348                                 if (strcasecmp(buf, "location") == 0) {
349                                         if (s[0] == '/')
350                                                 /* free(target.allocated); */
351                                                 target.path = /* target.allocated = */ xstrdup(s+1);
352                                         else {
353                                                 parse_url(s, &target);
354                                                 if (use_proxy == 0) {
355                                                         server.host = target.host;
356                                                         server.port = target.port;
357                                                 }
358                                                 free(lsa);
359                                                 lsa = xhost2sockaddr(server.host, server.port);
360                                                 break;
361                                         }
362                                 }
363                         }
364                 } while (status >= 300);
365
366                 dfp = sfp;
367
368         } else {
369
370                 /*
371                  *  FTP session
372                  */
373                 if (!target.user)
374                         target.user = xstrdup("anonymous:busybox@");
375
376                 sfp = open_socket(lsa);
377                 if (ftpcmd(NULL, NULL, sfp, buf) != 220)
378                         bb_error_msg_and_die("%s", buf+4);
379
380                 /*
381                  * Splitting username:password pair,
382                  * trying to log in
383                  */
384                 s = strchr(target.user, ':');
385                 if (s)
386                         *(s++) = '\0';
387                 switch (ftpcmd("USER ", target.user, sfp, buf)) {
388                 case 230:
389                         break;
390                 case 331:
391                         if (ftpcmd("PASS ", s, sfp, buf) == 230)
392                                 break;
393                         /* FALLTHRU (failed login) */
394                 default:
395                         bb_error_msg_and_die("ftp login: %s", buf+4);
396                 }
397
398                 ftpcmd("TYPE I", NULL, sfp, buf);
399
400                 /*
401                  * Querying file size
402                  */
403                 if (ftpcmd("SIZE ", target.path, sfp, buf) == 213) {
404                         content_len = BB_STRTOOFF(buf+4, NULL, 10);
405                         if (errno || content_len < 0) {
406                                 bb_error_msg_and_die("SIZE value is garbage");
407                         }
408                         got_clen = 1;
409                 }
410
411                 /*
412                  * Entering passive mode
413                  */
414                 if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
415  pasv_error:
416                         bb_error_msg_and_die("bad response to %s: %s", "PASV", buf);
417                 }
418                 // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
419                 // Server's IP is N1.N2.N3.N4 (we ignore it)
420                 // Server's port for data connection is P1*256+P2
421                 s = strrchr(buf, ')');
422                 if (s) s[0] = '\0';
423                 s = strrchr(buf, ',');
424                 if (!s) goto pasv_error;
425                 port = xatou_range(s+1, 0, 255);
426                 *s = '\0';
427                 s = strrchr(buf, ',');
428                 if (!s) goto pasv_error;
429                 port += xatou_range(s+1, 0, 255) * 256;
430                 set_nport(lsa, htons(port));
431                 dfp = open_socket(lsa);
432
433                 if (beg_range) {
434                         sprintf(buf, "REST %"OFF_FMT"d", beg_range);
435                         if (ftpcmd(buf, NULL, sfp, buf) == 350)
436                                 content_len -= beg_range;
437                 }
438
439                 if (ftpcmd("RETR ", target.path, sfp, buf) > 150)
440                         bb_error_msg_and_die("bad response to RETR: %s", buf);
441         }
442         if (opt & WGET_OPT_SPIDER) {
443                 if (ENABLE_FEATURE_CLEAN_UP)
444                         fclose(sfp);
445                 goto done;
446         }
447
448         /*
449          * Retrieve file
450          */
451         if (chunked) {
452                 fgets(buf, sizeof(buf), dfp);
453                 content_len = STRTOOFF(buf, NULL, 16);
454                 /* FIXME: error check?? */
455         }
456
457         /* Do it before progressmeter (want to have nice error message) */
458         if (output_fd < 0)
459                 output_fd = xopen(fname_out,
460                         O_WRONLY|O_CREAT|O_EXCL|O_TRUNC);
461
462         if (!(opt & WGET_OPT_QUIET))
463                 progressmeter(-1);
464
465         do {
466                 while (content_len > 0 || !got_clen) {
467                         unsigned rdsz = sizeof(buf);
468                         if (content_len < sizeof(buf) && (chunked || got_clen))
469                                 rdsz = (unsigned)content_len;
470                         n = safe_fread(buf, 1, rdsz, dfp);
471                         if (n <= 0)
472                                 break;
473                         if (full_write(output_fd, buf, n) != n) {
474                                 bb_perror_msg_and_die(bb_msg_write_error);
475                         }
476 #if ENABLE_FEATURE_WGET_STATUSBAR
477                         transferred += n;
478 #endif
479                         if (got_clen) {
480                                 content_len -= n;
481                         }
482                 }
483
484                 if (chunked) {
485                         safe_fgets(buf, sizeof(buf), dfp); /* This is a newline */
486                         safe_fgets(buf, sizeof(buf), dfp);
487                         content_len = STRTOOFF(buf, NULL, 16);
488                         /* FIXME: error check? */
489                         if (content_len == 0) {
490                                 chunked = 0; /* all done! */
491                         }
492                 }
493
494                 if (n == 0 && ferror(dfp)) {
495                         bb_perror_msg_and_die(bb_msg_read_error);
496                 }
497         } while (chunked);
498
499         if (!(opt & WGET_OPT_QUIET))
500                 progressmeter(1);
501
502         if ((use_proxy == 0) && target.is_ftp) {
503                 fclose(dfp);
504                 if (ftpcmd(NULL, NULL, sfp, buf) != 226)
505                         bb_error_msg_and_die("ftp error: %s", buf+4);
506                 ftpcmd("QUIT", NULL, sfp, buf);
507         }
508 done:
509         exit(EXIT_SUCCESS);
510 }
511
512
513 static void parse_url(char *src_url, struct host_info *h)
514 {
515         char *url, *p, *sp;
516
517         /* h->allocated = */ url = xstrdup(src_url);
518
519         if (strncmp(url, "http://", 7) == 0) {
520                 h->port = bb_lookup_port("http", "tcp", 80);
521                 h->host = url + 7;
522                 h->is_ftp = 0;
523         } else if (strncmp(url, "ftp://", 6) == 0) {
524                 h->port = bb_lookup_port("ftp", "tcp", 21);
525                 h->host = url + 6;
526                 h->is_ftp = 1;
527         } else
528                 bb_error_msg_and_die("not an http or ftp url: %s", url);
529
530         // FYI:
531         // "Real" wget 'http://busybox.net?var=a/b' sends this request:
532         //   'GET /?var=a/b HTTP 1.0'
533         //   and saves 'index.html?var=a%2Fb' (we save 'b')
534         // wget 'http://busybox.net?login=john@doe':
535         //   request: 'GET /?login=john@doe HTTP/1.0'
536         //   saves: 'index.html?login=john@doe' (we save '?login=john@doe')
537         // wget 'http://busybox.net#test/test':
538         //   request: 'GET / HTTP/1.0'
539         //   saves: 'index.html' (we save 'test')
540         //
541         // We also don't add unique .N suffix if file exists...
542         sp = strchr(h->host, '/');
543         p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
544         p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
545         if (!sp) {
546                 /* must be writable because of bb_get_last_path_component() */
547                 static char nullstr[] = "";
548                 h->path = nullstr;
549         } else if (*sp == '/') {
550                 *sp = '\0';
551                 h->path = sp + 1;
552         } else { // '#' or '?'
553                 // http://busybox.net?login=john@doe is a valid URL
554                 // memmove converts to:
555                 // http:/busybox.nett?login=john@doe...
556                 memmove(h->host-1, h->host, sp - h->host);
557                 h->host--;
558                 sp[-1] = '\0';
559                 h->path = sp;
560         }
561
562         sp = strrchr(h->host, '@');
563         h->user = NULL;
564         if (sp != NULL) {
565                 h->user = h->host;
566                 *sp = '\0';
567                 h->host = sp + 1;
568         }
569
570         sp = h->host;
571 }
572
573
574 static FILE *open_socket(len_and_sockaddr *lsa)
575 {
576         FILE *fp;
577
578         /* glibc 2.4 seems to try seeking on it - ??! */
579         /* hopefully it understands what ESPIPE means... */
580         fp = fdopen(xconnect_stream(lsa), "r+");
581         if (fp == NULL)
582                 bb_perror_msg_and_die("fdopen");
583
584         return fp;
585 }
586
587
588 static char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
589 {
590         char *s, *hdrval;
591         int c;
592
593         *istrunc = 0;
594
595         /* retrieve header line */
596         if (fgets(buf, bufsiz, fp) == NULL)
597                 return NULL;
598
599         /* see if we are at the end of the headers */
600         for (s = buf; *s == '\r'; ++s)
601                 ;
602         if (s[0] == '\n')
603                 return NULL;
604
605         /* convert the header name to lower case */
606         for (s = buf; isalnum(*s) || *s == '-'; ++s)
607                 *s = tolower(*s);
608
609         /* verify we are at the end of the header name */
610         if (*s != ':')
611                 bb_error_msg_and_die("bad header line: %s", buf);
612
613         /* locate the start of the header value */
614         for (*s++ = '\0'; *s == ' ' || *s == '\t'; ++s)
615                 ;
616         hdrval = s;
617
618         /* locate the end of header */
619         while (*s != '\0' && *s != '\r' && *s != '\n')
620                 ++s;
621
622         /* end of header found */
623         if (*s != '\0') {
624                 *s = '\0';
625                 return hdrval;
626         }
627
628         /* Rats!  The buffer isn't big enough to hold the entire header value. */
629         while (c = getc(fp), c != EOF && c != '\n')
630                 ;
631         *istrunc = 1;
632         return hdrval;
633 }
634
635 static int ftpcmd(const char *s1, const char *s2, FILE *fp, char *buf)
636 {
637         int result;
638         if (s1) {
639                 if (!s2) s2 = "";
640                 fprintf(fp, "%s%s\r\n", s1, s2);
641                 fflush(fp);
642         }
643
644         do {
645                 char *buf_ptr;
646
647                 if (fgets(buf, 510, fp) == NULL) {
648                         bb_perror_msg_and_die("error getting response");
649                 }
650                 buf_ptr = strstr(buf, "\r\n");
651                 if (buf_ptr) {
652                         *buf_ptr = '\0';
653                 }
654         } while (!isdigit(buf[0]) || buf[3] != ' ');
655
656         buf[3] = '\0';
657         result = xatoi_u(buf);
658         buf[3] = ' ';
659         return result;
660 }
661
662 #if ENABLE_FEATURE_WGET_STATUSBAR
663 /* Stuff below is from BSD rcp util.c, as added to openshh.
664  * Original copyright notice is retained at the end of this file.
665  */
666 static int
667 getttywidth(void)
668 {
669         int width;
670         get_terminal_width_height(0, &width, NULL);
671         return width;
672 }
673
674 static void
675 updateprogressmeter(int ignore)
676 {
677         int save_errno = errno;
678
679         progressmeter(0);
680         errno = save_errno;
681 }
682
683 static void alarmtimer(int iwait)
684 {
685         struct itimerval itv;
686
687         itv.it_value.tv_sec = iwait;
688         itv.it_value.tv_usec = 0;
689         itv.it_interval = itv.it_value;
690         setitimer(ITIMER_REAL, &itv, NULL);
691 }
692
693
694 static void
695 progressmeter(int flag)
696 {
697         static struct timeval lastupdate;
698         static off_t lastsize, totalsize;
699
700         struct timeval now, td, tvwait;
701         off_t abbrevsize;
702         int elapsed, ratio, barlength, i;
703         char buf[256];
704
705         if (flag == -1) { /* first call to progressmeter */
706                 gettimeofday(&start, (struct timezone *) 0);
707                 lastupdate = start;
708                 lastsize = 0;
709                 totalsize = content_len + beg_range; /* as content_len changes.. */
710         }
711
712         gettimeofday(&now, (struct timezone *) 0);
713         ratio = 100;
714         if (totalsize != 0 && !chunked) {
715                 /* long long helps to have working ETA even if !LFS */
716                 ratio = (int) (100 * (unsigned long long)(transferred+beg_range) / totalsize);
717                 ratio = MIN(ratio, 100);
718         }
719
720         fprintf(stderr, "\r%-20.20s%4d%% ", curfile, ratio);
721
722         barlength = getttywidth() - 51;
723         if (barlength > 0 && barlength < sizeof(buf)) {
724                 i = barlength * ratio / 100;
725                 memset(buf, '*', i);
726                 memset(buf + i, ' ', barlength - i);
727                 buf[barlength] = '\0';
728                 fprintf(stderr, "|%s|", buf);
729         }
730         i = 0;
731         abbrevsize = transferred + beg_range;
732         while (abbrevsize >= 100000) {
733                 i++;
734                 abbrevsize >>= 10;
735         }
736         /* see http://en.wikipedia.org/wiki/Tera */
737         fprintf(stderr, "%6d %c%c ", (int)abbrevsize, " KMGTPEZY"[i], i?'B':' ');
738
739         timersub(&now, &lastupdate, &tvwait);
740         if (transferred > lastsize) {
741                 lastupdate = now;
742                 lastsize = transferred;
743                 if (tvwait.tv_sec >= STALLTIME)
744                         timeradd(&start, &tvwait, &start);
745                 tvwait.tv_sec = 0;
746         }
747         timersub(&now, &start, &td);
748         elapsed = td.tv_sec;
749
750         if (tvwait.tv_sec >= STALLTIME) {
751                 fprintf(stderr, " - stalled -");
752         } else {
753                 off_t to_download = totalsize - beg_range;
754                 if (transferred <= 0 || 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  */