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