HTTP client: Fix cleanup of TLS BIO via 'bio_update_fn' callback function
[openssl.git] / apps / cmp.c
index 4a8b6e75fb2d07ee5cb9460358b17c6ac9aaa355..0f810129b3924cc0e55b8fbbcfbbdfa85c13c823 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright Nokia 2007-2019
  * Copyright Siemens AG 2015-2019
  *
@@ -9,6 +9,8 @@
  * https://www.openssl.org/source/license.html
  */
 
+/* This app is disabled when OPENSSL_NO_CMP is defined. */
+
 #include <string.h>
 #include <ctype.h>
 
@@ -20,7 +22,7 @@
 #include "cmp_mock_srv.h"
 
 /* tweaks needed due to missing unistd.h on Windows */
-#ifdef _WIN32
+#if defined(_WIN32) && !defined(__BORLANDC__)
 # define access _access
 #endif
 #ifndef F_OK
 #include <openssl/objects.h>
 #include <openssl/x509.h>
 
-DEFINE_STACK_OF(X509)
-DEFINE_STACK_OF(X509_EXTENSION)
-DEFINE_STACK_OF(OSSL_CMP_ITAV)
-
+static char *prog;
 static char *opt_config = NULL;
 #define CMP_SECTION "cmp"
 #define SECTION_NAME_MAX 40 /* max length of section name */
@@ -53,10 +52,6 @@ static char *opt_config = NULL;
 static char *opt_section = CMP_SECTION;
 static int opt_verbosity = OSSL_CMP_LOG_INFO;
 
-#undef PROG
-#define PROG cmp_main
-static char *prog = "cmp";
-
 static int read_config(void);
 
 static CONF *conf = NULL; /* OpenSSL config file context structure */
@@ -73,12 +68,14 @@ typedef enum {
 } cmp_cmd_t;
 
 /* message transfer */
+#ifndef OPENSSL_NO_SOCK
 static char *opt_server = NULL;
-static char server_port_s[32] = { '\0' };
-static int server_port = 0;
 static char *opt_proxy = NULL;
 static char *opt_no_proxy = NULL;
-static char *opt_path = "/";
+#endif
+static char *opt_recipient = NULL;
+static char *opt_path = NULL;
+static int opt_keep_alive = 1;
 static int opt_msg_timeout = -1;
 static int opt_total_timeout = -1;
 
@@ -86,7 +83,6 @@ static int opt_total_timeout = -1;
 static char *opt_trusted = NULL;
 static char *opt_untrusted = NULL;
 static char *opt_srvcert = NULL;
-static char *opt_recipient = NULL;
 static char *opt_expect_sender = NULL;
 static int opt_ignore_keyusage = 0;
 static int opt_unprotected_errors = 0;
@@ -97,6 +93,7 @@ static char *opt_cacertsout = NULL;
 static char *opt_ref = NULL;
 static char *opt_secret = NULL;
 static char *opt_cert = NULL;
+static char *opt_own_trusted = NULL;
 static char *opt_key = NULL;
 static char *opt_keypass = NULL;
 static char *opt_digest = NULL;
@@ -129,6 +126,7 @@ static char *opt_out_trusted = NULL;
 static int opt_implicit_confirm = 0;
 static int opt_disable_confirm = 0;
 static char *opt_certout = NULL;
+static char *opt_chainout = NULL;
 
 /* certificate enrollment and revocation */
 static char *opt_oldcert = NULL;
@@ -137,11 +135,12 @@ static int opt_revreason = CRL_REASON_NONE;
 /* credentials format */
 static char *opt_certform_s = "PEM";
 static int opt_certform = FORMAT_PEM;
-static char *opt_keyform_s = "PEM";
-static int opt_keyform = FORMAT_PEM;
+static char *opt_keyform_s = NULL;
+static int opt_keyform = FORMAT_UNDEF;
 static char *opt_otherpass = NULL;
 static char *opt_engine = NULL;
 
+#ifndef OPENSSL_NO_SOCK
 /* TLS connection */
 static int opt_tls_used = 0;
 static char *opt_tls_cert = NULL;
@@ -150,6 +149,7 @@ static char *opt_tls_keypass = NULL;
 static char *opt_tls_extra = NULL;
 static char *opt_tls_trusted = NULL;
 static char *opt_tls_host = NULL;
+#endif
 
 /* client-side debugging */
 static int opt_batch = 0;
@@ -161,10 +161,11 @@ static char *opt_rspin = NULL;
 static char *opt_rspout = NULL;
 static int opt_use_mock_srv = 0;
 
-/* server-side debugging */
+/* mock server */
+#ifndef OPENSSL_NO_SOCK
 static char *opt_port = NULL;
 static int opt_max_msgs = 0;
-
+#endif
 static char *opt_srv_ref = NULL;
 static char *opt_srv_secret = NULL;
 static char *opt_srv_cert = NULL;
