2 * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 * A minimal program to do SSL to a passed host and port.
12 * It is actually using non-blocking IO but in a very simple manner
13 * sconnect host:port - it does a 'GET / HTTP/1.0'
15 * cc -I../../include sconnect.c -L../.. -lssl -lcrypto
21 #include <openssl/err.h>
22 #include <openssl/ssl.h>
24 #define HOSTPORT "localhost:4433"
25 #define CAFILE "root.pem"
33 const char *hostport = HOSTPORT;
34 const char *CAfile = CAFILE;
38 char buf[1024 * 10], *p;
39 SSL_CTX *ssl_ctx = NULL;
42 int i, len, off, ret = 1;
49 hostname = OPENSSL_strdup(hostport);
50 if ((cp = strchr(hostname, ':')) != NULL)
58 /* Lets get nice error messages */
59 SSL_load_error_strings();
61 /* Setup all the global SSL stuff */
62 OpenSSL_add_ssl_algorithms();
63 ssl_ctx = SSL_CTX_new(TLS_client_method());
65 /* Enable trust chain verification */
66 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
67 SSL_CTX_load_verify_locations(ssl_ctx, CAfile, NULL);
69 /* Lets make a SSL structure */
70 ssl = SSL_new(ssl_ctx);
71 SSL_set_connect_state(ssl);
73 /* Enable peername verification */
74 if (SSL_set1_host(ssl, hostname) <= 0)
77 /* Use it inside an SSL BIO */
78 ssl_bio = BIO_new(BIO_f_ssl());
79 BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
81 /* Lets use a connect BIO under the SSL BIO */
82 out = BIO_new(BIO_s_connect());
83 BIO_set_conn_hostname(out, hostport);
85 out = BIO_push(ssl_bio, out);
87 p = "GET / HTTP/1.0\r\n\r\n";
92 i = BIO_write(out, &(p[off]), len);
94 if (BIO_should_retry(out)) {
95 fprintf(stderr, "write DELAY\n");
109 i = BIO_read(out, buf, sizeof(buf));
113 if (BIO_should_retry(out)) {
114 fprintf(stderr, "read DELAY\n");
120 fwrite(buf, 1, i, stdout);
127 if (ERR_peek_error() == 0) { /* system call error */
128 fprintf(stderr, "errno=%d ", errno);
131 ERR_print_errors_fp(stderr);
134 SSL_CTX_free(ssl_ctx);