fetch: print download status
[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 #include <unistd.h>
20 #include <stdio.h>
21 #include <dlfcn.h>
22 #include <getopt.h>
23 #include <fcntl.h>
24
25 #include <libubox/blobmsg.h>
26
27 #include "uclient.h"
28 #include "uclient-utils.h"
29
30 #ifdef __APPLE__
31 #define LIB_EXT "dylib"
32 #else
33 #define LIB_EXT "so"
34 #endif
35
36 static struct ustream_ssl_ctx *ssl_ctx;
37 static const struct ustream_ssl_ops *ssl_ops;
38 static int quiet = false;
39 static bool verify = true;
40 static const char *output_file;
41 static int output_fd = -1;
42 static int error_ret;
43 static int out_bytes;
44
45 static int open_output_file(const char *path, bool create)
46 {
47         char *filename;
48         int flags = O_WRONLY;
49         int ret;
50
51         if (create)
52                 flags |= O_CREAT;
53
54         if (output_file) {
55                 if (!strcmp(output_file, "-"))
56                         return STDOUT_FILENO;
57
58                 if (!quiet)
59                         fprintf(stderr, "Writing to stdout\n");
60
61                 return open(output_file, flags, 0644);
62         }
63
64         /* Don't automatically overwrite files if the name is derived from the URL */
65         if (create)
66                 flags |= O_EXCL;
67
68         filename = uclient_get_url_filename(path, "index.html");
69         if (!quiet)
70                 fprintf(stderr, "Writing to '%s'\n", filename);
71         ret = open(filename, flags, 0644);
72         free(filename);
73
74         return ret;
75 }
76
77 static void request_done(struct uclient *cl)
78 {
79         if (output_fd >= 0 && !output_file) {
80                 close(output_fd);
81                 output_fd = -1;
82         }
83         uclient_disconnect(cl);
84         uloop_end();
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                 output_fd = open_output_file(cl->url->location, true);
104                 if (output_fd < 0) {
105                         if (!quiet)
106                                 perror("Cannot open output file");
107                         error_ret = 3;
108                         request_done(cl);
109                 }
110                 break;
111
112         default:
113                 if (!quiet)
114                         fprintf(stderr, "HTTP error %d\n", cl->status_code);
115                 request_done(cl);
116                 error_ret = 8;
117                 break;
118         }
119 }
120
121 static void read_data_cb(struct uclient *cl)
122 {
123         char buf[256];
124         int len;
125
126         if (output_fd < 0)
127                 return;
128
129         while (1) {
130                 len = uclient_read(cl, buf, sizeof(buf));
131                 if (!len)
132                         return;
133
134                 out_bytes += len;
135                 write(output_fd, buf, len);
136         }
137 }
138
139 static void msg_connecting(struct uclient *cl)
140 {
141         char addr[INET6_ADDRSTRLEN];
142         int port;
143
144         if (quiet)
145                 return;
146
147         uclient_get_addr(addr, &port, &cl->remote_addr);
148         fprintf(stderr, "Connecting to %s %s:%d\n", cl->url->host, addr, port);
149 }
150
151 static void init_request(struct uclient *cl)
152 {
153         out_bytes = 0;
154         uclient_connect(cl);
155         msg_connecting(cl);
156         uclient_http_set_request_type(cl, "GET");
157         uclient_request(cl);
158 }
159
160 static void eof_cb(struct uclient *cl)
161 {
162         if (!cl->data_eof) {
163                 if (!quiet)
164                         fprintf(stderr, "Connection reset prematurely\n");
165                 error_ret = 4;
166         } else if (!quiet) {
167                 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
168         }
169         request_done(cl);
170 }
171
172 static void handle_uclient_error(struct uclient *cl, int code)
173 {
174         const char *type = "Unknown error";
175         bool ignore = false;
176
177         switch(code) {
178         case UCLIENT_ERROR_CONNECT:
179                 type = "Connection failed";
180                 error_ret = 4;
181                 break;
182         case UCLIENT_ERROR_SSL_INVALID_CERT:
183                 type = "Invalid SSL certificate";
184                 ignore = !verify;
185                 error_ret = 5;
186                 break;
187         case UCLIENT_ERROR_SSL_CN_MISMATCH:
188                 type = "Server hostname does not match SSL certificate";
189                 ignore = !verify;
190                 error_ret = 5;
191                 break;
192         default:
193                 error_ret = 1;
194                 break;
195         }
196
197         if (!quiet)
198                 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
199
200         if (ignore)
201                 error_ret = 0;
202         else
203                 request_done(cl);
204 }
205
206 static const struct uclient_cb cb = {
207         .header_done = header_done_cb,
208         .data_read = read_data_cb,
209         .data_eof = eof_cb,
210         .error = handle_uclient_error,
211 };
212
213 static int usage(const char *progname)
214 {
215         fprintf(stderr,
216                 "Usage: %s [options] <URL>\n"
217                 "Options:\n"
218                 "       -q:                             Turn off status messages\n"
219                 "       -O <file>:                      Redirect output to file (use \"-\" for stdout)\n"
220                 "\n"
221                 "HTTPS options:\n"
222                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
223                 "       --no-check-certificate:         don't validate the server's certificate\n"
224                 "\n", progname);
225         return 1;
226 }
227
228
229 static void init_ustream_ssl(void)
230 {
231         void *dlh;
232
233         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
234         if (!dlh)
235                 return;
236
237         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
238         if (!ssl_ops)
239                 return;
240
241         ssl_ctx = ssl_ops->context_new(false);
242 }
243
244 static int no_ssl(const char *progname)
245 {
246         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
247         return 1;
248 }
249
250 enum {
251         L_NO_CHECK_CERTIFICATE,
252         L_CA_CERTIFICATE,
253 };
254
255 static const struct option longopts[] = {
256         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
257         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
258         {}
259 };
260
261 int main(int argc, char **argv)
262 {
263         const char *progname = argv[0];
264         struct uclient *cl;
265         int ch;
266         int longopt_idx = 0;
267
268         init_ustream_ssl();
269
270         while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
271                 switch(ch) {
272                 case 0:
273                         switch (longopt_idx) {
274                         case L_NO_CHECK_CERTIFICATE:
275                                 verify = false;
276                                 break;
277                         case L_CA_CERTIFICATE:
278                                 if (ssl_ctx)
279                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
280                                 break;
281                         default:
282                                 return usage(progname);
283                         }
284                         break;
285                 case 'O':
286                         output_file = optarg;
287                         break;
288                 case 'q':
289                         quiet = true;
290                         break;
291                 default:
292                         return usage(progname);
293                 }
294         }
295
296         argv += optind;
297         argc -= optind;
298
299         if (argc != 1)
300                 return usage(progname);
301
302         if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
303                 return no_ssl(progname);
304
305         uloop_init();
306
307         cl = uclient_new(argv[0], NULL, &cb);
308         if (!cl) {
309                 fprintf(stderr, "Failed to allocate uclient context\n");
310                 return 1;
311         }
312
313         if (ssl_ctx)
314                 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
315
316         init_request(cl);
317         uloop_run();
318         uloop_done();
319
320         uclient_free(cl);
321
322         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
323                 close(output_fd);
324
325         if (ssl_ctx)
326                 ssl_ops->context_free(ssl_ctx);
327
328         return error_ret;
329 }