0617a02fea0bcfc711e7920b552befa52f39b6ae
[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 int init_request(struct uclient *cl)
153 {
154         int rc;
155
156         out_bytes = 0;
157
158         rc = uclient_connect(cl);
159         if (rc)
160                 return rc;
161
162         msg_connecting(cl);
163
164         rc = uclient_http_set_request_type(cl, "GET");
165         if (rc)
166                 return rc;
167
168         rc = uclient_request(cl);
169         if (rc)
170                 return rc;
171
172         return 0;
173 }
174
175 static void eof_cb(struct uclient *cl)
176 {
177         if (!cl->data_eof) {
178                 if (!quiet)
179                         fprintf(stderr, "Connection reset prematurely\n");
180                 error_ret = 4;
181         } else if (!quiet) {
182                 fprintf(stderr, "Download completed (%d bytes)\n", out_bytes);
183         }
184         request_done(cl);
185 }
186
187 static void handle_uclient_error(struct uclient *cl, int code)
188 {
189         const char *type = "Unknown error";
190         bool ignore = false;
191
192         switch(code) {
193         case UCLIENT_ERROR_CONNECT:
194                 type = "Connection failed";
195                 error_ret = 4;
196                 break;
197         case UCLIENT_ERROR_TIMEDOUT:
198                 type = "Connection timed out";
199                 error_ret = 4;
200                 break;
201         case UCLIENT_ERROR_SSL_INVALID_CERT:
202                 type = "Invalid SSL certificate";
203                 ignore = !verify;
204                 error_ret = 5;
205                 break;
206         case UCLIENT_ERROR_SSL_CN_MISMATCH:
207                 type = "Server hostname does not match SSL certificate";
208                 ignore = !verify;
209                 error_ret = 5;
210                 break;
211         default:
212                 error_ret = 1;
213                 break;
214         }
215
216         if (!quiet)
217                 fprintf(stderr, "Connection error: %s%s\n", type, ignore ? " (ignored)" : "");
218
219         if (ignore)
220                 error_ret = 0;
221         else
222                 request_done(cl);
223 }
224
225 static const struct uclient_cb cb = {
226         .header_done = header_done_cb,
227         .data_read = read_data_cb,
228         .data_eof = eof_cb,
229         .error = handle_uclient_error,
230 };
231
232 static int usage(const char *progname)
233 {
234         fprintf(stderr,
235                 "Usage: %s [options] <URL>\n"
236                 "Options:\n"
237                 "       -q:                             Turn off status messages\n"
238                 "       -O <file>:                      Redirect output to file (use \"-\" for stdout)\n"
239                 "\n"
240                 "HTTPS options:\n"
241                 "       --ca-certificate=<cert>:        Load CA certificates from file <cert>\n"
242                 "       --no-check-certificate:         don't validate the server's certificate\n"
243                 "\n", progname);
244         return 1;
245 }
246
247
248 static void init_ustream_ssl(void)
249 {
250         void *dlh;
251
252         dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
253         if (!dlh)
254                 return;
255
256         ssl_ops = dlsym(dlh, "ustream_ssl_ops");
257         if (!ssl_ops)
258                 return;
259
260         ssl_ctx = ssl_ops->context_new(false);
261 }
262
263 static int no_ssl(const char *progname)
264 {
265         fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
266         return 1;
267 }
268
269 enum {
270         L_NO_CHECK_CERTIFICATE,
271         L_CA_CERTIFICATE,
272         L_USER,
273         L_PASSWORD,
274 };
275
276 static const struct option longopts[] = {
277         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
278         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
279         [L_USER] = { "user", required_argument },
280         [L_PASSWORD] = { "password", required_argument },
281         {}
282 };
283
284 int main(int argc, char **argv)
285 {
286         const char *progname = argv[0];
287         struct uclient *cl;
288         int ch;
289         int longopt_idx = 0;
290         int rc;
291
292         init_ustream_ssl();
293
294         while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
295                 switch(ch) {
296                 case 0:
297                         switch (longopt_idx) {
298                         case L_NO_CHECK_CERTIFICATE:
299                                 verify = false;
300                                 break;
301                         case L_CA_CERTIFICATE:
302                                 if (ssl_ctx)
303                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
304                                 break;
305                         case L_USER:
306                                 if (!strlen(optarg))
307                                         break;
308                                 username = strdup(optarg);
309                                 memset(optarg, '*', strlen(optarg));
310                                 break;
311                         case L_PASSWORD:
312                                 if (!strlen(optarg))
313                                         break;
314                                 password = strdup(optarg);
315                                 memset(optarg, '*', strlen(optarg));
316                                 break;
317                         default:
318                                 return usage(progname);
319                         }
320                         break;
321                 case 'O':
322                         output_file = optarg;
323                         break;
324                 case 'q':
325                         quiet = true;
326                         break;
327                 default:
328                         return usage(progname);
329                 }
330         }
331
332         argv += optind;
333         argc -= optind;
334
335         if (argc != 1)
336                 return usage(progname);
337
338         if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
339                 return no_ssl(progname);
340
341         uloop_init();
342
343         if (username) {
344                 if (password)
345                         asprintf(&auth_str, "%s:%s", username, password);
346                 else
347                         auth_str = username;
348         }
349
350         if (!quiet)
351                 fprintf(stderr, "Downloading '%s'\n", argv[0]);
352
353         cl = uclient_new(argv[0], auth_str, &cb);
354         if (!cl) {
355                 fprintf(stderr, "Failed to allocate uclient context\n");
356                 return 1;
357         }
358
359         if (ssl_ctx)
360                 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
361
362         rc = init_request(cl);
363         if (!rc) {
364                 /* no error received, we can enter main loop */
365                 uloop_run();
366         } else {
367                 fprintf(stderr, "Failed to establish connection\n");
368                 error_ret = 4;
369         }
370
371         uloop_done();
372
373         uclient_free(cl);
374
375         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
376                 close(output_fd);
377
378         if (ssl_ctx)
379                 ssl_ops->context_free(ssl_ctx);
380
381         return error_ret;
382 }