blob: 9b8fedd1f962ba8c9fb0662813729dd388629c58 [file] [log] [blame]
Eric Andersen96700832000-09-04 15:15:55 +00001/* vi: set sw=4 ts=4: */
2/*
3 * wget - retrieve a file using HTTP
4 *
Eric Andersen4e573f42000-11-14 23:29:24 +00005 * Chip Rosenthal Covad Communications <chip@laserlink.net>
Eric Andersenb520e082000-10-03 00:21:45 +00006 *
Eric Andersen4e573f42000-11-14 23:29:24 +00007 * 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."
Eric Andersenb520e082000-10-03 00:21:45 +000010 *
Eric Andersen4e573f42000-11-14 23:29:24 +000011 * 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.
Eric Andersenb520e082000-10-03 00:21:45 +000014 *
Eric Andersen96700832000-09-04 15:15:55 +000015 */
16
Eric Andersen3570a342000-09-25 21:45:58 +000017#include "busybox.h"
Eric Andersen96700832000-09-04 15:15:55 +000018#include <stdio.h>
19#include <stdlib.h>
20#include <unistd.h>
21#include <ctype.h>
22#include <string.h>
Eric Andersenb520e082000-10-03 00:21:45 +000023#include <unistd.h>
24#include <signal.h>
25#include <sys/ioctl.h>
Eric Andersen96700832000-09-04 15:15:55 +000026
Eric Andersenb520e082000-10-03 00:21:45 +000027#include <sys/time.h>
Eric Andersen96700832000-09-04 15:15:55 +000028#include <sys/types.h>
29#include <sys/stat.h>
30#include <sys/socket.h>
31#include <netinet/in.h>
32#include <arpa/inet.h>
33#include <netdb.h>
34
35
36void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path);
37FILE *open_socket(char *host, int port);
38char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
Eric Andersenb520e082000-10-03 00:21:45 +000039void progressmeter(int flag);
Eric Andersen96700832000-09-04 15:15:55 +000040
Eric Andersenb520e082000-10-03 00:21:45 +000041/* Globals (can be accessed from signal handlers */
42static off_t filesize = 0; /* content-length of the file */
43#ifdef BB_FEATURE_STATUSBAR
44static char *curfile; /* Name of current file being transferred. */
45static struct timeval start; /* Time a transfer started. */
46volatile unsigned long statbytes; /* Number of bytes transferred so far. */
47/* For progressmeter() -- number of seconds before xfer considered "stalled" */
48#define STALLTIME 5
49#endif
Eric Andersen96700832000-09-04 15:15:55 +000050
51int wget_main(int argc, char **argv)
52{
53 FILE *sfp; /* socket to web server */
54 char *uri_host, *uri_path; /* parsed from command line url */
Eric Andersenf3b2b522000-12-07 22:42:11 +000055 char *proxy;
Eric Andersen96700832000-09-04 15:15:55 +000056 int uri_port;
57 char *s, buf[512];
58 int n;
59
60 char *fname_out = NULL; /* where to direct output (-O) */
61 int do_continue = 0; /* continue a prev transfer (-c) */
62 long beg_range = 0L; /* range at which continue begins */
63 int got_clen = 0; /* got content-length: from server */
Eric Andersenb520e082000-10-03 00:21:45 +000064 FILE *output; /* socket to web server */
Eric Andersen96700832000-09-04 15:15:55 +000065
66 /*
67 * Crack command line.
68 */
69 while ((n = getopt(argc, argv, "cO:")) != EOF) {
70 switch (n) {
71 case 'c':
72 ++do_continue;
73 break;
74 case 'O':
Randolph Chung02553a22000-12-07 03:53:47 +000075 /* can't set fname_out to NULL if outputting to stdout, because
76 * this gets interpreted as the auto-gen output filename
77 * case below - tausq@debian.org
78 */
79 fname_out = (strcmp(optarg, "-") == 0 ? (char *)1 : optarg);
Eric Andersen96700832000-09-04 15:15:55 +000080 break;
81 default:
82 usage(wget_usage);
83 }
84 }
Eric Andersen25b669c2000-10-02 23:19:38 +000085
Eric Andersen96700832000-09-04 15:15:55 +000086 if (argc - optind != 1)
87 usage(wget_usage);
Eric Andersen25b669c2000-10-02 23:19:38 +000088
89 /* Guess an output filename */
90 if (!fname_out) {
Eric Andersenb520e082000-10-03 00:21:45 +000091 fname_out =
92#ifdef BB_FEATURE_STATUSBAR
93 curfile =
94#endif
95 get_last_path_component(argv[optind]);
96#ifdef BB_FEATURE_STATUSBAR
97 } else {
98 curfile=argv[optind];
99#endif
Eric Andersen25b669c2000-10-02 23:19:38 +0000100 }
101
Eric Andersenb520e082000-10-03 00:21:45 +0000102
Eric Andersen25b669c2000-10-02 23:19:38 +0000103 if (do_continue && !fname_out)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000104 error_msg_and_die("cannot specify continue (-c) without a filename (-O)\n");
Eric Andersenf3b2b522000-12-07 22:42:11 +0000105
Eric Andersen96700832000-09-04 15:15:55 +0000106 /*
Eric Andersenf3b2b522000-12-07 22:42:11 +0000107 * Use the proxy if necessary.
Eric Andersen96700832000-09-04 15:15:55 +0000108 */
Eric Andersenf3b2b522000-12-07 22:42:11 +0000109 if ((proxy = getenv("http_proxy")) != NULL) {
110 proxy = xstrdup(proxy);
111 parse_url(proxy, &uri_host, &uri_port, &uri_path);
112 uri_path = argv[optind];
113 } else {
114 /*
115 * Parse url into components.
116 */
117 parse_url(argv[optind], &uri_host, &uri_port, &uri_path);
118 }
Eric Andersen96700832000-09-04 15:15:55 +0000119
120 /*
121 * Open socket to server.
122 */
123 sfp = open_socket(uri_host, uri_port);
124
125 /*
126 * Open the output stream.
127 */
Randolph Chung02553a22000-12-07 03:53:47 +0000128 if (fname_out != (char *)1) {
Eric Andersenb520e082000-10-03 00:21:45 +0000129 if ( (output=fopen(fname_out, (do_continue ? "a" : "w")))
130 == NULL)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000131 perror_msg_and_die("fopen(%s)", fname_out);
Randolph Chung02553a22000-12-07 03:53:47 +0000132 } else {
133 output = stdout;
Eric Andersen96700832000-09-04 15:15:55 +0000134 }
135
136 /*
137 * Determine where to start transfer.
138 */
139 if (do_continue) {
140 struct stat sbuf;
Eric Andersenb520e082000-10-03 00:21:45 +0000141 if (fstat(fileno(output), &sbuf) < 0)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000142 error_msg_and_die("fstat()");
Eric Andersen96700832000-09-04 15:15:55 +0000143 if (sbuf.st_size > 0)
144 beg_range = sbuf.st_size;
145 else
146 do_continue = 0;
147 }
148
149 /*
150 * Send HTTP request.
151 */
152 fprintf(sfp, "GET %s HTTP/1.1\r\nHost: %s\r\n", uri_path, uri_host);
153 if (do_continue)
154 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
155 fputs("Connection: close\r\n\r\n", sfp);
156
157 /*
158 * Retrieve HTTP response line and check for "200" status code.
159 */
160 if (fgets(buf, sizeof(buf), sfp) == NULL)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000161 error_msg_and_die("no response from server\n");
Eric Andersen96700832000-09-04 15:15:55 +0000162 for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
163 ;
164 for ( ; isspace(*s) ; ++s)
165 ;
166 switch (atoi(s)) {
Eric Andersenb520e082000-10-03 00:21:45 +0000167 case 200:
168 if (!do_continue)
169 break;
Mark Whitleyf57c9442000-12-07 19:56:48 +0000170 error_msg_and_die("server does not support ranges\n");
Eric Andersenb520e082000-10-03 00:21:45 +0000171 case 206:
172 if (do_continue)
173 break;
174 /*FALLTHRU*/
175 default:
Mark Whitleyf57c9442000-12-07 19:56:48 +0000176 error_msg_and_die("server returned error: %s", buf);
Eric Andersen96700832000-09-04 15:15:55 +0000177 }
178
179 /*
180 * Retrieve HTTP headers.
181 */
182 while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
183 if (strcmp(buf, "content-length") == 0) {
Eric Andersenb520e082000-10-03 00:21:45 +0000184 filesize = atol(s);
Eric Andersen96700832000-09-04 15:15:55 +0000185 got_clen = 1;
186 continue;
187 }
188 if (strcmp(buf, "transfer-encoding") == 0) {
Mark Whitleyf57c9442000-12-07 19:56:48 +0000189 error_msg_and_die("server wants to do %s transfer encoding\n", s);
Eric Andersen96700832000-09-04 15:15:55 +0000190 continue;
191 }
192 }
193
194 /*
195 * Retrieve HTTP body.
196 */
Eric Andersenb520e082000-10-03 00:21:45 +0000197#ifdef BB_FEATURE_STATUSBAR
198 statbytes=0;
199 progressmeter(-1);
200#endif
201 while (filesize > 0 && (n = fread(buf, 1, sizeof(buf), sfp)) > 0) {
202 fwrite(buf, 1, n, output);
203#ifdef BB_FEATURE_STATUSBAR
204 statbytes+=n;
205 progressmeter(1);
206#endif
Eric Andersen96700832000-09-04 15:15:55 +0000207 if (got_clen)
Eric Andersenb520e082000-10-03 00:21:45 +0000208 filesize -= n;
Eric Andersen96700832000-09-04 15:15:55 +0000209 }
210 if (n == 0 && ferror(sfp))
Mark Whitleyf57c9442000-12-07 19:56:48 +0000211 perror_msg_and_die("network read error");
Eric Andersen96700832000-09-04 15:15:55 +0000212
213 exit(0);
214}
215
216
217void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path)
218{
219 char *s, *h;
Randolph Chung02553a22000-12-07 03:53:47 +0000220 static char *defaultpath = "/";
Eric Andersen96700832000-09-04 15:15:55 +0000221
222 *uri_port = 80;
223
224 if (strncmp(url, "http://", 7) != 0)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000225 error_msg_and_die("not an http url: %s\n", url);
Eric Andersen96700832000-09-04 15:15:55 +0000226
227 /* pull the host portion to the front of the buffer */
Randolph Chung02553a22000-12-07 03:53:47 +0000228 for (s = url, h = url+7 ; *h != '/' && *h != 0; ++h) {
Eric Andersen96700832000-09-04 15:15:55 +0000229 if (*h == ':') {
230 *uri_port = atoi(h+1);
231 *h = '\0';
232 }
233 *s++ = *h;
234 }
235 *s = '\0';
Randolph Chung02553a22000-12-07 03:53:47 +0000236
237 if (*h == 0) h = defaultpath;
238
Eric Andersen96700832000-09-04 15:15:55 +0000239 *uri_host = url;
240 *uri_path = h;
241}
242
243
244FILE *open_socket(char *host, int port)
245{
246 struct sockaddr_in sin;
247 struct hostent *hp;
248 int fd;
249 FILE *fp;
250
251 memzero(&sin, sizeof(sin));
252 sin.sin_family = AF_INET;
253 if ((hp = (struct hostent *) gethostbyname(host)) == NULL)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000254 error_msg_and_die("cannot resolve %s\n", host);
Eric Andersen96700832000-09-04 15:15:55 +0000255 memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
256 sin.sin_port = htons(port);
257
258 /*
259 * Get the server onto a stdio stream.
260 */
261 if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000262 perror_msg_and_die("socket()");
Eric Andersen96700832000-09-04 15:15:55 +0000263 if (connect(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000264 perror_msg_and_die("connect(%s)", host);
Eric Andersen96700832000-09-04 15:15:55 +0000265 if ((fp = fdopen(fd, "r+")) == NULL)
Mark Whitleyf57c9442000-12-07 19:56:48 +0000266 perror_msg_and_die("fdopen()");
Eric Andersen96700832000-09-04 15:15:55 +0000267
268 return fp;
269}
270
271
272char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
273{
274 char *s, *hdrval;
275 int c;
276
277 *istrunc = 0;
278
279 /* retrieve header line */
280 if (fgets(buf, bufsiz, fp) == NULL)
281 return NULL;
282
283 /* see if we are at the end of the headers */
284 for (s = buf ; *s == '\r' ; ++s)
285 ;
286 if (s[0] == '\n')
287 return NULL;
288
289 /* convert the header name to lower case */
290 for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
291 *s = tolower(*s);
292
293 /* verify we are at the end of the header name */
294 if (*s != ':')
Mark Whitleyf57c9442000-12-07 19:56:48 +0000295 error_msg_and_die("bad header line: %s\n", buf);
Eric Andersen96700832000-09-04 15:15:55 +0000296
297 /* locate the start of the header value */
298 for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
299 ;
300 hdrval = s;
301
302 /* locate the end of header */
303 while (*s != '\0' && *s != '\r' && *s != '\n')
304 ++s;
305
306 /* end of header found */
307 if (*s != '\0') {
308 *s = '\0';
309 return hdrval;
310 }
311
Eric Andersen5d638842000-09-14 21:46:30 +0000312 /* Rats! The buffer isn't big enough to hold the entire header value. */
Eric Andersen96700832000-09-04 15:15:55 +0000313 while (c = getc(fp), c != EOF && c != '\n')
314 ;
315 *istrunc = 1;
316 return hdrval;
317}
318
Eric Andersenb520e082000-10-03 00:21:45 +0000319#ifdef BB_FEATURE_STATUSBAR
Eric Andersen4e573f42000-11-14 23:29:24 +0000320/* Stuff below is from BSD rcp util.c, as added to openshh.
321 * Original copyright notice is retained at the end of this file.
322 *
323 */
Eric Andersenb520e082000-10-03 00:21:45 +0000324
325
326int
327getttywidth(void)
328{
329 struct winsize winsize;
330
331 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
332 return (winsize.ws_col ? winsize.ws_col : 80);
333 else
334 return (80);
335}
336
337void
338updateprogressmeter(int ignore)
339{
340 int save_errno = errno;
341
342 progressmeter(0);
343 errno = save_errno;
344}
345
346void
347alarmtimer(int wait)
348{
349 struct itimerval itv;
350
351 itv.it_value.tv_sec = wait;
352 itv.it_value.tv_usec = 0;
353 itv.it_interval = itv.it_value;
354 setitimer(ITIMER_REAL, &itv, NULL);
355}
356
357
358void
359progressmeter(int flag)
360{
361 static const char prefixes[] = " KMGTP";
362 static struct timeval lastupdate;
363 static off_t lastsize;
364 struct timeval now, td, wait;
365 off_t cursize, abbrevsize;
366 double elapsed;
367 int ratio, barlength, i, remaining;
368 char buf[256];
369
370 if (flag == -1) {
371 (void) gettimeofday(&start, (struct timezone *) 0);
372 lastupdate = start;
373 lastsize = 0;
374 }
375
376 (void) gettimeofday(&now, (struct timezone *) 0);
377 cursize = statbytes;
378 if (filesize != 0) {
379 ratio = 100.0 * cursize / filesize;
380 ratio = MAX(ratio, 0);
381 ratio = MIN(ratio, 100);
382 } else
383 ratio = 100;
384
385 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
386
387 barlength = getttywidth() - 51;
388 if (barlength > 0) {
389 i = barlength * ratio / 100;
390 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
391 "|%.*s%*s|", i,
392 "*****************************************************************************"
393 "*****************************************************************************",
394 barlength - i, "");
395 }
396 i = 0;
397 abbrevsize = cursize;
398 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
399 i++;
400 abbrevsize >>= 10;
401 }
402 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
403 (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
404 'B');
405
406 timersub(&now, &lastupdate, &wait);
407 if (cursize > lastsize) {
408 lastupdate = now;
409 lastsize = cursize;
410 if (wait.tv_sec >= STALLTIME) {
411 start.tv_sec += wait.tv_sec;
412 start.tv_usec += wait.tv_usec;
413 }
414 wait.tv_sec = 0;
415 }
416 timersub(&now, &start, &td);
417 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
418
419 if (statbytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
420 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
421 " --:-- ETA");
422 } else if (wait.tv_sec >= STALLTIME) {
423 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
424 " - stalled -");
425 } else {
426 remaining = (int) (filesize / (statbytes / elapsed) - elapsed);
427 i = remaining / 3600;
428 if (i)
429 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
430 "%2d:", i);
431 else
432 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
433 " ");
434 i = remaining % 3600;
435 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
436 "%02d:%02d ETA", i / 60, i % 60);
437 }
Randolph Chungda7b8292000-12-07 03:55:35 +0000438 write(fileno(stderr), buf, strlen(buf));
Eric Andersenb520e082000-10-03 00:21:45 +0000439
440 if (flag == -1) {
441 struct sigaction sa;
442 sa.sa_handler = updateprogressmeter;
443 sigemptyset(&sa.sa_mask);
444 sa.sa_flags = SA_RESTART;
445 sigaction(SIGALRM, &sa, NULL);
446 alarmtimer(1);
447 } else if (flag == 1) {
448 alarmtimer(0);
449 statbytes = 0;
450 }
451}
452#endif
Eric Andersen4e573f42000-11-14 23:29:24 +0000453
454/* Original copyright notice which applies to the BB_FEATURE_STATUSBAR stuff,
455 * much of which was blatently stolen from openssh. */
456
457/*-
458 * Copyright (c) 1992, 1993
459 * The Regents of the University of California. All rights reserved.
460 *
461 * Redistribution and use in source and binary forms, with or without
462 * modification, are permitted provided that the following conditions
463 * are met:
464 * 1. Redistributions of source code must retain the above copyright
465 * notice, this list of conditions and the following disclaimer.
466 * 2. Redistributions in binary form must reproduce the above copyright
467 * notice, this list of conditions and the following disclaimer in the
468 * documentation and/or other materials provided with the distribution.
469 *
470 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
471 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
472 *
473 * 4. Neither the name of the University nor the names of its contributors
474 * may be used to endorse or promote products derived from this software
475 * without specific prior written permission.
476 *
477 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
478 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
479 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
480 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
481 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
482 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
483 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
484 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
485 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
486 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
487 * SUCH DAMAGE.
488 *
Eric Andersenf3b2b522000-12-07 22:42:11 +0000489 * $Id: wget.c,v 1.11 2000/12/07 22:42:11 andersen Exp $
Eric Andersen4e573f42000-11-14 23:29:24 +0000490 */
491
492
493
Eric Andersen96700832000-09-04 15:15:55 +0000494/*
495Local Variables:
496c-file-style: "linux"
497c-basic-offset: 4
498tab-width: 4
499End:
500*/
Eric Andersenb520e082000-10-03 00:21:45 +0000501
Eric Andersen4e573f42000-11-14 23:29:24 +0000502
503