@@ -194,7 +195,7 @@ static int opt_accept_raverified = 0;
 static X509_VERIFY_PARAM *vpm = NULL;
 
 typedef enum OPTION_choice {
-    OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
+    OPT_COMMON,
     OPT_CONFIG, OPT_SECTION, OPT_VERBOSITY,
 
     OPT_CMD, OPT_INFOTYPE, OPT_GENINFO,
@@ -205,19 +206,22 @@ typedef enum OPTION_choice {
     OPT_POLICIES, OPT_POLICY_OIDS, OPT_POLICY_OIDS_CRITICAL,
     OPT_POPO, OPT_CSR,
     OPT_OUT_TRUSTED, OPT_IMPLICIT_CONFIRM, OPT_DISABLE_CONFIRM,
-    OPT_CERTOUT,
+    OPT_CERTOUT, OPT_CHAINOUT,
 
     OPT_OLDCERT, OPT_REVREASON,
 
-    OPT_SERVER, OPT_PROXY, OPT_NO_PROXY, OPT_PATH,
-    OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT,
+#ifndef OPENSSL_NO_SOCK
+    OPT_SERVER, OPT_PROXY, OPT_NO_PROXY,
+#endif
+    OPT_RECIPIENT, OPT_PATH,
+    OPT_KEEP_ALIVE, OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT,
 
     OPT_TRUSTED, OPT_UNTRUSTED, OPT_SRVCERT,
-    OPT_RECIPIENT, OPT_EXPECT_SENDER,
+    OPT_EXPECT_SENDER,
     OPT_IGNORE_KEYUSAGE, OPT_UNPROTECTED_ERRORS,
     OPT_EXTRACERTSOUT, OPT_CACERTSOUT,
 
-    OPT_REF, OPT_SECRET, OPT_CERT, OPT_KEY, OPT_KEYPASS,
+    OPT_REF, OPT_SECRET, OPT_CERT, OPT_OWN_TRUSTED, OPT_KEY, OPT_KEYPASS,
     OPT_DIGEST, OPT_MAC, OPT_EXTRACERTS,
     OPT_UNPROTECTED_REQUESTS,
 
@@ -227,15 +231,21 @@ typedef enum OPTION_choice {
     OPT_ENGINE,
 #endif
     OPT_PROV_ENUM,
+    OPT_R_ENUM,
 
+#ifndef OPENSSL_NO_SOCK
     OPT_TLS_USED, OPT_TLS_CERT, OPT_TLS_KEY,
     OPT_TLS_KEYPASS,
     OPT_TLS_EXTRA, OPT_TLS_TRUSTED, OPT_TLS_HOST,
+#endif
 
     OPT_BATCH, OPT_REPEAT,
     OPT_REQIN, OPT_REQIN_NEW_TID, OPT_REQOUT, OPT_RSPIN, OPT_RSPOUT,
+    OPT_USE_MOCK_SRV,
 
-    OPT_USE_MOCK_SRV, OPT_PORT, OPT_MAX_MSGS,
+#ifndef OPENSSL_NO_SOCK
+    OPT_PORT, OPT_MAX_MSGS,
+#endif
     OPT_SRV_REF, OPT_SRV_SECRET,
     OPT_SRV_CERT, OPT_SRV_KEY, OPT_SRV_KEYPASS,
     OPT_SRV_TRUSTED, OPT_SRV_UNTRUSTED,
@@ -258,7 +268,7 @@ const OPTIONS cmp_options[] = {
      "Configuration file to use. \"\" = none. Default from env variable OPENSSL_CONF"},
     {"section", OPT_SECTION, 's',
      "Section(s) in config file to get options from. \"\" = 'default'. Default 'cmp'"},
-    {"verbosity", OPT_VERBOSITY, 'n',
+    {"verbosity", OPT_VERBOSITY, 'N',
      "Log level; 3=ERR, 4=WARN, 6=INFO, 7=DEBUG, 8=TRACE. Default 6 = INFO"},
 
     OPT_SECTION("Generic message"),
@@ -268,7 +278,7 @@ const OPTIONS cmp_options[] = {
     {"geninfo", OPT_GENINFO, 's',
      "generalInfo integer values to place in request PKIHeader with given OID"},
     {OPT_MORE_STR, 0, 0,
-     "specified in the form <OID>:int:<n>, e.g. \"1.2.3:int:987\""},
+     "specified in the form <OID>:int:<n>, e.g. \"1.2.3.4:int:56789\""},
 
     OPT_SECTION("Certificate enrollment"),
     {"newkey", OPT_NEWKEY, 's',
@@ -277,17 +287,19 @@ const OPTIONS cmp_options[] = {
     {"subject", OPT_SUBJECT, 's',
      "Distinguished Name (DN) of subject to use in the requested cert template"},
     {OPT_MORE_STR, 0, 0,
-     "For kur, default is the subject DN of the reference cert (see -oldcert);"},
+     "For kur, default is subject of -csr arg or reference cert (see -oldcert)"},
     {OPT_MORE_STR, 0, 0,
      "this default is used for ir and cr only if no Subject Alt Names are set"},
     {"issuer", OPT_ISSUER, 's',
      "DN of the issuer to place in the requested certificate template"},
     {OPT_MORE_STR, 0, 0,
      "also used as recipient if neither -recipient nor -srvcert are given"},
-    {"days", OPT_DAYS, 'n',
+    {"days", OPT_DAYS, 'N',
      "Requested validity time of the new certificate in number of days"},
     {"reqexts", OPT_REQEXTS, 's',
-     "Name of config file section defining certificate request extensions"},
+     "Name of config file section defining certificate request extensions."},
+    {OPT_MORE_STR, 0, 0,
+     "Augments or replaces any extensions contained CSR given with -csr"},
     {"sans", OPT_SANS, 's',
      "Subject Alt Names (IPADDR/DNS/URI) to add as (critical) cert req extension"},
     {"san_nodefault", OPT_SAN_NODEFAULT, '-',
@@ -303,7 +315,7 @@ const OPTIONS cmp_options[] = {
     {OPT_MORE_STR, 0, 0,
      "-1 = NONE, 0 = RAVERIFIED, 1 = SIGNATURE (default), 2 = KEYENC"},
     {"csr", OPT_CSR, 's',
-     "CSR file in PKCS#10 format to use in p10cr for legacy support"},
+     "PKCS#10 CSR file in PEM or DER format to convert or to use in p10cr"},
     {"out_trusted", OPT_OUT_TRUSTED, 's',
      "Certificates to trust when verifying newly enrolled certificates"},
     {"implicit_confirm", OPT_IMPLICIT_CONFIRM, '-',
@@ -314,6 +326,8 @@ const OPTIONS cmp_options[] = {
      "confirmation. WARNING: This leads to behavior violating RFC 4210"},
     {"certout", OPT_CERTOUT, 's',
      "File to save newly enrolled certificate"},
+    {"chainout", OPT_CHAINOUT, 's',
+     "File to save the chain of newly enrolled certificate"},
 
     OPT_SECTION("Certificate enrollment and revocation"),
 
@@ -322,28 +336,37 @@ const OPTIONS cmp_options[] = {
     {OPT_MORE_STR, 0, 0,
      "also used as reference (defaulting to -cert) for subject DN and SANs."},
     {OPT_MORE_STR, 0, 0,
-     "Its issuer is used as recipient unless -recipient, -srvcert, or -issuer given"},
+     "Issuer is used as recipient unless -recipient, -srvcert, or -issuer given"},
     {"revreason", OPT_REVREASON, 'n',
      "Reason code to include in revocation request (rr); possible values:"},
     {OPT_MORE_STR, 0, 0,
      "0..6, 8..10 (see RFC5280, 5.3.1) or -1. Default -1 = none included"},
 
     OPT_SECTION("Message transfer"),
+#ifdef OPENSSL_NO_SOCK
+    {OPT_MORE_STR, 0, 0,
+     "NOTE: -server, -proxy, and -no_proxy not supported due to no-sock build"},
+#else
     {"server", OPT_SERVER, 's',
-     "[http[s]://]address[:port] of CMP server. Default port 80 or 443."},
+     "[http[s]://]address[:port][/path] of CMP server. Default port 80 or 443."},
     {OPT_MORE_STR, 0, 0,
-     "The address may be a DNS name or an IP address"},
+     "address may be a DNS name or an IP address; path can be overridden by -path"},
     {"proxy", OPT_PROXY, 's',
      "[http[s]://]address[:port][/path] of HTTP(S) proxy to use; path is ignored"},
     {"no_proxy", OPT_NO_PROXY, 's',
      "List of addresses of servers not to use HTTP(S) proxy for"},
     {OPT_MORE_STR, 0, 0,
      "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
+#endif
+    {"recipient", OPT_RECIPIENT, 's',
+     "DN of CA. Default: subject of -srvcert, -issuer, issuer of -oldcert or -cert"},
     {"path", OPT_PATH, 's',
-     "HTTP path (aka CMP alias) at the CMP server. Default \"/\""},
-    {"msg_timeout", OPT_MSG_TIMEOUT, 'n',
-     "Timeout per CMP message round trip (or 0 for none). Default 120 seconds"},
-    {"total_timeout", OPT_TOTAL_TIMEOUT, 'n',
+     "HTTP path (aka CMP alias) at the CMP server. Default from -server, else \"/\""},
+    {"keep_alive", OPT_KEEP_ALIVE, 'N',
+     "Persistent HTTP connections. 0: no, 1 (the default): request, 2: require"},
+    {"msg_timeout", OPT_MSG_TIMEOUT, 'N',
+     "Number of seconds allowed per CMP message round trip, or 0 for infinite"},
+    {"total_timeout", OPT_TOTAL_TIMEOUT, 'N',
      "Overall time an enrollment incl. polling may take. Default 0 = infinite"},
 
     OPT_SECTION("Server authentication"),
@@ -354,8 +377,6 @@ const OPTIONS cmp_options[] = {
      "Intermediate CA certs for chain construction for CMP/TLS/enrolled certs"},
     {"srvcert", OPT_SRVCERT, 's',
      "Server cert to pin and trust directly when verifying signed CMP responses"},
-    {"recipient", OPT_RECIPIENT, 's',
-     "DN of CA. Default: subject of -srvcert, -issuer, issuer of -oldcert or -cert"},
     {"expect_sender", OPT_EXPECT_SENDER, 's',
      "DN of expected sender of responses. Defaults to subject of -srvcert, if any"},
     {"ignore_keyusage", OPT_IGNORE_KEYUSAGE, '-',
@@ -375,20 +396,26 @@ const OPTIONS cmp_options[] = {
     {"ref", OPT_REF, 's',
      "Reference value to use as senderKID in case no -cert is given"},
     {"secret", OPT_SECRET, 's',
-     "Password source for client authentication with a pre-shared key (secret)"},
+     "Prefer PBM (over signatures) for protecting msgs with given password source"},
     {"cert", OPT_CERT, 's',
-     "Client's current certificate (needed unless using -secret for PBM);"},
+     "Client's CMP signer certificate; its public key must match the -key argument"},
+    {OPT_MORE_STR, 0, 0,
+     "This also used as default reference for subject DN and SANs."},
     {OPT_MORE_STR, 0, 0,
-     "any further certs included are appended in extraCerts field"},
-    {"key", OPT_KEY, 's', "Private key for the client's current certificate"},
+     "Any further certs included are appended to the untrusted certs"},
+    {"own_trusted", OPT_OWN_TRUSTED, 's',
+     "Optional certs to verify chain building for own CMP signer cert"},
+    {"key", OPT_KEY, 's', "CMP signer private key, not used when -secret given"},
     {"keypass", OPT_KEYPASS, 's',
-     "Client private key (and cert and old cert file) pass phrase source"},
+     "Client private key (and cert and old cert) pass phrase source"},
     {"digest", OPT_DIGEST, 's',
      "Digest to use in message protection and POPO signatures. Default \"sha256\""},
     {"mac", OPT_MAC, 's',
      "MAC algorithm to use in PBM-based message protection. Default \"hmac-sha1\""},
     {"extracerts", OPT_EXTRACERTS, 's',
-     "Certificates to append in extraCerts field of outgoing messages"},
+     "Certificates to append in extraCerts field of outgoing messages."},
+    {OPT_MORE_STR, 0, 0,
+     "This can be used as the default CMP signer cert chain to include"},
     {"unprotected_requests", OPT_UNPROTECTED_REQUESTS, '-',
      "Send messages without CMP-level protection"},
 
@@ -403,15 +430,16 @@ const OPTIONS cmp_options[] = {
     {"engine", OPT_ENGINE, 's',
      "Use crypto engine with given identifier, possibly a hardware device."},
     {OPT_MORE_STR, 0, 0,
-     "Engines may be defined in OpenSSL config file engine section."},
-    {OPT_MORE_STR, 0, 0,
-     "Options like -key specifying keys held in the engine can give key IDs"},
-    {OPT_MORE_STR, 0, 0,
-     "prefixed by 'engine:', e.g. '-key engine:pkcs11:object=mykey;pin-value=1234'"},
+     "Engines may also be defined in OpenSSL config file engine section."},
 #endif
     OPT_PROV_OPTIONS,
+    OPT_R_OPTIONS,
 
     OPT_SECTION("TLS connection"),
+#ifdef OPENSSL_NO_SOCK
+    {OPT_MORE_STR, 0, 0,
+     "NOTE: -tls_used and all other TLS options not supported due to no-sock build"},
+#else
     {"tls_used", OPT_TLS_USED, '-',
      "Enable using TLS (also when other TLS options are not set)"},
     {"tls_cert", OPT_TLS_CERT, 's',
@@ -419,7 +447,7 @@ const OPTIONS cmp_options[] = {
     {"tls_key", OPT_TLS_KEY, 's',
      "Private key for the client's TLS certificate"},
     {"tls_keypass", OPT_TLS_KEYPASS, 's',
-     "Pass phrase source for the client's private TLS key (and TLS cert file)"},
+     "Pass phrase source for the client's private TLS key (and TLS cert)"},
     {"tls_extra", OPT_TLS_EXTRA, 's',
      "Extra certificates to provide to TLS server during TLS handshake"},
     {"tls_trusted", OPT_TLS_TRUSTED, 's',
@@ -427,12 +455,13 @@ const OPTIONS cmp_options[] = {
     {OPT_MORE_STR, 0, 0, "this implies host name validation"},
     {"tls_host", OPT_TLS_HOST, 's',
      "Address to be checked (rather than -server) during TLS host name validation"},
+#endif
 
     OPT_SECTION("Client-side debugging"),
     {"batch", OPT_BATCH, '-',
      "Do not interactively prompt for input when a password is required etc."},
-    {"repeat", OPT_REPEAT, 'n',
-     "Invoke the transaction the given number of times. Default 1"},
+    {"repeat", OPT_REPEAT, 'p',
+     "Invoke the transaction the given positive number of times. Default 1"},
     {"reqin", OPT_REQIN, 's', "Take sequence of CMP requests from file(s)"},
     {"reqin_new_tid", OPT_REQIN_NEW_TID, '-',
      "Use fresh transactionID for CMP requests read from -reqin"},
@@ -441,12 +470,19 @@ const OPTIONS cmp_options[] = {
      "Process sequence of CMP responses provided in file(s), skipping server"},
     {"rspout", OPT_RSPOUT, 's', "Save sequence of CMP responses to file(s)"},
 
-    {"use_mock_srv", OPT_USE_MOCK_SRV, '-', "Use mock server at API level, bypassing HTTP"},
+    {"use_mock_srv", OPT_USE_MOCK_SRV, '-',
+     "Use internal mock server at API level, bypassing socket-based HTTP"},
 
     OPT_SECTION("Mock server"),
-    {"port", OPT_PORT, 's', "Act as HTTP mock server listening on given port"},
-    {"max_msgs", OPT_MAX_MSGS, 'n',
+#ifdef OPENSSL_NO_SOCK
+    {OPT_MORE_STR, 0, 0,
+     "NOTE: -port and -max_msgs not supported due to no-sock build"},
+#else
+    {"port", OPT_PORT, 's',
+     "Act as HTTP-based mock server listening on given port"},
+    {"max_msgs", OPT_MAX_MSGS, 'N',
      "max number of messages handled by HTTP mock server. Default: 0 = unlimited"},
+#endif
 
     {"srv_ref", OPT_SRV_REF, 's',
      "Reference value to use as senderKID of server in case no -srv_cert is given"},
@@ -456,7 +492,7 @@ const OPTIONS cmp_options[] = {
     {"srv_key", OPT_SRV_KEY, 's',
      "Private key used by the server for signing messages"},
     {"srv_keypass", OPT_SRV_KEYPASS, 's',
-     "Server private key (and cert) file pass phrase source"},
+     "Server private key (and cert) pass phrase source"},
 
     {"srv_trusted", OPT_SRV_TRUSTED, 's',
      "Trusted certificates for client authentication"},
@@ -468,18 +504,18 @@ const OPTIONS cmp_options[] = {
      "Extra certificates to be included in mock certification responses"},
     {"rsp_capubs", OPT_RSP_CAPUBS, 's',
      "CA certificates to be included in mock ip response"},
-    {"poll_count", OPT_POLL_COUNT, 'n',
+    {"poll_count", OPT_POLL_COUNT, 'N',
      "Number of times the client must poll before receiving a certificate"},
-    {"check_after", OPT_CHECK_AFTER, 'n',
+    {"check_after", OPT_CHECK_AFTER, 'N',
      "The check_after value (time to wait) to include in poll response"},
     {"grant_implicitconf", OPT_GRANT_IMPLICITCONF, '-',
      "Grant implicit confirmation of newly enrolled certificate"},
 
-    {"pkistatus", OPT_PKISTATUS, 'n',
+    {"pkistatus", OPT_PKISTATUS, 'N',
      "PKIStatus to be included in server response. Possible values: 0..6"},
-    {"failure", OPT_FAILURE, 'n',
+    {"failure", OPT_FAILURE, 'N',
      "A single failure info bit number to include in server response, 0..26"},
-    {"failurebits", OPT_FAILUREBITS, 'n',
+    {"failurebits", OPT_FAILUREBITS, 'N',
      "Number representing failure bits to include in server response, 0..2^27 - 1"},
     {"statusstring", OPT_STATUSSTRING, 's',
      "Status string to be included in server response"},
@@ -521,19 +557,23 @@ static varref cmp_vars[] = { /* must be in same order as enumerated above! */
     {(char **)&opt_popo}, {&opt_csr},
     {&opt_out_trusted},
     {(char **)&opt_implicit_confirm}, {(char **)&opt_disable_confirm},
-    {&opt_certout},
+    {&opt_certout}, {&opt_chainout},
 
     {&opt_oldcert}, {(char **)&opt_revreason},
 
-    {&opt_server}, {&opt_proxy}, {&opt_no_proxy}, {&opt_path},
+#ifndef OPENSSL_NO_SOCK
+    {&opt_server}, {&opt_proxy}, {&opt_no_proxy},
+#endif
+    {&opt_recipient}, {&opt_path}, {(char **)&opt_keep_alive},
     {(char **)&opt_msg_timeout}, {(char **)&opt_total_timeout},
 
     {&opt_trusted}, {&opt_untrusted}, {&opt_srvcert},
-    {&opt_recipient}, {&opt_expect_sender},
+    {&opt_expect_sender},
     {(char **)&opt_ignore_keyusage}, {(char **)&opt_unprotected_errors},
     {&opt_extracertsout}, {&opt_cacertsout},
 
-    {&opt_ref}, {&opt_secret}, {&opt_cert}, {&opt_key}, {&opt_keypass},
+    {&opt_ref}, {&opt_secret},
+    {&opt_cert}, {&opt_own_trusted}, {&opt_key}, {&opt_keypass},
     {&opt_digest}, {&opt_mac}, {&opt_extracerts},
     {(char **)&opt_unprotected_requests},
 
@@ -543,15 +583,20 @@ static varref cmp_vars[] = { /* must be in same order as enumerated above! */
     {&opt_engine},
 #endif
 
+#ifndef OPENSSL_NO_SOCK
     {(char **)&opt_tls_used}, {&opt_tls_cert}, {&opt_tls_key},
     {&opt_tls_keypass},
     {&opt_tls_extra}, {&opt_tls_trusted}, {&opt_tls_host},
+#endif
 
     {(char **)&opt_batch}, {(char **)&opt_repeat},
     {&opt_reqin}, {(char **)&opt_reqin_new_tid},
     {&opt_reqout}, {&opt_rspin}, {&opt_rspout},
 
-    {(char **)&opt_use_mock_srv}, {&opt_port}, {(char **)&opt_max_msgs},
+    {(char **)&opt_use_mock_srv},
+#ifndef OPENSSL_NO_SOCK
+    {&opt_port}, {(char **)&opt_max_msgs},
+#endif
     {&opt_srv_ref}, {&opt_srv_secret},
     {&opt_srv_cert}, {&opt_srv_key}, {&opt_srv_keypass},
     {&opt_srv_trusted}, {&opt_srv_untrusted},
@@ -604,6 +649,12 @@ static int print_to_bio_out(const char *func, const char *file, int line,
     return OSSL_CMP_print_to_bio(bio_out, func, file, line, level, msg);
 }
 
+static int print_to_bio_err(const char *func, const char *file, int line,
+                            OSSL_CMP_severity level, const char *msg)
+{
+    return OSSL_CMP_print_to_bio(bio_err, func, file, line, level, msg);
+}
+
 static int set_verbosity(int level)
 {
     if (level < OSSL_CMP_LOG_EMERG || level > OSSL_CMP_LOG_MAX) {
@@ -614,25 +665,6 @@ static int set_verbosity(int level)
     return 1;
 }
 
-static char *next_item(char *opt) /* in list separated by comma and/or space */
-{
-    /* advance to separator (comma or whitespace), if any */
-    while (*opt != ',' && !isspace(*opt) && *opt != '\0') {
-        if (*opt == '\\' && opt[1] != '\0')
-            /* skip and unescape '\' escaped char */
-            memmove(opt, opt + 1, strlen(opt));
-        opt++;
-    }
-    if (*opt != '\0') {
-        /* terminate current item */
-        *opt++ = '\0';
-        /* skip over any whitespace after separator */
-        while (isspace(*opt))
-            opt++;
-    }
-    return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
-}
-
 static EVP_PKEY *load_key_pwd(const char *uri, int format,
                               const char *pass, ENGINE *eng, const char *desc)
 {
@@ -648,118 +680,41 @@ static X509 *load_cert_pwd(const char *uri, const char *pass, const char *desc)
     X509 *cert;
     char *pass_string = get_passwd(pass, desc);
 
-    cert = load_cert_pass(uri, 0, pass_string, desc);
+    cert = load_cert_pass(uri, FORMAT_UNDEF, 0, pass_string, desc);
     clear_free(pass_string);
     return cert;
 }
 
-/* TODO potentially move this and related functions to apps/lib/apps.c */
-static int adjust_format(const char **infile, int format, int engine_ok)
-{
-    if (!strncasecmp(*infile, "http://", 7)
-            || !strncasecmp(*infile, "https://", 8)) {
-        format = FORMAT_HTTP;
-    } else if (engine_ok && strncasecmp(*infile, "engine:", 7) == 0) {
-        *infile += 7;
-        format = FORMAT_ENGINE;
-    } else {
-        if (strncasecmp(*infile, "file:", 5) == 0)
-            *infile += 5;
-        /*
-         * the following is a heuristic whether first to try PEM or DER
-         * or PKCS12 as the input format for files
-         */
-        if (strlen(*infile) >= 4) {
-            const char *extension = *infile + strlen(*infile) - 4;
-
-            if (strncasecmp(extension, ".crt", 4) == 0
-                    || strncasecmp(extension, ".pem", 4) == 0)
-                /* weak recognition of PEM format */
-                format = FORMAT_PEM;
-            else if (strncasecmp(extension, ".cer", 4) == 0
-                         || strncasecmp(extension, ".der", 4) == 0)
-                /* weak recognition of DER format */
-                format = FORMAT_ASN1;
-            else if (strncasecmp(extension, ".p12", 4) == 0)
-                /* weak recognition of PKCS#12 format */
-                format = FORMAT_PKCS12;
-            /* else retain given format */
-        }
-    }
-    return format;
-}
-
-/*
- * TODO potentially move this and related functions to apps/lib/
- * or even better extend OSSL_STORE with type OSSL_STORE_INFO_CRL
- */
 static X509_REQ *load_csr_autofmt(const char *infile, const char *desc)
 {
     X509_REQ *csr;
     BIO *bio_bak = bio_err;
-    int can_retry;
-    int format = adjust_format(&infile, FORMAT_PEM, 0);
 
-    can_retry = format == FORMAT_PEM || format == FORMAT_ASN1;
-    if (can_retry)
-        bio_err = NULL; /* do not show errors on more than one try */
-    csr = load_csr(infile, format, desc);
+    bio_err = NULL; /* do not show errors on more than one try */
+    csr = load_csr(infile, FORMAT_PEM, desc);
     bio_err = bio_bak;
-    if (csr == NULL && can_retry) {
+    if (csr == NULL) {
         ERR_clear_error();
-        format = (format == FORMAT_PEM ? FORMAT_ASN1 : FORMAT_PEM);
-        csr = load_csr(infile, format, desc);
+        csr = load_csr(infile, FORMAT_ASN1, desc);
     }
     if (csr == NULL) {
         ERR_print_errors(bio_err);
         BIO_printf(bio_err, "error: unable to load %s from file '%s'\n", desc,
                    infile);
-    }
-    return csr;
-}
-
-static void warn_certs_expired(const char *file, STACK_OF(X509) **certs)
-{
-    int i, res;
-    X509 *cert;
-    char *subj;
-
-    for (i = 0; i < sk_X509_num(*certs); i++) {
-        cert = sk_X509_value(*certs, i);
-        res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
-                                 X509_get0_notAfter(cert));
-        if (res != 0) {
-            subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
-            CMP_warn3("certificate from '%s' with subject '%s' %s", file, subj,
-                      res > 0 ? "has expired" : "not yet valid");
-            OPENSSL_free(subj);
-        }
-    }
-}
-
-static int load_certs_pwd(const char *infile, STACK_OF(X509) **certs,
-                          int exclude_http, const char *pass,
-                          const char *desc)
-{
-    int ret = 0;
-    char *pass_string;
-    int format = adjust_format(&infile, FORMAT_PEM, 0);
+    } else {
+        EVP_PKEY *pkey = X509_REQ_get0_pubkey(csr);
+        int ret = do_X509_REQ_verify(csr, pkey, NULL /* vfyopts */);
 
-    if (exclude_http && format == FORMAT_HTTP) {
-        BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
-        return ret;
+        if (pkey == NULL || ret < 0)
+            CMP_warn("error while verifying CSR self-signature");
+        else if (ret == 0)
+            CMP_warn("CSR self-signature does not match the contents");
     }
-    pass_string = get_passwd(pass, desc);
-    ret = load_certs(infile, certs, pass_string, desc);
-    clear_free(pass_string);
-
-    if (ret)
-        warn_certs_expired(infile, certs);
-    return ret;
+    return csr;
 }
 
 /* set expected host name/IP addr and clears the email addr in the given ts */
-static int truststore_set_host_etc(X509_STORE *ts, char *host)
+static int truststore_set_host_etc(X509_STORE *ts, const char *host)
 {
     X509_VERIFY_PARAM *ts_vpm = X509_STORE_get0_param(ts);
 
@@ -775,24 +730,6 @@ static int truststore_set_host_etc(X509_STORE *ts, char *host)
         || X509_VERIFY_PARAM_set1_host(ts_vpm, host, 0);
 }
 
-static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
-                                    const STACK_OF(X509) *certs /* may NULL */)
-{
-    int i;
-
-    if (store == NULL)
-        store = X509_STORE_new();
-    if (store == NULL)
-        return NULL;
-    for (i = 0; i < sk_X509_num(certs); i++) {
-        if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
-            X509_STORE_free(store);
-            return NULL;
-        }
-    }
-    return store;
-}
-
 /* write OSSL_CMP_MSG DER-encoded to the specified file name item */
 static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames)
 {
@@ -803,14 +740,14 @@ static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames)
         return 0;
     }
     if (*filenames == NULL) {
-        CMP_err("Not enough file names provided for writing PKIMessage");
+        CMP_err("not enough file names provided for writing PKIMessage");
         return 0;
     }
 
     file = *filenames;
     *filenames = next_item(file);
     if (OSSL_CMP_MSG_write(file, msg) < 0) {
-        CMP_err1("Cannot write PKIMessage to file '%s'", file);
+        CMP_err1("cannot write PKIMessage to file '%s'", file);
         return 0;
     }
     return 1;
@@ -827,16 +764,16 @@ static OSSL_CMP_MSG *read_PKIMESSAGE(char **filenames)
         return NULL;
     }
     if (*filenames == NULL) {
-        CMP_err("Not enough file names provided for reading PKIMessage");
+        CMP_err("not enough file names provided for reading PKIMessage");
         return NULL;
     }
 
     file = *filenames;
     *filenames = next_item(file);
 
-    ret = OSSL_CMP_MSG_read(file);
+    ret = OSSL_CMP_MSG_read(file, app_get0_libctx(), app_get0_propq());
     if (ret == NULL)
-        CMP_err1("Cannot read PKIMessage from file '%s'", file);
+        CMP_err1("cannot read PKIMessage from file '%s'", file);
     return ret;
 }
 
@@ -852,9 +789,9 @@ static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx,
     OSSL_CMP_MSG *req_new = NULL;
     OSSL_CMP_MSG *res = NULL;
     OSSL_CMP_PKIHEADER *hdr;
+    const char *prev_opt_rspin = opt_rspin;
 
-    if (req != NULL && opt_reqout != NULL
-            && !write_PKIMESSAGE(req, &opt_reqout))
+    if (opt_reqout != NULL && !write_PKIMESSAGE(req, &opt_reqout))
         goto err;
     if (opt_reqin != NULL && opt_rspin == NULL) {
         if ((req_new = read_PKIMESSAGE(&opt_reqin)) == NULL)
@@ -881,7 +818,7 @@ static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx,
     if (res == NULL)
         goto err;
 
-    if (opt_reqin != NULL || opt_rspin != NULL) {
+    if (opt_reqin != NULL || prev_opt_rspin != NULL) {
         /* need to satisfy nonce and transactionID checks */
         ASN1_OCTET_STRING *nonce;
         ASN1_OCTET_STRING *tid;
@@ -907,72 +844,12 @@ static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx,
     return res;
 }
 
-/*
- * parse string as integer value, not allowing trailing garbage, see also
- * https://www.gnu.org/software/libc/manual/html_node/Parsing-of-Integers.html
- *
- * returns integer value, or INT_MIN on error
- */
-static int atoint(const char *str)
-{
-    char *tailptr;
-    long res = strtol(str, &tailptr, 10);
-
-    if  ((*tailptr != '\0') || (res < INT_MIN) || (res > INT_MAX))
-        return INT_MIN;
-    else
-        return (int)res;
-}
-
-static int parse_addr(char **opt_string, int port, const char *name)
-{
-    char *port_string;
-
-    if (strncasecmp(*opt_string, OSSL_HTTP_PREFIX,
-                    strlen(OSSL_HTTP_PREFIX)) == 0) {
-        *opt_string += strlen(OSSL_HTTP_PREFIX);
-    } else if (strncasecmp(*opt_string, OSSL_HTTPS_PREFIX,
-                           strlen(OSSL_HTTPS_PREFIX)) == 0) {
-        *opt_string += strlen(OSSL_HTTPS_PREFIX);
-        if (port == 0)
-            port = 443; /* == integer value of OSSL_HTTPS_PORT */
-    }
-
-    if ((port_string = strrchr(*opt_string, ':')) == NULL)
-        return port; /* using default */
-    *(port_string++) = '\0';
-    port = atoint(port_string);
-    if ((port <= 0) || (port > 65535)) {
-        CMP_err2("invalid %s port '%s' given, sane range 1-65535",
-                 name, port_string);
-        return -1;
-    }
-    return port;
-}
-
-static int set1_store_parameters(X509_STORE *ts)
-{
-    if (ts == NULL)
-        return 0;
-
-    /* copy vpm to store */
-    if (!X509_STORE_set1_param(ts, vpm /* may be NULL */)) {
-        BIO_printf(bio_err, "error setting verification parameters\n");
-        OSSL_CMP_CTX_print_errors(cmp_ctx);
-        return 0;
-    }
-
-    X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb);
-
-    return 1;
-}
-
 static int set_name(const char *str,
                     int (*set_fn) (OSSL_CMP_CTX *ctx, const X509_NAME *name),
                     OSSL_CMP_CTX *ctx, const char *desc)
 {
     if (str != NULL) {
-        X509_NAME *n = parse_name(str, MBSTRING_ASC, 0, desc);
+        X509_NAME *n = parse_name(str, MBSTRING_ASC, 1, desc);
 
         if (n == NULL)
             return 0;
@@ -1001,11 +878,12 @@ static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc)
             continue;
         }
 
-        /* try IP address first, then URI or domain name */
+        /* try IP address first, then email/URI/domain name */
         (void)ERR_set_mark();
         n = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_IPADD, names, 0);
         if (n == NULL)
             n = a2i_GENERAL_NAME(NULL, NULL, NULL,
+                                 strchr(names, '@') != NULL ? GEN_EMAIL :
                                  strchr(names, ':') != NULL ? GEN_URI : GEN_DNS,
                                  names, 0);
         (void)ERR_pop_to_mark();
@@ -1024,98 +902,39 @@ static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc)
     return 1;
 }
 
-/* TODO potentially move to apps/lib/apps.c */
-/*
- * create cert store structure with certificates read from given file(s)
- * returns pointer to created X509_STORE on success, NULL on error
- */
-static X509_STORE *load_certstore(char *input, const char *desc)
-{
-    X509_STORE *store = NULL;
-    STACK_OF(X509) *certs = NULL;
-
-    if (input == NULL)
-        goto err;
-
-    while (input != NULL) {
-        char *next = next_item(input);           \
-
-        if (!load_certs_pwd(input, &certs, 1, opt_otherpass, desc)
-                || !(store = sk_X509_to_store(store, certs))) {
-            /* CMP_err("out of memory"); */
-            X509_STORE_free(store);
-            store = NULL;
-            goto err;
-        }
-        sk_X509_pop_free(certs, X509_free);
-        certs = NULL;
-        input = next;
-    }
- err:
-    sk_X509_pop_free(certs, X509_free);
-    return store;
-}
-
-/* TODO potentially move to apps/lib/apps.c */
-static STACK_OF(X509) *load_certs_multifile(char *files,
-                                            const char *pass, const char *desc)
+static X509_STORE *load_trusted(char *input, int for_new_cert, const char *desc)
 {
-    STACK_OF(X509) *certs = NULL;
-    STACK_OF(X509) *result = sk_X509_new_null();
-
-    if (files == NULL)
-        goto err;
-    if (result == NULL)
-        goto oom;
+    X509_STORE *ts = load_certstore(input, opt_otherpass, desc, vpm);
 
-    while (files != NULL) {
-        char *next = next_item(files);
-
-        if (!load_certs_pwd(files, &certs, 0, pass, desc))
-            goto err;
-        if (!X509_add_certs(result, certs,
-                            X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
-            goto oom;
-        sk_X509_pop_free(certs, X509_free);
-        certs = NULL;
-        files = next;
-    }
-    return result;
+    if (ts == NULL)
+        return NULL;
+    X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb);
 
- oom:
-    BIO_printf(bio_err, "out of memory\n");
- err:
-    sk_X509_pop_free(certs, X509_free);
-    sk_X509_pop_free(result, X509_free);
+    /* copy vpm to store */
+    if (X509_STORE_set1_param(ts, vpm /* may be NULL */)
+            && (for_new_cert || truststore_set_host_etc(ts, NULL)))
+        return ts;
+    BIO_printf(bio_err, "error setting verification parameters for %s\n", desc);
+    OSSL_CMP_CTX_print_errors(cmp_ctx);
+    X509_STORE_free(ts);
     return NULL;
 }
 
 typedef int (*add_X509_stack_fn_t)(void *ctx, const STACK_OF(X509) *certs);
-typedef int (*add_X509_fn_t)(void *ctx, const X509 *cert);
 
 static int setup_certs(char *files, const char *desc, void *ctx,
-                       add_X509_stack_fn_t addn_fn, add_X509_fn_t add1_fn)
+                       add_X509_stack_fn_t set1_fn)
 {
-    int ret = 1;
-
-    if (files != NULL) {
-        STACK_OF(X509) *certs = load_certs_multifile(files, opt_otherpass,
-                                                     desc);
-        if (certs == NULL) {
-            ret = 0;
-        } else {
-            if (addn_fn != NULL) {
-                ret = (*addn_fn)(ctx, certs);
-            } else {
-                int i;
+    STACK_OF(X509) *certs;
+    int ok;
 
-                for (i = 0; i < sk_X509_num(certs /* may be NULL */); i++)
-                    ret &= (*add1_fn)(ctx, sk_X509_value(certs, i));
-            }
-            sk_X509_pop_free(certs, X509_free);
-        }
-    }
-    return ret;
+    if (files == NULL)
+        return 1;
+    if ((certs = load_certs_multifile(files, opt_otherpass, desc, vpm)) == NULL)
+        return 0;
+    ok = (*set1_fn)(ctx, certs);
+    OSSL_STACK_OF_X509_free(certs);
+    return ok;
 }
 
 
@@ -1147,7 +966,7 @@ static int transform_opts(void)
         return 0;
     }
 
-#ifdef OPENSSL_NO_ENGINE
+#ifndef OPENSSL_NO_ENGINE
 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12 | OPT_FMT_ENGINE)
 #else
 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12)
@@ -1183,7 +1002,7 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
     if (opt_srv_ref == NULL) {
         if (opt_srv_cert == NULL) {
             /* opt_srv_cert should determine the sender */
-            CMP_err("must give -srv_ref for server if no -srv_cert given");
+            CMP_err("must give -srv_ref for mock server if no -srv_cert given");
             goto err;
         }
     } else {
@@ -1194,7 +1013,7 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
 
     if (opt_srv_secret != NULL) {
         int res;
-        char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of server");
+        char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of mock server");
 
         if (pass_str != NULL) {
             cleanse(opt_srv_secret);
@@ -1205,10 +1024,10 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
                 goto err;
         }
     } else if (opt_srv_cert == NULL) {
-        CMP_err("server credentials must be given if -use_mock_srv or -port is used");
+        CMP_err("mock server credentials must be given if -use_mock_srv or -port is used");
         goto err;
     } else {
-        CMP_warn("server will not be able to handle PBM-protected requests since -srv_secret is not given");
+        CMP_warn("mock server will not be able to handle PBM-protected requests since -srv_secret is not given");
     }
 
     if (opt_srv_secret == NULL
@@ -1218,7 +1037,7 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
     }
     if (opt_srv_cert != NULL) {
         X509 *srv_cert = load_cert_pwd(opt_srv_cert, opt_srv_keypass,
-                                       "certificate of the server");
+                                       "certificate of the mock server");
 
         if (srv_cert == NULL || !OSSL_CMP_CTX_set1_cert(ctx, srv_cert)) {
             X509_free(srv_cert);
@@ -1229,7 +1048,7 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
     if (opt_srv_key != NULL) {
         EVP_PKEY *pkey = load_key_pwd(opt_srv_key, opt_keyform,
                                       opt_srv_keypass,
-                                      engine, "private key for server cert");
+                                      engine, "private key for mock server cert");
 
         if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
             EVP_PKEY_free(pkey);
@@ -1241,27 +1060,22 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
 
     if (opt_srv_trusted != NULL) {
         X509_STORE *ts =
-            load_certstore(opt_srv_trusted, "certificates trusted by server");
+            load_trusted(opt_srv_trusted, 0, "certs trusted by mock server");
 
-        if (ts == NULL)
-            goto err;
-        if (!set1_store_parameters(ts)
-                || !truststore_set_host_etc(ts, NULL)
-                || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
+        if (ts == NULL || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
             X509_STORE_free(ts);
             goto err;
         }
     } else {
-        CMP_warn("server will not be able to handle signature-protected requests since -srv_trusted is not given");
+        CMP_warn("mock server will not be able to handle signature-protected requests since -srv_trusted is not given");
     }
-    if (!setup_certs(opt_srv_untrusted, "untrusted certificates", ctx,
-                     (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted_certs,
-                     NULL))
+    if (!setup_certs(opt_srv_untrusted,
+                     "untrusted certificates for mock server", ctx,
+                     (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted))
         goto err;
 
     if (opt_rsp_cert == NULL) {
-        CMP_err("must give -rsp_cert for mock server");
-        goto err;
+        CMP_warn("no -rsp_cert given for mock server");
     } else {
         X509 *cert = load_cert_pwd(opt_rsp_cert, opt_keypass,
                                    "cert to be returned by the mock server");
@@ -1275,15 +1089,12 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
         }
         X509_free(cert);
     }
-    /* TODO find a cleaner solution not requiring type casts */
     if (!setup_certs(opt_rsp_extracerts,
                      "CMP extra certificates for mock server", srv_ctx,
-                     (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut,
-                     NULL))
+                     (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut))
         goto err;
     if (!setup_certs(opt_rsp_capubs, "caPubs for mock server", srv_ctx,
-                     (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut,
-                     NULL))
+                     (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut))
         goto err;
     (void)ossl_cmp_mock_srv_set_pollCount(srv_ctx, opt_poll_count);
     (void)ossl_cmp_mock_srv_set_checkAfterTime(srv_ctx, opt_check_after);
@@ -1337,16 +1148,15 @@ static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
 static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
 {
     if (!setup_certs(opt_untrusted, "untrusted certificates", ctx,
-                     (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted_certs,
-                     NULL))
-        goto err;
+                     (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted))
+        return 0;
 
     if (opt_srvcert != NULL || opt_trusted != NULL) {
-        X509_STORE *ts = NULL;
+        X509 *srvcert;
+        X509_STORE *ts;
+        int ok;
 
         if (opt_srvcert != NULL) {
-            X509 *srvcert;
-
             if (opt_trusted != NULL) {
                 CMP_warn("-trusted option is ignored since -srvcert option is present");
                 opt_trusted = NULL;
@@ -1357,33 +1167,22 @@ static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
             }
             srvcert = load_cert_pwd(opt_srvcert, opt_otherpass,
                                     "directly trusted CMP server certificate");
-            if (srvcert == NULL)
-                /*
-                 * opt_otherpass is needed in case
-                 * opt_srvcert is an encrypted PKCS#12 file
-                 */
-                goto err;
-            if (!OSSL_CMP_CTX_set1_srvCert(ctx, srvcert)) {
-                X509_free(srvcert);
-                goto oom;
-            }
+            ok = srvcert != NULL && OSSL_CMP_CTX_set1_srvCert(ctx, srvcert);
             X509_free(srvcert);
-            if ((ts = X509_STORE_new()) == NULL)
-                goto oom;
+            if (!ok)
+                return 0;
         }
-        if (opt_trusted != NULL
-                && (ts = load_certstore(opt_trusted, "trusted certificates"))
-            == NULL)
-            goto err;
-        if (!set1_store_parameters(ts) /* also copies vpm */
-                /*
-                 * clear any expected host/ip/email address;
-                 * opt_expect_sender is used instead
-                 */
-                || !truststore_set_host_etc(ts, NULL)
-                || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
-            X509_STORE_free(ts);
-            goto oom;
+        if (opt_trusted != NULL) {
+            /*
+             * the 0 arg below clears any expected host/ip/email address;
+             * opt_expect_sender is used instead
+             */
+            ts = load_trusted(opt_trusted, 0, "certs trusted by client");
+
+            if (ts == NULL || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
+                X509_STORE_free(ts);
+                return 0;
+            }
         }
     }
 
@@ -1396,14 +1195,11 @@ static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
     if (opt_out_trusted != NULL) { /* for use in OSSL_CMP_certConf_cb() */
         X509_VERIFY_PARAM *out_vpm = NULL;
         X509_STORE *out_trusted =
-            load_certstore(opt_out_trusted,
-                           "trusted certs for verifying newly enrolled cert");
+            load_trusted(opt_out_trusted, 1,
+                         "trusted certs for verifying newly enrolled cert");
 
         if (out_trusted == NULL)
-            goto err;
-        /* any -verify_hostname, -verify_ip, and -verify_email apply here */
-        if (!set1_store_parameters(out_trusted))
-            goto oom;
+            return 0;
         /* ignore any -attime here, new certs are current anyway */
         out_vpm = X509_STORE_get0_param(out_trusted);
         X509_VERIFY_PARAM_clear_flags(out_vpm, X509_V_FLAG_USE_CHECK_TIME);
@@ -1417,14 +1213,7 @@ static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
     if (opt_implicit_confirm)
         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, 1);
 
-    (void)OSSL_CMP_CTX_set_certConf_cb(ctx, OSSL_CMP_certConf_cb);
-
     return 1;
-
- oom:
-    CMP_err("out of memory");
- err:
-    return 0;
 }
 
 #ifndef OPENSSL_NO_SOCK
@@ -1432,9 +1221,10 @@ static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
  * set up ssl_ctx for the OSSL_CMP_CTX based on options from config file/CLI.
  * Returns pointer on success, NULL on error
  */
-static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
+static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, const char *host,
+                              ENGINE *engine)
 {
-    STACK_OF(X509) *untrusted_certs = OSSL_CMP_CTX_get0_untrusted_certs(ctx);
+    STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted(ctx);
     EVP_PKEY *pkey = NULL;
     X509_STORE *trust_store = NULL;
     SSL_CTX *ssl_ctx;
@@ -1444,70 +1234,76 @@ static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
     if (ssl_ctx == NULL)
         return NULL;
 
-    SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
-
     if (opt_tls_trusted != NULL) {
-        if ((trust_store = load_certstore(opt_tls_trusted,
-                                          "trusted TLS certificates")) == NULL)
+        trust_store = load_trusted(opt_tls_trusted, 0, "trusted TLS certs");
+        if (trust_store == NULL)
             goto err;
         SSL_CTX_set_cert_store(ssl_ctx, trust_store);
-        /* for improved diagnostics on SSL_CTX_build_cert_chain() errors: */
-        X509_STORE_set_verify_cb(trust_store, X509_STORE_CTX_print_verify_cb);
     }
 
     if (opt_tls_cert != NULL && opt_tls_key != NULL) {
         X509 *cert;
         STACK_OF(X509) *certs = NULL;
+        int ok;
 
-        if (!load_certs_pwd(opt_tls_cert, &certs, 0, opt_tls_keypass,
-                            "TLS client certificate (optionally with chain)"))
-            /*
-             * opt_tls_keypass is needed in case opt_tls_cert is an encrypted
-             * PKCS#12 file
-             */
+        if (!load_cert_certs(opt_tls_cert, &cert, &certs, 0, opt_tls_keypass,
+                             "TLS client certificate (optionally with chain)",
+                             vpm))
+            /* need opt_tls_keypass if opt_tls_cert is encrypted PKCS#12 file */
             goto err;
 
-        cert = sk_X509_delete(certs, 0);
-        if (cert == NULL || SSL_CTX_use_certificate(ssl_ctx, cert) <= 0) {
-            CMP_err1("unable to use client TLS certificate file '%s'",
-                     opt_tls_cert);
-            X509_free(cert);
-            sk_X509_pop_free(certs, X509_free);
-            goto err;
-        }
-        X509_free(cert); /* we do not need the handle any more */
+        ok = SSL_CTX_use_certificate(ssl_ctx, cert) > 0;
+        X509_free(cert);
 
         /*
          * Any further certs and any untrusted certs are used for constructing
          * the chain to be provided with the TLS client cert to the TLS server.
          */
-        if (!SSL_CTX_set0_chain(ssl_ctx, certs)) {
-            CMP_err("could not set TLS client cert chain");
-            sk_X509_pop_free(certs, X509_free);
+        if (!ok || !SSL_CTX_set0_chain(ssl_ctx, certs)) {
+            CMP_err1("unable to use client TLS certificate file '%s'",
+                     opt_tls_cert);
+            OSSL_STACK_OF_X509_free(certs);
             goto err;
         }
-        for (i = 0; i < sk_X509_num(untrusted_certs); i++) {
-            cert = sk_X509_value(untrusted_certs, i);
+        for (i = 0; i < sk_X509_num(untrusted); i++) {
+            cert = sk_X509_value(untrusted, i);
             if (!SSL_CTX_add1_chain_cert(ssl_ctx, cert)) {
                 CMP_err("could not add untrusted cert to TLS client cert chain");
                 goto err;
             }
         }
-        CMP_debug("trying to build cert chain for own TLS cert");
-        if (SSL_CTX_build_cert_chain(ssl_ctx,
-                                     SSL_BUILD_CHAIN_FLAG_UNTRUSTED |
-                                     SSL_BUILD_CHAIN_FLAG_NO_ROOT)) {
-            CMP_debug("succeeded building cert chain for own TLS cert");
-        } else {
-            OSSL_CMP_CTX_print_errors(ctx);
-            CMP_warn("could not build cert chain for own TLS cert");
+
+        {
+            X509_VERIFY_PARAM *tls_vpm = NULL;
+            unsigned long bak_flags = 0; /* compiler warns without init */
+
+            if (trust_store != NULL) {
+                tls_vpm = X509_STORE_get0_param(trust_store);
+                bak_flags = X509_VERIFY_PARAM_get_flags(tls_vpm);
+                /* disable any cert status/revocation checking etc. */
+                X509_VERIFY_PARAM_clear_flags(tls_vpm,
+                                              ~(X509_V_FLAG_USE_CHECK_TIME
+                                                | X509_V_FLAG_NO_CHECK_TIME));
+            }
+            CMP_debug("trying to build cert chain for own TLS cert");
+            if (SSL_CTX_build_cert_chain(ssl_ctx,
+                                         SSL_BUILD_CHAIN_FLAG_UNTRUSTED |
+                                         SSL_BUILD_CHAIN_FLAG_NO_ROOT)) {
+                CMP_debug("success building cert chain for own TLS cert");
+            } else {
+                OSSL_CMP_CTX_print_errors(ctx);
+                CMP_warn("could not build cert chain for own TLS cert");
+            }
+            if (trust_store != NULL)
+                X509_VERIFY_PARAM_set_flags(tls_vpm, bak_flags);
         }
 
         /* If present we append to the list also the certs from opt_tls_extra */
         if (opt_tls_extra != NULL) {
             STACK_OF(X509) *tls_extra = load_certs_multifile(opt_tls_extra,
                                                              opt_otherpass,
-                                                             "extra certificates for TLS");
+                                                             "extra certificates for TLS",
+                                                             vpm);
             int res = 1;
 
             if (tls_extra == NULL)
@@ -1555,9 +1351,7 @@ static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
     if (opt_tls_trusted != NULL) {
         /* enable and parameterize server hostname/IP address check */
         if (!truststore_set_host_etc(trust_store,
-                                     opt_tls_host != NULL ?
-                                     opt_tls_host : opt_server))
-            /* TODO: is the server host name correct for TLS via proxy? */
+                                     opt_tls_host != NULL ? opt_tls_host : host))
             goto err;
         SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
     }
@@ -1566,7 +1360,7 @@ static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
     SSL_CTX_free(ssl_ctx);
     return NULL;
 }
-#endif
+#endif /* OPENSSL_NO_SOCK */
 
 /*
  * set up protection aspects of OSSL_CMP_CTX based on options from config
@@ -1575,19 +1369,19 @@ static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
  */
 static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
 {
-    if (!opt_unprotected_requests && opt_secret == NULL && opt_cert == NULL) {
-        CMP_err("must give client credentials unless -unprotected_requests is set");
-        goto err;
+    if (!opt_unprotected_requests && opt_secret == NULL && opt_key == NULL) {
+        CMP_err("must give -key or -secret unless -unprotected_requests is used");
+        return 0;
     }
 
     if (opt_ref == NULL && opt_cert == NULL && opt_subject == NULL) {
         /* cert or subject should determine the sender */
         CMP_err("must give -ref if no -cert and no -subject given");
-        goto err;
+        return 0;
     }
     if (!opt_secret && ((opt_cert == NULL) != (opt_key == NULL))) {
         CMP_err("must give both -cert and -key options or neither");
-        goto err;
+        return 0;
     }
     if (opt_secret != NULL) {
         char *pass_string = get_passwd(opt_secret, "PBMAC");
@@ -1600,15 +1394,15 @@ static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
                                                 strlen(pass_string));
             clear_free(pass_string);
             if (res == 0)
-                goto err;
+                return 0;
         }
         if (opt_cert != NULL || opt_key != NULL)
-            CMP_warn("no signature-based protection used since -secret is given");
+            CMP_warn("-cert and -key not used for protection since -secret is given");
     }
     if (opt_ref != NULL
             && !OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_ref,
                                                  strlen(opt_ref)))
-        goto err;
+        return 0;
 
     if (opt_key != NULL) {
         EVP_PKEY *pkey = load_key_pwd(opt_key, opt_keyform, opt_keypass, engine,
@@ -1616,51 +1410,47 @@ static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
 
         if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
             EVP_PKEY_free(pkey);
-            goto err;
+            return 0;
         }
         EVP_PKEY_free(pkey);
     }
-    if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL) {
-        CMP_err("missing -secret or -srvcert or -trusted");
-        goto err;
-    }
+    if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL)
+        CMP_warn("will not authenticate server due to missing -secret, -trusted, or -srvcert");
 
     if (opt_cert != NULL) {
         X509 *cert;
         STACK_OF(X509) *certs = NULL;
+        X509_STORE *own_trusted = NULL;
         int ok;
 
-        if (!load_certs_pwd(opt_cert, &certs, 0, opt_keypass,
-                            "CMP client certificate (and optionally extra certs)"))
+        if (!load_cert_certs(opt_cert, &cert, &certs, 0, opt_keypass,
+                             "CMP client certificate (optionally with chain)",
+                             vpm))
             /* opt_keypass is needed if opt_cert is an encrypted PKCS#12 file */
-            goto err;
-
-        cert = sk_X509_delete(certs, 0);
-        if (cert == NULL) {
-            CMP_err("no client certificate found");
-            sk_X509_pop_free(certs, X509_free);
-            goto err;
-        }
+            return 0;
         ok = OSSL_CMP_CTX_set1_cert(ctx, cert);
         X509_free(cert);
-
-        if (ok) {
-            /* add any remaining certs to the list of untrusted certs */
-            STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted_certs(ctx);
-            ok = untrusted != NULL ?
-                X509_add_certs(untrusted, certs,
-                               X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)
-                : OSSL_CMP_CTX_set1_untrusted_certs(ctx, certs);
+        if (!ok) {
+            CMP_err("out of memory");
+        } else {
+            if (opt_own_trusted != NULL) {
+                own_trusted = load_trusted(opt_own_trusted, 0,
+                                           "trusted certs for verifying own CMP signer cert");
+                ok = own_trusted != NULL;
+            }
+            ok = ok && OSSL_CMP_CTX_build_cert_chain(ctx, own_trusted, certs);
         }
-        sk_X509_pop_free(certs, X509_free);
+        X509_STORE_free(own_trusted);
+        OSSL_STACK_OF_X509_free(certs);
         if (!ok)
-            goto oom;
+            return 0;
+    } else if (opt_own_trusted != NULL) {
+        CMP_warn("-own_trusted option is ignored without -cert");
     }
 
     if (!setup_certs(opt_extracerts, "extra certificates for CMP", ctx,
-                     (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut,
-                     NULL))
-        goto err;
+                     (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut))
+        return 0;
     cleanse(opt_otherpass);
 
     if (opt_unprotected_requests)
@@ -1671,12 +1461,12 @@ static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
 
         if (digest == NID_undef) {
             CMP_err1("digest algorithm name not recognized: '%s'", opt_digest);
-            goto err;
+            return 0;
         }
         if (!OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DIGEST_ALGNID, digest)
             || !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_OWF_ALGNID, digest)) {
             CMP_err1("digest algorithm name not supported: '%s'", opt_digest);
-            goto err;
+            return 0;
         }
     }
 
@@ -1684,16 +1474,11 @@ static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
         int mac = OBJ_ln2nid(opt_mac);
         if (mac == NID_undef) {
             CMP_err1("MAC algorithm name not recognized: '%s'", opt_mac);
-            goto err;
+            return 0;
         }
         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MAC_ALGNID, mac);
     }
     return 1;
-
- oom:
-    CMP_err("out of memory");
- err:
-    return 0;
 }
 
 /*
@@ -1703,75 +1488,168 @@ static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
  */
 static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
 {
-    if (opt_subject == NULL && opt_oldcert == NULL && opt_cert == NULL)
-        CMP_warn("no -subject given, neither -oldcert nor -cert available as default");
-    if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")
-            || !set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer"))
-        goto err;
+    X509_REQ *csr = NULL;
+    X509_EXTENSIONS *exts = NULL;
+    X509V3_CTX ext_ctx;
 
-    if (opt_newkey != NULL) {
-        const char *file = opt_newkey;
-        const int format = opt_keyform;
-        const char *pass = opt_newkeypass;
-        const char *desc = "new private or public key for cert to be enrolled";
-        EVP_PKEY *pkey = load_key_pwd(file, format, pass, engine, NULL);
-        int priv = 1;
+    if (opt_subject == NULL
+            && opt_csr == NULL && opt_oldcert == NULL && opt_cert == NULL
+            && opt_cmd != CMP_RR && opt_cmd != CMP_GENM)
+        CMP_warn("no -subject given; no -csr or -oldcert or -cert available for fallback");
 
-        if (pkey == NULL) {
-            ERR_clear_error();
-            pkey = load_pubkey(file, format, 0, pass, engine, desc);
-            priv = 0;
+    if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) {
+        if (opt_newkey == NULL && opt_key == NULL && opt_csr == NULL) {
+            CMP_err("missing -newkey (or -key) to be certified and no -csr given");
+            return 0;
         }
-        cleanse(opt_newkeypass);
-        if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) {
-            EVP_PKEY_free(pkey);
-            goto err;
+        if (opt_certout == NULL) {
+            CMP_err("-certout not given, nowhere to save newly enrolled certificate");
+            return 0;
         }
-    }
+        if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")
+                || !set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer"))
+            return 0;
+    } else {
+        const char *msg = "option is ignored for commands other than 'ir', 'cr', and 'kur'";
+
+        if (opt_subject != NULL) {
+            if (opt_ref == NULL && opt_cert == NULL) {
+                /* use subject as default sender unless oldcert subject is used */
+                if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject"))
+                    return 0;
+            } else {
+                CMP_warn1("-subject %s since -ref or -cert is given", msg);
+            }
+        }
+        if (opt_issuer != NULL)
+            CMP_warn1("-issuer %s", msg);
+        if (opt_reqexts != NULL)
+            CMP_warn1("-reqexts %s", msg);
+        if (opt_san_nodefault)
+            CMP_warn1("-san_nodefault %s", msg);
+        if (opt_sans != NULL)
+            CMP_warn1("-sans %s", msg);
+        if (opt_policies != NULL)
+            CMP_warn1("-policies %s", msg);
+        if (opt_policy_oids != NULL)
+            CMP_warn1("-policy_oids %s", msg);
+    }
+    if (opt_cmd == CMP_KUR) {
+        char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert;
+
+        if (ref_cert == NULL && opt_csr == NULL) {
+            CMP_err("missing -oldcert for certificate to be updated and no -csr given");
+            return 0;
+        }
+        if (opt_subject != NULL)
+            CMP_warn2("given -subject '%s' overrides the subject of '%s' for KUR",
+                      opt_subject, ref_cert != NULL ? ref_cert : opt_csr);
+    }
+    if (opt_cmd == CMP_RR) {
+        if (opt_oldcert == NULL && opt_csr == NULL) {
+            CMP_err("missing -oldcert for certificate to be revoked and no -csr given");
+            return 0;
+        }
+        if (opt_oldcert != NULL && opt_csr != NULL)
+            CMP_warn("ignoring -csr since certificate to be revoked is given");
+    }
+    if (opt_cmd == CMP_P10CR && opt_csr == NULL) {
+        CMP_err("missing PKCS#10 CSR for p10cr");
+        return 0;
+    }
+
+    if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL
+            && opt_oldcert == NULL && opt_cert == NULL)
+        CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient will be set to \"NULL-DN\"");
+
+    if (opt_cmd == CMP_P10CR || opt_cmd == CMP_RR) {
+        const char *msg = "option is ignored for 'p10cr' and 'rr' commands";
+
+        if (opt_newkeypass != NULL)
+            CMP_warn1("-newkeytype %s", msg);
+        if (opt_newkey != NULL)
+            CMP_warn1("-newkey %s", msg);
+        if (opt_days != 0)
+            CMP_warn1("-days %s", msg);
+        if (opt_popo != OSSL_CRMF_POPO_NONE - 1)
+            CMP_warn1("-popo %s", msg);
+    } else if (opt_newkey != NULL) {
+        const char *file = opt_newkey;
+        const int format = opt_keyform;
+        const char *pass = opt_newkeypass;
+        const char *desc = "new private key for cert to be enrolled";
+        EVP_PKEY *pkey;
+        int priv = 1;
+        BIO *bio_bak = bio_err;
+
+        bio_err = NULL; /* suppress diagnostics on first try loading key */
+        pkey = load_key_pwd(file, format, pass, engine, desc);
+        bio_err = bio_bak;
+        if (pkey == NULL) {
+            ERR_clear_error();
+            desc = opt_csr == NULL
+            ? "fallback public key for cert to be enrolled"
+            : "public key for checking cert resulting from p10cr";
+            pkey = load_pubkey(file, format, 0, pass, engine, desc);
+            priv = 0;
+        }
+        cleanse(opt_newkeypass);
+        if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) {
+            EVP_PKEY_free(pkey);
+            return 0;
+        }
+    }
 
     if (opt_days > 0
             && !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_VALIDITY_DAYS,
                                         opt_days)) {
         CMP_err("could not set requested cert validity period");
-        goto err;
+        return 0;
     }
 
     if (opt_policies != NULL && opt_policy_oids != NULL) {
         CMP_err("cannot have policies both via -policies and via -policy_oids");
-        goto err;
+        return 0;
     }
 
