965f62142e1f9551fb1510692bc71563211783c5
[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                 "       --user=<user>                   HTTP authentication username\n"
242                 "       --password=<password>           HTTP authentication password\n"
243                 "\n"
244                 "HTTPS options:\n"
245                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
246                 "       --no-check-certificate:         don't validate the server's certificate\n"
247                 "\n", progname);
248         return 1;
249 }
250
251 static void init_ca_cert(void)
252 {
253         glob_t gl;
254         int i;
255
256         glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
257         for (i = 0; i < gl.gl_pathc; i++)
258                 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
259 }
260
261 static void init_ustream_ssl(void)
262 {
263         void *dlh;
264
265         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
266         if (!dlh)
267                 return;
268
269         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
270         if (!ssl_ops)
271                 return;
272
273         ssl_ctx = ssl_ops->context_new(false);
274 }
275
276 static int no_ssl(const char *progname)
277 {
278         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
279         return 1;
280 }
281
282 enum {
283         L_NO_CHECK_CERTIFICATE,
284         L_CA_CERTIFICATE,
285         L_USER,
286         L_PASSWORD,
287 };
288
289 static const struct option longopts[] = {
290         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
291         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
292         [L_USER] = { "user", required_argument },
293         [L_PASSWORD] = { "password", required_argument },
294         {}
295 };
296
297 int main(int argc, char **argv)
298 {
299         const char *progname = argv[0];
300         struct uclient *cl;
301         int ch;
302         int longopt_idx = 0;
303         bool has_cert = false;
304         int rc;
305
306         init_ustream_ssl();
307
308         while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
309                 switch(ch) {
310                 case 0:
311                         switch (longopt_idx) {
312                         case L_NO_CHECK_CERTIFICATE:
313                                 verify = false;
314                                 break;
315                         case L_CA_CERTIFICATE:
316                                 has_cert = true;
317                                 if (ssl_ctx)
318                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
319                                 break;
320                         case L_USER:
321                                 if (!strlen(optarg))
322                                         break;
323                                 username = strdup(optarg);
324                                 memset(optarg, '*', strlen(optarg));
325                                 break;
326                         case L_PASSWORD:
327                                 if (!strlen(optarg))
328                                         break;
329                                 password = strdup(optarg);
330                                 memset(optarg, '*', strlen(optarg));
331                                 break;
332                         default:
333                                 return usage(progname);
334                         }
335                         break;
336                 case 'O':
337                         output_file = optarg;
338                         break;
339                 case 'q':
340                         quiet = true;
341                         break;
342                 default:
343                         return usage(progname);
344                 }
345         }
346
347         argv += optind;
348         argc -= optind;
349
350         if (verify && !has_cert)
351                 default_certs = true;
352
353         if (argc != 1)
354                 return usage(progname);
355
356         if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
357                 return no_ssl(progname);
358
359         uloop_init();
360
361         if (username) {
362                 if (password)
363                         asprintf(&auth_str, "%s:%s", username, password);
364                 else
365                         auth_str = username;
366         }
367
368         if (!quiet)
369                 fprintf(stderr, "Downloading '%s'\n", argv[0]);
370
371         cl = uclient_new(argv[0], auth_str, &cb);
372         if (!cl) {
373                 fprintf(stderr, "Failed to allocate uclient context\n");
374                 return 1;
375         }
376
377         if (ssl_ctx) {
378                 init_ca_cert();
379                 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
380         }
381
382         rc = init_request(cl);
383         if (!rc) {
384                 /* no error received, we can enter main loop */
385                 uloop_run();
386         } else {
387                 fprintf(stderr, "Failed to establish connection\n");
388                 error_ret = 4;
389         }
390
391         uloop_done();
392
393         uclient_free(cl);
394
395         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
396                 close(output_fd);
397
398         if (ssl_ctx)
399                 ssl_ops->context_free(ssl_ctx);
400
401         return error_ret;
402 }