]>
git.ipfire.org Git - thirdparty/openssl.git/blob - demos/bio/sconnect.c
2 * Copyright 1998-2020 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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
22 #include <openssl/err.h>
23 #include <openssl/ssl.h>
25 #define HOSTPORT "localhost:4433"
26 #define CAFILE "root.pem"
28 int main(int argc
, char *argv
[])
30 const char *hostport
= HOSTPORT
;
31 const char *CAfile
= CAFILE
;
35 char buf
[1024 * 10], *p
;
36 SSL_CTX
*ssl_ctx
= NULL
;
39 int i
, len
, off
, ret
= EXIT_FAILURE
;
51 ssl_ctx
= SSL_CTX_new(TLS_client_method());
53 /* Enable trust chain verification */
54 SSL_CTX_set_verify(ssl_ctx
, SSL_VERIFY_PEER
, NULL
);
55 SSL_CTX_load_verify_locations(ssl_ctx
, CAfile
, NULL
);
57 /* Lets make a SSL structure */
58 ssl
= SSL_new(ssl_ctx
);
59 SSL_set_connect_state(ssl
);
62 /* Use it inside an SSL BIO */
63 ssl_bio
= BIO_new(BIO_f_ssl());
64 BIO_set_ssl(ssl_bio
, ssl
, BIO_CLOSE
);
66 /* Lets use a connect BIO under the SSL BIO */
67 out
= BIO_new(BIO_s_connect());
68 BIO_set_conn_hostname(out
, hostport
);
70 /* The BIO has parsed the host:port and even IPv6 literals in [] */
71 hostname
= BIO_get_conn_hostname(out
);
72 if (!hostname
|| SSL_set1_host(ssl
, hostname
) <= 0)
76 out
= BIO_push(ssl_bio
, out
);
78 p
= "GET / HTTP/1.0\r\n\r\n";
83 i
= BIO_write(out
, &(p
[off
]), len
);
85 if (BIO_should_retry(out
)) {
86 fprintf(stderr
, "write DELAY\n");
100 i
= BIO_read(out
, buf
, sizeof(buf
));
104 if (BIO_should_retry(out
)) {
105 fprintf(stderr
, "read DELAY\n");
111 fwrite(buf
, 1, i
, stdout
);
118 if (ERR_peek_error() == 0) { /* system call error */
119 fprintf(stderr
, "errno=%d ", errno
);
122 ERR_print_errors_fp(stderr
);
126 SSL_CTX_free(ssl_ctx
);