+    if (opt_csr != NULL) {
+        if (opt_cmd == CMP_GENM) {
+            CMP_warn("-csr option is ignored for command 'genm'");
+        } else {
+            if ((csr = load_csr_autofmt(opt_csr, "PKCS#10 CSR")) == NULL)
+                return 0;
+            if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr))
+                goto oom;
+        }
+    }
     if (opt_reqexts != NULL || opt_policies != NULL) {
-        X509V3_CTX ext_ctx;
-        X509_EXTENSIONS *exts = sk_X509_EXTENSION_new_null();
-
-        if (exts == NULL)
-            goto err;
-        X509V3_set_ctx(&ext_ctx, NULL, NULL, NULL, NULL, 0);
+        if ((exts = sk_X509_EXTENSION_new_null()) == NULL)
+            goto oom;
+        X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, X509V3_CTX_REPLACE);
         X509V3_set_nconf(&ext_ctx, conf);
         if (opt_reqexts != NULL
             && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_reqexts, &exts)) {
             CMP_err1("cannot load certificate request extension section '%s'",
                      opt_reqexts);
-            sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
-            goto err;
+            goto exts_err;
         }
         if (opt_policies != NULL
             && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_policies, &exts)) {
             CMP_err1("cannot load policy cert request extension section '%s'",
                      opt_policies);
-            sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
-            goto err;
+            goto exts_err;
         }
         OSSL_CMP_CTX_set0_reqExtensions(ctx, exts);
     }
