Path: blob/main/crypto/openssl/demos/bio/sconnect.c
101200 views
/*1* Copyright 1998-2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89/*-10* A minimal program to do SSL to a passed host and port.11* It is actually using non-blocking IO but in a very simple manner12* sconnect host:port - it does a 'GET / HTTP/1.0'13*14* cc -I../../include sconnect.c -L../.. -lssl -lcrypto15*/16#include <stdio.h>17#include <stdlib.h>18#include <string.h>19#include <errno.h>20#include <openssl/err.h>21#include <openssl/ssl.h>22#if !defined(OPENSSL_SYS_WINDOWS)23#include <unistd.h>24#else25#include <windows.h>26#define sleep(x) Sleep(x * 1000)27#endif2829#define HOSTPORT "localhost:4433"30#define CAFILE "root.pem"3132int main(int argc, char *argv[])33{34const char *hostport = HOSTPORT;35const char *CAfile = CAFILE;36const char *hostname;37BIO *out = NULL;38char buf[1024 * 10], *p;39SSL_CTX *ssl_ctx = NULL;40SSL *ssl;41BIO *ssl_bio;42int i, len, off, ret = EXIT_FAILURE;4344if (argc > 1)45hostport = argv[1];46if (argc > 2)47CAfile = argv[2];4849#ifdef WATT3250dbug_init();51sock_init();52#endif5354ssl_ctx = SSL_CTX_new(TLS_client_method());5556/* Enable trust chain verification */57SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);58if (!SSL_CTX_load_verify_locations(ssl_ctx, CAfile, NULL))59goto err;6061/* Let's make an SSL structure */62ssl = SSL_new(ssl_ctx);63SSL_set_connect_state(ssl);6465/* Use it inside an SSL BIO */66ssl_bio = BIO_new(BIO_f_ssl());67BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);6869/* Lets use a connect BIO under the SSL BIO */70out = BIO_new(BIO_s_connect());71BIO_set_conn_hostname(out, hostport);7273/* The BIO has parsed the host:port and even IPv6 literals in [] */74hostname = BIO_get_conn_hostname(out);75if (!hostname || SSL_set1_host(ssl, hostname) <= 0) {76BIO_free(ssl_bio);77goto err;78}7980BIO_set_nbio(out, 1);81out = BIO_push(ssl_bio, out);8283p = "GET / HTTP/1.0\r\n\r\n";84len = strlen(p);8586off = 0;87for (;;) {88i = BIO_write(out, &(p[off]), len);89if (i <= 0) {90if (BIO_should_retry(out)) {91fprintf(stderr, "write DELAY\n");92sleep(1);93continue;94} else {95goto err;96}97}98off += i;99len -= i;100if (len <= 0)101break;102}103104for (;;) {105i = BIO_read(out, buf, sizeof(buf));106if (i == 0)107break;108if (i < 0) {109if (BIO_should_retry(out)) {110fprintf(stderr, "read DELAY\n");111sleep(1);112continue;113}114goto err;115}116fwrite(buf, 1, i, stdout);117}118119ret = EXIT_SUCCESS;120goto done;121122err:123if (ERR_peek_error() == 0) { /* system call error */124fprintf(stderr, "errno=%d ", errno);125perror("error");126} else {127ERR_print_errors_fp(stderr);128}129done:130BIO_free_all(out);131SSL_CTX_free(ssl_ctx);132return ret;133}134135136