Path: blob/main/crypto/openssl/demos/bio/sconnect.c
34869 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);646566/* Use it inside an SSL BIO */67ssl_bio = BIO_new(BIO_f_ssl());68BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);6970/* Lets use a connect BIO under the SSL BIO */71out = BIO_new(BIO_s_connect());72BIO_set_conn_hostname(out, hostport);7374/* The BIO has parsed the host:port and even IPv6 literals in [] */75hostname = BIO_get_conn_hostname(out);76if (!hostname || SSL_set1_host(ssl, hostname) <= 0) {77BIO_free(ssl_bio);78goto err;79}8081BIO_set_nbio(out, 1);82out = BIO_push(ssl_bio, out);8384p = "GET / HTTP/1.0\r\n\r\n";85len = strlen(p);8687off = 0;88for (;;) {89i = BIO_write(out, &(p[off]), len);90if (i <= 0) {91if (BIO_should_retry(out)) {92fprintf(stderr, "write DELAY\n");93sleep(1);94continue;95} else {96goto err;97}98}99off += i;100len -= i;101if (len <= 0)102break;103}104105for (;;) {106i = BIO_read(out, buf, sizeof(buf));107if (i == 0)108break;109if (i < 0) {110if (BIO_should_retry(out)) {111fprintf(stderr, "read DELAY\n");112sleep(1);113continue;114}115goto err;116}117fwrite(buf, 1, i, stdout);118}119120ret = EXIT_SUCCESS;121goto done;122123err:124if (ERR_peek_error() == 0) { /* system call error */125fprintf(stderr, "errno=%d ", errno);126perror("error");127} else {128ERR_print_errors_fp(stderr);129}130done:131BIO_free_all(out);132SSL_CTX_free(ssl_ctx);133return ret;134}135136137