+    X509_REQ_free(csr);
+    /* After here, must not goto oom/exts_err */
+
     if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) && opt_sans != NULL) {
         CMP_err("cannot have Subject Alternative Names both via -reqexts and via -sans");
-        goto err;
+        return 0;
     }
-
     if (!set_gennames(ctx, opt_sans, "Subject Alternative Name"))
-        goto err;
+        return 0;
 
     if (opt_san_nodefault) {
         if (opt_sans != NULL)
@@ -1793,19 +1671,19 @@ static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
 
         if ((policy = OBJ_txt2obj(opt_policy_oids, 1)) == 0) {
             CMP_err1("unknown policy OID '%s'", opt_policy_oids);
-            goto err;
+            return 0;
         }
 
         if ((pinfo = POLICYINFO_new()) == NULL) {
             ASN1_OBJECT_free(policy);
-            goto err;
+            return 0;
         }
         pinfo->policyid = policy;
 
         if (!OSSL_CMP_CTX_push0_policy(ctx, pinfo)) {
             CMP_err1("cannot add policy with OID '%s'", opt_policy_oids);
             POLICYINFO_free(pinfo);
-            goto err;
+            return 0;
         }
         opt_policy_oids = next;
     }
@@ -1813,35 +1691,27 @@ static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
     if (opt_popo >= OSSL_CRMF_POPO_NONE)
         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POPO_METHOD, opt_popo);
 
