5 #include <libubox/usock.h>
6 #include <libubox/uloop.h>
7 #include "ustream-ssl.h"
9 static struct uloop_fd fd
;
11 static struct ustream_fd stream
, s_input
;
12 static struct ustream_ssl ssl
;
13 static const char *host
, *port
;
17 static void client_teardown(void)
19 if (s_input
.fd
.registered
)
20 ustream_free(&s_input
.stream
);
22 ustream_free(&ssl
.stream
);
23 ustream_free(&stream
.stream
);
28 static void client_input_notify_read(struct ustream
*s
, int bytes
)
33 buf
= ustream_get_read_buf(s
, &len
);
34 ustream_write(&ssl
.stream
, buf
, len
, false);
35 ustream_consume(s
, len
);
38 static void client_ssl_notify_read(struct ustream
*s
, int bytes
)
43 buf
= ustream_get_read_buf(s
, &len
);
44 fwrite(buf
, len
, 1, stdout
);
46 ustream_consume(s
, len
);
49 static void client_notify_connected(struct ustream_ssl
*ssl
)
51 fprintf(stderr
, "SSL connection established (CN verified: %d)\n", ssl
->valid_cn
);
52 s_input
.stream
.notify_read
= client_input_notify_read
;
53 ustream_fd_init(&s_input
, 0);
56 static void client_notify_error(struct ustream_ssl
*ssl
, int error
, const char *str
)
58 fprintf(stderr
, "SSL connection error(%d): %s\n", error
, str
);
62 static void client_notify_verify_error(struct ustream_ssl
*ssl
, int error
, const char *str
)
64 fprintf(stderr
, "WARNING: SSL certificate error(%d): %s\n", error
, str
);
67 static void client_notify_state(struct ustream
*us
)
69 if (!us
->write_error
&& !us
->eof
)
72 fprintf(stderr
, "Connection closed\n");
76 static void example_connect_ssl(int fd
)
78 fprintf(stderr
, "Starting SSL negnotiation\n");
80 ssl
.notify_error
= client_notify_error
;
81 ssl
.notify_verify_error
= client_notify_verify_error
;
82 ssl
.notify_connected
= client_notify_connected
;
83 ssl
.stream
.notify_read
= client_ssl_notify_read
;
84 ssl
.stream
.notify_state
= client_notify_state
;
86 ustream_fd_init(&stream
, fd
);
87 ustream_ssl_init(&ssl
, &stream
.stream
, ctx
, false);
88 ustream_ssl_set_peer_cn(&ssl
, host
);
91 static void example_connect_cb(struct uloop_fd
*f
, unsigned int events
)
93 if (fd
.eof
|| fd
.error
) {
94 fprintf(stderr
, "Connection failed\n");
99 fprintf(stderr
, "Connection established\n");
100 uloop_fd_delete(&fd
);
101 example_connect_ssl(fd
.fd
);
104 static void connect_client(void)
106 fd
.fd
= usock(USOCK_TCP
| USOCK_NONBLOCK
, host
, port
);
107 fd
.cb
= example_connect_cb
;
108 uloop_fd_add(&fd
, ULOOP_WRITE
| ULOOP_EDGE_TRIGGER
);
111 static int usage(const char *progname
)
114 "Usage: %s [options] <hostname> <port>\n"
116 " -c <cert>: Load CA certificates from file <cert>\n"
121 int main(int argc
, char **argv
)
123 const char *progname
= argv
[0];
126 ctx
= ustream_ssl_context_new(false);
128 while ((ch
= getopt(argc
, argv
, "c:")) != -1) {
131 ustream_ssl_context_add_ca_crt_file(ctx
, optarg
);
134 return usage(progname
);
142 return usage(progname
);