Path: blob/main/crypto/openssl/apps/lib/s_socket.c
103743 views
/*1* Copyright 1995-2026 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/* socket-related functions used by s_client and s_server */10#include <stdio.h>11#include <stdlib.h>12#include <string.h>13#include <errno.h>14#include <signal.h>15#include <openssl/opensslconf.h>1617/*18* With IPv6, it looks like Digital has mixed up the proper order of19* recursive header file inclusion, resulting in the compiler complaining20* that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is21* needed to have fileno() declared correctly... So let's define u_int22*/23#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)24#define __U_INT25typedef unsigned int u_int;26#endif2728#ifdef _WIN3229#include <process.h>3031/* MSVC renamed some POSIX functions to have an underscore prefix. */32#ifdef _MSC_VER33#define getpid _getpid34#endif35#endif3637#ifndef OPENSSL_NO_SOCK3839#include "internal/e_os.h"40#include "apps.h"41#include "s_apps.h"42#include "internal/sockets.h" /* for openssl_fdset() */4344#include <openssl/bio.h>45#include <openssl/err.h>4647/* Keep track of our peer's address for the cookie callback */48BIO_ADDR *ourpeer = NULL;4950/*51* init_client - helper routine to set up socket communication52* @sock: pointer to storage of resulting socket.53* @host: the hostname or path (for AF_UNIX) to connect to.54* @port: the port to connect to (ignored for AF_UNIX).55* @bindhost: source host or path (for AF_UNIX).56* @bindport: source port (ignored for AF_UNIX).57* @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or58* AF_UNSPEC59* @type: socket type, must be SOCK_STREAM or SOCK_DGRAM60* @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any)61* @tfo: flag to enable TCP Fast Open62* @doconn: whether we should call BIO_connect() on the socket63* @ba_ret: BIO_ADDR for the remote peer, to be freed by caller64*65* This will create a socket and use it to connect to a host:port, or if66* family == AF_UNIX, to the path found in host.67*68* If the host has more than one address, it will try them one by one until69* a successful connection is established. The resulting socket will be70* found in *sock on success, it will be given INVALID_SOCKET otherwise.71*72* Returns 1 on success, 0 on failure.73*/74int init_client(int *sock, const char *host, const char *port,75const char *bindhost, const char *bindport,76int family, int type, int protocol, int tfo, int doconn,77BIO_ADDR **ba_ret)78{79BIO_ADDRINFO *res = NULL;80BIO_ADDRINFO *bindaddr = NULL;81const BIO_ADDRINFO *ai = NULL;82const BIO_ADDRINFO *bi = NULL;83int found = 0;84int ret;85int options = 0;8687if (BIO_sock_init() != 1)88return 0;8990ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol,91&res);92if (ret == 0) {93ERR_print_errors(bio_err);94return 0;95}9697if (bindhost != NULL || bindport != NULL) {98ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT,99family, type, protocol, &bindaddr);100if (ret == 0) {101ERR_print_errors(bio_err);102goto out;103}104}105106ret = 0;107for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {108/* Admittedly, these checks are quite paranoid, we should not get109* anything in the BIO_ADDRINFO chain that we haven't110* asked for. */111OPENSSL_assert((family == AF_UNSPEC112|| family == BIO_ADDRINFO_family(ai))113&& (type == 0 || type == BIO_ADDRINFO_socktype(ai))114&& (protocol == 0115|| protocol == BIO_ADDRINFO_protocol(ai)));116117if (bindaddr != NULL) {118for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) {119if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai))120break;121}122if (bi == NULL)123continue;124++found;125}126127*sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai),128BIO_ADDRINFO_protocol(ai), 0);129if (*sock == INVALID_SOCKET) {130/* Maybe the kernel doesn't support the socket family, even if131* BIO_lookup() added it in the returned result...132*/133continue;134}135136if (bi != NULL) {137if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi),138BIO_SOCK_REUSEADDR)) {139BIO_closesocket(*sock);140*sock = INVALID_SOCKET;141break;142}143}144145#ifndef OPENSSL_NO_SCTP146if (protocol == IPPROTO_SCTP) {147/*148* For SCTP we have to set various options on the socket prior to149* connecting. This is done automatically by BIO_new_dgram_sctp().150* We don't actually need the created BIO though so we free it again151* immediately.152*/153BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE);154155if (tmpbio == NULL) {156BIO_closesocket(*sock);157*sock = INVALID_SOCKET;158continue;159}160BIO_free(tmpbio);161}162#endif163if (BIO_ADDRINFO_protocol(ai) == IPPROTO_TCP) {164options |= BIO_SOCK_NODELAY;165if (tfo)166options |= BIO_SOCK_TFO;167}168169if (doconn && !BIO_connect(*sock, BIO_ADDRINFO_address(ai), options)) {170BIO_closesocket(*sock);171*sock = INVALID_SOCKET;172continue;173}174175/* Save the address */176if (tfo || !doconn) {177if (ba_ret == NULL) {178BIO_printf(bio_err, "Internal error\n");179BIO_closesocket(*sock);180*sock = INVALID_SOCKET;181goto out;182}183184*ba_ret = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));185}186187/* Success, don't try any more addresses */188break;189}190191if (*sock == INVALID_SOCKET) {192if (bindaddr != NULL && !found) {193BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n",194#ifdef AF_INET6195BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " :196#endif197BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 "198: BIO_ADDRINFO_family(res) == AF_UNIX ? "unix "199: "",200bindhost != NULL ? bindhost : "",201bindport != NULL ? ":" : "",202bindport != NULL ? bindport : "");203ERR_clear_error();204ret = 0;205}206ERR_print_errors(bio_err);207} else {208char *hostname = NULL;209210hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1);211if (hostname != NULL) {212BIO_printf(bio_err, "Connecting to %s\n", hostname);213OPENSSL_free(hostname);214}215/* Remove any stale errors from previous connection attempts */216ERR_clear_error();217ret = 1;218}219out:220if (bindaddr != NULL) {221BIO_ADDRINFO_free(bindaddr);222}223BIO_ADDRINFO_free(res);224return ret;225}226227void get_sock_info_address(int asock, char **hostname, char **service)228{229union BIO_sock_info_u info;230231if (hostname != NULL)232*hostname = NULL;233if (service != NULL)234*service = NULL;235236if ((info.addr = BIO_ADDR_new()) != NULL237&& BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)) {238if (hostname != NULL)239*hostname = BIO_ADDR_hostname_string(info.addr, 1);240if (service != NULL)241*service = BIO_ADDR_service_string(info.addr, 1);242}243BIO_ADDR_free(info.addr);244}245246int report_server_accept(BIO *out, int asock, int with_address, int with_pid)247{248int success = 1;249250if (BIO_printf(out, "ACCEPT") <= 0)251return 0;252if (with_address) {253char *hostname, *service;254255get_sock_info_address(asock, &hostname, &service);256success = hostname != NULL && service != NULL;257if (success)258success = BIO_printf(out,259strchr(hostname, ':') == NULL260? /* IPv4 */ " %s:%s"261: /* IPv6 */ " [%s]:%s",262hostname, service)263> 0;264else265(void)BIO_printf(out, "unknown:error\n");266OPENSSL_free(hostname);267OPENSSL_free(service);268}269if (with_pid)270success *= BIO_printf(out, " PID=%d", getpid()) > 0;271success *= BIO_printf(out, "\n") > 0;272(void)BIO_flush(out);273274return success;275}276277/*278* do_server - helper routine to perform a server operation279* @accept_sock: pointer to storage of resulting socket.280* @host: the hostname or path (for AF_UNIX) to connect to.281* @port: the port to connect to (ignored for AF_UNIX).282* @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or283* AF_UNSPEC284* @type: socket type, must be SOCK_STREAM or SOCK_DGRAM285* @cb: pointer to a function that receives the accepted socket and286* should perform the communication with the connecting client.287* @context: pointer to memory that's passed verbatim to the cb function.288* @naccept: number of times an incoming connect should be accepted. If -1,289* unlimited number.290*291* This will create a socket and use it to listen to a host:port, or if292* family == AF_UNIX, to the path found in host, then start accepting293* incoming connections and run cb on the resulting socket.294*295* 0 on failure, something other on success.296*/297int do_server(int *accept_sock, const char *host, const char *port,298int family, int type, int protocol, do_server_cb cb,299unsigned char *context, int naccept, BIO *bio_s_out,300int tfo)301{302int asock = 0;303int sock;304int i;305BIO_ADDRINFO *res = NULL;306const BIO_ADDRINFO *next;307int sock_family, sock_type, sock_protocol, sock_port;308const BIO_ADDR *sock_address;309int sock_family_fallback = AF_UNSPEC;310const BIO_ADDR *sock_address_fallback = NULL;311int sock_options = BIO_SOCK_REUSEADDR;312int ret = 0;313314if (BIO_sock_init() != 1)315return 0;316317if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol,318&res)) {319ERR_print_errors(bio_err);320return 0;321}322323/* Admittedly, these checks are quite paranoid, we should not get324* anything in the BIO_ADDRINFO chain that we haven't asked for */325OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res))326&& (type == 0 || type == BIO_ADDRINFO_socktype(res))327&& (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res)));328329sock_family = BIO_ADDRINFO_family(res);330sock_type = BIO_ADDRINFO_socktype(res);331sock_protocol = BIO_ADDRINFO_protocol(res);332sock_address = BIO_ADDRINFO_address(res);333next = BIO_ADDRINFO_next(res);334if (tfo && sock_type == SOCK_STREAM)335sock_options |= BIO_SOCK_TFO;336#ifdef AF_INET6337if (sock_family == AF_INET6)338sock_options |= BIO_SOCK_V6_ONLY;339if (next != NULL340&& BIO_ADDRINFO_socktype(next) == sock_type341&& BIO_ADDRINFO_protocol(next) == sock_protocol) {342if (sock_family == AF_INET343&& BIO_ADDRINFO_family(next) == AF_INET6) {344/* In case AF_INET6 is returned but not supported by the345* kernel, retry with the first detected address family */346sock_family_fallback = sock_family;347sock_address_fallback = sock_address;348sock_family = AF_INET6;349sock_address = BIO_ADDRINFO_address(next);350} else if (sock_family == AF_INET6351&& BIO_ADDRINFO_family(next) == AF_INET) {352sock_options &= ~BIO_SOCK_V6_ONLY;353}354}355#endif356357asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);358if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {359asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);360sock_address = sock_address_fallback;361}362if (asock == INVALID_SOCKET363|| !BIO_listen(asock, sock_address, sock_options)) {364BIO_ADDRINFO_free(res);365ERR_print_errors(bio_err);366if (asock != INVALID_SOCKET)367BIO_closesocket(asock);368goto end;369}370371#ifndef OPENSSL_NO_SCTP372if (protocol == IPPROTO_SCTP) {373/*374* For SCTP we have to set various options on the socket prior to375* accepting. This is done automatically by BIO_new_dgram_sctp().376* We don't actually need the created BIO though so we free it again377* immediately.378*/379BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE);380381if (tmpbio == NULL) {382BIO_ADDRINFO_free(res);383BIO_closesocket(asock);384ERR_print_errors(bio_err);385goto end;386}387BIO_free(tmpbio);388}389#endif390391sock_port = BIO_ADDR_rawport(sock_address);392393BIO_ADDRINFO_free(res);394res = NULL;395396if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) {397BIO_closesocket(asock);398ERR_print_errors(bio_err);399goto end;400}401402if (accept_sock != NULL)403*accept_sock = asock;404for (;;) {405char sink[64];406struct timeval timeout;407fd_set readfds;408409if (type == SOCK_STREAM) {410BIO_ADDR_free(ourpeer);411ourpeer = BIO_ADDR_new();412if (ourpeer == NULL) {413BIO_closesocket(asock);414ERR_print_errors(bio_err);415goto end;416}417do {418sock = BIO_accept_ex(asock, ourpeer, 0);419} while (sock < 0 && BIO_sock_should_retry(sock));420if (sock < 0) {421ERR_print_errors(bio_err);422BIO_closesocket(asock);423break;424}425426if (naccept != -1)427naccept--;428429BIO_set_tcp_ndelay(sock, 1);430i = (*cb)(sock, type, protocol, context);431432/*433* If we ended with an alert being sent, but still with data in the434* network buffer to be read, then calling BIO_closesocket() will435* result in a TCP-RST being sent. On some platforms (notably436* Windows) then this will result in the peer immediately abandoning437* the connection including any buffered alert data before it has438* had a chance to be read. Shutting down the sending side first,439* and then closing the socket sends TCP-FIN first followed by440* TCP-RST. This seems to allow the peer to read the alert data.441*/442shutdown(sock, 1); /* SHUT_WR */443/*444* We just said we have nothing else to say, but it doesn't mean445* that the other side has nothing. It's even recommended to446* consume incoming data. [In testing context this ensures that447* alerts are passed on...]448*/449timeout.tv_sec = 0;450timeout.tv_usec = 500000; /* some extreme round-trip */451do {452FD_ZERO(&readfds);453openssl_fdset(sock, &readfds);454} while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0455&& readsocket(sock, sink, sizeof(sink)) > 0);456457BIO_closesocket(sock);458} else {459if (naccept != -1)460naccept--;461462i = (*cb)(asock, type, protocol, context);463}464465if (i < 0 || naccept == 0) {466BIO_closesocket(asock);467asock = INVALID_SOCKET;468ret = i;469break;470}471}472end:473#ifdef AF_UNIX474if (family == AF_UNIX)475unlink(host);476#endif477BIO_ADDR_free(ourpeer);478ourpeer = NULL;479return ret;480}481482void do_ssl_shutdown(SSL *ssl)483{484int ret;485486do {487/* We only do unidirectional shutdown */488ret = SSL_shutdown(ssl);489if (ret < 0) {490switch (SSL_get_error(ssl, ret)) {491case SSL_ERROR_WANT_READ:492case SSL_ERROR_WANT_WRITE:493case SSL_ERROR_WANT_ASYNC:494case SSL_ERROR_WANT_ASYNC_JOB:495/* We just do busy waiting. Nothing clever */496continue;497}498ret = 0;499}500} while (ret < 0);501}502503#endif /* OPENSSL_NO_SOCK */504505506