-    if (opt_csr != NULL) {
-        if (opt_cmd != CMP_P10CR) {
-            CMP_warn("-csr option is ignored for command other than p10cr");
+    if (opt_oldcert != NULL) {
+        if (opt_cmd == CMP_GENM) {
+            CMP_warn("-oldcert option is ignored for command 'genm'");
         } else {
-            X509_REQ *csr =
-                load_csr_autofmt(opt_csr, "PKCS#10 CSR for p10cr");
-
-            if (csr == NULL)
-                goto err;
-            if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr)) {
-                X509_REQ_free(csr);
-                goto oom;
+            X509 *oldcert = load_cert_pwd(opt_oldcert, opt_keypass,
+                                          opt_cmd == CMP_KUR ?
+                                          "certificate to be updated" :
+                                          opt_cmd == CMP_RR ?
+                                          "certificate to be revoked" :
+                                          "reference certificate (oldcert)");
+            /* opt_keypass needed if opt_oldcert is an encrypted PKCS#12 file */
+
+            if (oldcert == NULL)
+                return 0;
+            if (!OSSL_CMP_CTX_set1_oldCert(ctx, oldcert)) {
+                X509_free(oldcert);
+                CMP_err("out of memory");
+                return 0;
             }
-            X509_REQ_free(csr);
-        }
-    }
-
-    if (opt_oldcert != NULL) {
-        X509 *oldcert = load_cert_pwd(opt_oldcert, opt_keypass,
-                                      "certificate to be updated/revoked");
-        /* opt_keypass is needed if opt_oldcert is an encrypted PKCS#12 file */
-
-        if (oldcert == NULL)
-            goto err;
-        if (!OSSL_CMP_CTX_set1_oldCert(ctx, oldcert)) {
             X509_free(oldcert);
-            goto oom;
         }
-        X509_free(oldcert);
     }
     cleanse(opt_keypass);
     if (opt_revreason > CRL_REASON_NONE)
@@ -1852,7 +1722,9 @@ static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
 
  oom:
     CMP_err("out of memory");
- err:
+ exts_err:
+    sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
+    X509_REQ_free(csr);
     return 0;
 }
 
@@ -1873,11 +1745,10 @@ static int handle_opt_geninfo(OSSL_CMP_CTX *ctx)
     valptr[0] = '\0';
     valptr++;
 
