7418f823122653d2295814cf03df8a754c20f5f6
[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 const char *user_agent = "uclient-fetch";
39 static const char *post_data;
40 static struct ustream_ssl_ctx *ssl_ctx;
41 static const struct ustream_ssl_ops *ssl_ops;
42 static int quiet = false;
43 static bool verify = true;
44 static bool default_certs = false;
45 static bool no_output;
46 static const char *output_file;
47 static int output_fd = -1;
48 static int error_ret;
49 static int out_bytes;
50 static char *username;
51 static char *password;
52 static char *auth_str;
53 static char **urls;
54 static int n_urls;
55 static int timeout;
56
57 static void request_done(struct uclient *cl);
58
59 static int open_output_file(const char *path, bool create)
60 {
61         char *filename;
62         int flags = O_WRONLY;
63         int ret;
64
65         if (create)
66                 flags |= O_CREAT | O_EXCL;
67
68         if (output_file) {
69                 if (!strcmp(output_file, "-"))
70                         return STDOUT_FILENO;
71
72                 if (!quiet)
73                         fprintf(stderr, "Writing to stdout\n");
74
75                 unlink(output_file);
76                 return open(output_file, flags, 0644);
77         }
78
79         filename = uclient_get_url_filename(path, "index.html");
80         if (!quiet)
81                 fprintf(stderr, "Writing to '%s'\n", filename);
82         ret = open(filename, flags, 0644);
83         free(filename);
84
85         return ret;
86 }
87
88 static void header_done_cb(struct uclient *cl)
89 {
90         static int retries;
91
92         if (retries < 10 && uclient_http_redirect(cl)) {
93                 if (!quiet)
94                         fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
95
96                 retries++;
97                 return;
98         }
99
100         retries = 0;
101         switch (cl->status_code) {
102         case 204:
103         case 200:
104                 if (no_output)
105                         break;
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 (!no_output && 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                 if (!no_output)
139                         write(output_fd, buf, len);
140         }
141 }
142
143 static void msg_connecting(struct uclient *cl)
144 {
145         char addr[INET6_ADDRSTRLEN];
146         int port;
147
148         if (quiet)
149                 return;
150
151         uclient_get_addr(addr, &port, &cl->remote_addr);
152         fprintf(stderr, "Connecting to %s:%d\n", addr, port);
153 }
154
155 static int init_request(struct uclient *cl)
156 {
157         int rc;
158
159         out_bytes = 0;
160         uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
161
162         if (timeout)
163                 cl->timeout_msecs = timeout * 1000;
164
165         rc = uclient_connect(cl);
166         if (rc)
167                 return rc;
168
169         msg_connecting(cl);
170
171         rc = uclient_http_set_request_type(cl, post_data ? "POST" : "GET");
172         if (rc)
173                 return rc;
174
175         uclient_http_reset_headers(cl);
176         uclient_http_set_header(cl, "User-Agent", user_agent);
177
178         if (post_data) {
179                 uclient_http_set_header(cl, "Content-Type", "application/x-www-form-urlencoded");
180                 uclient_write(cl, post_data, strlen(post_data));
181         }
182
183         rc = uclient_request(cl);
184         if (rc)
185                 return rc;
186
187         return 0;
188 }
189
190 static void request_done(struct uclient *cl)
191 {
192         if (n_urls) {
193                 uclient_set_url(cl, *urls, auth_str);
194                 n_urls--;
195                 error_ret = init_request(cl);
196                 if (error_ret == 0)
197                         return;
198         }
199
200         if (output_fd >= 0 && !output_file) {
201                 close(output_fd);
202                 output_fd = -1;
203         }
204         uclient_disconnect(cl);
205         uloop_end();
206 }
207
208
209 static void eof_cb(struct uclient *cl)
210 {
211         if (!cl->data_eof) {
212                 if (!quiet)
213                         fprintf(stderr, "Connection reset prematurely\n");
214                 error_ret = 4;
215         } else if (!quiet) {
216                 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
217         }
218         request_done(cl);
219 }
220
221 static void handle_uclient_error(struct uclient *cl, int code)
222 {
223         const char *type = "Unknown error";
224         bool ignore = false;
225
226         switch(code) {
227         case UCLIENT_ERROR_CONNECT:
228                 type = "Connection failed";
229                 error_ret = 4;
230                 break;
231         case UCLIENT_ERROR_TIMEDOUT:
232                 type = "Connection timed out";
233                 error_ret = 4;
234                 break;
235         case UCLIENT_ERROR_SSL_INVALID_CERT:
236                 type = "Invalid SSL certificate";
237                 ignore = !verify;
238                 error_ret = 5;
239                 break;
240         case UCLIENT_ERROR_SSL_CN_MISMATCH:
241                 type = "Server hostname does not match SSL certificate";
242                 ignore = !verify;
243                 error_ret = 5;
244                 break;
245         default:
246                 error_ret = 1;
247                 break;
248         }
249
250         if (!quiet)
251                 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
252
253         if (ignore)
254                 error_ret = 0;
255         else
256                 request_done(cl);
257 }
258
259 static const struct uclient_cb cb = {
260         .header_done = header_done_cb,
261         .data_read = read_data_cb,
262         .data_eof = eof_cb,
263         .error = handle_uclient_error,
264 };
265
266 static int usage(const char *progname)
267 {
268         fprintf(stderr,
269                 "Usage: %s [options] <URL>\n"
270                 "Options:\n"
271                 "       -q:                             Turn off status messages\n"
272                 "       -O <file>:                      Redirect output to file (use \"-\" for stdout)\n"
273                 "       --user=<user>                   HTTP authentication username\n"
274                 "       --password=<password>           HTTP authentication password\n"
275                 "       --user-agent|-U <str>           Set HTTP user agent\n"
276                 "       --post-data=STRING              use the POST method; send STRING as the data\n"
277                 "       --spider|-s                     Spider mode - only check file existence\n"
278                 "       --timeout=N|-T N                Set connect/request timeout to N seconds\n"
279                 "\n"
280                 "HTTPS options:\n"
281                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
282                 "       --no-check-certificate:         don't validate the server's certificate\n"
283                 "\n", progname);
284         return 1;
285 }
286
287 static void init_ca_cert(void)
288 {
289         glob_t gl;
290         int i;
291
292         glob("/etc/ssl/certs/*.crt", 0, NULL, &gl);
293         for (i = 0; i < gl.gl_pathc; i++)
294                 ssl_ops->context_add_ca_crt_file(ssl_ctx, gl.gl_pathv[i]);
295 }
296
297 static void init_ustream_ssl(void)
298 {
299         void *dlh;
300
301         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
302         if (!dlh)
303                 return;
304
305         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
306         if (!ssl_ops)
307                 return;
308
309         ssl_ctx = ssl_ops->context_new(false);
310 }
311
312 static int no_ssl(const char *progname)
313 {
314         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
315         return 1;
316 }
317
318 enum {
319         L_NO_CHECK_CERTIFICATE,
320         L_CA_CERTIFICATE,
321         L_USER,
322         L_PASSWORD,
323         L_USER_AGENT,
324         L_POST_DATA,
325         L_SPIDER,
326         L_TIMEOUT,
327 };
328
329 static const struct option longopts[] = {
330         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
331         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
332         [L_USER] = { "user", required_argument },
333         [L_PASSWORD] = { "password", required_argument },
334         [L_USER_AGENT] = { "user-agent", required_argument },
335         [L_POST_DATA] = { "post-data", required_argument },
336         [L_SPIDER] = { "spider", no_argument },
337         [L_TIMEOUT] = { "timeout", required_argument },
338         {}
339 };
340
341
342
343 int main(int argc, char **argv)
344 {
345         const char *progname = argv[0];
346         struct uclient *cl;
347         int longopt_idx = 0;
348         bool has_cert = false;
349         int i, ch;
350         int rc;
351
352         init_ustream_ssl();
353
354         while ((ch = getopt_long(argc, argv, "O:qsU:", longopts, &longopt_idx)) != -1) {
355                 switch(ch) {
356                 case 0:
357                         switch (longopt_idx) {
358                         case L_NO_CHECK_CERTIFICATE:
359                                 verify = false;
360                                 break;
361                         case L_CA_CERTIFICATE:
362                                 has_cert = true;
363                                 if (ssl_ctx)
364                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
365                                 break;
366                         case L_USER:
367                                 if (!strlen(optarg))
368                                         break;
369                                 username = strdup(optarg);
370                                 memset(optarg, '*', strlen(optarg));
371                                 break;
372                         case L_PASSWORD:
373                                 if (!strlen(optarg))
374                                         break;
375                                 password = strdup(optarg);
376                                 memset(optarg, '*', strlen(optarg));
377                                 break;
378                         case L_USER_AGENT:
379                                 user_agent = optarg;
380                                 break;
381                         case L_POST_DATA:
382                                 post_data = optarg;
383                                 break;
384                         case L_SPIDER:
385                                 no_output = true;
386                                 break;
387                         case L_TIMEOUT:
388                                 timeout = atoi(optarg);
389                                 break;
390                         default:
391                                 return usage(progname);
392                         }
393                         break;
394                 case 'U':
395                         user_agent = optarg;
396                         break;
397                 case 'O':
398                         output_file = optarg;
399                         break;
400                 case 'q':
401                         quiet = true;
402                         break;
403                 case 's':
404                         no_output = true;
405                         break;
406                 case 'T':
407                         timeout = atoi(optarg);
408                         break;
409                 default:
410                         return usage(progname);
411                 }
412         }
413
414         argv += optind;
415         argc -= optind;
416
417         if (verify && !has_cert)
418                 default_certs = true;
419
420         if (argc < 1)
421                 return usage(progname);
422
423         if (!ssl_ctx) {
424                 for (i = 0; i < argc; i++) {
425                         if (!strncmp(argv[i], "https", 5))
426                                 return no_ssl(progname);
427                 }
428         }
429
430         urls = argv + 1;
431         n_urls = argc - 1;
432
433         uloop_init();
434
435         if (username) {
436                 if (password)
437                         asprintf(&auth_str, "%s:%s", username, password);
438                 else
439                         auth_str = username;
440         }
441
442         if (!quiet)
443                 fprintf(stderr, "Downloading '%s'\n", argv[0]);
444
445         cl = uclient_new(argv[0], auth_str, &cb);
446         if (!cl) {
447                 fprintf(stderr, "Failed to allocate uclient context\n");
448                 return 1;
449         }
450
451         if (ssl_ctx && default_certs)
452                 init_ca_cert();
453
454         rc = init_request(cl);
455         if (!rc) {
456                 /* no error received, we can enter main loop */
457                 uloop_run();
458         } else {
459                 fprintf(stderr, "Failed to establish connection\n");
460                 error_ret = 4;
461         }
462
463         uloop_done();
464
465         uclient_free(cl);
466
467         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
468                 close(output_fd);
469
470         if (ssl_ctx)
471                 ssl_ops->context_free(ssl_ctx);
472
473         return error_ret;
474 }