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