-    if (strncasecmp(valptr, "int:", 4) != 0) {
+    if (!CHECK_AND_SKIP_CASE_PREFIX(valptr, "int:")) {
         CMP_err("missing 'int:' in -geninfo option");
         return 0;
     }
-    valptr += 4;
 
     value = strtol(valptr, &endstr, 10);
     if (endstr == valptr || *endstr != '\0') {
@@ -1928,73 +1799,73 @@ static int handle_opt_geninfo(OSSL_CMP_CTX *ctx)
 static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
 {
     int ret = 0;
-    char server_buf[200] = { '\0' };
-    char proxy_buf[200] = { '\0' };
-    char *proxy_host = NULL;
-    char *proxy_port_str = NULL;
+    char *host = NULL, *port = NULL, *path = NULL, *used_path = opt_path;
+#ifndef OPENSSL_NO_SOCK
+    int portnum, ssl;
+    static char server_port[32] = { '\0' };
+    const char *proxy_host = NULL;
+#endif
+    char server_buf[200] = "mock server";
+    char proxy_buf[200] = "";
 
+    if (!opt_use_mock_srv && opt_rspin == NULL) { /* note: -port is not given */
+#ifndef OPENSSL_NO_SOCK
+        if (opt_server == NULL) {
+            CMP_err("missing -server or -use_mock_srv or -rspin option");
+            goto err;
+        }
+#else
+        CMP_err("missing -use_mock_srv or -rspin option; -server option is not supported due to no-sock build");
+        goto err;
+#endif
+    }
+#ifndef OPENSSL_NO_SOCK
     if (opt_server == NULL) {
-        CMP_err("missing server address[:port]");
+        if (opt_proxy != NULL)
+            CMP_warn("ignoring -proxy option since -server is not given");
+        if (opt_no_proxy != NULL)
+            CMP_warn("ignoring -no_proxy option since -server is not given");
+        if (opt_tls_used) {
+            CMP_warn("ignoring -tls_used option since -server is not given");
+            opt_tls_used = 0;
+        }
+        goto set_path;
+    }
+    if (!OSSL_HTTP_parse_url(opt_server, &ssl, NULL /* user */, &host, &port,
+                             &portnum, &path, NULL /* q */, NULL /* frag */)) {
+        CMP_err1("cannot parse -server URL: %s", opt_server);
         goto err;
-    } else if ((server_port =
-                parse_addr(&opt_server, server_port, "server")) < 0) {
+    }
+    if (ssl && !opt_tls_used) {
+        CMP_err("missing -tls_used option since -server URL indicates https");
         goto err;
     }
-    if (server_port != 0)
-        BIO_snprintf(server_port_s, sizeof(server_port_s), "%d", server_port);
-    if (!OSSL_CMP_CTX_set1_server(ctx, opt_server)
-            || !OSSL_CMP_CTX_set_serverPort(ctx, server_port)
-            || !OSSL_CMP_CTX_set1_serverPath(ctx, opt_path))
+
+    BIO_snprintf(server_port, sizeof(server_port), "%s", port);
+    if (opt_path == NULL)
+        used_path = path;
+    if (!OSSL_CMP_CTX_set1_server(ctx, host)
+            || !OSSL_CMP_CTX_set_serverPort(ctx, portnum))
         goto oom;
     if (opt_proxy != NULL && !OSSL_CMP_CTX_set1_proxy(ctx, opt_proxy))
         goto oom;
     if (opt_no_proxy != NULL && !OSSL_CMP_CTX_set1_no_proxy(ctx, opt_no_proxy))
         goto oom;
-    (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s://%s%s%s/%s",
-                       opt_tls_used ? "s" : "", opt_server,
-                       server_port == 0 ? "" : ":", server_port_s,
-                       opt_path == NULL ? "" :
-                       opt_path[0] == '/' ? opt_path + 1 : opt_path);
+    (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s://%s:%s/%s",
+                       opt_tls_used ? "s" : "", host, port,
+                       *used_path == '/' ? used_path + 1 : used_path);
 
-    if (opt_proxy != NULL)
-        (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", opt_proxy);
+    proxy_host = OSSL_HTTP_adapt_proxy(opt_proxy, opt_no_proxy, host, ssl);
+    if (proxy_host != NULL)
+        (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", proxy_host);
 
-    if (!transform_opts())
-        goto err;
-
-    if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) {
-        if (opt_newkey == NULL && opt_key == NULL && opt_csr == NULL) {
-            CMP_err("missing -newkey (or -key) to be certified");
-            goto err;
-        }
-        if (opt_certout == NULL) {
-            CMP_err("-certout not given, nowhere to save certificate");
-            goto err;
-        }
-    }
-    if (opt_cmd == CMP_KUR) {
-        char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert;
+ set_path:
+#endif
 
-        if (ref_cert == NULL) {
-            CMP_err("missing -oldcert option for certificate to be updated");
-            goto err;
-        }
-        if (opt_subject != NULL)
-            CMP_warn2("-subject '%s' given, which overrides the subject of '%s' in KUR",
-                      opt_subject, ref_cert);
-    }
-    if (opt_cmd == CMP_RR && opt_oldcert == NULL) {
-        CMP_err("missing certificate to be revoked");
-        goto err;
-    }
-    if (opt_cmd == CMP_P10CR && opt_csr == NULL) {
-        CMP_err("missing PKCS#10 CSR for p10cr");
+    if (!OSSL_CMP_CTX_set1_serverPath(ctx, used_path))
+        goto oom;
+    if (!transform_opts())
         goto err;
-    }
-
-    if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL
-            && opt_oldcert == NULL && opt_cert == NULL)
-        CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient will be set to \"NULL-DN\"");
 
     if (opt_infotype_s != NULL) {
         char id_buf[100] = "id-it-";
@@ -2009,6 +1880,15 @@ static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
     if (!setup_verification_ctx(ctx))
         goto err;
 
+    if (opt_keep_alive != 1)
+        (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_KEEP_ALIVE,
+                                      opt_keep_alive);
+    if (opt_total_timeout > 0 && opt_msg_timeout > 0
+            && opt_total_timeout < opt_msg_timeout) {
+        CMP_err2("-total_timeout argument = %d must not be < %d (-msg_timeout)",
+                 opt_total_timeout, opt_msg_timeout);
+        goto err;
+    }
     if (opt_msg_timeout >= 0) /* must do this before setup_ssl_ctx() */
         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT,
                                       opt_msg_timeout);
@@ -2024,16 +1904,8 @@ static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
             || opt_rspin != NULL || opt_rspout != NULL || opt_use_mock_srv)
         (void)OSSL_CMP_CTX_set_transfer_cb(ctx, read_write_req_resp);
 
-    if ((opt_tls_cert != NULL || opt_tls_key != NULL
-         || opt_tls_keypass != NULL || opt_tls_extra != NULL
-         || opt_tls_trusted != NULL || opt_tls_host != NULL)
-            && !opt_tls_used)
-        CMP_warn("TLS options(s) given but not -tls_used");
+#ifndef OPENSSL_NO_SOCK
     if (opt_tls_used) {
-#ifdef OPENSSL_NO_SOCK
-        BIO_printf(bio_err, "Cannot use TLS - sockets not supported\n");
-        goto err;
-#else
         APP_HTTP_TLS_INFO *info;
 
         if (opt_tls_cert != NULL
@@ -2046,24 +1918,20 @@ static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
                 goto err;
             }
         }
-        if (opt_use_mock_srv) {
-            CMP_err("cannot use TLS options together with -use_mock_srv");
-            goto err;
-        }
         if ((info = OPENSSL_zalloc(sizeof(*info))) == NULL)
             goto err;
         (void)OSSL_CMP_CTX_set_http_cb_arg(ctx, info);
         /* info will be freed along with CMP ctx */
         info->server = opt_server;
-        info->port = server_port_s;
+        info->port = server_port;
         info->use_proxy = opt_proxy != NULL;
         info->timeout = OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT);
-        info->ssl_ctx = setup_ssl_ctx(ctx, engine);
+        info->ssl_ctx = setup_ssl_ctx(ctx, host, engine);
         if (info->ssl_ctx == NULL)
             goto err;
         (void)OSSL_CMP_CTX_set_http_cb(ctx, app_http_tls_cb);
-#endif
     }
+#endif
 
     if (!setup_protection_ctx(ctx, engine))
         goto err;
@@ -2080,13 +1948,17 @@ static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
         goto err;
 
     /* not printing earlier, to minimize confusion in case setup fails before */
-    CMP_info2("will contact %s%s", server_buf, proxy_buf);
+    if (opt_rspin != NULL)
+        CMP_info("will not contact any server since -rspin is given");
+    else
+        CMP_info2("will contact %s%s", server_buf, proxy_buf);
 
     ret = 1;
 
  err:
-    OPENSSL_free(proxy_host);
-    OPENSSL_free(proxy_port_str);
+    OPENSSL_free(host);
+    OPENSSL_free(port);
+    OPENSSL_free(path);
     return ret;
  oom:
     CMP_err("out of memory");
@@ -2111,18 +1983,21 @@ static int write_cert(BIO *bio, X509 *cert)
 }
 
 /*
- * writes out a stack of certs to the given file.
+ * If destFile != NULL writes out a stack of certs to the given file.
+ * In any case frees the certs.
  * Depending on options use either PEM or DER format,
  * where DER does not make much sense for writing more than one cert!
- * Returns number of written certificates on success, 0 on error.
+ * Returns number of written certificates on success, -1 on error.
  */
-static int save_certs(OSSL_CMP_CTX *ctx,
-                      STACK_OF(X509) *certs, char *destFile, char *desc)
+static int save_free_certs(OSSL_CMP_CTX *ctx,
+                           STACK_OF(X509) *certs, char *destFile, char *desc)
 {
     BIO *bio = NULL;
     int i;
     int n = sk_X509_num(certs);
 
+    if (destFile == NULL)
+        goto end;
     CMP_info3("received %d %s certificate(s), saving to file '%s'",
               n, desc, destFile);
     if (n > 1 && opt_certform != FORMAT_PEM)
@@ -2132,19 +2007,20 @@ static int save_certs(OSSL_CMP_CTX *ctx,
             || !BIO_write_filename(bio, (char *)destFile)) {
         CMP_err1("could not open file '%s' for writing", destFile);
         n = -1;
-        goto err;
+        goto end;
     }
 
     for (i = 0; i < n; i++) {
         if (!write_cert(bio, sk_X509_value(certs, i))) {
             CMP_err1("cannot write certificate to file '%s'", destFile);
             n = -1;
-            goto err;
+            goto end;
         }
     }
 
- err:
+ end:
     BIO_free(bio);
+    OSSL_STACK_OF_X509_free(certs);
     return n;
 }
 
@@ -2173,7 +2049,7 @@ static void print_itavs(STACK_OF(OSSL_CMP_ITAV) *itavs)
 }
 
 static char opt_item[SECTION_NAME_MAX + 1];
-/* get previous name from a comma-separated list of names */
+/* get previous name from a comma or space-separated list of names */
 static const char *prev_item(const char *opt, const char *end)
 {
     const char *beg;
@@ -2182,19 +2058,28 @@ static const char *prev_item(const char *opt, const char *end)
     if (end == opt)
         return NULL;
     beg = end;
-    while (beg != opt && beg[-1] != ',' && !isspace(beg[-1]))
-        beg--;
+    while (beg > opt) {
+        --beg;
+        if (beg[0] == ',' || isspace(beg[0])) {
+            ++beg;
+            break;
+        }
+    }
     len = end - beg;
-    if (len > SECTION_NAME_MAX)
+    if (len > SECTION_NAME_MAX) {
+        CMP_warn3("using only first %d characters of section name starting with \"%.*s\"",
+                  SECTION_NAME_MAX, SECTION_NAME_MAX, beg);
         len = SECTION_NAME_MAX;
-    strncpy(opt_item, beg, len);
-    opt_item[SECTION_NAME_MAX] = '\0'; /* avoid gcc v8 O3 stringop-truncation */
+    }
+    memcpy(opt_item, beg, len);
     opt_item[len] = '\0';
-    if (len > SECTION_NAME_MAX)
-        CMP_warn2("using only first %d characters of section name starting with \"%s\"",
-                  SECTION_NAME_MAX, opt_item);
-    while (beg != opt && (beg[-1] == ',' || isspace(beg[-1])))
-        beg--;
+    while (beg > opt) {
+        --beg;
+        if (beg[0] != ',' && !isspace(beg[0])) {
+            ++beg;
+            break;
+        }
+    }
     return beg;
 }
 
@@ -2242,42 +2127,62 @@ static int read_config(void)
     long num = 0;
     char *txt = NULL;
     const OPTIONS *opt;
-    int provider_option;
-    int verification_option;
-    int start = OPT_VERBOSITY;
+    int start_opt = OPT_VERBOSITY - OPT_HELP;
+    int start_idx = OPT_VERBOSITY - 2;
     /*
      * starting with offset OPT_VERBOSITY because OPT_CONFIG and OPT_SECTION
      * would not make sense within the config file.
-     * Moreover, these two options and OPT_VERBOSITY have already been handled.
      */
+    int n_options = OSSL_NELEM(cmp_options) - 1;
 
