Add errno.h
[oweals/busybox.git] / wget.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * wget - retrieve a file using HTTP
4  *
5  * Chip Rosenthal Covad Communications <chip@laserlink.net>
6  *
7  * Note: According to RFC2616 section 3.6.1, "All HTTP/1.1 applications MUST be
8  * able to receive and decode the "chunked" transfer-coding, and MUST ignore
9  * chunk-extension extensions they do not understand."  
10  *
11  * This prevents this particular wget app from completely RFC compliant, and as
12  * such, prevents it from being used as a general purpose web browser...  This
13  * is a design decision, since it makes the code smaller.
14  *
15  */
16
17 #include "busybox.h"
18 #include <stdio.h>
19 #include <errno.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <ctype.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <signal.h>
26 #include <sys/ioctl.h>
27
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <netdb.h>
35
36
37 void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path);
38 FILE *open_socket(char *host, int port);
39 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
40 void progressmeter(int flag);
41
42 /* Globals (can be accessed from signal handlers */
43 static off_t filesize = 0;              /* content-length of the file */
44 #ifdef BB_FEATURE_WGET_STATUSBAR
45 static char *curfile;                   /* Name of current file being transferred. */
46 static struct timeval start;    /* Time a transfer started. */
47 volatile unsigned long statbytes; /* Number of bytes transferred so far. */
48 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
49 static const int STALLTIME = 5;
50 #endif
51                 
52 void close_and_delete_outfile(FILE* output, char *fname_out, int do_continue)
53 {
54         if (output != stdout && do_continue==0) {
55                 fclose(output);
56                 unlink(fname_out);
57         }
58 }
59
60 int wget_main(int argc, char **argv)
61 {
62         int n;
63         char *proxy, *proxy_host;
64         int uri_port, proxy_port;
65         char *s, buf[512];
66         struct stat sbuf;
67
68         FILE *sfp;                                      /* socket to web server                         */
69         char *uri_host, *uri_path;      /* parsed from command line url         */
70         char *fname_out = NULL;         /* where to direct output (-O)          */
71         int do_continue = 0;            /* continue a prev transfer (-c)        */
72         long beg_range = 0L;            /*   range at which continue begins     */
73         int got_clen = 0;                       /* got content-length: from server      */
74         FILE *output;                           /* socket to web server                         */
75         int quiet_flag = FALSE;         /* Be verry, verry quiet...                     */
76
77         /*
78          * Crack command line.
79          */
80         while ((n = getopt(argc, argv, "cqO:")) != EOF) {
81                 switch (n) {
82                 case 'c':
83                         ++do_continue;
84                         break;
85                 case 'q':
86                         quiet_flag = TRUE;
87                         break;
88                 case 'O':
89                         /* can't set fname_out to NULL if outputting to stdout, because
90                          * this gets interpreted as the auto-gen output filename
91                          * case below  - tausq@debian.org
92                          */
93                         fname_out = (strcmp(optarg, "-") == 0 ? (char *)1 : optarg);
94                         break;
95                 default:
96                         usage(wget_usage);
97                 }
98         }
99
100         if (argc - optind != 1)
101                         usage(wget_usage);
102
103         /*
104          * Use the proxy if necessary.
105          */
106         if ((proxy = getenv("http_proxy")) != NULL) {
107                 proxy = xstrdup(proxy);
108                 parse_url(proxy, &proxy_host, &proxy_port, &uri_path);
109                 parse_url(argv[optind], &uri_host, &uri_port, &uri_path);
110         } else {
111                 /*
112                  * Parse url into components.
113                  */
114                 parse_url(argv[optind], &uri_host, &uri_port, &uri_path);
115                 proxy_host=uri_host;
116                 proxy_port=uri_port;
117         }
118         
119         /* Guess an output filename */
120         if (!fname_out) {
121                 fname_out = 
122 #ifdef BB_FEATURE_WGET_STATUSBAR
123                         curfile = 
124 #endif
125                         get_last_path_component(uri_path);
126                 if (fname_out==NULL || strlen(fname_out)<1) {
127                         fname_out = 
128 #ifdef BB_FEATURE_WGET_STATUSBAR
129                                 curfile = 
130 #endif
131                                 "index.html";
132                 }
133 #ifdef BB_FEATURE_WGET_STATUSBAR
134         } else {
135                 curfile=argv[optind];
136 #endif
137         }
138         if (do_continue && !fname_out)
139                 error_msg_and_die("cannot specify continue (-c) without a filename (-O)\n");
140
141
142         /*
143          * Open socket to server.
144          */
145         sfp = open_socket(proxy_host, proxy_port);
146
147         /* Make the assumption that if the file already exists
148          * on disk that the intention is to continue downloading
149          * a previously aborted download  -Erik */
150         if (stat(fname_out, &sbuf) == 0) {
151                 ++do_continue;
152         }
153
154         /*
155          * Open the output file stream.
156          */
157         if (fname_out != (char *)1) {
158                 if ( (output=fopen(fname_out, (do_continue ? "a" : "w"))) == NULL)
159                         perror_msg_and_die("fopen(%s)", fname_out);
160         } else {
161                 output = stdout;
162         }
163
164         /*
165          * Determine where to start transfer.
166          */
167         if (do_continue) {
168                 if (fstat(fileno(output), &sbuf) < 0)
169                         perror_msg_and_die("fstat()");
170                 if (sbuf.st_size > 0)
171                         beg_range = sbuf.st_size;
172                 else
173                         do_continue = 0;
174         }
175
176         /*
177          * Send HTTP request.
178          */
179         fprintf(sfp, "GET http://%s:%d/%s HTTP/1.1\r\n", 
180                         uri_host, uri_port, uri_path);
181         fprintf(sfp, "Host: %s\r\nUser-Agent: Wget\r\n", uri_host);
182
183         if (do_continue)
184                 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
185         fprintf(sfp,"Connection: close\r\n\r\n");
186
187         /*
188          * Retrieve HTTP response line and check for "200" status code.
189          */
190         if (fgets(buf, sizeof(buf), sfp) == NULL) {
191                 close_and_delete_outfile(output, fname_out, do_continue);
192                 error_msg_and_die("no response from server\n");
193         }
194         for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
195                 ;
196         for ( ; isspace(*s) ; ++s)
197                 ;
198         switch (atoi(s)) {
199                 case 0:
200                 case 200:
201                         break;
202                 case 206:
203                         if (do_continue)
204                                 break;
205                         /*FALLTHRU*/
206                 default:
207                         close_and_delete_outfile(output, fname_out, do_continue);
208                         error_msg_and_die("server returned error %d: %s", atoi(s), buf);
209         }
210
211         /*
212          * Retrieve HTTP headers.
213          */
214         while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
215                 if (strcasecmp(buf, "content-length") == 0) {
216                         filesize = atol(s);
217                         got_clen = 1;
218                         continue;
219                 }
220                 if (strcasecmp(buf, "transfer-encoding") == 0) {
221                         close_and_delete_outfile(output, fname_out, do_continue);
222                         error_msg_and_die("server wants to do %s transfer encoding\n", s);
223                         continue;
224                 }
225         }
226
227         /*
228          * Retrieve HTTP body.
229          */
230 #ifdef BB_FEATURE_WGET_STATUSBAR
231         statbytes=0;
232         if (quiet_flag==FALSE)
233                 progressmeter(-1);
234 #endif
235         while (filesize > 0 && (n = fread(buf, 1, sizeof(buf), sfp)) > 0) {
236                 fwrite(buf, 1, n, output);
237 #ifdef BB_FEATURE_WGET_STATUSBAR
238                 statbytes+=n;
239                 if (quiet_flag==FALSE)
240                         progressmeter(1);
241 #endif
242                 if (got_clen)
243                         filesize -= n;
244         }
245         if (n == 0 && ferror(sfp))
246                 perror_msg_and_die("network read error");
247
248         exit(0);
249 }
250
251
252 void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path)
253 {
254         char *cp, *sp;
255
256         *uri_port = 80;
257
258         if (strncmp(url, "http://", 7) != 0)
259                 error_msg_and_die("not an http url: %s\n", url);
260
261         *uri_host = url + 7;
262
263         cp = strchr(*uri_host, ':');
264         sp = strchr(*uri_host, '/');
265
266         if (cp != NULL && (sp == NULL || cp < sp)) {
267                 *cp++ = '\0';
268                 *uri_port = atoi(cp);
269         }
270
271         if (sp != NULL) {
272                 *sp++ = '\0';
273                 *uri_path = sp;
274         } else
275                 *uri_path = "";
276 }
277
278
279 FILE *open_socket(char *host, int port)
280 {
281         struct sockaddr_in sin;
282         struct hostent *hp;
283         int fd;
284         FILE *fp;
285
286         memzero(&sin, sizeof(sin));
287         sin.sin_family = AF_INET;
288         if ((hp = (struct hostent *) gethostbyname(host)) == NULL)
289                 error_msg_and_die("cannot resolve %s\n", host);
290         memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
291         sin.sin_port = htons(port);
292
293         /*
294          * Get the server onto a stdio stream.
295          */
296         if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
297                 perror_msg_and_die("socket()");
298         if (connect(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
299                 perror_msg_and_die("connect(%s)", host);
300         if ((fp = fdopen(fd, "r+")) == NULL)
301                 perror_msg_and_die("fdopen()");
302
303         return fp;
304 }
305
306
307 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
308 {
309         char *s, *hdrval;
310         int c;
311
312         *istrunc = 0;
313
314         /* retrieve header line */
315         if (fgets(buf, bufsiz, fp) == NULL)
316                 return NULL;
317
318         /* see if we are at the end of the headers */
319         for (s = buf ; *s == '\r' ; ++s)
320                 ;
321         if (s[0] == '\n')
322                 return NULL;
323
324         /* convert the header name to lower case */
325         for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
326                 *s = tolower(*s);
327
328         /* verify we are at the end of the header name */
329         if (*s != ':')
330                 error_msg_and_die("bad header line: %s\n", buf);
331
332         /* locate the start of the header value */
333         for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
334                 ;
335         hdrval = s;
336
337         /* locate the end of header */
338         while (*s != '\0' && *s != '\r' && *s != '\n')
339                 ++s;
340
341         /* end of header found */
342         if (*s != '\0') {
343                 *s = '\0';
344                 return hdrval;
345         }
346
347         /* Rats!  The buffer isn't big enough to hold the entire header value. */
348         while (c = getc(fp), c != EOF && c != '\n')
349                 ;
350         *istrunc = 1;
351         return hdrval;
352 }
353
354 #ifdef BB_FEATURE_WGET_STATUSBAR
355 /* Stuff below is from BSD rcp util.c, as added to openshh. 
356  * Original copyright notice is retained at the end of this file.
357  * 
358  */ 
359
360
361 int
362 getttywidth(void)
363 {
364         struct winsize winsize;
365
366         if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
367                 return (winsize.ws_col ? winsize.ws_col : 80);
368         else
369                 return (80);
370 }
371
372 void
373 updateprogressmeter(int ignore)
374 {
375         int save_errno = errno;
376
377         progressmeter(0);
378         errno = save_errno;
379 }
380
381 void
382 alarmtimer(int wait)
383 {
384         struct itimerval itv;
385
386         itv.it_value.tv_sec = wait;
387         itv.it_value.tv_usec = 0;
388         itv.it_interval = itv.it_value;
389         setitimer(ITIMER_REAL, &itv, NULL);
390 }
391
392
393 void
394 progressmeter(int flag)
395 {
396         static const char prefixes[] = " KMGTP";
397         static struct timeval lastupdate;
398         static off_t lastsize;
399         struct timeval now, td, wait;
400         off_t cursize, abbrevsize;
401         double elapsed;
402         int ratio, barlength, i, remaining;
403         char buf[256];
404
405         if (flag == -1) {
406                 (void) gettimeofday(&start, (struct timezone *) 0);
407                 lastupdate = start;
408                 lastsize = 0;
409         }
410
411         (void) gettimeofday(&now, (struct timezone *) 0);
412         cursize = statbytes;
413         if (filesize != 0) {
414                 ratio = 100.0 * cursize / filesize;
415                 ratio = MAX(ratio, 0);
416                 ratio = MIN(ratio, 100);
417         } else
418                 ratio = 100;
419
420         snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
421
422         barlength = getttywidth() - 51;
423         if (barlength > 0) {
424                 i = barlength * ratio / 100;
425                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
426                          "|%.*s%*s|", i,
427                          "*****************************************************************************"
428                          "*****************************************************************************",
429                          barlength - i, "");
430         }
431         i = 0;
432         abbrevsize = cursize;
433         while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
434                 i++;
435                 abbrevsize >>= 10;
436         }
437         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
438              (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
439                  'B');
440
441         timersub(&now, &lastupdate, &wait);
442         if (cursize > lastsize) {
443                 lastupdate = now;
444                 lastsize = cursize;
445                 if (wait.tv_sec >= STALLTIME) {
446                         start.tv_sec += wait.tv_sec;
447                         start.tv_usec += wait.tv_usec;
448                 }
449                 wait.tv_sec = 0;
450         }
451         timersub(&now, &start, &td);
452         elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
453
454         if (statbytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
455                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
456                          "   --:-- ETA");
457         } else if (wait.tv_sec >= STALLTIME) {
458                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
459                          " - stalled -");
460         } else {
461                 remaining = (int) (filesize / (statbytes / elapsed) - elapsed);
462                 i = remaining / 3600;
463                 if (i)
464                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
465                                  "%2d:", i);
466                 else
467                         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
468                                  "   ");
469                 i = remaining % 3600;
470                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
471                          "%02d:%02d ETA", i / 60, i % 60);
472         }
473         write(fileno(stderr), buf, strlen(buf));
474
475         if (flag == -1) {
476                 struct sigaction sa;
477                 sa.sa_handler = updateprogressmeter;
478                 sigemptyset(&sa.sa_mask);
479                 sa.sa_flags = SA_RESTART;
480                 sigaction(SIGALRM, &sa, NULL);
481                 alarmtimer(1);
482         } else if (flag == 1) {
483                 alarmtimer(0);
484                 statbytes = 0;
485         }
486 }
487 #endif
488
489 /* Original copyright notice which applies to the BB_FEATURE_WGET_STATUSBAR stuff,
490  * much of which was blatently stolen from openssh.  */
491  
492 /*-
493  * Copyright (c) 1992, 1993
494  *      The Regents of the University of California.  All rights reserved.
495  *
496  * Redistribution and use in source and binary forms, with or without
497  * modification, are permitted provided that the following conditions
498  * are met:
499  * 1. Redistributions of source code must retain the above copyright
500  *    notice, this list of conditions and the following disclaimer.
501  * 2. Redistributions in binary form must reproduce the above copyright
502  *    notice, this list of conditions and the following disclaimer in the
503  *    documentation and/or other materials provided with the distribution.
504  *
505  * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change 
506  *              ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change> 
507  *
508  * 4. Neither the name of the University nor the names of its contributors
509  *    may be used to endorse or promote products derived from this software
510  *    without specific prior written permission.
511  *
512  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
513  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
514  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
515  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
516  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
517  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
518  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
519  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
520  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
521  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
522  * SUCH DAMAGE.
523  *
524  *      $Id: wget.c,v 1.22 2001/01/26 02:04:49 andersen Exp $
525  */
526
527
528
529 /*
530 Local Variables:
531 c-file-style: "linux"
532 c-basic-offset: 4
533 tab-width: 4
534 End:
535 */
536
537
538