c95271b0da1460db0b7e45bc825c348bb62f46b6
[oweals/busybox.git] / networking / 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 "busybox.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 = (strcmp(optarg, "-") == 0 ? NULL : optarg);
54                         break;
55                 default:
56                         usage(wget_usage);
57                 }
58         }
59
60         if (argc - optind != 1)
61                         usage(wget_usage);
62
63         /* Guess an output filename */
64         if (!fname_out) {
65                 fname_out = get_last_path_component(argv[optind]);
66         }
67
68         if (do_continue && !fname_out)
69                 fatalError("wget: cannot specify continue (-c) without a filename (-O)\n");
70
71         /*
72          * Parse url into components.
73          */
74         parse_url(argv[optind], &uri_host, &uri_port, &uri_path);
75
76         /*
77          * Open socket to server.
78          */
79         sfp = open_socket(uri_host, uri_port);
80
81         /*
82          * Open the output stream.
83          */
84         if (fname_out != NULL) {
85                 if (freopen(fname_out, (do_continue ? "a" : "w"), stdout) == NULL)
86                         fatalError("wget: freopen(%s): %s\n", fname_out, strerror(errno));
87         }
88
89         /*
90          * Determine where to start transfer.
91          */
92         if (do_continue) {
93                 struct stat sbuf;
94                 if (fstat(fileno(stdout), &sbuf) < 0)
95                         fatalError("wget: fstat(): %s\n", strerror(errno));
96                 if (sbuf.st_size > 0)
97                         beg_range = sbuf.st_size;
98                 else
99                         do_continue = 0;
100         }
101
102         /*
103          * Send HTTP request.
104          */
105         fprintf(sfp, "GET %s HTTP/1.1\r\nHost: %s\r\n", uri_path, uri_host);
106         if (do_continue)
107                 fprintf(sfp, "Range: bytes=%ld-\r\n", beg_range);
108         fputs("Connection: close\r\n\r\n", sfp);
109
110         /*
111          * Retrieve HTTP response line and check for "200" status code.
112          */
113         if (fgets(buf, sizeof(buf), sfp) == NULL)
114                 fatalError("wget: no response from server\n");
115         for (s = buf ; *s != '\0' && !isspace(*s) ; ++s)
116                 ;
117         for ( ; isspace(*s) ; ++s)
118                 ;
119         switch (atoi(s)) {
120         case 200:
121                 if (!do_continue)
122                         break;
123                 fatalError("wget: cannot continue - server does not properly support ranges\n");
124         case 206:
125                 if (do_continue)
126                         break;
127                 /*FALLTHRU*/
128         default:
129                 fatalError("wget: server returned error: %s", buf);
130         }
131
132         /*
133          * Retrieve HTTP headers.
134          */
135         while ((s = gethdr(buf, sizeof(buf), sfp, &n)) != NULL) {
136                 if (strcmp(buf, "content-length") == 0) {
137                         clen = atol(s);
138                         got_clen = 1;
139                         continue;
140                 }
141                 if (strcmp(buf, "transfer-encoding") == 0) {
142                         fatalError("wget: i do not do transfer encodings, server wants to do: %s\n", s);
143                         continue;
144                 }
145         }
146
147         /*
148          * Retrieve HTTP body.
149          */
150         while (clen > 0 && (n = fread(buf, 1, sizeof(buf), sfp)) > 0) {
151                 fwrite(buf, 1, n, stdout);
152                 if (got_clen)
153                         clen -= n;
154         }
155         if (n == 0 && ferror(sfp))
156                 fatalError("wget: network read error: %s", strerror(errno));
157
158         exit(0);
159 }
160
161
162 void parse_url(char *url, char **uri_host, int *uri_port, char **uri_path)
163 {
164         char *s, *h;
165
166         *uri_port = 80;
167
168         if (strncmp(url, "http://", 7) != 0)
169                 fatalError("wget: not an http url: %s\n", url);
170
171         /* pull the host portion to the front of the buffer */
172         for (s = url, h = url+7 ; *h != '/' ; ++h) {
173                 if (*h == '\0')
174                         fatalError("wget: cannot parse url: %s\n", url);
175                 if (*h == ':') {
176                         *uri_port = atoi(h+1);
177                         *h = '\0';
178                 }
179                 *s++ = *h;
180         }
181         *s = '\0';
182         *uri_host = url;
183         *uri_path = h;
184 }
185
186
187 FILE *open_socket(char *host, int port)
188 {
189         struct sockaddr_in sin;
190         struct hostent *hp;
191         int fd;
192         FILE *fp;
193
194         memzero(&sin, sizeof(sin));
195         sin.sin_family = AF_INET;
196         if ((hp = (struct hostent *) gethostbyname(host)) == NULL)
197                 fatalError("wget: cannot resolve %s\n", host);
198         memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
199         sin.sin_port = htons(port);
200
201         /*
202          * Get the server onto a stdio stream.
203          */
204         if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
205                 fatalError("wget: socket(): %s\n", strerror(errno));
206         if (connect(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0)
207                 fatalError("wget: connect(%s): %s\n", host, strerror(errno));
208         if ((fp = fdopen(fd, "r+")) == NULL)
209                 fatalError("wget: fdopen(): %s\n", strerror(errno));
210
211         return fp;
212 }
213
214
215 char *gethdr(char *buf, size_t bufsiz, FILE *fp, int *istrunc)
216 {
217         char *s, *hdrval;
218         int c;
219
220         *istrunc = 0;
221
222         /* retrieve header line */
223         if (fgets(buf, bufsiz, fp) == NULL)
224                 return NULL;
225
226         /* see if we are at the end of the headers */
227         for (s = buf ; *s == '\r' ; ++s)
228                 ;
229         if (s[0] == '\n')
230                 return NULL;
231
232         /* convert the header name to lower case */
233         for (s = buf ; isalnum(*s) || *s == '-' ; ++s)
234                 *s = tolower(*s);
235
236         /* verify we are at the end of the header name */
237         if (*s != ':')
238                 fatalError("wget: bad header line: %s\n", buf);
239
240         /* locate the start of the header value */
241         for (*s++ = '\0' ; *s == ' ' || *s == '\t' ; ++s)
242                 ;
243         hdrval = s;
244
245         /* locate the end of header */
246         while (*s != '\0' && *s != '\r' && *s != '\n')
247                 ++s;
248
249         /* end of header found */
250         if (*s != '\0') {
251                 *s = '\0';
252                 return hdrval;
253         }
254
255         /* Rats!  The buffer isn't big enough to hold the entire header value. */
256         while (c = getc(fp), c != EOF && c != '\n')
257                 ;
258         *istrunc = 1;
259         return hdrval;
260 }
261
262 /*
263 Local Variables:
264 c-file-style: "linux"
265 c-basic-offset: 4
266 tab-width: 4
267 End:
268 */