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