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