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