example: only write output data on http 200/204
[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 const char *output_file;
39 static int output_fd = -1;
40 static int error_ret;
41
42 static int open_output_file(const char *path, bool create)
43 {
44 const char *str;
45 char *filename;
46 int len;
47 int flags = O_WRONLY;
48
49 if (create)
50 flags |= O_CREAT;
51
52 if (output_file) {
53 if (!strcmp(output_file, "-"))
54 return STDOUT_FILENO;
55
56 return open(output_file, flags, 0644);
57 }
58
59 /* Don't automatically overwrite files if the name is derived from the URL */
60 if (create)
61 flags |= O_EXCL;
62
63 len = strcspn(path, ";&");
64 while (len > 0 && path[len - 1] == '/')
65 len--;
66
67 for (str = path + len - 1; str >= path; str--) {
68 if (*str == '/')
69 break;
70 }
71
72 str++;
73 len -= str - path;
74
75 if (len > 0) {
76 filename = alloca(len + 1);
77 strncpy(filename, str, len);
78 filename[len] = 0;
79 } else {
80 filename = "index.html";
81 }
82
83 return open(filename, flags, 0644);
84 }
85
86 static void request_done(struct uclient *cl)
87 {
88 uclient_disconnect(cl);
89 uloop_end();
90 }
91
92 static void example_header_done(struct uclient *cl)
93 {
94 static int retries;
95
96 struct blob_attr *cur;
97 int rem;
98
99 if (retries < 10 && uclient_http_redirect(cl)) {
100 if (!quiet)
101 fprintf(stderr, "Redirected to %s on %s\n", cl->url->location, cl->url->host);
102
103 retries++;
104 return;
105 }
106
107 retries = 0;
108 if (!quiet) {
109 fprintf(stderr, "Headers (%d): \n", cl->status_code);
110 blobmsg_for_each_attr(cur, cl->meta, rem) {
111 fprintf(stderr, "%s=%s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
112 }
113 }
114
115 switch (cl->status_code) {
116 case 204:
117 case 200:
118 output_fd = open_output_file(cl->url->location, true);
119 if (output_fd < 0) {
120 if (!quiet)
121 perror("Cannot open output file");
122 error_ret = 3;
123 request_done(cl);
124 }
125 break;
126
127 default:
128 request_done(cl);
129 break;
130 }
131 }
132
133 static void example_read_data(struct uclient *cl)
134 {
135 char buf[256];
136 int len;
137
138 if (output_fd < 0)
139 return;
140
141 while (1) {
142 len = uclient_read(cl, buf, sizeof(buf));
143 if (!len)
144 return;
145
146 write(output_fd, buf, len);
147 }
148 }
149
150 static void msg_connecting(struct uclient *cl)
151 {
152 char addr[INET6_ADDRSTRLEN];
153 int port;
154
155 if (quiet)
156 return;
157
158 uclient_get_addr(addr, &port, &cl->remote_addr);
159 fprintf(stderr, "Connecting to %s %s:%d\n", cl->url->host, addr, port);
160 }
161
162 static void init_request(struct uclient *cl)
163 {
164 uclient_connect(cl);
165 msg_connecting(cl);
166 uclient_http_set_request_type(cl, "GET");
167 uclient_request(cl);
168 }
169
170 static void example_eof(struct uclient *cl)
171 {
172 request_done(cl);
173 }
174
175 static void example_error(struct uclient *cl, int code)
176 {
177 if (!quiet)
178 fprintf(stderr, "Error %d!\n", code);
179
180 request_done(cl);
181 }
182
183 static const struct uclient_cb cb = {
184 .header_done = example_header_done,
185 .data_read = example_read_data,
186 .data_eof = example_eof,
187 .error = example_error,
188 };
189
190 static int usage(const char *progname)
191 {
192 fprintf(stderr,
193 "Usage: %s [options] <URL>\n"
194 "Options:\n"
195 " -O <file>: Redirect output to file (use \"-\" for stdout)\n"
196 "\n"
197 "HTTPS options:\n"
198 " --ca-certificate=<cert>: Load CA certificates from file <cert>\n"
199 " --no-check-certificate: don't validate the server's certificate\n"
200 "\n", progname);
201 return 1;
202 }
203
204
205 static void init_ustream_ssl(void)
206 {
207 void *dlh;
208
209 dlh = dlopen("libustream-ssl." LIB_EXT, RTLD_LAZY | RTLD_LOCAL);
210 if (!dlh)
211 return;
212
213 ssl_ops = dlsym(dlh, "ustream_ssl_ops");
214 if (!ssl_ops)
215 return;
216
217 ssl_ctx = ssl_ops->context_new(false);
218 }
219
220 static int no_ssl(const char *progname)
221 {
222 fprintf(stderr, "%s: SSL support not available, please install ustream-ssl\n", progname);
223 return 1;
224 }
225
226 enum {
227 L_NO_CHECK_CERTIFICATE,
228 L_CA_CERTIFICATE,
229 };
230
231 static const struct option longopts[] = {
232 [L_NO_CHECK_CERTIFICATE] = { "no-check-certificate", no_argument },
233 [L_CA_CERTIFICATE] = { "ca-certificate", required_argument },
234 {}
235 };
236
237 int main(int argc, char **argv)
238 {
239 const char *progname = argv[0];
240 struct uclient *cl;
241 bool verify = true;
242 int ch;
243 int longopt_idx = 0;
244
245 init_ustream_ssl();
246
247 while ((ch = getopt_long(argc, argv, "qO:", longopts, &longopt_idx)) != -1) {
248 switch(ch) {
249 case 0:
250 switch (longopt_idx) {
251 case L_NO_CHECK_CERTIFICATE:
252 verify = false;
253 break;
254 case L_CA_CERTIFICATE:
255 if (ssl_ctx)
256 ssl_ops->context_add_ca_crt_file(ssl_ctx, optarg);
257 break;
258 default:
259 return usage(progname);
260 }
261 break;
262 case 'O':
263 output_file = optarg;
264 break;
265 case 'q':
266 quiet = true;
267 break;
268 default:
269 return usage(progname);
270 }
271 }
272
273 argv += optind;
274 argc -= optind;
275
276 if (argc != 1)
277 return usage(progname);
278
279 if (!strncmp(argv[0], "https", 5) && !ssl_ctx)
280 return no_ssl(progname);
281
282 uloop_init();
283
284 cl = uclient_new(argv[0], NULL, &cb);
285 if (!cl) {
286 fprintf(stderr, "Failed to allocate uclient context\n");
287 return 1;
288 }
289
290 if (ssl_ctx)
291 uclient_http_set_ssl_ctx(cl, ssl_ops, ssl_ctx, verify);
292
293 init_request(cl);
294 uloop_run();
295 uloop_done();
296
297 uclient_free(cl);
298
299 if (ssl_ctx)
300 ssl_ops->context_free(ssl_ctx);
301
302 return error_ret;
303 }