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