164492128319a7f8e966aa979f29707be56a7809
[project/uclient.git] / uclient-fetch.c
1 /*
2  * uclient - ustream based protocol client library
3  *
4  * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <dlfcn.h>
22 #include <getopt.h>
23 #include <fcntl.h>
24
25 #include <libubox/blobmsg.h>
26
27 #include "uclient.h"
28 #include "uclient-utils.h"
29
30 #ifdef __APPLE__
31 #define LIB_EXT "dylib"
32 #else
33 #define LIB_EXT "so"
34 #endif
35
36 static struct ustream_ssl_ctx *ssl_ctx;
37 static const struct ustream_ssl_ops *ssl_ops;
38 static int quiet = false;
39 static bool verify = true;
40 static const char *output_file;
41 static int output_fd = -1;
42 static int error_ret;
43 static int out_bytes;
44
45 static int open_output_file(const char *path, bool create)
46 {
47         char *filename;
48         int flags = O_WRONLY;
49         int ret;
50
51         if (create)
52                 flags |= O_CREAT | O_EXCL;
53
54         if (output_file) {
55                 if (!strcmp(output_file, "-"))
56                         return STDOUT_FILENO;
57
58                 if (!quiet)
59                         fprintf(stderr, "Writing to stdout\n");
60
61                 unlink(output_file);
62                 return open(output_file, flags, 0644);
63         }
64
65         filename = uclient_get_url_filename(path, "index.html");
66         if (!quiet)
67                 fprintf(stderr, "Writing to '%s'\n", filename);
68         ret = open(filename, flags, 0644);
69         free(filename);
70
71         return ret;
72 }
73
74 static void request_done(struct uclient *cl)
75 {
76         if (output_fd >= 0 && !output_file) {
77                 close(output_fd);
78                 output_fd = -1;
79         }
80         uclient_disconnect(cl);
81         uloop_end();
82 }
83
84 static void header_done_cb(struct uclient *cl)
85 {
86         static int retries;
87
88         if (retries < 10 && uclient_http_redirect(cl)) {
89                 if (!quiet)
90                         fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
91
92                 retries++;
93                 return;
94         }
95
96         retries = 0;
97         switch (cl->status_code) {
98         case 204:
99         case 200:
100                 output_fd = open_output_file(cl->url->location, true);
101                 if (output_fd < 0) {
102                         if (!quiet)
103                                 perror("Cannot open output file");
104                         error_ret = 3;
105                         request_done(cl);
106                 }
107                 break;
108
109         default:
110                 if (!quiet)
111                         fprintf(stderr, "HTTP error %d\n", cl->status_code);
112                 request_done(cl);
113                 error_ret = 8;
114                 break;
115         }
116 }
117
118 static void read_data_cb(struct uclient *cl)
119 {
120         char buf[256];
121         int len;
122
123         if (output_fd < 0)
124                 return;
125
126         while (1) {
127                 len = uclient_read(cl, buf, sizeof(buf));
128                 if (!len)
129                         return;
130
131                 out_bytes += len;
132                 write(output_fd, buf, len);
133         }
134 }
135
136 static void msg_connecting(struct uclient *cl)
137 {
138         char addr[INET6_ADDRSTRLEN];
139         int port;
140
141         if (quiet)
142                 return;
143
144         uclient_get_addr(addr, &port, &cl->remote_addr);
145         fprintf(stderr, "Connecting to %s %s:%d\n", cl->url->host, addr, port);
146 }
147
148 static void init_request(struct uclient *cl)
149 {
150         out_bytes = 0;
151         uclient_connect(cl);
152         msg_connecting(cl);
153         uclient_http_set_request_type(cl, "GET");
154         uclient_request(cl);
155 }
156
157 static void eof_cb(struct uclient *cl)
158 {
159         if (!cl->data_eof) {
160                 if (!quiet)
161                         fprintf(stderr, "Connection reset prematurely\n");
162                 error_ret = 4;
163         } else if (!quiet) {
164                 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
165         }
166         request_done(cl);
167 }
168
169 static void handle_uclient_error(struct uclient *cl, int code)
170 {
171         const char *type = "Unknown error";
172         bool ignore = false;
173
174         switch(code) {
175         case UCLIENT_ERROR_CONNECT:
176                 type = "Connection failed";
177                 error_ret = 4;
178                 break;
179         case UCLIENT_ERROR_SSL_INVALID_CERT:
180                 type = "Invalid SSL certificate";
181                 ignore = !verify;
182                 error_ret = 5;
183                 break;
184         case UCLIENT_ERROR_SSL_CN_MISMATCH:
185                 type = "Server hostname does not match SSL certificate";
186                 ignore = !verify;
187                 error_ret = 5;
188                 break;
189         default:
190                 error_ret = 1;
191                 break;
192         }
193
194         if (!quiet)
195                 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
196
197         if (ignore)
198                 error_ret = 0;
199         else
200                 request_done(cl);
201 }
202
203 static const struct uclient_cb cb = {
204         .header_done = header_done_cb,
205         .data_read = read_data_cb,
206         .data_eof = eof_cb,
207         .error = handle_uclient_error,
208 };
209
210 static int usage(const char *progname)
211 {
212         fprintf(stderr,
213                 "Usage: %s [options] <URL>\n"
214                 "Options:\n"
215                 "       -q:                             Turn off status messages\n"
216                 "       -O <file>:                      Redirect output to file (use \"-\" for stdout)\n"
217                 "\n"
218                 "HTTPS options:\n"
219                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
220                 "       --no-check-certificate:         don't validate the server's certificate\n"
221                 "\n", progname);
222         return 1;
223 }
224
225
226 static void init_ustream_ssl(void)
227 {
228         void *dlh;
229
230         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
231         if (!dlh)
232                 return;
233
234         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
235         if (!ssl_ops)
236                 return;
237
238         ssl_ctx = ssl_ops->context_new(false);
239 }
240
241 static int no_ssl(const char *progname)
242 {
243         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
244         return 1;
245 }
246
247 enum {
248         L_NO_CHECK_CERTIFICATE,
249         L_CA_CERTIFICATE,
250 };
251
252 static const struct option longopts[] = {
253         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
254         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
255         {}
256 };
257
258 int main(int argc, char **argv)
259 {
260         const char *progname = argv[0];
261         struct uclient *cl;
262         int ch;
263         int longopt_idx = 0;
264
265         init_ustream_ssl();
266
267         while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
268                 switch(ch) {
269                 case 0:
270                         switch (longopt_idx) {
271                         case L_NO_CHECK_CERTIFICATE:
272                                 verify = false;
273                                 break;
274                         case L_CA_CERTIFICATE:
275                                 if (ssl_ctx)
276                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
277                                 break;
278                         default:
279                                 return usage(progname);
280                         }
281                         break;
282                 case 'O':
283                         output_file = optarg;
284                         break;
285                 case 'q':
286                         quiet = true;
287                         break;
288                 default:
289                         return usage(progname);
290                 }
291         }
292
293         argv += optind;
294         argc -= optind;
295
296         if (argc != 1)
297                 return usage(progname);
298
299         if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
300                 return no_ssl(progname);
301
302         uloop_init();
303
304         cl = uclient_new(argv[0], NULL, &cb);
305         if (!cl) {
306                 fprintf(stderr, "Failed to allocate uclient context\n");
307                 return 1;
308         }
309
310         if (ssl_ctx)
311                 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
312
313         init_request(cl);
314         uloop_run();
315         uloop_done();
316
317         uclient_free(cl);
318
319         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
320                 close(output_fd);
321
322         if (ssl_ctx)
323                 ssl_ops->context_free(ssl_ctx);
324
325         return error_ret;
326 }