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