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