uclient-fetch: load CA certificates
[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 #define _GNU_SOURCE
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <dlfcn.h>
23 #include <getopt.h>
24 #include <fcntl.h>
25 #include <glob.h>
26
27 #include <libubox/blobmsg.h>
28
29 #include "uclient.h"
30 #include "uclient-utils.h"
31
32 #ifdef __APPLE__
33 #define LIB_EXT "dylib"
34 #else
35 #define LIB_EXT "so"
36 #endif
37
38 static struct ustream_ssl_ctx *ssl_ctx;
39 static const struct ustream_ssl_ops *ssl_ops;
40 static int quiet = false;
41 static bool verify = true;
42 static bool default_certs = false;
43 static const char *output_file;
44 static int output_fd = -1;
45 static int error_ret;
46 static int out_bytes;
47 static char *username;
48 static char *password;
49 static char *auth_str;
50
51 static int open_output_file(const char *path, bool create)
52 {
53         char *filename;
54         int flags = O_WRONLY;
55         int ret;
56
57         if (create)
58                 flags |= O_CREAT | O_EXCL;
59
60         if (output_file) {
61                 if (!strcmp(output_file, "-"))
62                         return STDOUT_FILENO;
63
64                 if (!quiet)
65                         fprintf(stderr, "Writing to stdout\n");
66
67                 unlink(output_file);
68                 return open(output_file, flags, 0644);
69         }
70
71         filename = uclient_get_url_filename(path, "index.html");
72         if (!quiet)
73                 fprintf(stderr, "Writing to '%s'\n", filename);
74         ret = open(filename, flags, 0644);
75         free(filename);
76
77         return ret;
78 }
79
80 static void request_done(struct uclient *cl)
81 {
82         if (output_fd >= 0 && !output_file) {
83                 close(output_fd);
84                 output_fd = -1;
85         }
86         uclient_disconnect(cl);
87         uloop_end();
88 }
89
90 static void header_done_cb(struct uclient *cl)
91 {
92         static int retries;
93
94         if (retries < 10 && uclient_http_redirect(cl)) {
95                 if (!quiet)
96                         fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
97
98                 retries++;
99                 return;
100         }
101
102         retries = 0;
103         switch (cl->status_code) {
104         case 204:
105         case 200:
106                 output_fd = open_output_file(cl->url->location, true);
107                 if (output_fd < 0) {
108                         if (!quiet)
109                                 perror("Cannot open output file");
110                         error_ret = 3;
111                         request_done(cl);
112                 }
113                 break;
114
115         default:
116                 if (!quiet)
117                         fprintf(stderr, "HTTP error %d\n", cl->status_code);
118                 request_done(cl);
119                 error_ret = 8;
120                 break;
121         }
122 }
123
124 static void read_data_cb(struct uclient *cl)
125 {
126         char buf[256];
127         int len;
128
129         if (output_fd < 0)
130                 return;
131
132         while (1) {
133                 len = uclient_read(cl, buf, sizeof(buf));
134                 if (!len)
135                         return;
136
137                 out_bytes += len;
138                 write(output_fd, buf, len);
139         }
140 }
141
142 static void msg_connecting(struct uclient *cl)
143 {
144         char addr[INET6_ADDRSTRLEN];
145         int port;
146
147         if (quiet)
148                 return;
149
150         uclient_get_addr(addr, &port, &cl->remote_addr);
151         fprintf(stderr, "Connecting to %s:%d\n", addr, port);
152 }
153
154 static int init_request(struct uclient *cl)
155 {
156         int rc;
157
158         out_bytes = 0;
159
160         rc = uclient_connect(cl);
161         if (rc)
162                 return rc;
163
164         msg_connecting(cl);
165
166         rc = uclient_http_set_request_type(cl, "GET");
167         if (rc)
168                 return rc;
169
170         rc = uclient_request(cl);
171         if (rc)
172                 return rc;
173
174         return 0;
175 }
176
177 static void eof_cb(struct uclient *cl)
178 {
179         if (!cl->data_eof) {
180                 if (!quiet)
181                         fprintf(stderr, "Connection reset prematurely\n");
182                 error_ret = 4;
183         } else if (!quiet) {
184                 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
185         }
186         request_done(cl);
187 }
188
189 static void handle_uclient_error(struct uclient *cl, int code)
190 {
191         const char *type = "Unknown error";
192         bool ignore = false;
193
194         switch(code) {
195         case UCLIENT_ERROR_CONNECT:
196                 type = "Connection failed";
197                 error_ret = 4;
198                 break;
199         case UCLIENT_ERROR_TIMEDOUT:
200                 type = "Connection timed out";
201                 error_ret = 4;
202                 break;
203         case UCLIENT_ERROR_SSL_INVALID_CERT:
204                 type = "Invalid SSL certificate";
205                 ignore = !verify;
206                 error_ret = 5;
207                 break;
208         case UCLIENT_ERROR_SSL_CN_MISMATCH:
209                 type = "Server hostname does not match SSL certificate";
210                 ignore = !verify;
211                 error_ret = 5;
212                 break;
213         default:
214                 error_ret = 1;
215                 break;
216         }
217
218         if (!quiet)
219                 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
220
221         if (ignore)
222                 error_ret = 0;
223         else
224                 request_done(cl);
225 }
226
227 static const struct uclient_cb cb = {
228         .header_done = header_done_cb,
229         .data_read = read_data_cb,
230         .data_eof = eof_cb,
231         .error = handle_uclient_error,
232 };
233
234 static int usage(const char *progname)
235 {
236         fprintf(stderr,
237                 "Usage: %s [options] <URL>\n"
238                 "Options:\n"
239                 "       -q:                             Turn off status messages\n"
240                 "       -O <file>:                      Redirect output to file (use \"-\" for stdout)\n"
241                 "\n"
242                 "HTTPS options:\n"
243                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
244                 "       --no-check-certificate:         don't validate the server's certificate\n"
245                 "\n", progname);
246         return 1;
247 }
248
249 static void init_ca_cert(void)
250 {
251         glob_t gl;
252         int i;
253
254         glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
255         for (i = 0; i < gl.gl_pathc; i++)
256                 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
257 }
258
259 static void init_ustream_ssl(void)
260 {
261         void *dlh;
262
263         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
264         if (!dlh)
265                 return;
266
267         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
268         if (!ssl_ops)
269                 return;
270
271         ssl_ctx = ssl_ops->context_new(false);
272 }
273
274 static int no_ssl(const char *progname)
275 {
276         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
277         return 1;
278 }
279
280 enum {
281         L_NO_CHECK_CERTIFICATE,
282         L_CA_CERTIFICATE,
283         L_USER,
284         L_PASSWORD,
285 };
286
287 static const struct option longopts[] = {
288         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
289         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
290         [L_USER] = { "user", required_argument },
291         [L_PASSWORD] = { "password", required_argument },
292         {}
293 };
294
295 int main(int argc, char **argv)
296 {
297         const char *progname = argv[0];
298         struct uclient *cl;
299         int ch;
300         int longopt_idx = 0;
301         bool has_cert = false;
302         int rc;
303
304         init_ustream_ssl();
305
306         while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
307                 switch(ch) {
308                 case 0:
309                         switch (longopt_idx) {
310                         case L_NO_CHECK_CERTIFICATE:
311                                 verify = false;
312                                 break;
313                         case L_CA_CERTIFICATE:
314                                 has_cert = true;
315                                 if (ssl_ctx)
316                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
317                                 break;
318                         case L_USER:
319                                 if (!strlen(optarg))
320                                         break;
321                                 username = strdup(optarg);
322                                 memset(optarg, '*', strlen(optarg));
323                                 break;
324                         case L_PASSWORD:
325                                 if (!strlen(optarg))
326                                         break;
327                                 password = strdup(optarg);
328                                 memset(optarg, '*', strlen(optarg));
329                                 break;
330                         default:
331                                 return usage(progname);
332                         }
333                         break;
334                 case 'O':
335                         output_file = optarg;
336                         break;
337                 case 'q':
338                         quiet = true;
339                         break;
340                 default:
341                         return usage(progname);
342                 }
343         }
344
345         argv += optind;
346         argc -= optind;
347
348         if (verify && !has_cert)
349                 default_certs = true;
350
351         if (argc != 1)
352                 return usage(progname);
353
354         if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
355                 return no_ssl(progname);
356
357         uloop_init();
358
359         if (username) {
360                 if (password)
361                         asprintf(&auth_str, "%s:%s", username, password);
362                 else
363                         auth_str = username;
364         }
365
366         if (!quiet)
367                 fprintf(stderr, "Downloading '%s'\n", argv[0]);
368
369         cl = uclient_new(argv[0], auth_str, &cb);
370         if (!cl) {
371                 fprintf(stderr, "Failed to allocate uclient context\n");
372                 return 1;
373         }
374
375         if (ssl_ctx) {
376                 init_ca_cert();
377                 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
378         }
379
380         rc = init_request(cl);
381         if (!rc) {
382                 /* no error received, we can enter main loop */
383                 uloop_run();
384         } else {
385                 fprintf(stderr, "Failed to establish connection\n");
386                 error_ret = 4;
387         }
388
389         uloop_done();
390
391         uclient_free(cl);
392
393         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
394                 close(output_fd);
395
396         if (ssl_ctx)
397                 ssl_ops->context_free(ssl_ctx);
398
399         return error_ret;
400 }