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