4f894fcaa6a43dd73b31e040a772a6ac6d0c4f55
[oweals/busybox.git] / wget.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * wget - retrieve a file using HTTP
4  *
5  * Chip Rosenthal
6  * Covad Communications
7  * <chip@laserlink.net>
8  */
9
10 #include "internal.h"
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <ctype.h>
15 #include <string.h>
16
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <netdb.h>
23
24
25 void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path);
26 FILE *open_socket(char *host, int port);
27 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc);
28
29
30 int wget_main(int argc, char **argv)
31 {
32         FILE *sfp;                                      /* socket to web server                         */
33         char *uri_host, *uri_path;      /* parsed from command line url         */
34         int uri_port;
35         char *s, buf[512];
36         int n;
37
38         char *fname_out = NULL;         /* where to direct output (-O)          */
39         int do_continue = 0;            /* continue a prev transfer (-c)        */
40         long beg_range = 0L;            /*   range at which continue begins     */
41         int got_clen = 0;                       /* got content-length: from server      */
42         long clen = 1L;                         /*   the content length                         */
43
44         /*
45          * Crack command line.
46          */
47         while ((n = getopt(argc, argv, "cO:")) != EOF) {
48                 switch (n) {
49                 case 'c':
50                         ++do_continue;
51                         break;
52                 case 'O':
53                         fname_out = optarg;
54                         break;
55                 default:
56                         usage(wget_usage);
57                 }
58         }
59         if (do_continue && !fname_out)
60                 fatalError("wget: cannot specify continue (-c) without a filename (-O)\n");
61         if (argc - optind != 1)
62                         usage(wget_usage);
63         /*
64          * Parse url into components.
65          */
66         parse_url(argv[optind], &uri_host, &uri_port, &uri_path);
67
68         /*
69          * Open socket to server.
70          */
71         sfp = open_socket(uri_host, uri_port);
72
73         /*
74          * Open the output stream.
75          */
76         if (fname_out != NULL) {
77                 /* Check if the file is supposed to go to stdout */
78                 if (!strcmp(fname_out, "-") == 0) {
79                         /* Nope -- so open the output file */
80                         if (freopen(fname_out, (do_continue ? "a" : "w"), stdout) == NULL)
81                                 fatalError("wget: freopen(%s): %s\n", fname_out, strerror(errno));
82                 }
83         }
84
85         /*
86          * Determine where to start transfer.
87          */
88         if (do_continue) {
89                 struct stat sbuf;
90                 if (fstat(fileno(stdout), &sbuf) < 0)
91                         fatalError("wget: fstat(): %s\n", strerror(errno));
92                 if (sbuf.st_size > 0)
93                         beg_range = sbuf.st_size;
94                 else
95                         do_continue = 0;
96         }
97
98         /*
99          * Send HTTP request.
100          */
101         fprintf(sfp, "GET %s HTTP/1.1\r\nHost: %s\r\n", uri_path, uri_host);
102         if (do_continue)
103                 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
104         fputs("Connection: close\r\n\r\n", sfp);
105
106         /*
107          * Retrieve HTTP response line and check for "200" status code.
108          */
109         if (fgets(buf, sizeof(buf), sfp) == NULL)
110                 fatalError("wget: no response from server\n");
111         for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
112                 ;
113         for ( ; isspace(*s) ; ++s)
114                 ;
115         switch (atoi(s)) {
116         case 200:
117                 if (!do_continue)
118                         break;
119                 fatalError("wget: cannot continue - server does not properly support ranges\n");
120         case 206:
121                 if (do_continue)
122                         break;
123                 /*FALLTHRU*/
124         default:
125                 fatalError("wget: server returned error: %s", buf);
126         }
127
128         /*
129          * Retrieve HTTP headers.
130          */
131         while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
132                 if (strcmp(buf, "content-length") == 0) {
133                         clen = atol(s);
134                         got_clen = 1;
135                         continue;
136                 }
137                 if (strcmp(buf, "transfer-encoding") == 0) {
138                         fatalError("wget: i do not do transfer encodings, server wants to do: %s\n", s);
139                         continue;
140                 }
141         }
142
143         /*
144          * Retrieve HTTP body.
145          */
146         while (clen > 0 && (n = fread(buf, 1, sizeof(buf), sfp)) > 0) {
147                 fwrite(buf, 1, n, stdout);
148                 if (got_clen)
149                         clen -= n;
150         }
151         if (n == 0 && ferror(sfp))
152                 fatalError("wget: network read error: %s", strerror(errno));
153
154         exit(0);
155 }
156
157
158 void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path)
159 {
160         char *s, *h;
161
162         *uri_port = 80;
163
164         if (strncmp(url, "http://", 7) != 0)
165                 fatalError("wget: not an http url: %s\n", url);
166
167         /* pull the host portion to the front of the buffer */
168         for (s = url, h = url+7 ; *h != '/' ; ++h) {
169                 if (*h == '\0')
170                         fatalError("wget: cannot parse url: %s\n", url);
171                 if (*h == ':') {
172                         *uri_port = atoi(h+1);
173                         *h = '\0';
174                 }
175                 *s++ = *h;
176         }
177         *s = '\0';
178         *uri_host = url;
179         *uri_path = h;
180 }
181
182
183 FILE *open_socket(char *host, int port)
184 {
185         struct sockaddr_in sin;
186         struct hostent *hp;
187         int fd;
188         FILE *fp;
189
190         memzero(&sin, sizeof(sin));
191         sin.sin_family = AF_INET;
192         if ((hp = (struct hostent *) gethostbyname(host)) == NULL)
193                 fatalError("wget: cannot resolve %s\n", host);
194         memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
195         sin.sin_port = htons(port);
196
197         /*
198          * Get the server onto a stdio stream.
199          */
200         if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
201                 fatalError("wget: socket(): %s\n", strerror(errno));
202         if (connect(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
203                 fatalError("wget: connect(%s): %s\n", host, strerror(errno));
204         if ((fp = fdopen(fd, "r+")) == NULL)
205                 fatalError("wget: fdopen(): %s\n", strerror(errno));
206
207         return fp;
208 }
209
210
211 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
212 {
213         char *s, *hdrval;
214         int c;
215
216         *istrunc = 0;
217
218         /* retrieve header line */
219         if (fgets(buf, bufsiz, fp) == NULL)
220                 return NULL;
221
222         /* see if we are at the end of the headers */
223         for (s = buf ; *s == '\r' ; ++s)
224                 ;
225         if (s[0] == '\n')
226                 return NULL;
227
228         /* convert the header name to lower case */
229         for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
230                 *s = tolower(*s);
231
232         /* verify we are at the end of the header name */
233         if (*s != ':')
234                 fatalError("wget: bad header line: %s\n", buf);
235
236         /* locate the start of the header value */
237         for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
238                 ;
239         hdrval = s;
240
241         /* locate the end of header */
242         while (*s != '\0' && *s != '\r' && *s != '\n')
243                 ++s;
244
245         /* end of header found */
246         if (*s != '\0') {
247                 *s = '\0';
248                 return hdrval;
249         }
250
251         /* Rat!  The buffer isn't big enough to hold the entire header value. */
252         while (c = getc(fp), c != EOF && c != '\n')
253                 ;
254         *istrunc = 1;
255         return hdrval;
256 }
257
258 /*
259 Local Variables:
260 c-file-style: "linux"
261 c-basic-offset: 4
262 tab-width: 4
263 End:
264 */