example: only close output fd after request completion if -O was not used
[project/uclient.git] / uclient-example.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 example_header_done(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 example_read_data(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 example_eof(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 = example_header_done,
217 .data_read = example_read_data,
218 .data_eof = example_eof,
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 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
228 "\n"
229 "HTTPS options:\n"
230 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
231 " --no-check-certificate: don't validate the server's certificate\n"
232 "\n", progname);
233 return 1;
234 }
235
236
237 static void init_ustream_ssl(void)
238 {
239 void *dlh;
240
241 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
242 if (!dlh)
243 return;
244
245 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
246 if (!ssl_ops)
247 return;
248
249 ssl_ctx = ssl_ops->context_new(false);
250 }
251
252 static int no_ssl(const char *progname)
253 {
254 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
255 return 1;
256 }
257
258 enum {
259 L_NO_CHECK_CERTIFICATE,
260 L_CA_CERTIFICATE,
261 };
262
263 static const struct option longopts[] = {
264 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
265 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
266 {}
267 };
268
269 int main(int argc, char **argv)
270 {
271 const char *progname = argv[0];
272 struct uclient *cl;
273 int ch;
274 int longopt_idx = 0;
275
276 init_ustream_ssl();
277
278 while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
279 switch(ch) {
280 case 0:
281 switch (longopt_idx) {
282 case L_NO_CHECK_CERTIFICATE:
283 verify = false;
284 break;
285 case L_CA_CERTIFICATE:
286 if (ssl_ctx)
287 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
288 break;
289 default:
290 return usage(progname);
291 }
292 break;
293 case 'O':
294 output_file = optarg;
295 break;
296 case 'q':
297 quiet = true;
298 break;
299 default:
300 return usage(progname);
301 }
302 }
303
304 argv += optind;
305 argc -= optind;
306
307 if (argc != 1)
308 return usage(progname);
309
310 if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
311 return no_ssl(progname);
312
313 uloop_init();
314
315 cl = uclient_new(argv[0], NULL, &cb);
316 if (!cl) {
317 fprintf(stderr, "Failed to allocate uclient context\n");
318 return 1;
319 }
320
321 if (ssl_ctx)
322 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
323
324 init_request(cl);
325 uloop_run();
326 uloop_done();
327
328 uclient_free(cl);
329
330 if (output_fd >= 0 && output_fd != STDOUT_FILENO)
331 close(output_fd);
332
333 if (ssl_ctx)
334 ssl_ops->context_free(ssl_ctx);
335
336 return error_ret;
337 }