2 /* demos/bio/sconnect.c */
5 * A minimal program to do SSL to a passed host and port.
6 * It is actually using non-blocking IO but in a very simple manner
7 * sconnect host:port - it does a 'GET / HTTP/1.0'
9 * cc -I../../include sconnect.c -L../.. -lssl -lcrypto
15 #include <openssl/err.h>
16 #include <openssl/ssl.h>
18 #define HOSTPORT "localhost:4433"
19 #define CAFILE "root.pem"
27 const char *hostport = HOSTPORT;
28 const char *CAfile = CAFILE;
32 char buf[1024 * 10], *p;
33 SSL_CTX *ssl_ctx = NULL;
36 int i, len, off, ret = 1;
43 hostname = OPENSSL_strdup(hostport);
44 if ((cp = strchr(hostname, ':')) != NULL)
52 /* Lets get nice error messages */
53 SSL_load_error_strings();
55 /* Setup all the global SSL stuff */
56 OpenSSL_add_ssl_algorithms();
57 ssl_ctx = SSL_CTX_new(TLS_client_method());
59 /* Enable trust chain verification */
60 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
61 SSL_CTX_load_verify_locations(ssl_ctx, CAfile, NULL);
63 /* Lets make a SSL structure */
64 ssl = SSL_new(ssl_ctx);
65 SSL_set_connect_state(ssl);
67 /* Enable peername verification */
68 if (SSL_set1_host(ssl, hostname) <= 0)
71 /* Use it inside an SSL BIO */
72 ssl_bio = BIO_new(BIO_f_ssl());
73 BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
75 /* Lets use a connect BIO under the SSL BIO */
76 out = BIO_new(BIO_s_connect());
77 BIO_set_conn_hostname(out, hostport);
79 out = BIO_push(ssl_bio, out);
81 p = "GET / HTTP/1.0\r\n\r\n";
86 i = BIO_write(out, &(p[off]), len);
88 if (BIO_should_retry(out)) {
89 fprintf(stderr, "write DELAY\n");
103 i = BIO_read(out, buf, sizeof(buf));
107 if (BIO_should_retry(out)) {
108 fprintf(stderr, "read DELAY\n");
114 fwrite(buf, 1, i, stdout);
121 if (ERR_peek_error() == 0) { /* system call error */
122 fprintf(stderr, "errno=%d ", errno);
125 ERR_print_errors_fp(stderr);
128 SSL_CTX_free(ssl_ctx);