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