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