2 * uclient - ustream based protocol client library
4 * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
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.
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.
22 #include <libubox/blobmsg.h>
27 static void example_header_done(struct uclient *cl)
29 struct blob_attr *cur;
30 char local[INET6_ADDRSTRLEN], remote[INET6_ADDRSTRLEN];
31 int local_port, remote_port;
34 uclient_get_addr(local, &local_port, &cl->local_addr);
35 uclient_get_addr(remote, &remote_port, &cl->remote_addr);
37 fprintf(stderr, "Connected: %s:%d -> %s:%d\n",
38 local, local_port, remote, remote_port);
40 printf("Headers (%d): \n", cl->status_code);
41 blobmsg_for_each_attr(cur, cl->meta, rem) {
42 printf("%s=%s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
45 printf("Contents:\n");
48 static void example_read_data(struct uclient *cl)
54 len = uclient_read(cl, buf, sizeof(buf));
58 write(STDOUT_FILENO, buf, len);
62 static void example_request_sm(struct uclient *cl)
69 uclient_http_set_request_type(cl, "HEAD");
74 uclient_http_set_request_type(cl, "GET");
83 static void example_eof(struct uclient *cl)
87 if (retries < 10 && uclient_http_redirect(cl)) {
93 example_request_sm(cl);
96 static void example_error(struct uclient *cl, int code)
98 fprintf(stderr, "Error %d!\n", code);
99 example_request_sm(cl);
102 static const struct uclient_cb cb = {
103 .header_done = example_header_done,
104 .data_read = example_read_data,
105 .data_eof = example_eof,
106 .error = example_error,
109 static int usage(const char *progname)
112 "Usage: %s [options] <hostname> <port>\n"
114 " -c <cert>: Load CA certificates from file <cert>\n"
115 " -C: Skip certificate CN verification against hostname\n"
121 int main(int argc, char **argv)
123 struct ustream_ssl_ctx *ctx;
124 const char *progname = argv[0];
129 ctx = ustream_ssl_context_new(false);
131 while ((ch = getopt(argc, argv, "Cc:")) != -1) {
134 ustream_ssl_context_add_ca_crt_file(ctx, optarg);
140 return usage(progname);
148 return usage(progname);
152 cl = uclient_new(argv[0], NULL, &cb);
154 fprintf(stderr, "Failed to allocate uclient context\n");
158 uclient_http_set_ssl_ctx(cl, &ustream_ssl_ops, ctx, verify);
159 example_request_sm(cl);
164 ustream_ssl_context_free(ctx);