b65a9fdd7ffe9670eef56071f65b750ff93c1a33
[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 static char **urls;
51 static int n_urls;
52
53 static void request_done(struct uclient *cl);
54
55 static int open_output_file(const char *path, bool create)
56 {
57         char *filename;
58         int flags = O_WRONLY;
59         int ret;
60
61         if (create)
62                 flags |= O_CREAT | O_EXCL;
63
64         if (output_file) {
65                 if (!strcmp(output_file, "-"))
66                         return STDOUT_FILENO;
67
68                 if (!quiet)
69                         fprintf(stderr, "Writing to stdout\n");
70
71                 unlink(output_file);
72                 return open(output_file, flags, 0644);
73         }
74
75         filename = uclient_get_url_filename(path, "index.html");
76         if (!quiet)
77                 fprintf(stderr, "Writing to '%s'\n", filename);
78         ret = open(filename, flags, 0644);
79         free(filename);
80
81         return ret;
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:%d\n", addr, port);
146 }
147
148 static int init_request(struct uclient *cl)
149 {
150         int rc;
151
152         out_bytes = 0;
153         uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
154
155         rc = uclient_connect(cl);
156         if (rc)
157                 return rc;
158
159         msg_connecting(cl);
160
161         rc = uclient_http_set_request_type(cl, "GET");
162         if (rc)
163                 return rc;
164
165         rc = uclient_request(cl);
166         if (rc)
167                 return rc;
168
169         return 0;
170 }
171
172 static void request_done(struct uclient *cl)
173 {
174         if (n_urls) {
175                 uclient_set_url(cl, *urls, auth_str);
176                 n_urls--;
177                 error_ret = init_request(cl);
178                 if (error_ret == 0)
179                         return;
180         }
181
182         if (output_fd >= 0 && !output_file) {
183                 close(output_fd);
184                 output_fd = -1;
185         }
186         uclient_disconnect(cl);
187         uloop_end();
188 }
189
190
191 static void eof_cb(struct uclient *cl)
192 {
193         if (!cl->data_eof) {
194                 if (!quiet)
195                         fprintf(stderr, "Connection reset prematurely\n");
196                 error_ret = 4;
197         } else if (!quiet) {
198                 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
199         }
200         request_done(cl);
201 }
202
203 static void handle_uclient_error(struct uclient *cl, int code)
204 {
205         const char *type = "Unknown error";
206         bool ignore = false;
207
208         switch(code) {
209         case UCLIENT_ERROR_CONNECT:
210                 type = "Connection failed";
211                 error_ret = 4;
212                 break;
213         case UCLIENT_ERROR_TIMEDOUT:
214                 type = "Connection timed out";
215                 error_ret = 4;
216                 break;
217         case UCLIENT_ERROR_SSL_INVALID_CERT:
218                 type = "Invalid SSL certificate";
219                 ignore = !verify;
220                 error_ret = 5;
221                 break;
222         case UCLIENT_ERROR_SSL_CN_MISMATCH:
223                 type = "Server hostname does not match SSL certificate";
224                 ignore = !verify;
225                 error_ret = 5;
226                 break;
227         default:
228                 error_ret = 1;
229                 break;
230         }
231
232         if (!quiet)
233                 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
234
235         if (ignore)
236                 error_ret = 0;
237         else
238                 request_done(cl);
239 }
240
241 static const struct uclient_cb cb = {
242         .header_done = header_done_cb,
243         .data_read = read_data_cb,
244         .data_eof = eof_cb,
245         .error = handle_uclient_error,
246 };
247
248 static int usage(const char *progname)
249 {
250         fprintf(stderr,
251                 "Usage: %s [options] <URL>\n"
252                 "Options:\n"
253                 "       -q:                             Turn off status messages\n"
254                 "       -O <file>:                      Redirect output to file (use \"-\" for stdout)\n"
255                 "       --user=<user>                   HTTP authentication username\n"
256                 "       --password=<password>           HTTP authentication password\n"
257                 "\n"
258                 "HTTPS options:\n"
259                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
260                 "       --no-check-certificate:         don't validate the server's certificate\n"
261                 "\n", progname);
262         return 1;
263 }
264
265 static void init_ca_cert(void)
266 {
267         glob_t gl;
268         int i;
269
270         glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
271         for (i = 0; i < gl.gl_pathc; i++)
272                 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
273 }
274
275 static void init_ustream_ssl(void)
276 {
277         void *dlh;
278
279         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
280         if (!dlh)
281                 return;
282
283         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
284         if (!ssl_ops)
285                 return;
286
287         ssl_ctx = ssl_ops->context_new(false);
288 }
289
290 static int no_ssl(const char *progname)
291 {
292         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
293         return 1;
294 }
295
296 enum {
297         L_NO_CHECK_CERTIFICATE,
298         L_CA_CERTIFICATE,
299         L_USER,
300         L_PASSWORD,
301 };
302
303 static const struct option longopts[] = {
304         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
305         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
306         [L_USER] = { "user", required_argument },
307         [L_PASSWORD] = { "password", required_argument },
308         {}
309 };
310
311
312
313 int main(int argc, char **argv)
314 {
315         const char *progname = argv[0];
316         struct uclient *cl;
317         int longopt_idx = 0;
318         bool has_cert = false;
319         int i, ch;
320         int rc;
321
322         init_ustream_ssl();
323
324         while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
325                 switch(ch) {
326                 case 0:
327                         switch (longopt_idx) {
328                         case L_NO_CHECK_CERTIFICATE:
329                                 verify = false;
330                                 break;
331                         case L_CA_CERTIFICATE:
332                                 has_cert = true;
333                                 if (ssl_ctx)
334                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
335                                 break;
336                         case L_USER:
337                                 if (!strlen(optarg))
338                                         break;
339                                 username = strdup(optarg);
340                                 memset(optarg, '*', strlen(optarg));
341                                 break;
342                         case L_PASSWORD:
343                                 if (!strlen(optarg))
344                                         break;
345                                 password = strdup(optarg);
346                                 memset(optarg, '*', strlen(optarg));
347                                 break;
348                         default:
349                                 return usage(progname);
350                         }
351                         break;
352                 case 'O':
353                         output_file = optarg;
354                         break;
355                 case 'q':
356                         quiet = true;
357                         break;
358                 default:
359                         return usage(progname);
360                 }
361         }
362
363         argv += optind;
364         argc -= optind;
365
366         if (verify && !has_cert)
367                 default_certs = true;
368
369         if (argc < 1)
370                 return usage(progname);
371
372         if (!ssl_ctx) {
373                 for (i = 0; i < argc; i++) {
374                         if (!strncmp(argv[i], "https", 5))
375                                 return no_ssl(progname);
376                 }
377         }
378
379         urls = argv + 1;
380         n_urls = argc - 1;
381
382         uloop_init();
383
384         if (username) {
385                 if (password)
386                         asprintf(&auth_str, "%s:%s", username, password);
387                 else
388                         auth_str = username;
389         }
390
391         if (!quiet)
392                 fprintf(stderr, "Downloading '%s'\n", argv[0]);
393
394         cl = uclient_new(argv[0], auth_str, &cb);
395         if (!cl) {
396                 fprintf(stderr, "Failed to allocate uclient context\n");
397                 return 1;
398         }
399
400         if (ssl_ctx)
401                 init_ca_cert();
402
403         rc = init_request(cl);
404         if (!rc) {
405                 /* no error received, we can enter main loop */
406                 uloop_run();
407         } else {
408                 fprintf(stderr, "Failed to establish connection\n");
409                 error_ret = 4;
410         }
411
412         uloop_done();
413
414         uclient_free(cl);
415
416         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
417                 close(output_fd);
418
419         if (ssl_ctx)
420                 ssl_ops->context_free(ssl_ctx);
421
422         return error_ret;
423 }