-    for (i = start - OPT_HELP, opt = &cmp_options[start];
-         opt->name; i++, opt++) {
+    for (opt = &cmp_options[start_opt], i = start_idx;
+         opt->name != NULL; i++, opt++)
         if (!strcmp(opt->name, OPT_SECTION_STR)
-                || !strcmp(opt->name, OPT_MORE_STR)) {
-            i--;
-            continue;
-        }
-        provider_option = (OPT_PROV__FIRST <= opt->retval
+                || !strcmp(opt->name, OPT_MORE_STR))
+            n_options--;
+    OPENSSL_assert(OSSL_NELEM(cmp_vars) == n_options
+                 + OPT_PROV__FIRST + 1 - OPT_PROV__LAST
+                 + OPT_R__FIRST + 1 - OPT_R__LAST
+                 + OPT_V__FIRST + 1 - OPT_V__LAST);
+    for (opt = &cmp_options[start_opt], i = start_idx;
+         opt->name != NULL; i++, opt++) {
+        int provider_option = (OPT_PROV__FIRST <= opt->retval
                                && opt->retval < OPT_PROV__LAST);
-        verification_option = (OPT_V__FIRST <= opt->retval
+        int rand_state_option = (OPT_R__FIRST <= opt->retval
+                                 && opt->retval < OPT_R__LAST);
+        int verification_option = (OPT_V__FIRST <= opt->retval
                                    && opt->retval < OPT_V__LAST);
-        if (provider_option || verification_option)
+
+        if (strcmp(opt->name, OPT_SECTION_STR) == 0
+                || strcmp(opt->name, OPT_MORE_STR) == 0) {
             i--;
-        if (cmp_vars[i].txt == NULL) {
-            CMP_err1("internal: cmp_vars array too short, i=%d", i);
-            return 0;
+            continue;
         }
+        if (provider_option || rand_state_option || verification_option)
+            i--;
         switch (opt->valtype) {
         case '-':
+        case 'p':
         case 'n':
+        case 'N':
         case 'l':
             if (!conf_get_number_e(conf, opt_section, opt->name, &num)) {
                 ERR_clear_error();
                 continue; /* option not provided */
             }
+            if (opt->valtype == 'p' && num <= 0) {
+                opt_printf_stderr("Non-positive number \"%ld\" for config option -%s\n",
+                                  num, opt->name);
+                return -1;
+            }
+            if (opt->valtype == 'N' && num < 0) {
+                opt_printf_stderr("Negative number \"%ld\" for config option -%s\n",
+                                  num, opt->name);
+                return -1;
+            }
             break;
         case 's':
+        case '>':
         case 'M':
             txt = conf_get_string(conf, opt_section, opt->name);
             if (txt == NULL) {
@@ -2321,7 +2226,9 @@ static int read_config(void)
         } else {
             switch (opt->valtype) {
             case '-':
+            case 'p':
             case 'n':
+            case 'N':
                 if (num < INT_MIN || INT_MAX < num) {
                     BIO_printf(bio_err,
                                "integer value out of range for option '%s'\n",
@@ -2345,30 +2252,20 @@ static int read_config(void)
     return 1;
 }
 
-static char *opt_str(char *opt)
+static char *opt_str(void)
 {
     char *arg = opt_arg();
 
     if (arg[0] == '\0') {
-        CMP_warn1("argument of -%s option is empty string, resetting option",
-                  opt);
+        CMP_warn1("%s option argument is empty string, resetting option",
+                  opt_flag());
         arg = NULL;
     } else if (arg[0] == '-') {
-        CMP_warn1("argument of -%s option starts with hyphen", opt);
+        CMP_warn1("%s option argument starts with hyphen", opt_flag());
     }
     return arg;
 }
 
-static int opt_nat(void)
-{
-    int result = -1;
-
-    if (opt_int(opt_arg(), &result) && result < 0)
-        BIO_printf(bio_err, "error: argument '%s' must not be negative\n",
-                   opt_arg());
-    return result;
-}
-
 /* returns 1 on success, 0 on error, -1 on -help (i.e., stop with success) */
 static int get_opts(int argc, char **argv)
 {
@@ -2380,97 +2277,115 @@ static int get_opts(int argc, char **argv)
         switch (o) {
         case OPT_EOF:
         case OPT_ERR:
-            goto opt_err;
+ opthelp:
+            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
+            return 0;
         case OPT_HELP:
             opt_help(cmp_options);
             return -1;
         case OPT_CONFIG: /* has already been handled */
         case OPT_SECTION: /* has already been handled */
-        case OPT_VERBOSITY: /* has already been handled */
             break;
+        case OPT_VERBOSITY:
+            if (!set_verbosity(opt_int_arg()))
+                goto opthelp;
+            break;
+#ifndef OPENSSL_NO_SOCK
         case OPT_SERVER:
-            opt_server = opt_str("server");
+            opt_server = opt_str();
             break;
         case OPT_PROXY:
-            opt_proxy = opt_str("proxy");
+            opt_proxy = opt_str();
             break;
         case OPT_NO_PROXY:
-            opt_no_proxy = opt_str("no_proxy");
+            opt_no_proxy = opt_str();
+            break;
+#endif
+        case OPT_RECIPIENT:
+            opt_recipient = opt_str();
             break;
         case OPT_PATH:
-            opt_path = opt_str("path");
+            opt_path = opt_str();
+            break;
+        case OPT_KEEP_ALIVE:
+            opt_keep_alive = opt_int_arg();
+            if (opt_keep_alive > 2) {
+                CMP_err("-keep_alive argument must be 0, 1, or 2");
+                goto opthelp;
+            }
             break;
         case OPT_MSG_TIMEOUT:
-            if ((opt_msg_timeout = opt_nat()) < 0)
-                goto opt_err;
+            opt_msg_timeout = opt_int_arg();
             break;
         case OPT_TOTAL_TIMEOUT:
-            if ((opt_total_timeout = opt_nat()) < 0)
-                goto opt_err;
+            opt_total_timeout = opt_int_arg();
             break;
+#ifndef OPENSSL_NO_SOCK
         case OPT_TLS_USED:
             opt_tls_used = 1;
             break;
         case OPT_TLS_CERT:
-            opt_tls_cert = opt_str("tls_cert");
+            opt_tls_cert = opt_str();
             break;
         case OPT_TLS_KEY:
-            opt_tls_key = opt_str("tls_key");
+            opt_tls_key = opt_str();
             break;
         case OPT_TLS_KEYPASS:
-            opt_tls_keypass = opt_str("tls_keypass");
+            opt_tls_keypass = opt_str();
             break;
         case OPT_TLS_EXTRA:
-            opt_tls_extra = opt_str("tls_extra");
+            opt_tls_extra = opt_str();
             break;
         case OPT_TLS_TRUSTED:
-            opt_tls_trusted = opt_str("tls_trusted");
+            opt_tls_trusted = opt_str();
             break;
         case OPT_TLS_HOST:
-            opt_tls_host = opt_str("tls_host");
+            opt_tls_host = opt_str();
             break;
+#endif
+
         case OPT_REF:
-            opt_ref = opt_str("ref");
+            opt_ref = opt_str();
             break;
         case OPT_SECRET:
-            opt_secret = opt_str("secret");
+            opt_secret = opt_str();
             break;
         case OPT_CERT:
-            opt_cert = opt_str("cert");
+            opt_cert = opt_str();
+            break;
+        case OPT_OWN_TRUSTED:
+            opt_own_trusted = opt_str();
             break;
         case OPT_KEY:
-            opt_key = opt_str("key");
+            opt_key = opt_str();
             break;
         case OPT_KEYPASS:
-            opt_keypass = opt_str("keypass");
+            opt_keypass = opt_str();
             break;
         case OPT_DIGEST:
-            opt_digest = opt_str("digest");
+            opt_digest = opt_str();
             break;
         case OPT_MAC:
-            opt_mac = opt_str("mac");
+            opt_mac = opt_str();
             break;
         case OPT_EXTRACERTS:
-            opt_extracerts = opt_str("extracerts");
+            opt_extracerts = opt_str();
             break;
         case OPT_UNPROTECTED_REQUESTS:
             opt_unprotected_requests = 1;
             break;
 
         case OPT_TRUSTED:
-            opt_trusted = opt_str("trusted");
+            opt_trusted = opt_str();
             break;
         case OPT_UNTRUSTED:
-            opt_untrusted = opt_str("untrusted");
+            opt_untrusted = opt_str();
             break;
         case OPT_SRVCERT:
-            opt_srvcert = opt_str("srvcert");
-            break;
-        case OPT_RECIPIENT:
-            opt_recipient = opt_str("recipient");
+            opt_srvcert = opt_str();
             break;
         case OPT_EXPECT_SENDER:
-            opt_expect_sender = opt_str("expect_sender");
+            opt_expect_sender = opt_str();
             break;
         case OPT_IGNORE_KEYUSAGE:
             opt_ignore_keyusage = 1;
@@ -2479,73 +2394,72 @@ static int get_opts(int argc, char **argv)
             opt_unprotected_errors = 1;
             break;
         case OPT_EXTRACERTSOUT:
-            opt_extracertsout = opt_str("extracertsout");
+            opt_extracertsout = opt_str();
             break;
         case OPT_CACERTSOUT:
-            opt_cacertsout = opt_str("cacertsout");
+            opt_cacertsout = opt_str();
             break;
 
         case OPT_V_CASES:
             if (!opt_verify(o, vpm))
-                goto opt_err;
+                goto opthelp;
             break;
         case OPT_CMD:
-            opt_cmd_s = opt_str("cmd");
+            opt_cmd_s = opt_str();
             break;
         case OPT_INFOTYPE:
-            opt_infotype_s = opt_str("infotype");
+            opt_infotype_s = opt_str();
             break;
         case OPT_GENINFO:
-            opt_geninfo = opt_str("geninfo");
+            opt_geninfo = opt_str();
             break;
 
         case OPT_NEWKEY:
-            opt_newkey = opt_str("newkey");
+            opt_newkey = opt_str();
             break;
         case OPT_NEWKEYPASS:
-            opt_newkeypass = opt_str("newkeypass");
+            opt_newkeypass = opt_str();
             break;
         case OPT_SUBJECT:
-            opt_subject = opt_str("subject");
+            opt_subject = opt_str();
             break;
         case OPT_ISSUER:
-            opt_issuer = opt_str("issuer");
+            opt_issuer = opt_str();
             break;
         case OPT_DAYS:
-            if ((opt_days = opt_nat()) < 0)
-                goto opt_err;
+            opt_days = opt_int_arg();
             break;
         case OPT_REQEXTS:
-            opt_reqexts = opt_str("reqexts");
+            opt_reqexts = opt_str();
             break;
         case OPT_SANS:
-            opt_sans = opt_str("sans");
+            opt_sans = opt_str();
             break;
         case OPT_SAN_NODEFAULT:
             opt_san_nodefault = 1;
             break;
         case OPT_POLICIES:
-            opt_policies = opt_str("policies");
+            opt_policies = opt_str();
             break;
         case OPT_POLICY_OIDS:
-            opt_policy_oids = opt_str("policy_oids");
+            opt_policy_oids = opt_str();
             break;
         case OPT_POLICY_OIDS_CRITICAL:
             opt_policy_oids_critical = 1;
             break;
         case OPT_POPO:
-            if (!opt_int(opt_arg(), &opt_popo)
-                    || opt_popo < OSSL_CRMF_POPO_NONE
+            opt_popo = opt_int_arg();
+            if (opt_popo < OSSL_CRMF_POPO_NONE
                     || opt_popo > OSSL_CRMF_POPO_KEYENC) {
                 CMP_err("invalid popo spec. Valid values are -1 .. 2");
-                goto opt_err;
+                goto opthelp;
             }
             break;
         case OPT_CSR:
             opt_csr = opt_arg();
             break;
         case OPT_OUT_TRUSTED:
-            opt_out_trusted = opt_str("out_trusted");
+            opt_out_trusted = opt_str();
             break;
         case OPT_IMPLICIT_CONFIRM:
             opt_implicit_confirm = 1;
@@ -2554,120 +2468,129 @@ static int get_opts(int argc, char **argv)
             opt_disable_confirm = 1;
             break;
         case OPT_CERTOUT:
-            opt_certout = opt_str("certout");
+            opt_certout = opt_str();
+            break;
+        case OPT_CHAINOUT:
+            opt_chainout = opt_str();
             break;
         case OPT_OLDCERT:
-            opt_oldcert = opt_str("oldcert");
+            opt_oldcert = opt_str();
             break;
         case OPT_REVREASON:
-            if (!opt_int(opt_arg(), &opt_revreason)
-                    || opt_revreason < CRL_REASON_NONE
+            opt_revreason = opt_int_arg();
+                if (opt_revreason < CRL_REASON_NONE
                     || opt_revreason > CRL_REASON_AA_COMPROMISE
                     || opt_revreason == 7) {
                 CMP_err("invalid revreason. Valid values are -1 .. 6, 8 .. 10");
-                goto opt_err;
+                goto opthelp;
             }
             break;
         case OPT_CERTFORM:
-            opt_certform_s = opt_str("certform");
+            opt_certform_s = opt_str();
             break;
         case OPT_KEYFORM:
-            opt_keyform_s = opt_str("keyform");
+            opt_keyform_s = opt_str();
             break;
         case OPT_OTHERPASS:
-            opt_otherpass = opt_str("otherpass");
+            opt_otherpass = opt_str();
             break;
 #ifndef OPENSSL_NO_ENGINE
         case OPT_ENGINE:
-            opt_engine = opt_str("engine");
+            opt_engine = opt_str();
             break;
 #endif
         case OPT_PROV_CASES:
             if (!opt_provider(o))
-                goto opt_err;
+                goto opthelp;
+            break;
+        case OPT_R_CASES:
+            if (!opt_rand(o))
+                goto opthelp;
             break;
 
         case OPT_BATCH:
             opt_batch = 1;
             break;
         case OPT_REPEAT:
-            opt_repeat = opt_nat();
+            opt_repeat = opt_int_arg();
             break;
         case OPT_REQIN:
-            opt_reqin = opt_str("reqin");
+            opt_reqin = opt_str();
             break;
         case OPT_REQIN_NEW_TID:
             opt_reqin_new_tid = 1;
             break;
         case OPT_REQOUT:
-            opt_reqout = opt_str("reqout");
+            opt_reqout = opt_str();
             break;
         case OPT_RSPIN:
-            opt_rspin = opt_str("rspin");
+            opt_rspin = opt_str();
             break;
         case OPT_RSPOUT:
-            opt_rspout = opt_str("rspout");
+            opt_rspout = opt_str();
             break;
         case OPT_USE_MOCK_SRV:
             opt_use_mock_srv = 1;
             break;
+
+#ifndef OPENSSL_NO_SOCK
         case OPT_PORT:
-            opt_port = opt_str("port");
+            opt_port = opt_str();
             break;
         case OPT_MAX_MSGS:
-            if ((opt_max_msgs = opt_nat()) < 0)
-                goto opt_err;
+            opt_max_msgs = opt_int_arg();
             break;
+#endif
         case OPT_SRV_REF:
-            opt_srv_ref = opt_str("srv_ref");
+            opt_srv_ref = opt_str();
             break;
         case OPT_SRV_SECRET:
-            opt_srv_secret = opt_str("srv_secret");
+            opt_srv_secret = opt_str();
             break;
         case OPT_SRV_CERT:
-            opt_srv_cert = opt_str("srv_cert");
+            opt_srv_cert = opt_str();
             break;
         case OPT_SRV_KEY:
-            opt_srv_key = opt_str("srv_key");
+            opt_srv_key = opt_str();
             break;
         case OPT_SRV_KEYPASS:
-            opt_srv_keypass = opt_str("srv_keypass");
+            opt_srv_keypass = opt_str();
             break;
         case OPT_SRV_TRUSTED:
-            opt_srv_trusted = opt_str("srv_trusted");
+            opt_srv_trusted = opt_str();
             break;
         case OPT_SRV_UNTRUSTED:
-            opt_srv_untrusted = opt_str("srv_untrusted");
+            opt_srv_untrusted = opt_str();
             break;
         case OPT_RSP_CERT:
-            opt_rsp_cert = opt_str("rsp_cert");
+            opt_rsp_cert = opt_str();
             break;
         case OPT_RSP_EXTRACERTS:
-            opt_rsp_extracerts = opt_str("rsp_extracerts");
+            opt_rsp_extracerts = opt_str();
             break;
         case OPT_RSP_CAPUBS:
-            opt_rsp_capubs = opt_str("rsp_capubs");
+            opt_rsp_capubs = opt_str();
             break;
         case OPT_POLL_COUNT:
-            opt_poll_count = opt_nat();
+            opt_poll_count = opt_int_arg();
             break;
         case OPT_CHECK_AFTER:
-            opt_check_after = opt_nat();
+            opt_check_after = opt_int_arg();
             break;
         case OPT_GRANT_IMPLICITCONF:
             opt_grant_implicitconf = 1;
             break;
         case OPT_PKISTATUS:
-            opt_pkistatus = opt_nat();
+            opt_pkistatus = opt_int_arg();
             break;
         case OPT_FAILURE:
-            opt_failure = opt_nat();
+            opt_failure = opt_int_arg();
             break;
         case OPT_FAILUREBITS:
-            opt_failurebits = opt_nat();
+            opt_failurebits = opt_int_arg();
             break;
         case OPT_STATUSSTRING:
-            opt_statusstring = opt_str("statusstring");
+            opt_statusstring = opt_str();
             break;
         case OPT_SEND_ERROR:
             opt_send_error = 1;
@@ -2689,18 +2612,90 @@ static int get_opts(int argc, char **argv)
             break;
         }
     }
-    argc = opt_num_rest();
-    argv = opt_rest();
-    if (argc != 0) {
-        CMP_err1("unknown parameter %s", argv[0]);
-        goto opt_err;
-    }
+
+    /* No extra args. */
+    if (!opt_check_rest_arg(NULL))
+        goto opthelp;
     return 1;
+}
 
- opt_err:
-    CMP_err1("use -help for summary of '%s' options", prog);
-    return 0;
+#ifndef OPENSSL_NO_SOCK
+static int cmp_server(OSSL_CMP_CTX *srv_cmp_ctx) {
+    BIO *acbio;
+    BIO *cbio = NULL;
+    int keep_alive = 0;
+    int msgs = 0;
+    int retry = 1;
+    int ret = 1;
+
+    if ((acbio = http_server_init(prog, opt_port, opt_verbosity)) == NULL)
+        return 0;
+    while (opt_max_msgs <= 0 || msgs < opt_max_msgs) {
+        char *path = NULL;
+        OSSL_CMP_MSG *req = NULL;
+        OSSL_CMP_MSG *resp = NULL;
+
+        ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG),
+                                       (ASN1_VALUE **)&req, &path,
+                                       &cbio, acbio, &keep_alive,
+                                       prog, 0, 0);
+        if (ret == 0) { /* no request yet */
+            if (retry) {
+                ossl_sleep(1000);
+                retry = 0;
+                continue;
+            }
+            ret = 0;
+            goto next;
+        }
+        if (ret++ == -1) /* fatal error */
+            break;
+
+        ret = 0;
+        msgs++;
+        if (req != NULL) {
+            if (strcmp(path, "") != 0 && strcmp(path, "pkix/") != 0) {
+                (void)http_server_send_status(cbio, 404, "Not Found");
+                CMP_err1("expecting empty path or 'pkix/' but got '%s'",
+                         path);
+                OPENSSL_free(path);
+                OSSL_CMP_MSG_free(req);
+                goto next;
+            }
+            OPENSSL_free(path);
+            resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req);
+            OSSL_CMP_MSG_free(req);
+            if (resp == NULL) {
+                (void)http_server_send_status(cbio,
+                                              500, "Internal Server Error");
+                break; /* treated as fatal error */
+            }
+            ret = http_server_send_asn1_resp(cbio, keep_alive,
+                                             "application/pkixcmp",
+                                             ASN1_ITEM_rptr(OSSL_CMP_MSG),
+                                             (const ASN1_VALUE *)resp);
+            OSSL_CMP_MSG_free(resp);
+            if (!ret)
+                break; /* treated as fatal error */
+        }
+    next:
+        if (!ret) { /* on transmission error, cancel CMP transaction */
+            (void)OSSL_CMP_CTX_set1_transactionID(srv_cmp_ctx, NULL);
+            (void)OSSL_CMP_CTX_set1_senderNonce(srv_cmp_ctx, NULL);
+        }
+        if (!ret || !keep_alive
+            || OSSL_CMP_CTX_get_status(srv_cmp_ctx) == -1
+             /* transaction closed by OSSL_CMP_CTX_server_perform() */) {
+            BIO_free_all(cbio);
+            cbio = NULL;
+        }
+    }
+
+    BIO_free_all(cbio);
+    BIO_free_all(acbio);
+    return ret;
 }
+#endif
 
 int cmp_main(int argc, char **argv)
 {
@@ -2708,9 +2703,10 @@ int cmp_main(int argc, char **argv)
     int i;
     X509 *newcert = NULL;
     ENGINE *engine = NULL;
-    char mock_server[] = "mock server:1";
+    OSSL_CMP_CTX *srv_cmp_ctx = NULL;
     int ret = 0; /* default: failure */
 
+    prog = opt_appname(argv[0]);
     if (argc <= 1) {
         opt_help(cmp_options);
         goto err;
@@ -2744,10 +2740,10 @@ int cmp_main(int argc, char **argv)
 
     /* read default values for options from config file */
     configfile = opt_config != NULL ? opt_config : default_config_file;
-    if (configfile && configfile[0] != '\0' /* non-empty string */
-            && (configfile != default_config_file
-                    || access(configfile, F_OK) != -1)) {
-        CMP_info1("using OpenSSL configuration file '%s'", configfile);
+    if (configfile != NULL && configfile[0] != '\0' /* non-empty string */
+            && (configfile != default_config_file || access(configfile, F_OK) != -1)) {
+        CMP_info2("using section(s) '%s' of OpenSSL configuration file '%s'",
+                  opt_section, configfile);
         conf = app_load_config(configfile);
         if (conf == NULL) {
             goto err;
@@ -2767,8 +2763,14 @@ int cmp_main(int argc, char **argv)
                     }
                 }
             }
-            if (!read_config())
+            ret = read_config();
+            if (!set_verbosity(opt_verbosity)) /* just for checking range */
+                ret = -1;
+            if (ret <= 0) {
+                if (ret == -1)
+                    BIO_printf(bio_err, "Use -help for summary.\n");
                 goto err;
+            }
         }
     }
     (void)BIO_flush(bio_err); /* prevent interference with opt_help() */
@@ -2777,27 +2779,16 @@ int cmp_main(int argc, char **argv)
     if (ret <= 0)
         goto err;
     ret = 0;
+    if (!app_RAND_load())
+        goto err;
 
-    if (opt_batch) {
-        UI_METHOD *ui_fallback_method;
-#ifndef OPENSSL_NO_UI_CONSOLE
-        ui_fallback_method = UI_OpenSSL();
-#else
-        ui_fallback_method = (UI_METHOD *)UI_null();
-#endif
-        UI_method_set_reader(ui_fallback_method, NULL);
-    }
+    if (opt_batch)
+        set_base_ui_method(UI_null());
 
-    if (opt_engine != NULL)
+    if (opt_engine != NULL) {
         engine = setup_engine_methods(opt_engine, 0 /* not: ENGINE_METHOD_ALL */, 0);
-
-    if (opt_port != NULL) {
-        if (opt_use_mock_srv) {
-            CMP_err("cannot use both -port and -use_mock_srv options");
-            goto err;
-        }
-        if (opt_server != NULL) {
-            CMP_err("cannot use both -port and -server options");
+        if (engine == NULL) {
+            CMP_err1("cannot load engine %s", opt_engine);
             goto err;
         }
     }
@@ -2810,99 +2801,71 @@ int cmp_main(int argc, char **argv)
         CMP_err1("cannot set up error reporting and logging for %s", prog);
         goto err;
     }
-    if ((opt_use_mock_srv || opt_port != NULL)) {
+
+#ifndef OPENSSL_NO_SOCK
+    if ((opt_tls_cert != NULL || opt_tls_key != NULL
+         || opt_tls_keypass != NULL || opt_tls_extra != NULL
+         || opt_tls_trusted != NULL || opt_tls_host != NULL)
+            && !opt_tls_used)
+        CMP_warn("Ingnoring TLS options(s) since -tls_used is not given");
+    if (opt_port != NULL) {
+        if (opt_tls_used) {
+            CMP_err("-tls_used option not supported with -port option");
+            goto err;
+        }
+        if (opt_use_mock_srv || opt_server != NULL || opt_rspin != NULL) {
+            CMP_err("cannot use -port with -use_mock_srv, -server, or -rspin options");
+            goto err;
+        }
+    }
+    if (opt_server != NULL && opt_use_mock_srv) {
+        CMP_err("cannot use both -server and -use_mock_srv options");
+        goto err;
+    }
+#endif
+    if (opt_rspin != NULL && opt_use_mock_srv) {
+        CMP_err("cannot use both -rspin and -use_mock_srv options");
+        goto err;
+    }
+
+    if (opt_use_mock_srv
+#ifndef OPENSSL_NO_SOCK
+        || opt_port != NULL
+#endif
+        ) {
         OSSL_CMP_SRV_CTX *srv_ctx;
 
         if ((srv_ctx = setup_srv_ctx(engine)) == NULL)
             goto err;
+        srv_cmp_ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx);
         OSSL_CMP_CTX_set_transfer_cb_arg(cmp_ctx, srv_ctx);
-        if (!OSSL_CMP_CTX_set_log_cb(OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx),
-                                     print_to_bio_out)) {
+        if (!OSSL_CMP_CTX_set_log_cb(srv_cmp_ctx, print_to_bio_err)) {
             CMP_err1("cannot set up error reporting and logging for %s", prog);
             goto err;
         }
+        OSSL_CMP_CTX_set_log_verbosity(srv_cmp_ctx, opt_verbosity);
     }
 
+#ifndef OPENSSL_NO_SOCK
+    if (opt_tls_used && (opt_use_mock_srv || opt_rspin != NULL)) {
+        CMP_warn("ignoring -tls_used option since -use_mock_srv or -rspin is given");
+        opt_tls_used = 0;
+    }
 
     if (opt_port != NULL) { /* act as very basic CMP HTTP server */
-#ifdef OPENSSL_NO_SOCK
-        BIO_printf(bio_err, "Cannot act as server - sockets not supported\n");
-#else
-        BIO *acbio;
-        BIO *cbio = NULL;
-        int msgs = 0;
-
-        if ((acbio = http_server_init_bio(prog, opt_port)) == NULL)
-            goto err;
-        while (opt_max_msgs <= 0 || msgs < opt_max_msgs) {
-            char *path = NULL;
-            OSSL_CMP_MSG *req = NULL;
-            OSSL_CMP_MSG *resp = NULL;
-
-            ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG),
-                                           (ASN1_VALUE **)&req, &path,
-                                           &cbio, acbio, prog, 0, 0);
-            if (ret == 0)
-                continue;
-            if (ret++ == -1)
-                break; /* fatal error */
-
-            ret = 0;
-            msgs++;
-            if (req != NULL) {
-                if (strcmp(path, "") != 0 && strcmp(path, "pkix/") != 0) {
-                    (void)http_server_send_status(cbio, 404, "Not Found");
-                    CMP_err1("Expecting empty path or 'pkix/' but got '%s'",
-                             path);
-                    OPENSSL_free(path);
-                    OSSL_CMP_MSG_free(req);
-                    goto cont;
-                }
-                OPENSSL_free(path);
-                resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req);
-                OSSL_CMP_MSG_free(req);
-                if (resp == NULL) {
-                    (void)http_server_send_status(cbio,
-                                                  500, "Internal Server Error");
-                    break; /* treated as fatal error */
-                }
-                ret = http_server_send_asn1_resp(cbio, "application/pkixcmp",
-                                                 ASN1_ITEM_rptr(OSSL_CMP_MSG),
-                                                 (const ASN1_VALUE *)resp);
-                OSSL_CMP_MSG_free(resp);
-                if (!ret)
-                    break; /* treated as fatal error */
-            } else {
-                (void)http_server_send_status(cbio, 400, "Bad Request");
-            }
-        cont:
-            BIO_free_all(cbio);
-            cbio = NULL;
-        }
-        BIO_free_all(cbio);
-        BIO_free_all(acbio);
-#endif
+        ret = cmp_server(srv_cmp_ctx);
         goto err;
     }
-    /* else act as CMP client */
 
-    if (opt_use_mock_srv) {
-        if (opt_server != NULL) {
-            CMP_err("cannot use both -use_mock_srv and -server options");
-            goto err;
-        }
-        if (opt_proxy != NULL) {
-            CMP_err("cannot use both -use_mock_srv and -proxy options");
-            goto err;
-        }
-        opt_server = mock_server;
-        opt_proxy = "API";
-    } else {
-        if (opt_server == NULL) {
-            CMP_err("missing -server option");
-            goto err;
+    /* act as CMP client, possibly using internal mock server */
+
+    if (opt_server != NULL) {
+        if (opt_rspin != NULL) {
+            CMP_warn("ignoring -server option since -rspin is given");
+            opt_server = NULL;
         }
     }
+#endif
 
     if (!setup_client_ctx(cmp_ctx, engine)) {
         CMP_err("cannot set up CMP context");
@@ -2913,27 +2876,26 @@ int cmp_main(int argc, char **argv)
         switch (opt_cmd) {
         case CMP_IR:
             newcert = OSSL_CMP_exec_IR_ses(cmp_ctx);
-            if (newcert == NULL)
-                goto err;
+            if (newcert != NULL)
+                ret = 1;
             break;
         case CMP_KUR:
             newcert = OSSL_CMP_exec_KUR_ses(cmp_ctx);
-            if (newcert == NULL)
-                goto err;
+            if (newcert != NULL)
+                ret = 1;
             break;
         case CMP_CR:
             newcert = OSSL_CMP_exec_CR_ses(cmp_ctx);
-            if (newcert == NULL)
-                goto err;
+            if (newcert != NULL)
+                ret = 1;
             break;
         case CMP_P10CR:
             newcert = OSSL_CMP_exec_P10CR_ses(cmp_ctx);
-            if (newcert == NULL)
-                goto err;
+            if (newcert != NULL)
+                ret = 1;
             break;
         case CMP_RR:
-            if (OSSL_CMP_exec_RR_ses(cmp_ctx) == NULL)
-                goto err;
+            ret = OSSL_CMP_exec_RR_ses(cmp_ctx);
             break;
         case CMP_GENM:
             {
@@ -2947,24 +2909,34 @@ int cmp_main(int argc, char **argv)
                     OSSL_CMP_CTX_push0_genm_ITAV(cmp_ctx, itav);
                 }
 
-                if ((itavs = OSSL_CMP_exec_GENM_ses(cmp_ctx)) == NULL)
-                    goto err;
-                print_itavs(itavs);
-                sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
+                if ((itavs = OSSL_CMP_exec_GENM_ses(cmp_ctx)) != NULL) {
+                    print_itavs(itavs);
+                    sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
+                    ret = 1;
+                }
                 break;
             }
         default:
             break;
         }
+        if (OSSL_CMP_CTX_get_status(cmp_ctx) < 0)
+            goto err; /* we got no response, maybe even did not send request */
 
         {
-            /* print PKIStatusInfo (this is in case there has been no error) */
+            /* print PKIStatusInfo */
             int status = OSSL_CMP_CTX_get_status(cmp_ctx);
             char *buf = app_malloc(OSSL_CMP_PKISI_BUFLEN, "PKIStatusInfo buf");
             const char *string =
                 OSSL_CMP_CTX_snprint_PKIStatus(cmp_ctx, buf,
                                                OSSL_CMP_PKISI_BUFLEN);
+            const char *from = "", *server = "";
 
+#ifndef OPENSSL_NO_SOCK
+            if (opt_server != NULL) {
+                from = " from ";
+                server = opt_server;
+            }
+#endif
             CMP_print(bio_err,
                       status == OSSL_CMP_PKISTATUS_accepted
                       ? OSSL_CMP_LOG_INFO :
@@ -2975,44 +2947,34 @@ int cmp_main(int argc, char **argv)
                       status == OSSL_CMP_PKISTATUS_rejection ? "server error" :
                       status == OSSL_CMP_PKISTATUS_waiting ? "internal error"
                                                            : "warning",
-                      "received from %s %s %s", opt_server,
-                      string != NULL ? string : "<unknown PKIStatus>", "");
+                      "received%s%s %s", from, server,
+                      string != NULL ? string : "<unknown PKIStatus>");
             OPENSSL_free(buf);
         }
 
-        if (opt_cacertsout != NULL) {
-            STACK_OF(X509) *certs = OSSL_CMP_CTX_get1_caPubs(cmp_ctx);
-
-            if (sk_X509_num(certs) > 0
-                    && save_certs(cmp_ctx, certs, opt_cacertsout, "CA") < 0) {
-                sk_X509_pop_free(certs, X509_free);
-                goto err;
-            }
-            sk_X509_pop_free(certs, X509_free);
-        }
-
-        if (opt_extracertsout != NULL) {
-            STACK_OF(X509) *certs = OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx);
-            if (sk_X509_num(certs) > 0
-                    && save_certs(cmp_ctx, certs, opt_extracertsout,
-                                  "extra") < 0) {
-                sk_X509_pop_free(certs, X509_free);
-                goto err;
-            }
-            sk_X509_pop_free(certs, X509_free);
-        }
-
-        if (opt_certout != NULL && newcert != NULL) {
+        if (save_free_certs(cmp_ctx, OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx),
+                            opt_extracertsout, "extra") < 0)
+            ret = 0;
+        if (!ret)
+            goto err;
+        ret = 0;
+        if (save_free_certs(cmp_ctx, OSSL_CMP_CTX_get1_caPubs(cmp_ctx),
+                            opt_cacertsout, "CA") < 0)
+            goto err;
+        if (newcert != NULL) {
             STACK_OF(X509) *certs = sk_X509_new_null();
 
-            if (certs == NULL || !sk_X509_push(certs, newcert)
-                    || save_certs(cmp_ctx, certs, opt_certout,
-                                  "enrolled") < 0) {
+            if (!X509_add_cert(certs, newcert, X509_ADD_FLAG_UP_REF)) {
                 sk_X509_free(certs);
                 goto err;
             }
-            sk_X509_free(certs);
+            if (save_free_certs(cmp_ctx, certs, opt_certout, "enrolled") < 0)
+                goto err;
         }
+        if (save_free_certs(cmp_ctx, OSSL_CMP_CTX_get1_newChain(cmp_ctx),
+                            opt_chainout, "chain") < 0)
+            goto err;
+
         if (!OSSL_CMP_CTX_reinit(cmp_ctx))
             goto err;
     }
@@ -3023,7 +2985,9 @@ int cmp_main(int argc, char **argv)
     cleanse(opt_keypass);
     cleanse(opt_newkeypass);
     cleanse(opt_otherpass);
+#ifndef OPENSSL_NO_SOCK
     cleanse(opt_tls_keypass);
+#endif
     cleanse(opt_secret);
     cleanse(opt_srv_keypass);
     cleanse(opt_srv_secret);
@@ -3032,15 +2996,9 @@ int cmp_main(int argc, char **argv)
         OSSL_CMP_CTX_print_errors(cmp_ctx);
 
     ossl_cmp_mock_srv_free(OSSL_CMP_CTX_get_transfer_cb_arg(cmp_ctx));
-    {
-        APP_HTTP_TLS_INFO *http_tls_info =
-            OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx);
-
-        if (http_tls_info != NULL) {
-            SSL_CTX_free(http_tls_info->ssl_ctx);
-            OPENSSL_free(http_tls_info);
-        }
-    }
+#ifndef OPENSSL_NO_SOCK
+    APP_HTTP_TLS_INFO_free(OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx));
+#endif
     X509_STORE_free(OSSL_CMP_CTX_get_certConf_cb_arg(cmp_ctx));
     OSSL_CMP_CTX_free(cmp_ctx);
     X509_VERIFY_PARAM_free(vpm);
@@ -3049,5 +3007,5 @@ int cmp_main(int argc, char **argv)
     NCONF_free(conf); /* must not do as long as opt_... variables are used */
     OSSL_CMP_log_close();
 
-    return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+    return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS; /* ret == -1 for -help */
 }