Path: blob/main/crypto/openssl/demos/guide/tls-client-non-block.c
34876 views
/*1* Copyright 2023-2024 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* NB: Changes to this file should also be reflected in11* doc/man7/ossl-guide-tls-client-non-block.pod12*/1314#include <string.h>1516/* Include the appropriate header file for SOCK_STREAM */17#ifdef _WIN32 /* Windows */18# include <winsock2.h>19#else /* Linux/Unix */20# include <sys/socket.h>21# include <sys/select.h>22#endif2324#include <openssl/bio.h>25#include <openssl/ssl.h>26#include <openssl/err.h>2728/* Helper function to create a BIO connected to the server */29static BIO *create_socket_bio(const char *hostname, const char *port, int family)30{31int sock = -1;32BIO_ADDRINFO *res;33const BIO_ADDRINFO *ai = NULL;34BIO *bio;3536/*37* Lookup IP address info for the server.38*/39if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_STREAM, 0,40&res))41return NULL;4243/*44* Loop through all the possible addresses for the server and find one45* we can connect to.46*/47for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {48/*49* Create a TCP socket. We could equally use non-OpenSSL calls such50* as "socket" here for this and the subsequent connect and close51* functions. But for portability reasons and also so that we get52* errors on the OpenSSL stack in the event of a failure we use53* OpenSSL's versions of these functions.54*/55sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_STREAM, 0, 0);56if (sock == -1)57continue;5859/* Connect the socket to the server's address */60if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), BIO_SOCK_NODELAY)) {61BIO_closesocket(sock);62sock = -1;63continue;64}6566/* Set to nonblocking mode */67if (!BIO_socket_nbio(sock, 1)) {68sock = -1;69continue;70}7172/* We have a connected socket so break out of the loop */73break;74}7576/* Free the address information resources we allocated earlier */77BIO_ADDRINFO_free(res);7879/* If sock is -1 then we've been unable to connect to the server */80if (sock == -1)81return NULL;8283/* Create a BIO to wrap the socket */84bio = BIO_new(BIO_s_socket());85if (bio == NULL) {86BIO_closesocket(sock);87return NULL;88}8990/*91* Associate the newly created BIO with the underlying socket. By92* passing BIO_CLOSE here the socket will be automatically closed when93* the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which94* case you must close the socket explicitly when it is no longer95* needed.96*/97BIO_set_fd(bio, sock, BIO_CLOSE);9899return bio;100}101102static void wait_for_activity(SSL *ssl, int write)103{104fd_set fds;105int width, sock;106107/* Get hold of the underlying file descriptor for the socket */108sock = SSL_get_fd(ssl);109110FD_ZERO(&fds);111FD_SET(sock, &fds);112width = sock + 1;113114/*115* Wait until the socket is writeable or readable. We use select here116* for the sake of simplicity and portability, but you could equally use117* poll/epoll or similar functions118*119* NOTE: For the purposes of this demonstration code this effectively120* makes this demo block until it has something more useful to do. In a121* real application you probably want to go and do other work here (e.g.122* update a GUI, or service other connections).123*124* Let's say for example that you want to update the progress counter on125* a GUI every 100ms. One way to do that would be to add a 100ms timeout126* in the last parameter to "select" below. Then, when select returns,127* you check if it did so because of activity on the file descriptors or128* because of the timeout. If it is due to the timeout then update the129* GUI and then restart the "select".130*/131if (write)132select(width, NULL, &fds, NULL, NULL);133else134select(width, &fds, NULL, NULL, NULL);135}136137static int handle_io_failure(SSL *ssl, int res)138{139switch (SSL_get_error(ssl, res)) {140case SSL_ERROR_WANT_READ:141/* Temporary failure. Wait until we can read and try again */142wait_for_activity(ssl, 0);143return 1;144145case SSL_ERROR_WANT_WRITE:146/* Temporary failure. Wait until we can write and try again */147wait_for_activity(ssl, 1);148return 1;149150case SSL_ERROR_ZERO_RETURN:151/* EOF */152return 0;153154case SSL_ERROR_SYSCALL:155return -1;156157case SSL_ERROR_SSL:158/*159* If the failure is due to a verification error we can get more160* information about it from SSL_get_verify_result().161*/162if (SSL_get_verify_result(ssl) != X509_V_OK)163printf("Verify error: %s\n",164X509_verify_cert_error_string(SSL_get_verify_result(ssl)));165return -1;166167default:168return -1;169}170}171172/*173* Simple application to send a basic HTTP/1.0 request to a server and174* print the response on the screen.175*/176int main(int argc, char *argv[])177{178SSL_CTX *ctx = NULL;179SSL *ssl = NULL;180BIO *bio = NULL;181int res = EXIT_FAILURE;182int ret;183const char *request_start = "GET / HTTP/1.0\r\nConnection: close\r\nHost: ";184const char *request_end = "\r\n\r\n";185size_t written, readbytes = 0;186char buf[160];187int eof = 0;188char *hostname, *port;189int argnext = 1;190int ipv6 = 0;191192if (argc < 3) {193printf("Usage: tls-client-non-block [-6] hostname port\n");194goto end;195}196197if (!strcmp(argv[argnext], "-6")) {198if (argc < 4) {199printf("Usage: tls-client-non-block [-6] hostname port\n");200goto end;201}202ipv6 = 1;203argnext++;204}205206hostname = argv[argnext++];207port = argv[argnext];208209/*210* Create an SSL_CTX which we can use to create SSL objects from. We211* want an SSL_CTX for creating clients so we use TLS_client_method()212* here.213*/214ctx = SSL_CTX_new(TLS_client_method());215if (ctx == NULL) {216printf("Failed to create the SSL_CTX\n");217goto end;218}219220/*221* Configure the client to abort the handshake if certificate222* verification fails. Virtually all clients should do this unless you223* really know what you are doing.224*/225SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);226227/* Use the default trusted certificate store */228if (!SSL_CTX_set_default_verify_paths(ctx)) {229printf("Failed to set the default trusted certificate store\n");230goto end;231}232233/*234* TLSv1.1 or earlier are deprecated by IETF and are generally to be235* avoided if possible. We require a minimum TLS version of TLSv1.2.236*/237if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {238printf("Failed to set the minimum TLS protocol version\n");239goto end;240}241242/* Create an SSL object to represent the TLS connection */243ssl = SSL_new(ctx);244if (ssl == NULL) {245printf("Failed to create the SSL object\n");246goto end;247}248249/*250* Create the underlying transport socket/BIO and associate it with the251* connection.252*/253bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET);254if (bio == NULL) {255printf("Failed to crete the BIO\n");256goto end;257}258SSL_set_bio(ssl, bio, bio);259260/*261* Tell the server during the handshake which hostname we are attempting262* to connect to in case the server supports multiple hosts.263*/264if (!SSL_set_tlsext_host_name(ssl, hostname)) {265printf("Failed to set the SNI hostname\n");266goto end;267}268269/*270* Ensure we check during certificate verification that the server has271* supplied a certificate for the hostname that we were expecting.272* Virtually all clients should do this unless you really know what you273* are doing.274*/275if (!SSL_set1_host(ssl, hostname)) {276printf("Failed to set the certificate verification hostname");277goto end;278}279280/* Do the handshake with the server */281while ((ret = SSL_connect(ssl)) != 1) {282if (handle_io_failure(ssl, ret) == 1)283continue; /* Retry */284printf("Failed to connect to server\n");285goto end; /* Cannot retry: error */286}287288/* Write an HTTP GET request to the peer */289while (!SSL_write_ex(ssl, request_start, strlen(request_start), &written)) {290if (handle_io_failure(ssl, 0) == 1)291continue; /* Retry */292printf("Failed to write start of HTTP request\n");293goto end; /* Cannot retry: error */294}295while (!SSL_write_ex(ssl, hostname, strlen(hostname), &written)) {296if (handle_io_failure(ssl, 0) == 1)297continue; /* Retry */298printf("Failed to write hostname in HTTP request\n");299goto end; /* Cannot retry: error */300}301while (!SSL_write_ex(ssl, request_end, strlen(request_end), &written)) {302if (handle_io_failure(ssl, 0) == 1)303continue; /* Retry */304printf("Failed to write end of HTTP request\n");305goto end; /* Cannot retry: error */306}307308do {309/*310* Get up to sizeof(buf) bytes of the response. We keep reading until311* the server closes the connection.312*/313while (!eof && !SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {314switch (handle_io_failure(ssl, 0)) {315case 1:316continue; /* Retry */317case 0:318eof = 1;319continue;320case -1:321default:322printf("Failed reading remaining data\n");323goto end; /* Cannot retry: error */324}325}326/*327* OpenSSL does not guarantee that the returned data is a string or328* that it is NUL terminated so we use fwrite() to write the exact329* number of bytes that we read. The data could be non-printable or330* have NUL characters in the middle of it. For this simple example331* we're going to print it to stdout anyway.332*/333if (!eof)334fwrite(buf, 1, readbytes, stdout);335} while (!eof);336/* In case the response didn't finish with a newline we add one now */337printf("\n");338339/*340* The peer already shutdown gracefully (we know this because of the341* SSL_ERROR_ZERO_RETURN (i.e. EOF) above). We should do the same back.342*/343while ((ret = SSL_shutdown(ssl)) != 1) {344if (ret < 0 && handle_io_failure(ssl, ret) == 1)345continue; /* Retry */346/*347* ret == 0 is unexpected here because that means "we've sent a348* close_notify and we're waiting for one back". But we already know349* we got one from the peer because of the SSL_ERROR_ZERO_RETURN350* (i.e. EOF) above.351*/352printf("Error shutting down\n");353goto end; /* Cannot retry: error */354}355356/* Success! */357res = EXIT_SUCCESS;358end:359/*360* If something bad happened then we will dump the contents of the361* OpenSSL error stack to stderr. There might be some useful diagnostic362* information there.363*/364if (res == EXIT_FAILURE)365ERR_print_errors_fp(stderr);366367/*368* Free the resources we allocated. We do not free the BIO object here369* because ownership of it was immediately transferred to the SSL object370* via SSL_set_bio(). The BIO will be freed when we free the SSL object.371*/372SSL_free(ssl);373SSL_CTX_free(ctx);374return res;375}376377378