fetch: print error messages on http error codes
[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         if (retries < 10 && uclient_http_redirect(cl)) {
102                 if (!quiet)
103                         fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
104
105                 retries++;
106                 return;
107         }
108
109         retries = 0;
110         switch (cl->status_code) {
111         case 204:
112         case 200:
113                 output_fd = open_output_file(cl->url->location, true);
114                 if (output_fd < 0) {
115                         if (!quiet)
116                                 perror("Cannot open output file");
117                         error_ret = 3;
118                         request_done(cl);
119                 }
120                 break;
121
122         default:
123                 if (!quiet)
124                         fprintf(stderr, "HTTP error %d\n", cl->status_code);
125                 request_done(cl);
126                 error_ret = 8;
127                 break;
128         }
129 }
130
131 static void read_data_cb(struct uclient *cl)
132 {
133         char buf[256];
134         int len;
135
136         if (output_fd < 0)
137                 return;
138
139         while (1) {
140                 len = uclient_read(cl, buf, sizeof(buf));
141                 if (!len)
142                         return;
143
144                 write(output_fd, buf, len);
145         }
146 }
147
148 static void msg_connecting(struct uclient *cl)
149 {
150         char addr[INET6_ADDRSTRLEN];
151         int port;
152
153         if (quiet)
154                 return;
155
156         uclient_get_addr(addr, &port, &cl->remote_addr);
157         fprintf(stderr, "Connecting to %s %s:%d\n", cl->url->host, addr, port);
158 }
159
160 static void init_request(struct uclient *cl)
161 {
162         uclient_connect(cl);
163         msg_connecting(cl);
164         uclient_http_set_request_type(cl, "GET");
165         uclient_request(cl);
166 }
167
168 static void eof_cb(struct uclient *cl)
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 };
255
256 static const struct option longopts[] = {
257         [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
258         [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
259         {}
260 };
261
262 int main(int argc, char **argv)
263 {
264         const char *progname = argv[0];
265         struct uclient *cl;
266         int ch;
267         int longopt_idx = 0;
268
269         init_ustream_ssl();
270
271         while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
272                 switch(ch) {
273                 case 0:
274                         switch (longopt_idx) {
275                         case L_NO_CHECK_CERTIFICATE:
276                                 verify = false;
277                                 break;
278                         case L_CA_CERTIFICATE:
279                                 if (ssl_ctx)
280                                         ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
281                                 break;
282                         default:
283                                 return usage(progname);
284                         }
285                         break;
286                 case 'O':
287                         output_file = optarg;
288                         break;
289                 case 'q':
290                         quiet = true;
291                         break;
292                 default:
293                         return usage(progname);
294                 }
295         }
296
297         argv += optind;
298         argc -= optind;
299
300         if (argc != 1)
301                 return usage(progname);
302
303         if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
304                 return no_ssl(progname);
305
306         uloop_init();
307
308         cl = uclient_new(argv[0], NULL, &cb);
309         if (!cl) {
310                 fprintf(stderr, "Failed to allocate uclient context\n");
311                 return 1;
312         }
313
314         if (ssl_ctx)
315                 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
316
317         init_request(cl);
318         uloop_run();
319         uloop_done();
320
321         uclient_free(cl);
322
323         if (output_fd >= 0 && output_fd != STDOUT_FILENO)
324                 close(output_fd);
325
326         if (ssl_ctx)
327                 ssl_ops->context_free(ssl_ctx);
328
329         return error_ret;
330 }