8dcb97b1349eedcea101c1fcae14ca280b7b89ee
[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 request_done(cl);
155 }
156
157 static void handle_uclient_error(struct uclient *cl, int code)
158 {
159 const char *type = "Unknown error";
160 bool ignore = false;
161
162 switch(code) {
163 case UCLIENT_ERROR_CONNECT:
164 type = "Connection failed";
165 error_ret = 4;
166 break;
167 case UCLIENT_ERROR_SSL_INVALID_CERT:
168 type = "Invalid SSL certificate";
169 ignore = !verify;
170 error_ret = 5;
171 break;
172 case UCLIENT_ERROR_SSL_CN_MISMATCH:
173 type = "Server hostname does not match SSL certificate";
174 ignore = !verify;
175 error_ret = 5;
176 break;
177 default:
178 error_ret = 1;
179 break;
180 }
181
182 if (!quiet)
183 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
184
185 if (ignore)
186 error_ret = 0;
187 else
188 request_done(cl);
189 }
190
191 static const struct uclient_cb cb = {
192 .header_done = header_done_cb,
193 .data_read = read_data_cb,
194 .data_eof = eof_cb,
195 .error = handle_uclient_error,
196 };
197
198 static int usage(const char *progname)
199 {
200 fprintf(stderr,
201 "Usage: %s [options] <URL>\n"
202 "Options:\n"
203 " -q: Turn off status messages\n"
204 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
205 "\n"
206 "HTTPS options:\n"
207 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
208 " --no-check-certificate: don't validate the server's certificate\n"
209 "\n", progname);
210 return 1;
211 }
212
213
214 static void init_ustream_ssl(void)
215 {
216 void *dlh;
217
218 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
219 if (!dlh)
220 return;
221
222 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
223 if (!ssl_ops)
224 return;
225
226 ssl_ctx = ssl_ops->context_new(false);
227 }
228
229 static int no_ssl(const char *progname)
230 {
231 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
232 return 1;
233 }
234
235 enum {
236 L_NO_CHECK_CERTIFICATE,
237 L_CA_CERTIFICATE,
238 };
239
240 static const struct option longopts[] = {
241 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
242 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
243 {}
244 };
245
246 int main(int argc, char **argv)
247 {
248 const char *progname = argv[0];
249 struct uclient *cl;
250 int ch;
251 int longopt_idx = 0;
252
253 init_ustream_ssl();
254
255 while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
256 switch(ch) {
257 case 0:
258 switch (longopt_idx) {
259 case L_NO_CHECK_CERTIFICATE:
260 verify = false;
261 break;
262 case L_CA_CERTIFICATE:
263 if (ssl_ctx)
264 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
265 break;
266 default:
267 return usage(progname);
268 }
269 break;
270 case 'O':
271 output_file = optarg;
272 break;
273 case 'q':
274 quiet = true;
275 break;
276 default:
277 return usage(progname);
278 }
279 }
280
281 argv += optind;
282 argc -= optind;
283
284 if (argc != 1)
285 return usage(progname);
286
287 if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
288 return no_ssl(progname);
289
290 uloop_init();
291
292 cl = uclient_new(argv[0], NULL, &cb);
293 if (!cl) {
294 fprintf(stderr, "Failed to allocate uclient context\n");
295 return 1;
296 }
297
298 if (ssl_ctx)
299 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
300
301 init_request(cl);
302 uloop_run();
303 uloop_done();
304
305 uclient_free(cl);
306
307 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
308 close(output_fd);
309
310 if (ssl_ctx)
311 ssl_ops->context_free(ssl_ctx);
312
313 return error_ret;
314 }