Home | History | Annotate | Download | only in ssl
      1 /*
      2  * vtables (and methods that call through them) for the 4 types of
      3  * SSLSockets supported.  Only one type is still supported.
      4  * Various other functions.
      5  *
      6  * This Source Code Form is subject to the terms of the Mozilla Public
      7  * License, v. 2.0. If a copy of the MPL was not distributed with this
      8  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      9 #include "seccomon.h"
     10 #include "cert.h"
     11 #include "keyhi.h"
     12 #include "ssl.h"
     13 #include "sslimpl.h"
     14 #include "sslproto.h"
     15 #include "nspr.h"
     16 #include "private/pprio.h"
     17 #ifndef NO_PKCS11_BYPASS
     18 #include "blapi.h"
     19 #endif
     20 #include "pk11pub.h"
     21 #include "nss.h"
     22 
     23 /* This is a bodge to allow this code to be compiled against older NSS headers
     24  * that don't contain the TLS 1.2 changes. */
     25 #ifndef CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
     26 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
     27 #endif
     28 
     29 #define SET_ERROR_CODE   /* reminder */
     30 
     31 struct cipherPolicyStr {
     32 	int		cipher;
     33 	unsigned char 	export;	/* policy value for export policy */
     34 	unsigned char 	france;	/* policy value for france policy */
     35 };
     36 
     37 typedef struct cipherPolicyStr cipherPolicy;
     38 
     39 /* This table contains two preconfigured policies: Export and France.
     40 ** It is used only by the functions NSS_SetDomesticPolicy,
     41 ** NSS_SetExportPolicy, and NSS_SetFrancePolicy.
     42 ** Order of entries is not important.
     43 */
     44 static cipherPolicy ssl_ciphers[] = {	   /*   Export           France   */
     45  {  SSL_EN_RC4_128_WITH_MD5,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     46  {  SSL_EN_RC4_128_EXPORT40_WITH_MD5,	    SSL_ALLOWED,     SSL_ALLOWED },
     47  {  SSL_EN_RC2_128_CBC_WITH_MD5,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     48  {  SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5,   SSL_ALLOWED,     SSL_ALLOWED },
     49  {  SSL_EN_DES_64_CBC_WITH_MD5,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     50  {  SSL_EN_DES_192_EDE3_CBC_WITH_MD5,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     51  {  SSL_RSA_WITH_RC4_128_MD5,		    SSL_RESTRICTED,  SSL_NOT_ALLOWED },
     52  {  SSL_RSA_WITH_RC4_128_SHA,		    SSL_RESTRICTED,  SSL_NOT_ALLOWED },
     53  {  SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     54  {  SSL_RSA_WITH_3DES_EDE_CBC_SHA,	    SSL_RESTRICTED,  SSL_NOT_ALLOWED },
     55  {  SSL_RSA_FIPS_WITH_DES_CBC_SHA,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     56  {  SSL_RSA_WITH_DES_CBC_SHA,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     57  {  SSL_RSA_EXPORT_WITH_RC4_40_MD5,	    SSL_ALLOWED,     SSL_ALLOWED },
     58  {  SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,	    SSL_ALLOWED,     SSL_ALLOWED },
     59  {  SSL_DHE_RSA_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     60  {  SSL_DHE_DSS_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     61  {  SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     62  {  SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     63  {  TLS_DHE_DSS_WITH_RC4_128_SHA,           SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     64  {  SSL_RSA_WITH_NULL_MD5,		    SSL_ALLOWED,     SSL_ALLOWED },
     65  {  SSL_RSA_WITH_NULL_SHA,		    SSL_ALLOWED,     SSL_ALLOWED },
     66  {  TLS_RSA_WITH_NULL_SHA256,		    SSL_ALLOWED,     SSL_ALLOWED },
     67  {  TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     68  {  TLS_DHE_RSA_WITH_AES_128_CBC_SHA,       SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     69  {  TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     70  {  TLS_RSA_WITH_AES_128_CBC_SHA,     	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     71  {  TLS_RSA_WITH_AES_128_CBC_SHA256,        SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     72  {  TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     73  {  TLS_DHE_RSA_WITH_AES_256_CBC_SHA,       SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     74  {  TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     75  {  TLS_RSA_WITH_AES_256_CBC_SHA,     	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     76  {  TLS_RSA_WITH_AES_256_CBC_SHA256,        SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     77  {  TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     78  {  TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     79  {  TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     80  {  TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     81  {  TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     82  {  TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     83  {  TLS_RSA_WITH_SEED_CBC_SHA,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     84  {  TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,    SSL_ALLOWED,     SSL_NOT_ALLOWED },
     85  {  TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,     SSL_ALLOWED,     SSL_NOT_ALLOWED },
     86 #ifdef NSS_ENABLE_ECC
     87  {  TLS_ECDH_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED,     SSL_ALLOWED },
     88  {  TLS_ECDH_ECDSA_WITH_RC4_128_SHA,        SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     89  {  TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     90  {  TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     91  {  TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     92  {  TLS_ECDHE_ECDSA_WITH_NULL_SHA,          SSL_ALLOWED,     SSL_ALLOWED },
     93  {  TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,       SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     94  {  TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     95  {  TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,   SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     96  {  TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     97  {  TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,   SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
     98  {  TLS_ECDH_RSA_WITH_NULL_SHA,             SSL_ALLOWED,     SSL_ALLOWED },
     99  {  TLS_ECDH_RSA_WITH_RC4_128_SHA,          SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    100  {  TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    101  {  TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    102  {  TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    103  {  TLS_ECDHE_RSA_WITH_NULL_SHA,            SSL_ALLOWED,     SSL_ALLOWED },
    104  {  TLS_ECDHE_RSA_WITH_RC4_128_SHA,         SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    105  {  TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    106  {  TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,     SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    107  {  TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    108  {  TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,     SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
    109 #endif /* NSS_ENABLE_ECC */
    110  {  0,					    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }
    111 };
    112 
    113 static const sslSocketOps ssl_default_ops = {	/* No SSL. */
    114     ssl_DefConnect,
    115     NULL,
    116     ssl_DefBind,
    117     ssl_DefListen,
    118     ssl_DefShutdown,
    119     ssl_DefClose,
    120     ssl_DefRecv,
    121     ssl_DefSend,
    122     ssl_DefRead,
    123     ssl_DefWrite,
    124     ssl_DefGetpeername,
    125     ssl_DefGetsockname
    126 };
    127 
    128 static const sslSocketOps ssl_secure_ops = {	/* SSL. */
    129     ssl_SecureConnect,
    130     NULL,
    131     ssl_DefBind,
    132     ssl_DefListen,
    133     ssl_SecureShutdown,
    134     ssl_SecureClose,
    135     ssl_SecureRecv,
    136     ssl_SecureSend,
    137     ssl_SecureRead,
    138     ssl_SecureWrite,
    139     ssl_DefGetpeername,
    140     ssl_DefGetsockname
    141 };
    142 
    143 /*
    144 ** default settings for socket enables
    145 */
    146 static sslOptions ssl_defaults = {
    147     { siBuffer, NULL, 0 }, /* nextProtoNego */
    148     PR_TRUE, 	/* useSecurity        */
    149     PR_FALSE,	/* useSocks           */
    150     PR_FALSE,	/* requestCertificate */
    151     2,	        /* requireCertificate */
    152     PR_FALSE,	/* handshakeAsClient  */
    153     PR_FALSE,	/* handshakeAsServer  */
    154     PR_FALSE,	/* enableSSL2         */ /* now defaults to off in NSS 3.13 */
    155     PR_FALSE,	/* unusedBit9         */
    156     PR_FALSE, 	/* unusedBit10        */
    157     PR_FALSE,	/* noCache            */
    158     PR_FALSE,	/* fdx                */
    159     PR_FALSE,	/* v2CompatibleHello  */ /* now defaults to off in NSS 3.13 */
    160     PR_TRUE,	/* detectRollBack     */
    161     PR_FALSE,   /* noStepDown         */
    162     PR_FALSE,   /* bypassPKCS11       */
    163     PR_FALSE,   /* noLocks            */
    164     PR_FALSE,   /* enableSessionTickets */
    165     PR_FALSE,   /* enableDeflate      */
    166     2,          /* enableRenegotiation (default: requires extension) */
    167     PR_FALSE,   /* requireSafeNegotiation */
    168     PR_FALSE,   /* enableFalseStart   */
    169     PR_TRUE,    /* cbcRandomIV        */
    170     PR_FALSE    /* enableOCSPStapling */
    171 };
    172 
    173 /*
    174  * default range of enabled SSL/TLS protocols
    175  */
    176 static SSLVersionRange versions_defaults_stream = {
    177     SSL_LIBRARY_VERSION_3_0,
    178     SSL_LIBRARY_VERSION_TLS_1_0
    179 };
    180 
    181 static SSLVersionRange versions_defaults_datagram = {
    182     SSL_LIBRARY_VERSION_TLS_1_1,
    183     SSL_LIBRARY_VERSION_TLS_1_1
    184 };
    185 
    186 #define VERSIONS_DEFAULTS(variant) \
    187     (variant == ssl_variant_stream ? &versions_defaults_stream : \
    188                                      &versions_defaults_datagram)
    189 
    190 sslSessionIDLookupFunc  ssl_sid_lookup;
    191 sslSessionIDCacheFunc   ssl_sid_cache;
    192 sslSessionIDUncacheFunc ssl_sid_uncache;
    193 
    194 static PRBool ssl_inited = PR_FALSE;
    195 static PRDescIdentity ssl_layer_id;
    196 
    197 PRBool                  locksEverDisabled; 	/* implicitly PR_FALSE */
    198 PRBool			ssl_force_locks;  	/* implicitly PR_FALSE */
    199 int                     ssl_lock_readers	= 1;	/* default true. */
    200 char                    ssl_debug;
    201 char                    ssl_trace;
    202 FILE *                  ssl_trace_iob;
    203 FILE *                  ssl_keylog_iob;
    204 char lockStatus[] = "Locks are ENABLED.  ";
    205 #define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */
    206 
    207 /* SRTP_NULL_HMAC_SHA1_80 and SRTP_NULL_HMAC_SHA1_32 are not implemented. */
    208 static const PRUint16 srtpCiphers[] = {
    209     SRTP_AES128_CM_HMAC_SHA1_80,
    210     SRTP_AES128_CM_HMAC_SHA1_32,
    211     0
    212 };
    213 
    214 /* forward declarations. */
    215 static sslSocket *ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant variant);
    216 static SECStatus  ssl_MakeLocks(sslSocket *ss);
    217 static void       ssl_SetDefaultsFromEnvironment(void);
    218 static PRStatus   ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack,
    219                                   PRDescIdentity id);
    220 
    221 /************************************************************************/
    222 
    223 /*
    224 ** Lookup a socket structure from a file descriptor.
    225 ** Only functions called through the PRIOMethods table should use this.
    226 ** Other app-callable functions should use ssl_FindSocket.
    227 */
    228 static sslSocket *
    229 ssl_GetPrivate(PRFileDesc *fd)
    230 {
    231     sslSocket *ss;
    232 
    233     PORT_Assert(fd != NULL);
    234     PORT_Assert(fd->methods->file_type == PR_DESC_LAYERED);
    235     PORT_Assert(fd->identity == ssl_layer_id);
    236 
    237     if (fd->methods->file_type != PR_DESC_LAYERED ||
    238         fd->identity != ssl_layer_id) {
    239 	PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
    240 	return NULL;
    241     }
    242 
    243     ss = (sslSocket *)fd->secret;
    244     ss->fd = fd;
    245     return ss;
    246 }
    247 
    248 /* This function tries to find the SSL layer in the stack.
    249  * It searches for the first SSL layer at or below the argument fd,
    250  * and failing that, it searches for the nearest SSL layer above the
    251  * argument fd.  It returns the private sslSocket from the found layer.
    252  */
    253 sslSocket *
    254 ssl_FindSocket(PRFileDesc *fd)
    255 {
    256     PRFileDesc *layer;
    257     sslSocket *ss;
    258 
    259     PORT_Assert(fd != NULL);
    260     PORT_Assert(ssl_layer_id != 0);
    261 
    262     layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
    263     if (layer == NULL) {
    264 	PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
    265 	return NULL;
    266     }
    267 
    268     ss = (sslSocket *)layer->secret;
    269     ss->fd = layer;
    270     return ss;
    271 }
    272 
    273 static sslSocket *
    274 ssl_DupSocket(sslSocket *os)
    275 {
    276     sslSocket *ss;
    277     SECStatus rv;
    278 
    279     ss = ssl_NewSocket((PRBool)(!os->opt.noLocks), os->protocolVariant);
    280     if (ss) {
    281 	ss->opt                = os->opt;
    282 	ss->opt.useSocks       = PR_FALSE;
    283 	ss->vrange             = os->vrange;
    284 
    285 	ss->peerID             = !os->peerID ? NULL : PORT_Strdup(os->peerID);
    286 	ss->url                = !os->url    ? NULL : PORT_Strdup(os->url);
    287 
    288 	ss->ops      = os->ops;
    289 	ss->rTimeout = os->rTimeout;
    290 	ss->wTimeout = os->wTimeout;
    291 	ss->cTimeout = os->cTimeout;
    292 	ss->dbHandle = os->dbHandle;
    293 
    294 	/* copy ssl2&3 policy & prefs, even if it's not selected (yet) */
    295 	ss->allowedByPolicy	= os->allowedByPolicy;
    296 	ss->maybeAllowedByPolicy= os->maybeAllowedByPolicy;
    297 	ss->chosenPreference 	= os->chosenPreference;
    298 	PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites);
    299 	PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, os->ssl3.dtlsSRTPCiphers,
    300 		    sizeof(PRUint16) * os->ssl3.dtlsSRTPCipherCount);
    301 	ss->ssl3.dtlsSRTPCipherCount = os->ssl3.dtlsSRTPCipherCount;
    302 
    303 	if (os->cipherSpecs) {
    304 	    ss->cipherSpecs  = (unsigned char*)PORT_Alloc(os->sizeCipherSpecs);
    305 	    if (ss->cipherSpecs)
    306 	    	PORT_Memcpy(ss->cipherSpecs, os->cipherSpecs,
    307 		            os->sizeCipherSpecs);
    308 	    ss->sizeCipherSpecs    = os->sizeCipherSpecs;
    309 	    ss->preferredCipher    = os->preferredCipher;
    310 	} else {
    311 	    ss->cipherSpecs        = NULL;  /* produced lazily */
    312 	    ss->sizeCipherSpecs    = 0;
    313 	    ss->preferredCipher    = NULL;
    314 	}
    315 	if (ss->opt.useSecurity) {
    316 	    /* This int should be SSLKEAType, but CC on Irix complains,
    317 	     * during the for loop.
    318 	     */
    319 	    int i;
    320 	    sslServerCerts * oc = os->serverCerts;
    321 	    sslServerCerts * sc = ss->serverCerts;
    322 
    323 	    for (i=kt_null; i < kt_kea_size; i++, oc++, sc++) {
    324 		if (oc->serverCert && oc->serverCertChain) {
    325 		    sc->serverCert      = CERT_DupCertificate(oc->serverCert);
    326 		    sc->serverCertChain = CERT_DupCertList(oc->serverCertChain);
    327 		    if (!sc->serverCertChain)
    328 		    	goto loser;
    329 		} else {
    330 		    sc->serverCert      = NULL;
    331 		    sc->serverCertChain = NULL;
    332 		}
    333 		sc->serverKeyPair = oc->serverKeyPair ?
    334 				ssl3_GetKeyPairRef(oc->serverKeyPair) : NULL;
    335 		if (oc->serverKeyPair && !sc->serverKeyPair)
    336 		    goto loser;
    337 	        sc->serverKeyBits = oc->serverKeyBits;
    338 		ss->certStatusArray[i] = !os->certStatusArray[i] ? NULL :
    339 				SECITEM_DupArray(NULL, os->certStatusArray[i]);
    340 	    }
    341 	    ss->stepDownKeyPair = !os->stepDownKeyPair ? NULL :
    342 		                  ssl3_GetKeyPairRef(os->stepDownKeyPair);
    343 	    ss->ephemeralECDHKeyPair = !os->ephemeralECDHKeyPair ? NULL :
    344 		                  ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair);
    345 /*
    346  * XXX the preceding CERT_ and SECKEY_ functions can fail and return NULL.
    347  * XXX We should detect this, and not just march on with NULL pointers.
    348  */
    349 	    ss->authCertificate       = os->authCertificate;
    350 	    ss->authCertificateArg    = os->authCertificateArg;
    351 	    ss->getClientAuthData     = os->getClientAuthData;
    352 	    ss->getClientAuthDataArg  = os->getClientAuthDataArg;
    353 #ifdef NSS_PLATFORM_CLIENT_AUTH
    354 	    ss->getPlatformClientAuthData    = os->getPlatformClientAuthData;
    355 	    ss->getPlatformClientAuthDataArg = os->getPlatformClientAuthDataArg;
    356 #endif
    357             ss->sniSocketConfig       = os->sniSocketConfig;
    358             ss->sniSocketConfigArg    = os->sniSocketConfigArg;
    359 	    ss->handleBadCert         = os->handleBadCert;
    360 	    ss->badCertArg            = os->badCertArg;
    361 	    ss->handshakeCallback     = os->handshakeCallback;
    362 	    ss->handshakeCallbackData = os->handshakeCallbackData;
    363 	    ss->pkcs11PinArg          = os->pkcs11PinArg;
    364 	    ss->getChannelID          = os->getChannelID;
    365 	    ss->getChannelIDArg       = os->getChannelIDArg;
    366 
    367 	    /* Create security data */
    368 	    rv = ssl_CopySecurityInfo(ss, os);
    369 	    if (rv != SECSuccess) {
    370 		goto loser;
    371 	    }
    372 	}
    373     }
    374     return ss;
    375 
    376 loser:
    377     ssl_FreeSocket(ss);
    378     return NULL;
    379 }
    380 
    381 static void
    382 ssl_DestroyLocks(sslSocket *ss)
    383 {
    384     /* Destroy locks. */
    385     if (ss->firstHandshakeLock) {
    386     	PZ_DestroyMonitor(ss->firstHandshakeLock);
    387 	ss->firstHandshakeLock = NULL;
    388     }
    389     if (ss->ssl3HandshakeLock) {
    390     	PZ_DestroyMonitor(ss->ssl3HandshakeLock);
    391 	ss->ssl3HandshakeLock = NULL;
    392     }
    393     if (ss->specLock) {
    394     	NSSRWLock_Destroy(ss->specLock);
    395 	ss->specLock = NULL;
    396     }
    397 
    398     if (ss->recvLock) {
    399     	PZ_DestroyLock(ss->recvLock);
    400 	ss->recvLock = NULL;
    401     }
    402     if (ss->sendLock) {
    403     	PZ_DestroyLock(ss->sendLock);
    404 	ss->sendLock = NULL;
    405     }
    406     if (ss->xmitBufLock) {
    407     	PZ_DestroyMonitor(ss->xmitBufLock);
    408 	ss->xmitBufLock = NULL;
    409     }
    410     if (ss->recvBufLock) {
    411     	PZ_DestroyMonitor(ss->recvBufLock);
    412 	ss->recvBufLock = NULL;
    413     }
    414 }
    415 
    416 /* Caller holds any relevant locks */
    417 static void
    418 ssl_DestroySocketContents(sslSocket *ss)
    419 {
    420     /* "i" should be of type SSLKEAType, but CC on IRIX complains during
    421      * the for loop.
    422      */
    423     int        i;
    424 
    425     /* Free up socket */
    426     ssl_DestroySecurityInfo(&ss->sec);
    427 
    428     ssl3_DestroySSL3Info(ss);
    429 
    430     PORT_Free(ss->saveBuf.buf);
    431     PORT_Free(ss->pendingBuf.buf);
    432     ssl_DestroyGather(&ss->gs);
    433 
    434     if (ss->peerID != NULL)
    435 	PORT_Free(ss->peerID);
    436     if (ss->url != NULL)
    437 	PORT_Free((void *)ss->url);	/* CONST */
    438     if (ss->cipherSpecs) {
    439 	PORT_Free(ss->cipherSpecs);
    440 	ss->cipherSpecs     = NULL;
    441 	ss->sizeCipherSpecs = 0;
    442     }
    443 
    444     /* Clean up server configuration */
    445     for (i=kt_null; i < kt_kea_size; i++) {
    446 	sslServerCerts * sc = ss->serverCerts + i;
    447 	if (sc->serverCert != NULL)
    448 	    CERT_DestroyCertificate(sc->serverCert);
    449 	if (sc->serverCertChain != NULL)
    450 	    CERT_DestroyCertificateList(sc->serverCertChain);
    451 	if (sc->serverKeyPair != NULL)
    452 	    ssl3_FreeKeyPair(sc->serverKeyPair);
    453 	if (ss->certStatusArray[i] != NULL) {
    454 	    SECITEM_FreeArray(ss->certStatusArray[i], PR_TRUE);
    455 	    ss->certStatusArray[i] = NULL;
    456 	}
    457     }
    458     if (ss->stepDownKeyPair) {
    459 	ssl3_FreeKeyPair(ss->stepDownKeyPair);
    460 	ss->stepDownKeyPair = NULL;
    461     }
    462     if (ss->ephemeralECDHKeyPair) {
    463 	ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
    464 	ss->ephemeralECDHKeyPair = NULL;
    465     }
    466     SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
    467     PORT_Assert(!ss->xtnData.sniNameArr);
    468     if (ss->xtnData.sniNameArr) {
    469         PORT_Free(ss->xtnData.sniNameArr);
    470         ss->xtnData.sniNameArr = NULL;
    471     }
    472 }
    473 
    474 /*
    475  * free an sslSocket struct, and all the stuff that hangs off of it
    476  */
    477 void
    478 ssl_FreeSocket(sslSocket *ss)
    479 {
    480 /* Get every lock you can imagine!
    481 ** Caller already holds these:
    482 **  SSL_LOCK_READER(ss);
    483 **  SSL_LOCK_WRITER(ss);
    484 */
    485     ssl_Get1stHandshakeLock(ss);
    486     ssl_GetRecvBufLock(ss);
    487     ssl_GetSSL3HandshakeLock(ss);
    488     ssl_GetXmitBufLock(ss);
    489     ssl_GetSpecWriteLock(ss);
    490 
    491     ssl_DestroySocketContents(ss);
    492 
    493     /* Release all the locks acquired above.  */
    494     SSL_UNLOCK_READER(ss);
    495     SSL_UNLOCK_WRITER(ss);
    496     ssl_Release1stHandshakeLock(ss);
    497     ssl_ReleaseRecvBufLock(ss);
    498     ssl_ReleaseSSL3HandshakeLock(ss);
    499     ssl_ReleaseXmitBufLock(ss);
    500     ssl_ReleaseSpecWriteLock(ss);
    501 
    502     ssl_DestroyLocks(ss);
    503 
    504 #ifdef DEBUG
    505     PORT_Memset(ss, 0x1f, sizeof *ss);
    506 #endif
    507     PORT_Free(ss);
    508     return;
    509 }
    510 
    511 /************************************************************************/
    512 SECStatus
    513 ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled)
    514 {
    515     PRFileDesc *       osfd = ss->fd->lower;
    516     SECStatus         rv = SECFailure;
    517     PRSocketOptionData opt;
    518 
    519     opt.option         = PR_SockOpt_NoDelay;
    520     opt.value.no_delay = (PRBool)!enabled;
    521 
    522     if (osfd->methods->setsocketoption) {
    523         rv = (SECStatus) osfd->methods->setsocketoption(osfd, &opt);
    524     } else {
    525         PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
    526     }
    527 
    528     return rv;
    529 }
    530 
    531 static void
    532 ssl_ChooseOps(sslSocket *ss)
    533 {
    534     ss->ops = ss->opt.useSecurity ? &ssl_secure_ops : &ssl_default_ops;
    535 }
    536 
    537 /* Called from SSL_Enable (immediately below) */
    538 static SECStatus
    539 PrepareSocket(sslSocket *ss)
    540 {
    541     SECStatus     rv = SECSuccess;
    542 
    543     ssl_ChooseOps(ss);
    544     return rv;
    545 }
    546 
    547 SECStatus
    548 SSL_Enable(PRFileDesc *fd, int which, PRBool on)
    549 {
    550     return SSL_OptionSet(fd, which, on);
    551 }
    552 
    553 #ifndef NO_PKCS11_BYPASS
    554 static const PRCallOnceType pristineCallOnce;
    555 static PRCallOnceType setupBypassOnce;
    556 
    557 static SECStatus SSL_BypassShutdown(void* appData, void* nssData)
    558 {
    559     /* unload freeBL shared library from memory */
    560     BL_Unload();
    561     setupBypassOnce = pristineCallOnce;
    562     return SECSuccess;
    563 }
    564 
    565 static PRStatus SSL_BypassRegisterShutdown(void)
    566 {
    567     SECStatus rv = NSS_RegisterShutdown(SSL_BypassShutdown, NULL);
    568     PORT_Assert(SECSuccess == rv);
    569     return SECSuccess == rv ? PR_SUCCESS : PR_FAILURE;
    570 }
    571 #endif
    572 
    573 static PRStatus SSL_BypassSetup(void)
    574 {
    575 #ifdef NO_PKCS11_BYPASS
    576     /* Guarantee binary compatibility */
    577     return PR_SUCCESS;
    578 #else
    579     return PR_CallOnce(&setupBypassOnce, &SSL_BypassRegisterShutdown);
    580 #endif
    581 }
    582 
    583 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_TLS, on) described in
    584  * ssl.h in the section "SSL version range setting API".
    585  */
    586 static void
    587 ssl_EnableTLS(SSLVersionRange *vrange, PRBool on)
    588 {
    589     if (SSL3_ALL_VERSIONS_DISABLED(vrange)) {
    590 	if (on) {
    591 	    vrange->min = SSL_LIBRARY_VERSION_TLS_1_0;
    592 	    vrange->max = SSL_LIBRARY_VERSION_TLS_1_0;
    593 	} /* else don't change anything */
    594 	return;
    595     }
    596 
    597     if (on) {
    598 	/* Expand the range of enabled version to include TLS 1.0 */
    599 	vrange->min = PR_MIN(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
    600 	vrange->max = PR_MAX(vrange->max, SSL_LIBRARY_VERSION_TLS_1_0);
    601     } else {
    602 	/* Disable all TLS versions, leaving only SSL 3.0 if it was enabled */
    603 	if (vrange->min == SSL_LIBRARY_VERSION_3_0) {
    604 	    vrange->max = SSL_LIBRARY_VERSION_3_0;
    605 	} else {
    606 	    /* Only TLS was enabled, so now no versions are. */
    607 	    vrange->min = SSL_LIBRARY_VERSION_NONE;
    608 	    vrange->max = SSL_LIBRARY_VERSION_NONE;
    609 	}
    610     }
    611 }
    612 
    613 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_SSL3, on) described in
    614  * ssl.h in the section "SSL version range setting API".
    615  */
    616 static void
    617 ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on)
    618 {
    619    if (SSL3_ALL_VERSIONS_DISABLED(vrange)) {
    620 	if (on) {
    621 	    vrange->min = SSL_LIBRARY_VERSION_3_0;
    622 	    vrange->max = SSL_LIBRARY_VERSION_3_0;
    623 	} /* else don't change anything */
    624 	return;
    625     }
    626 
    627    if (on) {
    628 	/* Expand the range of enabled versions to include SSL 3.0. We know
    629 	 * SSL 3.0 or some version of TLS is already enabled at this point, so
    630 	 * we don't need to change vrange->max.
    631 	 */
    632 	vrange->min = SSL_LIBRARY_VERSION_3_0;
    633    } else {
    634 	/* Disable SSL 3.0, leaving TLS unaffected. */
    635 	if (vrange->max > SSL_LIBRARY_VERSION_3_0) {
    636 	    vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
    637 	} else {
    638 	    /* Only SSL 3.0 was enabled, so now no versions are. */
    639 	    vrange->min = SSL_LIBRARY_VERSION_NONE;
    640 	    vrange->max = SSL_LIBRARY_VERSION_NONE;
    641 	}
    642     }
    643 }
    644 
    645 SECStatus
    646 SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on)
    647 {
    648     sslSocket *ss = ssl_FindSocket(fd);
    649     SECStatus  rv = SECSuccess;
    650     PRBool     holdingLocks;
    651 
    652     if (!ss) {
    653 	SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
    654 	return SECFailure;
    655     }
    656 
    657     holdingLocks = (!ss->opt.noLocks);
    658     ssl_Get1stHandshakeLock(ss);
    659     ssl_GetSSL3HandshakeLock(ss);
    660 
    661     switch (which) {
    662       case SSL_SOCKS:
    663 	ss->opt.useSocks = PR_FALSE;
    664 	rv = PrepareSocket(ss);
    665 	if (on) {
    666 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    667 	    rv = SECFailure;
    668 	}
    669 	break;
    670 
    671       case SSL_SECURITY:
    672 	ss->opt.useSecurity = on;
    673 	rv = PrepareSocket(ss);
    674 	break;
    675 
    676       case SSL_REQUEST_CERTIFICATE:
    677 	ss->opt.requestCertificate = on;
    678 	break;
    679 
    680       case SSL_REQUIRE_CERTIFICATE:
    681 	ss->opt.requireCertificate = on;
    682 	break;
    683 
    684       case SSL_HANDSHAKE_AS_CLIENT:
    685 	if ( ss->opt.handshakeAsServer && on ) {
    686 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    687 	    rv = SECFailure;
    688 	    break;
    689 	}
    690 	ss->opt.handshakeAsClient = on;
    691 	break;
    692 
    693       case SSL_HANDSHAKE_AS_SERVER:
    694 	if ( ss->opt.handshakeAsClient && on ) {
    695 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    696 	    rv = SECFailure;
    697 	    break;
    698 	}
    699 	ss->opt.handshakeAsServer = on;
    700 	break;
    701 
    702       case SSL_ENABLE_TLS:
    703         if (IS_DTLS(ss)) {
    704 	    if (on) {
    705 		PORT_SetError(SEC_ERROR_INVALID_ARGS);
    706 		rv = SECFailure; /* not allowed */
    707 	    }
    708 	    break;
    709 	}
    710 	ssl_EnableTLS(&ss->vrange, on);
    711 	ss->preferredCipher     = NULL;
    712 	if (ss->cipherSpecs) {
    713 	    PORT_Free(ss->cipherSpecs);
    714 	    ss->cipherSpecs     = NULL;
    715 	    ss->sizeCipherSpecs = 0;
    716 	}
    717 	break;
    718 
    719       case SSL_ENABLE_SSL3:
    720         if (IS_DTLS(ss)) {
    721 	    if (on) {
    722 		PORT_SetError(SEC_ERROR_INVALID_ARGS);
    723 		rv = SECFailure; /* not allowed */
    724 	    }
    725 	    break;
    726 	}
    727 	ssl_EnableSSL3(&ss->vrange, on);
    728 	ss->preferredCipher     = NULL;
    729 	if (ss->cipherSpecs) {
    730 	    PORT_Free(ss->cipherSpecs);
    731 	    ss->cipherSpecs     = NULL;
    732 	    ss->sizeCipherSpecs = 0;
    733 	}
    734 	break;
    735 
    736       case SSL_ENABLE_SSL2:
    737         if (IS_DTLS(ss)) {
    738 	    if (on) {
    739 		PORT_SetError(SEC_ERROR_INVALID_ARGS);
    740 		rv = SECFailure; /* not allowed */
    741 	    }
    742 	    break;
    743 	}
    744 	ss->opt.enableSSL2       = on;
    745 	if (on) {
    746 	    ss->opt.v2CompatibleHello = on;
    747 	}
    748 	ss->preferredCipher     = NULL;
    749 	if (ss->cipherSpecs) {
    750 	    PORT_Free(ss->cipherSpecs);
    751 	    ss->cipherSpecs     = NULL;
    752 	    ss->sizeCipherSpecs = 0;
    753 	}
    754 	break;
    755 
    756       case SSL_NO_CACHE:
    757 	ss->opt.noCache = on;
    758 	break;
    759 
    760       case SSL_ENABLE_FDX:
    761 	if (on && ss->opt.noLocks) {
    762 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    763 	    rv = SECFailure;
    764 	}
    765       	ss->opt.fdx = on;
    766 	break;
    767 
    768       case SSL_V2_COMPATIBLE_HELLO:
    769         if (IS_DTLS(ss)) {
    770 	    if (on) {
    771 		PORT_SetError(SEC_ERROR_INVALID_ARGS);
    772 		rv = SECFailure; /* not allowed */
    773 	    }
    774 	    break;
    775 	}
    776       	ss->opt.v2CompatibleHello = on;
    777 	if (!on) {
    778 	    ss->opt.enableSSL2    = on;
    779 	}
    780 	break;
    781 
    782       case SSL_ROLLBACK_DETECTION:
    783 	ss->opt.detectRollBack = on;
    784         break;
    785 
    786       case SSL_NO_STEP_DOWN:
    787 	ss->opt.noStepDown     = on;
    788 	if (on)
    789 	    SSL_DisableExportCipherSuites(fd);
    790 	break;
    791 
    792       case SSL_BYPASS_PKCS11:
    793 	if (ss->handshakeBegun) {
    794 	    PORT_SetError(PR_INVALID_STATE_ERROR);
    795 	    rv = SECFailure;
    796 	} else {
    797             if (PR_FALSE != on) {
    798                 if (PR_SUCCESS == SSL_BypassSetup() ) {
    799 #ifdef NO_PKCS11_BYPASS
    800                     ss->opt.bypassPKCS11 = PR_FALSE;
    801 #else
    802                     ss->opt.bypassPKCS11 = on;
    803 #endif
    804                 } else {
    805                     rv = SECFailure;
    806                 }
    807             } else {
    808                 ss->opt.bypassPKCS11 = PR_FALSE;
    809             }
    810 	}
    811 	break;
    812 
    813       case SSL_NO_LOCKS:
    814 	if (on && ss->opt.fdx) {
    815 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    816 	    rv = SECFailure;
    817 	}
    818 	if (on && ssl_force_locks)
    819 	    on = PR_FALSE;	/* silent override */
    820 	ss->opt.noLocks   = on;
    821 	if (on) {
    822 	    locksEverDisabled = PR_TRUE;
    823 	    strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
    824 	} else if (!holdingLocks) {
    825 	    rv = ssl_MakeLocks(ss);
    826 	    if (rv != SECSuccess) {
    827 		ss->opt.noLocks   = PR_TRUE;
    828 	    }
    829 	}
    830 	break;
    831 
    832       case SSL_ENABLE_SESSION_TICKETS:
    833 	ss->opt.enableSessionTickets = on;
    834 	break;
    835 
    836       case SSL_ENABLE_DEFLATE:
    837 	ss->opt.enableDeflate = on;
    838 	break;
    839 
    840       case SSL_ENABLE_RENEGOTIATION:
    841 	ss->opt.enableRenegotiation = on;
    842 	break;
    843 
    844       case SSL_REQUIRE_SAFE_NEGOTIATION:
    845 	ss->opt.requireSafeNegotiation = on;
    846 	break;
    847 
    848       case SSL_ENABLE_FALSE_START:
    849 	ss->opt.enableFalseStart = on;
    850 	break;
    851 
    852       case SSL_CBC_RANDOM_IV:
    853 	ss->opt.cbcRandomIV = on;
    854 	break;
    855 
    856       case SSL_ENABLE_OCSP_STAPLING:
    857        ss->opt.enableOCSPStapling = on;
    858        break;
    859 
    860       default:
    861 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
    862 	rv = SECFailure;
    863     }
    864 
    865     /* We can't use the macros for releasing the locks here,
    866      * because ss->opt.noLocks might have changed just above.
    867      * We must release these locks (monitors) here, if we aquired them above,
    868      * regardless of the current value of ss->opt.noLocks.
    869      */
    870     if (holdingLocks) {
    871 	PZ_ExitMonitor((ss)->ssl3HandshakeLock);
    872 	PZ_ExitMonitor((ss)->firstHandshakeLock);
    873     }
    874 
    875     return rv;
    876 }
    877 
    878 SECStatus
    879 SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn)
    880 {
    881     sslSocket *ss = ssl_FindSocket(fd);
    882     SECStatus  rv = SECSuccess;
    883     PRBool     on = PR_FALSE;
    884 
    885     if (!pOn) {
    886 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
    887 	return SECFailure;
    888     }
    889     if (!ss) {
    890 	SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
    891 	*pOn = PR_FALSE;
    892 	return SECFailure;
    893     }
    894 
    895     ssl_Get1stHandshakeLock(ss);
    896     ssl_GetSSL3HandshakeLock(ss);
    897 
    898     switch (which) {
    899     case SSL_SOCKS:               on = PR_FALSE;               break;
    900     case SSL_SECURITY:            on = ss->opt.useSecurity;        break;
    901     case SSL_REQUEST_CERTIFICATE: on = ss->opt.requestCertificate; break;
    902     case SSL_REQUIRE_CERTIFICATE: on = ss->opt.requireCertificate; break;
    903     case SSL_HANDSHAKE_AS_CLIENT: on = ss->opt.handshakeAsClient;  break;
    904     case SSL_HANDSHAKE_AS_SERVER: on = ss->opt.handshakeAsServer;  break;
    905     case SSL_ENABLE_TLS:
    906 	on = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0;
    907 	break;
    908     case SSL_ENABLE_SSL3:
    909 	on = ss->vrange.min == SSL_LIBRARY_VERSION_3_0;
    910 	break;
    911     case SSL_ENABLE_SSL2:         on = ss->opt.enableSSL2;         break;
    912     case SSL_NO_CACHE:            on = ss->opt.noCache;            break;
    913     case SSL_ENABLE_FDX:          on = ss->opt.fdx;                break;
    914     case SSL_V2_COMPATIBLE_HELLO: on = ss->opt.v2CompatibleHello;  break;
    915     case SSL_ROLLBACK_DETECTION:  on = ss->opt.detectRollBack;     break;
    916     case SSL_NO_STEP_DOWN:        on = ss->opt.noStepDown;         break;
    917     case SSL_BYPASS_PKCS11:       on = ss->opt.bypassPKCS11;       break;
    918     case SSL_NO_LOCKS:            on = ss->opt.noLocks;            break;
    919     case SSL_ENABLE_SESSION_TICKETS:
    920 	on = ss->opt.enableSessionTickets;
    921 	break;
    922     case SSL_ENABLE_DEFLATE:      on = ss->opt.enableDeflate;      break;
    923     case SSL_ENABLE_RENEGOTIATION:
    924                                   on = ss->opt.enableRenegotiation; break;
    925     case SSL_REQUIRE_SAFE_NEGOTIATION:
    926                                   on = ss->opt.requireSafeNegotiation; break;
    927     case SSL_ENABLE_FALSE_START:  on = ss->opt.enableFalseStart;   break;
    928     case SSL_CBC_RANDOM_IV:       on = ss->opt.cbcRandomIV;        break;
    929     case SSL_ENABLE_OCSP_STAPLING: on = ss->opt.enableOCSPStapling; break;
    930 
    931     default:
    932 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
    933 	rv = SECFailure;
    934     }
    935 
    936     ssl_ReleaseSSL3HandshakeLock(ss);
    937     ssl_Release1stHandshakeLock(ss);
    938 
    939     *pOn = on;
    940     return rv;
    941 }
    942 
    943 SECStatus
    944 SSL_OptionGetDefault(PRInt32 which, PRBool *pOn)
    945 {
    946     SECStatus  rv = SECSuccess;
    947     PRBool     on = PR_FALSE;
    948 
    949     if (!pOn) {
    950 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
    951 	return SECFailure;
    952     }
    953 
    954     ssl_SetDefaultsFromEnvironment();
    955 
    956     switch (which) {
    957     case SSL_SOCKS:               on = PR_FALSE;                        break;
    958     case SSL_SECURITY:            on = ssl_defaults.useSecurity;        break;
    959     case SSL_REQUEST_CERTIFICATE: on = ssl_defaults.requestCertificate; break;
    960     case SSL_REQUIRE_CERTIFICATE: on = ssl_defaults.requireCertificate; break;
    961     case SSL_HANDSHAKE_AS_CLIENT: on = ssl_defaults.handshakeAsClient;  break;
    962     case SSL_HANDSHAKE_AS_SERVER: on = ssl_defaults.handshakeAsServer;  break;
    963     case SSL_ENABLE_TLS:
    964 	on = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0;
    965 	break;
    966     case SSL_ENABLE_SSL3:
    967 	on = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0;
    968 	break;
    969     case SSL_ENABLE_SSL2:         on = ssl_defaults.enableSSL2;         break;
    970     case SSL_NO_CACHE:            on = ssl_defaults.noCache;		break;
    971     case SSL_ENABLE_FDX:          on = ssl_defaults.fdx;                break;
    972     case SSL_V2_COMPATIBLE_HELLO: on = ssl_defaults.v2CompatibleHello;  break;
    973     case SSL_ROLLBACK_DETECTION:  on = ssl_defaults.detectRollBack;     break;
    974     case SSL_NO_STEP_DOWN:        on = ssl_defaults.noStepDown;         break;
    975     case SSL_BYPASS_PKCS11:       on = ssl_defaults.bypassPKCS11;       break;
    976     case SSL_NO_LOCKS:            on = ssl_defaults.noLocks;            break;
    977     case SSL_ENABLE_SESSION_TICKETS:
    978 	on = ssl_defaults.enableSessionTickets;
    979 	break;
    980     case SSL_ENABLE_DEFLATE:      on = ssl_defaults.enableDeflate;      break;
    981     case SSL_ENABLE_RENEGOTIATION:
    982                                   on = ssl_defaults.enableRenegotiation; break;
    983     case SSL_REQUIRE_SAFE_NEGOTIATION:
    984                                   on = ssl_defaults.requireSafeNegotiation;
    985 				  break;
    986     case SSL_ENABLE_FALSE_START:  on = ssl_defaults.enableFalseStart;   break;
    987     case SSL_CBC_RANDOM_IV:       on = ssl_defaults.cbcRandomIV;        break;
    988     case SSL_ENABLE_OCSP_STAPLING:
    989        on = ssl_defaults.enableOCSPStapling;
    990        break;
    991 
    992     default:
    993 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
    994 	rv = SECFailure;
    995     }
    996 
    997     *pOn = on;
    998     return rv;
    999 }
   1000 
   1001 /* XXX Use Global Lock to protect this stuff. */
   1002 SECStatus
   1003 SSL_EnableDefault(int which, PRBool on)
   1004 {
   1005     return SSL_OptionSetDefault(which, on);
   1006 }
   1007 
   1008 SECStatus
   1009 SSL_OptionSetDefault(PRInt32 which, PRBool on)
   1010 {
   1011     SECStatus status = ssl_Init();
   1012 
   1013     if (status != SECSuccess) {
   1014 	return status;
   1015     }
   1016 
   1017     ssl_SetDefaultsFromEnvironment();
   1018 
   1019     switch (which) {
   1020       case SSL_SOCKS:
   1021 	ssl_defaults.useSocks = PR_FALSE;
   1022 	if (on) {
   1023 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1024 	    return SECFailure;
   1025 	}
   1026 	break;
   1027 
   1028       case SSL_SECURITY:
   1029 	ssl_defaults.useSecurity = on;
   1030 	break;
   1031 
   1032       case SSL_REQUEST_CERTIFICATE:
   1033 	ssl_defaults.requestCertificate = on;
   1034 	break;
   1035 
   1036       case SSL_REQUIRE_CERTIFICATE:
   1037 	ssl_defaults.requireCertificate = on;
   1038 	break;
   1039 
   1040       case SSL_HANDSHAKE_AS_CLIENT:
   1041 	if ( ssl_defaults.handshakeAsServer && on ) {
   1042 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1043 	    return SECFailure;
   1044 	}
   1045 	ssl_defaults.handshakeAsClient = on;
   1046 	break;
   1047 
   1048       case SSL_HANDSHAKE_AS_SERVER:
   1049 	if ( ssl_defaults.handshakeAsClient && on ) {
   1050 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1051 	    return SECFailure;
   1052 	}
   1053 	ssl_defaults.handshakeAsServer = on;
   1054 	break;
   1055 
   1056       case SSL_ENABLE_TLS:
   1057 	ssl_EnableTLS(&versions_defaults_stream, on);
   1058 	break;
   1059 
   1060       case SSL_ENABLE_SSL3:
   1061 	ssl_EnableSSL3(&versions_defaults_stream, on);
   1062 	break;
   1063 
   1064       case SSL_ENABLE_SSL2:
   1065 	ssl_defaults.enableSSL2 = on;
   1066 	if (on) {
   1067 	    ssl_defaults.v2CompatibleHello = on;
   1068 	}
   1069 	break;
   1070 
   1071       case SSL_NO_CACHE:
   1072 	ssl_defaults.noCache = on;
   1073 	break;
   1074 
   1075       case SSL_ENABLE_FDX:
   1076 	if (on && ssl_defaults.noLocks) {
   1077 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1078 	    return SECFailure;
   1079 	}
   1080       	ssl_defaults.fdx = on;
   1081 	break;
   1082 
   1083       case SSL_V2_COMPATIBLE_HELLO:
   1084       	ssl_defaults.v2CompatibleHello = on;
   1085 	if (!on) {
   1086 	    ssl_defaults.enableSSL2    = on;
   1087 	}
   1088 	break;
   1089 
   1090       case SSL_ROLLBACK_DETECTION:
   1091 	ssl_defaults.detectRollBack = on;
   1092 	break;
   1093 
   1094       case SSL_NO_STEP_DOWN:
   1095 	ssl_defaults.noStepDown     = on;
   1096 	if (on)
   1097 	    SSL_DisableDefaultExportCipherSuites();
   1098 	break;
   1099 
   1100       case SSL_BYPASS_PKCS11:
   1101         if (PR_FALSE != on) {
   1102             if (PR_SUCCESS == SSL_BypassSetup()) {
   1103 #ifdef NO_PKCS11_BYPASS
   1104                 ssl_defaults.bypassPKCS11   = PR_FALSE;
   1105 #else
   1106                 ssl_defaults.bypassPKCS11   = on;
   1107 #endif
   1108             } else {
   1109                 return SECFailure;
   1110             }
   1111         } else {
   1112             ssl_defaults.bypassPKCS11   = PR_FALSE;
   1113         }
   1114 	break;
   1115 
   1116       case SSL_NO_LOCKS:
   1117 	if (on && ssl_defaults.fdx) {
   1118 	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1119 	    return SECFailure;
   1120 	}
   1121 	if (on && ssl_force_locks)
   1122 	    on = PR_FALSE;		/* silent override */
   1123 	ssl_defaults.noLocks        = on;
   1124 	if (on) {
   1125 	    locksEverDisabled = PR_TRUE;
   1126 	    strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
   1127 	}
   1128 	break;
   1129 
   1130       case SSL_ENABLE_SESSION_TICKETS:
   1131 	ssl_defaults.enableSessionTickets = on;
   1132 	break;
   1133 
   1134       case SSL_ENABLE_DEFLATE:
   1135 	ssl_defaults.enableDeflate = on;
   1136 	break;
   1137 
   1138       case SSL_ENABLE_RENEGOTIATION:
   1139 	ssl_defaults.enableRenegotiation = on;
   1140 	break;
   1141 
   1142       case SSL_REQUIRE_SAFE_NEGOTIATION:
   1143 	ssl_defaults.requireSafeNegotiation = on;
   1144 	break;
   1145 
   1146       case SSL_ENABLE_FALSE_START:
   1147 	ssl_defaults.enableFalseStart = on;
   1148 	break;
   1149 
   1150       case SSL_CBC_RANDOM_IV:
   1151 	ssl_defaults.cbcRandomIV = on;
   1152 	break;
   1153 
   1154       case SSL_ENABLE_OCSP_STAPLING:
   1155        ssl_defaults.enableOCSPStapling = on;
   1156        break;
   1157 
   1158       default:
   1159 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1160 	return SECFailure;
   1161     }
   1162     return SECSuccess;
   1163 }
   1164 
   1165 /* function tells us if the cipher suite is one that we no longer support. */
   1166 static PRBool
   1167 ssl_IsRemovedCipherSuite(PRInt32 suite)
   1168 {
   1169     switch (suite) {
   1170     case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
   1171     case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
   1172     case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA:
   1173     	return PR_TRUE;
   1174     default:
   1175     	return PR_FALSE;
   1176     }
   1177 }
   1178 
   1179 /* Part of the public NSS API.
   1180  * Since this is a global (not per-socket) setting, we cannot use the
   1181  * HandshakeLock to protect this.  Probably want a global lock.
   1182  */
   1183 SECStatus
   1184 SSL_SetPolicy(long which, int policy)
   1185 {
   1186     if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
   1187     	/* one of the two old FIPS ciphers */
   1188 	if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
   1189 	    which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
   1190 	else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
   1191 	    which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
   1192     }
   1193     if (ssl_IsRemovedCipherSuite(which))
   1194     	return SECSuccess;
   1195     return SSL_CipherPolicySet(which, policy);
   1196 }
   1197 
   1198 SECStatus
   1199 SSL_CipherPolicySet(PRInt32 which, PRInt32 policy)
   1200 {
   1201     SECStatus rv = ssl_Init();
   1202 
   1203     if (rv != SECSuccess) {
   1204 	return rv;
   1205     }
   1206 
   1207     if (ssl_IsRemovedCipherSuite(which)) {
   1208     	rv = SECSuccess;
   1209     } else if (SSL_IS_SSL2_CIPHER(which)) {
   1210 	rv = ssl2_SetPolicy(which, policy);
   1211     } else {
   1212 	rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy);
   1213     }
   1214     return rv;
   1215 }
   1216 
   1217 SECStatus
   1218 SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy)
   1219 {
   1220     SECStatus rv;
   1221 
   1222     if (!oPolicy) {
   1223 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1224 	return SECFailure;
   1225     }
   1226     if (ssl_IsRemovedCipherSuite(which)) {
   1227 	*oPolicy = SSL_NOT_ALLOWED;
   1228     	rv = SECSuccess;
   1229     } else if (SSL_IS_SSL2_CIPHER(which)) {
   1230 	rv = ssl2_GetPolicy(which, oPolicy);
   1231     } else {
   1232 	rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy);
   1233     }
   1234     return rv;
   1235 }
   1236 
   1237 /* Part of the public NSS API.
   1238  * Since this is a global (not per-socket) setting, we cannot use the
   1239  * HandshakeLock to protect this.  Probably want a global lock.
   1240  * These changes have no effect on any sslSockets already created.
   1241  */
   1242 SECStatus
   1243 SSL_EnableCipher(long which, PRBool enabled)
   1244 {
   1245     if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
   1246     	/* one of the two old FIPS ciphers */
   1247 	if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
   1248 	    which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
   1249 	else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
   1250 	    which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
   1251     }
   1252     if (ssl_IsRemovedCipherSuite(which))
   1253     	return SECSuccess;
   1254     return SSL_CipherPrefSetDefault(which, enabled);
   1255 }
   1256 
   1257 SECStatus
   1258 SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
   1259 {
   1260     SECStatus rv = ssl_Init();
   1261 
   1262     if (rv != SECSuccess) {
   1263 	return rv;
   1264     }
   1265 
   1266     if (ssl_IsRemovedCipherSuite(which))
   1267     	return SECSuccess;
   1268     if (enabled && ssl_defaults.noStepDown && SSL_IsExportCipherSuite(which)) {
   1269     	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
   1270 	return SECFailure;
   1271     }
   1272     if (SSL_IS_SSL2_CIPHER(which)) {
   1273 	rv = ssl2_CipherPrefSetDefault(which, enabled);
   1274     } else {
   1275 	rv = ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled);
   1276     }
   1277     return rv;
   1278 }
   1279 
   1280 SECStatus
   1281 SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
   1282 {
   1283     SECStatus  rv;
   1284 
   1285     if (!enabled) {
   1286 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1287 	return SECFailure;
   1288     }
   1289     if (ssl_IsRemovedCipherSuite(which)) {
   1290 	*enabled = PR_FALSE;
   1291     	rv = SECSuccess;
   1292     } else if (SSL_IS_SSL2_CIPHER(which)) {
   1293 	rv = ssl2_CipherPrefGetDefault(which, enabled);
   1294     } else {
   1295 	rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled);
   1296     }
   1297     return rv;
   1298 }
   1299 
   1300 SECStatus
   1301 SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled)
   1302 {
   1303     SECStatus rv;
   1304     sslSocket *ss = ssl_FindSocket(fd);
   1305 
   1306     if (!ss) {
   1307 	SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefSet", SSL_GETPID(), fd));
   1308 	return SECFailure;
   1309     }
   1310     if (ssl_IsRemovedCipherSuite(which))
   1311     	return SECSuccess;
   1312     if (enabled && ss->opt.noStepDown && SSL_IsExportCipherSuite(which)) {
   1313     	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
   1314 	return SECFailure;
   1315     }
   1316     if (SSL_IS_SSL2_CIPHER(which)) {
   1317 	rv = ssl2_CipherPrefSet(ss, which, enabled);
   1318     } else {
   1319 	rv = ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled);
   1320     }
   1321     return rv;
   1322 }
   1323 
   1324 SECStatus
   1325 SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled)
   1326 {
   1327     SECStatus  rv;
   1328     sslSocket *ss = ssl_FindSocket(fd);
   1329 
   1330     if (!enabled) {
   1331 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1332 	return SECFailure;
   1333     }
   1334     if (!ss) {
   1335 	SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefGet", SSL_GETPID(), fd));
   1336 	*enabled = PR_FALSE;
   1337 	return SECFailure;
   1338     }
   1339     if (ssl_IsRemovedCipherSuite(which)) {
   1340 	*enabled = PR_FALSE;
   1341     	rv = SECSuccess;
   1342     } else if (SSL_IS_SSL2_CIPHER(which)) {
   1343 	rv = ssl2_CipherPrefGet(ss, which, enabled);
   1344     } else {
   1345 	rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled);
   1346     }
   1347     return rv;
   1348 }
   1349 
   1350 SECStatus
   1351 NSS_SetDomesticPolicy(void)
   1352 {
   1353     SECStatus      status = SECSuccess;
   1354     cipherPolicy * policy;
   1355 
   1356     for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
   1357 	status = SSL_SetPolicy(policy->cipher, SSL_ALLOWED);
   1358 	if (status != SECSuccess)
   1359 	    break;
   1360     }
   1361     return status;
   1362 }
   1363 
   1364 SECStatus
   1365 NSS_SetExportPolicy(void)
   1366 {
   1367     return NSS_SetDomesticPolicy();
   1368 }
   1369 
   1370 SECStatus
   1371 NSS_SetFrancePolicy(void)
   1372 {
   1373     return NSS_SetDomesticPolicy();
   1374 }
   1375 
   1376 SECStatus
   1377 SSL_GetChannelBinding(PRFileDesc *fd,
   1378 		      SSLChannelBindingType binding_type,
   1379 		      unsigned char *out,
   1380 		      unsigned int *outLen,
   1381 		      unsigned int outLenMax) {
   1382     sslSocket *ss = ssl_FindSocket(fd);
   1383 
   1384     if (!ss) {
   1385 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetChannelBinding",
   1386 		 SSL_GETPID(), fd));
   1387 	return SECFailure;
   1388     }
   1389 
   1390     if (binding_type != SSL_CHANNEL_BINDING_TLS_UNIQUE) {
   1391 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   1392 	return SECFailure;
   1393     }
   1394 
   1395     return ssl3_GetTLSUniqueChannelBinding(ss, out, outLen, outLenMax);
   1396 }
   1397 
   1398 
   1399 /* LOCKS ??? XXX */
   1400 static PRFileDesc *
   1401 ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant)
   1402 {
   1403     sslSocket * ns = NULL;
   1404     PRStatus    rv;
   1405     PRNetAddr   addr;
   1406     SECStatus	status = ssl_Init();
   1407 
   1408     if (status != SECSuccess) {
   1409 	return NULL;
   1410     }
   1411 
   1412     if (model == NULL) {
   1413 	/* Just create a default socket if we're given NULL for the model */
   1414 	ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks), variant);
   1415     } else {
   1416 	sslSocket * ss = ssl_FindSocket(model);
   1417 	if (ss == NULL || ss->protocolVariant != variant) {
   1418 	    SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD",
   1419 	    	      SSL_GETPID(), model));
   1420 	    return NULL;
   1421 	}
   1422 	ns = ssl_DupSocket(ss);
   1423     }
   1424     if (ns == NULL)
   1425     	return NULL;
   1426 
   1427     rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER);
   1428     if (rv != PR_SUCCESS) {
   1429 	ssl_FreeSocket(ns);
   1430 	SET_ERROR_CODE
   1431 	return NULL;
   1432     }
   1433     ns = ssl_FindSocket(fd);
   1434     PORT_Assert(ns);
   1435     if (ns)
   1436 	ns->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ns, &addr));
   1437     return fd;
   1438 }
   1439 
   1440 PRFileDesc *
   1441 SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd)
   1442 {
   1443     return ssl_ImportFD(model, fd, ssl_variant_stream);
   1444 }
   1445 
   1446 PRFileDesc *
   1447 DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd)
   1448 {
   1449     return ssl_ImportFD(model, fd, ssl_variant_datagram);
   1450 }
   1451 
   1452 SECStatus
   1453 SSL_SetNextProtoCallback(PRFileDesc *fd, SSLNextProtoCallback callback,
   1454 			 void *arg)
   1455 {
   1456     sslSocket *ss = ssl_FindSocket(fd);
   1457 
   1458     if (!ss) {
   1459 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoCallback", SSL_GETPID(),
   1460 		 fd));
   1461 	return SECFailure;
   1462     }
   1463 
   1464     ssl_GetSSL3HandshakeLock(ss);
   1465     ss->nextProtoCallback = callback;
   1466     ss->nextProtoArg = arg;
   1467     ssl_ReleaseSSL3HandshakeLock(ss);
   1468 
   1469     return SECSuccess;
   1470 }
   1471 
   1472 /* ssl_NextProtoNegoCallback is set as an NPN callback for the case when
   1473  * SSL_SetNextProtoNego is used.
   1474  */
   1475 static SECStatus
   1476 ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd,
   1477 			  const unsigned char *protos, unsigned int protos_len,
   1478 			  unsigned char *protoOut, unsigned int *protoOutLen,
   1479 			  unsigned int protoMaxLen)
   1480 {
   1481     unsigned int i, j;
   1482     const unsigned char *result;
   1483     sslSocket *ss = ssl_FindSocket(fd);
   1484 
   1485     if (!ss) {
   1486 	SSL_DBG(("%d: SSL[%d]: bad socket in ssl_NextProtoNegoCallback",
   1487 		 SSL_GETPID(), fd));
   1488 	return SECFailure;
   1489     }
   1490 
   1491     if (protos_len == 0) {
   1492 	/* The server supports the extension, but doesn't have any protocols
   1493 	 * configured. In this case we request our favoured protocol. */
   1494 	goto pick_first;
   1495     }
   1496 
   1497     /* For each protocol in server preference, see if we support it. */
   1498     for (i = 0; i < protos_len; ) {
   1499 	for (j = 0; j < ss->opt.nextProtoNego.len; ) {
   1500 	    if (protos[i] == ss->opt.nextProtoNego.data[j] &&
   1501 		PORT_Memcmp(&protos[i+1], &ss->opt.nextProtoNego.data[j+1],
   1502 			     protos[i]) == 0) {
   1503 		/* We found a match. */
   1504 		ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
   1505 		result = &protos[i];
   1506 		goto found;
   1507 	    }
   1508 	    j += 1 + (unsigned int)ss->opt.nextProtoNego.data[j];
   1509 	}
   1510 	i += 1 + (unsigned int)protos[i];
   1511     }
   1512 
   1513 pick_first:
   1514     ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP;
   1515     result = ss->opt.nextProtoNego.data;
   1516 
   1517 found:
   1518     if (protoMaxLen < result[0]) {
   1519 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
   1520 	return SECFailure;
   1521     }
   1522     memcpy(protoOut, result + 1, result[0]);
   1523     *protoOutLen = result[0];
   1524     return SECSuccess;
   1525 }
   1526 
   1527 SECStatus
   1528 SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
   1529 		     unsigned int length)
   1530 {
   1531     sslSocket *ss;
   1532     SECStatus rv;
   1533     SECItem dataItem = { siBuffer, (unsigned char *) data, length };
   1534 
   1535     ss = ssl_FindSocket(fd);
   1536     if (!ss) {
   1537 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoNego",
   1538 		 SSL_GETPID(), fd));
   1539 	return SECFailure;
   1540     }
   1541 
   1542     if (ssl3_ValidateNextProtoNego(data, length) != SECSuccess)
   1543 	return SECFailure;
   1544 
   1545     ssl_GetSSL3HandshakeLock(ss);
   1546     SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
   1547     rv = SECITEM_CopyItem(NULL, &ss->opt.nextProtoNego, &dataItem);
   1548     ssl_ReleaseSSL3HandshakeLock(ss);
   1549 
   1550     if (rv != SECSuccess)
   1551 	return rv;
   1552 
   1553     return SSL_SetNextProtoCallback(fd, ssl_NextProtoNegoCallback, NULL);
   1554 }
   1555 
   1556 SECStatus
   1557 SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf,
   1558 		 unsigned int *bufLen, unsigned int bufLenMax)
   1559 {
   1560     sslSocket *ss = ssl_FindSocket(fd);
   1561 
   1562     if (!ss) {
   1563 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNextProto", SSL_GETPID(),
   1564 		 fd));
   1565 	return SECFailure;
   1566     }
   1567 
   1568     if (!state || !buf || !bufLen) {
   1569 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1570 	return SECFailure;
   1571     }
   1572 
   1573     *state = ss->ssl3.nextProtoState;
   1574 
   1575     if (ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
   1576 	ss->ssl3.nextProto.data) {
   1577 	if (ss->ssl3.nextProto.len > bufLenMax) {
   1578 	    PORT_SetError(SEC_ERROR_OUTPUT_LEN);
   1579 	    return SECFailure;
   1580 	}
   1581 	PORT_Memcpy(buf, ss->ssl3.nextProto.data, ss->ssl3.nextProto.len);
   1582 	*bufLen = ss->ssl3.nextProto.len;
   1583     } else {
   1584 	*bufLen = 0;
   1585     }
   1586 
   1587     return SECSuccess;
   1588 }
   1589 
   1590 SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd,
   1591 			     const PRUint16 *ciphers,
   1592 			     unsigned int numCiphers)
   1593 {
   1594     sslSocket *ss;
   1595     unsigned int i;
   1596 
   1597     ss = ssl_FindSocket(fd);
   1598     if (!ss || !IS_DTLS(ss)) {
   1599 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSRTPCiphers",
   1600 		 SSL_GETPID(), fd));
   1601 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1602 	return SECFailure;
   1603     }
   1604 
   1605     if (numCiphers > MAX_DTLS_SRTP_CIPHER_SUITES) {
   1606 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1607 	return SECFailure;
   1608     }
   1609 
   1610     ss->ssl3.dtlsSRTPCipherCount = 0;
   1611     for (i = 0; i < numCiphers; i++) {
   1612 	const PRUint16 *srtpCipher = srtpCiphers;
   1613 
   1614 	while (*srtpCipher) {
   1615 	    if (ciphers[i] == *srtpCipher)
   1616 		break;
   1617 	    srtpCipher++;
   1618 	}
   1619 	if (*srtpCipher) {
   1620 	    ss->ssl3.dtlsSRTPCiphers[ss->ssl3.dtlsSRTPCipherCount++] =
   1621 		ciphers[i];
   1622 	} else {
   1623 	    SSL_DBG(("%d: SSL[%d]: invalid or unimplemented SRTP cipher "
   1624 		    "suite specified: 0x%04hx", SSL_GETPID(), fd,
   1625 		    ciphers[i]));
   1626 	}
   1627     }
   1628 
   1629     if (ss->ssl3.dtlsSRTPCipherCount == 0) {
   1630 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1631 	return SECFailure;
   1632     }
   1633 
   1634     return SECSuccess;
   1635 }
   1636 
   1637 SECStatus
   1638 SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher)
   1639 {
   1640     sslSocket * ss;
   1641 
   1642     ss = ssl_FindSocket(fd);
   1643     if (!ss) {
   1644 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetSRTPCipher",
   1645 		 SSL_GETPID(), fd));
   1646 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1647 	return SECFailure;
   1648     }
   1649 
   1650     if (!ss->ssl3.dtlsSRTPCipherSuite) {
   1651 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1652 	return SECFailure;
   1653     }
   1654 
   1655     *cipher = ss->ssl3.dtlsSRTPCipherSuite;
   1656     return SECSuccess;
   1657 }
   1658 
   1659 PRFileDesc *
   1660 SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd)
   1661 {
   1662     PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
   1663     PR_NOT_REACHED("not implemented");
   1664     return NULL;
   1665 
   1666 #if 0
   1667     sslSocket * sm = NULL, *ss = NULL;
   1668     int i;
   1669     sslServerCerts * mc = NULL;
   1670     sslServerCerts * sc = NULL;
   1671 
   1672     if (model == NULL) {
   1673         PR_SetError(SEC_ERROR_INVALID_ARGS, 0);
   1674         return NULL;
   1675     }
   1676     sm = ssl_FindSocket(model);
   1677     if (sm == NULL) {
   1678         SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ReconfigFD",
   1679                  SSL_GETPID(), model));
   1680         return NULL;
   1681     }
   1682     ss = ssl_FindSocket(fd);
   1683     PORT_Assert(ss);
   1684     if (ss == NULL) {
   1685         PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1686         return NULL;
   1687     }
   1688 
   1689     ss->opt  = sm->opt;
   1690     ss->vrange = sm->vrange;
   1691     PORT_Memcpy(ss->cipherSuites, sm->cipherSuites, sizeof sm->cipherSuites);
   1692     PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, sm->ssl3.dtlsSRTPCiphers,
   1693                 sizeof(PRUint16) * sm->ssl3.dtlsSRTPCipherCount);
   1694     ss->ssl3.dtlsSRTPCipherCount = sm->ssl3.dtlsSRTPCipherCount;
   1695 
   1696     if (!ss->opt.useSecurity) {
   1697         PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1698         return NULL;
   1699     }
   1700     /* This int should be SSLKEAType, but CC on Irix complains,
   1701      * during the for loop.
   1702      */
   1703     for (i=kt_null; i < kt_kea_size; i++) {
   1704         mc = &(sm->serverCerts[i]);
   1705         sc = &(ss->serverCerts[i]);
   1706         if (mc->serverCert && mc->serverCertChain) {
   1707             if (sc->serverCert) {
   1708                 CERT_DestroyCertificate(sc->serverCert);
   1709             }
   1710             sc->serverCert      = CERT_DupCertificate(mc->serverCert);
   1711             if (sc->serverCertChain) {
   1712                 CERT_DestroyCertificateList(sc->serverCertChain);
   1713             }
   1714             sc->serverCertChain = CERT_DupCertList(mc->serverCertChain);
   1715             if (!sc->serverCertChain)
   1716                 goto loser;
   1717 	    if (sm->certStatusArray[i]) {
   1718 		if (ss->certStatusArray[i]) {
   1719 		    SECITEM_FreeArray(ss->certStatusArray[i], PR_TRUE);
   1720 		    ss->certStatusArray[i] = NULL;
   1721 		}
   1722 		ss->certStatusArray[i] = SECITEM_DupArray(NULL, sm->certStatusArray[i]);
   1723 		if (!ss->certStatusArray[i])
   1724 		    goto loser;
   1725 	    }
   1726         }
   1727         if (mc->serverKeyPair) {
   1728             if (sc->serverKeyPair) {
   1729                 ssl3_FreeKeyPair(sc->serverKeyPair);
   1730             }
   1731             sc->serverKeyPair = ssl3_GetKeyPairRef(mc->serverKeyPair);
   1732             sc->serverKeyBits = mc->serverKeyBits;
   1733         }
   1734     }
   1735     if (sm->stepDownKeyPair) {
   1736         if (ss->stepDownKeyPair) {
   1737             ssl3_FreeKeyPair(ss->stepDownKeyPair);
   1738         }
   1739         ss->stepDownKeyPair = ssl3_GetKeyPairRef(sm->stepDownKeyPair);
   1740     }
   1741     if (sm->ephemeralECDHKeyPair) {
   1742         if (ss->ephemeralECDHKeyPair) {
   1743             ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
   1744         }
   1745         ss->ephemeralECDHKeyPair =
   1746             ssl3_GetKeyPairRef(sm->ephemeralECDHKeyPair);
   1747     }
   1748     /* copy trust anchor names */
   1749     if (sm->ssl3.ca_list) {
   1750         if (ss->ssl3.ca_list) {
   1751             CERT_FreeDistNames(ss->ssl3.ca_list);
   1752         }
   1753         ss->ssl3.ca_list = CERT_DupDistNames(sm->ssl3.ca_list);
   1754         if (!ss->ssl3.ca_list) {
   1755             goto loser;
   1756         }
   1757     }
   1758 
   1759     if (sm->authCertificate)
   1760         ss->authCertificate       = sm->authCertificate;
   1761     if (sm->authCertificateArg)
   1762         ss->authCertificateArg    = sm->authCertificateArg;
   1763     if (sm->getClientAuthData)
   1764         ss->getClientAuthData     = sm->getClientAuthData;
   1765     if (sm->getClientAuthDataArg)
   1766         ss->getClientAuthDataArg  = sm->getClientAuthDataArg;
   1767 #ifdef NSS_PLATFORM_CLIENT_AUTH
   1768     if (sm->getPlatformClientAuthData)
   1769         ss->getPlatformClientAuthData    = sm->getPlatformClientAuthData;
   1770     if (sm->getPlatformClientAuthDataArg)
   1771         ss->getPlatformClientAuthDataArg = sm->getPlatformClientAuthDataArg;
   1772 #endif
   1773     if (sm->sniSocketConfig)
   1774         ss->sniSocketConfig       = sm->sniSocketConfig;
   1775     if (sm->sniSocketConfigArg)
   1776         ss->sniSocketConfigArg    = sm->sniSocketConfigArg;
   1777     if (sm->handleBadCert)
   1778         ss->handleBadCert         = sm->handleBadCert;
   1779     if (sm->badCertArg)
   1780         ss->badCertArg            = sm->badCertArg;
   1781     if (sm->handshakeCallback)
   1782         ss->handshakeCallback     = sm->handshakeCallback;
   1783     if (sm->handshakeCallbackData)
   1784         ss->handshakeCallbackData = sm->handshakeCallbackData;
   1785     if (sm->pkcs11PinArg)
   1786         ss->pkcs11PinArg          = sm->pkcs11PinArg;
   1787     if (sm->getChannelID)
   1788         ss->getChannelID          = sm->getChannelID;
   1789     if (sm->getChannelIDArg)
   1790         ss->getChannelIDArg       = sm->getChannelIDArg;
   1791     return fd;
   1792 loser:
   1793     return NULL;
   1794 #endif
   1795 }
   1796 
   1797 PRBool
   1798 ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
   1799 			SSL3ProtocolVersion version)
   1800 {
   1801     switch (protocolVariant) {
   1802     case ssl_variant_stream:
   1803 	return (version >= SSL_LIBRARY_VERSION_3_0 &&
   1804 		version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
   1805     case ssl_variant_datagram:
   1806 	return (version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
   1807 		version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
   1808     default:
   1809 	/* Can't get here */
   1810 	PORT_Assert(PR_FALSE);
   1811 	return PR_FALSE;
   1812     }
   1813 }
   1814 
   1815 /* Returns PR_TRUE if the given version range is valid and
   1816 ** fully supported; otherwise, returns PR_FALSE.
   1817 */
   1818 static PRBool
   1819 ssl3_VersionRangeIsValid(SSLProtocolVariant protocolVariant,
   1820 			 const SSLVersionRange *vrange)
   1821 {
   1822     return vrange &&
   1823 	   vrange->min <= vrange->max &&
   1824 	   ssl3_VersionIsSupported(protocolVariant, vrange->min) &&
   1825 	   ssl3_VersionIsSupported(protocolVariant, vrange->max);
   1826 }
   1827 
   1828 SECStatus
   1829 SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant,
   1830 			     SSLVersionRange *vrange)
   1831 {
   1832     if (!vrange) {
   1833 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1834 	return SECFailure;
   1835     }
   1836 
   1837     switch (protocolVariant) {
   1838     case ssl_variant_stream:
   1839 	vrange->min = SSL_LIBRARY_VERSION_3_0;
   1840 	vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
   1841 	break;
   1842     case ssl_variant_datagram:
   1843 	vrange->min = SSL_LIBRARY_VERSION_TLS_1_1;
   1844 	vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
   1845 	break;
   1846     default:
   1847 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1848 	return SECFailure;
   1849     }
   1850 
   1851     return SECSuccess;
   1852 }
   1853 
   1854 SECStatus
   1855 SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant,
   1856 			   SSLVersionRange *vrange)
   1857 {
   1858     if ((protocolVariant != ssl_variant_stream &&
   1859 	 protocolVariant != ssl_variant_datagram) || !vrange) {
   1860 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1861 	return SECFailure;
   1862     }
   1863 
   1864     *vrange = *VERSIONS_DEFAULTS(protocolVariant);
   1865 
   1866     return SECSuccess;
   1867 }
   1868 
   1869 SECStatus
   1870 SSL_VersionRangeSetDefault(SSLProtocolVariant protocolVariant,
   1871 			   const SSLVersionRange *vrange)
   1872 {
   1873     if (!ssl3_VersionRangeIsValid(protocolVariant, vrange)) {
   1874 	PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
   1875 	return SECFailure;
   1876     }
   1877 
   1878     *VERSIONS_DEFAULTS(protocolVariant) = *vrange;
   1879 
   1880     return SECSuccess;
   1881 }
   1882 
   1883 SECStatus
   1884 SSL_VersionRangeGet(PRFileDesc *fd, SSLVersionRange *vrange)
   1885 {
   1886     sslSocket *ss = ssl_FindSocket(fd);
   1887 
   1888     if (!ss) {
   1889 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeGet",
   1890 		SSL_GETPID(), fd));
   1891 	return SECFailure;
   1892     }
   1893 
   1894     if (!vrange) {
   1895 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1896 	return SECFailure;
   1897     }
   1898 
   1899     ssl_Get1stHandshakeLock(ss);
   1900     ssl_GetSSL3HandshakeLock(ss);
   1901 
   1902     *vrange = ss->vrange;
   1903 
   1904     ssl_ReleaseSSL3HandshakeLock(ss);
   1905     ssl_Release1stHandshakeLock(ss);
   1906 
   1907     return SECSuccess;
   1908 }
   1909 
   1910 static PRCallOnceType checkTLS12TokenOnce;
   1911 static PRBool tls12TokenExists;
   1912 
   1913 static PRStatus
   1914 ssl_CheckTLS12Token(void)
   1915 {
   1916     tls12TokenExists =
   1917 	PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256);
   1918     return PR_SUCCESS;
   1919 }
   1920 
   1921 static PRBool
   1922 ssl_TLS12TokenExists(void)
   1923 {
   1924     (void) PR_CallOnce(&checkTLS12TokenOnce, ssl_CheckTLS12Token);
   1925     return tls12TokenExists;
   1926 }
   1927 
   1928 SECStatus
   1929 SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange)
   1930 {
   1931     sslSocket *ss = ssl_FindSocket(fd);
   1932 
   1933     if (!ss) {
   1934 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeSet",
   1935 		SSL_GETPID(), fd));
   1936 	return SECFailure;
   1937     }
   1938 
   1939     if (!ssl3_VersionRangeIsValid(ss->protocolVariant, vrange)) {
   1940 	PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
   1941 	return SECFailure;
   1942     }
   1943 
   1944     ssl_Get1stHandshakeLock(ss);
   1945     ssl_GetSSL3HandshakeLock(ss);
   1946 
   1947     ss->vrange = *vrange;
   1948     /* If we don't have a sufficiently up-to-date softoken then we cannot do
   1949      * TLS 1.2. */
   1950     if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
   1951         !ssl_TLS12TokenExists()) {
   1952 	/* If the user requested a minimum version of 1.2, then we don't
   1953 	 * silently downgrade. */
   1954 	if (ss->vrange.min >= SSL_LIBRARY_VERSION_TLS_1_2) {
   1955 	    ssl_ReleaseSSL3HandshakeLock(ss);
   1956 	    ssl_Release1stHandshakeLock(ss);
   1957 	    PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
   1958 	    return SECFailure;
   1959 	}
   1960 	ss->vrange.max = SSL_LIBRARY_VERSION_TLS_1_1;
   1961     }
   1962 
   1963     ssl_ReleaseSSL3HandshakeLock(ss);
   1964     ssl_Release1stHandshakeLock(ss);
   1965 
   1966     return SECSuccess;
   1967 }
   1968 
   1969 const SECItemArray *
   1970 SSL_PeerStapledOCSPResponses(PRFileDesc *fd)
   1971 {
   1972     sslSocket *ss = ssl_FindSocket(fd);
   1973 
   1974     if (!ss) {
   1975        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerStapledOCSPResponses",
   1976                 SSL_GETPID(), fd));
   1977        return NULL;
   1978     }
   1979 
   1980     if (!ss->sec.ci.sid) {
   1981        PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
   1982        return NULL;
   1983     }
   1984 
   1985     return &ss->sec.ci.sid->peerCertStatus;
   1986 }
   1987 
   1988 SECStatus
   1989 SSL_HandshakeResumedSession(PRFileDesc *fd, PRBool *handshake_resumed) {
   1990     sslSocket *ss = ssl_FindSocket(fd);
   1991 
   1992     if (!ss) {
   1993 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_HandshakeResumedSession",
   1994 		 SSL_GETPID(), fd));
   1995 	return SECFailure;
   1996     }
   1997 
   1998     *handshake_resumed = ss->ssl3.hs.isResuming;
   1999     return SECSuccess;
   2000 }
   2001 
   2002 const SECItem *
   2003 SSL_GetRequestedClientCertificateTypes(PRFileDesc *fd)
   2004 {
   2005   sslSocket *ss = ssl_FindSocket(fd);
   2006 
   2007   if (!ss) {
   2008       SSL_DBG(("%d: SSL[%d]: bad socket in "
   2009                "SSL_GetRequestedClientCertificateTypes", SSL_GETPID(), fd));
   2010       return NULL;
   2011   }
   2012 
   2013   return ss->requestedCertTypes;
   2014 }
   2015 
   2016 /************************************************************************/
   2017 /* The following functions are the TOP LEVEL SSL functions.
   2018 ** They all get called through the NSPRIOMethods table below.
   2019 */
   2020 
   2021 static PRFileDesc * PR_CALLBACK
   2022 ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout)
   2023 {
   2024     sslSocket  *ss;
   2025     sslSocket  *ns 	= NULL;
   2026     PRFileDesc *newfd 	= NULL;
   2027     PRFileDesc *osfd;
   2028     PRStatus    status;
   2029 
   2030     ss = ssl_GetPrivate(fd);
   2031     if (!ss) {
   2032 	SSL_DBG(("%d: SSL[%d]: bad socket in accept", SSL_GETPID(), fd));
   2033 	return NULL;
   2034     }
   2035 
   2036     /* IF this is a listen socket, there shouldn't be any I/O going on */
   2037     SSL_LOCK_READER(ss);
   2038     SSL_LOCK_WRITER(ss);
   2039     ssl_Get1stHandshakeLock(ss);
   2040     ssl_GetSSL3HandshakeLock(ss);
   2041 
   2042     ss->cTimeout = timeout;
   2043 
   2044     osfd = ss->fd->lower;
   2045 
   2046     /* First accept connection */
   2047     newfd = osfd->methods->accept(osfd, sockaddr, timeout);
   2048     if (newfd == NULL) {
   2049 	SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d",
   2050 		 SSL_GETPID(), ss->fd, PORT_GetError()));
   2051     } else {
   2052 	/* Create ssl module */
   2053 	ns = ssl_DupSocket(ss);
   2054     }
   2055 
   2056     ssl_ReleaseSSL3HandshakeLock(ss);
   2057     ssl_Release1stHandshakeLock(ss);
   2058     SSL_UNLOCK_WRITER(ss);
   2059     SSL_UNLOCK_READER(ss);			/* ss isn't used below here. */
   2060 
   2061     if (ns == NULL)
   2062 	goto loser;
   2063 
   2064     /* push ssl module onto the new socket */
   2065     status = ssl_PushIOLayer(ns, newfd, PR_TOP_IO_LAYER);
   2066     if (status != PR_SUCCESS)
   2067 	goto loser;
   2068 
   2069     /* Now start server connection handshake with client.
   2070     ** Don't need locks here because nobody else has a reference to ns yet.
   2071     */
   2072     if ( ns->opt.useSecurity ) {
   2073 	if ( ns->opt.handshakeAsClient ) {
   2074 	    ns->handshake = ssl2_BeginClientHandshake;
   2075 	    ss->handshaking = sslHandshakingAsClient;
   2076 	} else {
   2077 	    ns->handshake = ssl2_BeginServerHandshake;
   2078 	    ss->handshaking = sslHandshakingAsServer;
   2079 	}
   2080     }
   2081     ns->TCPconnected = 1;
   2082     return newfd;
   2083 
   2084 loser:
   2085     if (ns != NULL)
   2086 	ssl_FreeSocket(ns);
   2087     if (newfd != NULL)
   2088 	PR_Close(newfd);
   2089     return NULL;
   2090 }
   2091 
   2092 static PRStatus PR_CALLBACK
   2093 ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout)
   2094 {
   2095     sslSocket *ss;
   2096     PRStatus   rv;
   2097 
   2098     ss = ssl_GetPrivate(fd);
   2099     if (!ss) {
   2100 	SSL_DBG(("%d: SSL[%d]: bad socket in connect", SSL_GETPID(), fd));
   2101 	return PR_FAILURE;
   2102     }
   2103 
   2104     /* IF this is a listen socket, there shouldn't be any I/O going on */
   2105     SSL_LOCK_READER(ss);
   2106     SSL_LOCK_WRITER(ss);
   2107 
   2108     ss->cTimeout = timeout;
   2109     rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr);
   2110 
   2111     SSL_UNLOCK_WRITER(ss);
   2112     SSL_UNLOCK_READER(ss);
   2113 
   2114     return rv;
   2115 }
   2116 
   2117 static PRStatus PR_CALLBACK
   2118 ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr)
   2119 {
   2120     sslSocket * ss = ssl_GetPrivate(fd);
   2121     PRStatus    rv;
   2122 
   2123     if (!ss) {
   2124 	SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd));
   2125 	return PR_FAILURE;
   2126     }
   2127     SSL_LOCK_READER(ss);
   2128     SSL_LOCK_WRITER(ss);
   2129 
   2130     rv = (PRStatus)(*ss->ops->bind)(ss, addr);
   2131 
   2132     SSL_UNLOCK_WRITER(ss);
   2133     SSL_UNLOCK_READER(ss);
   2134     return rv;
   2135 }
   2136 
   2137 static PRStatus PR_CALLBACK
   2138 ssl_Listen(PRFileDesc *fd, PRIntn backlog)
   2139 {
   2140     sslSocket * ss = ssl_GetPrivate(fd);
   2141     PRStatus    rv;
   2142 
   2143     if (!ss) {
   2144 	SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd));
   2145 	return PR_FAILURE;
   2146     }
   2147     SSL_LOCK_READER(ss);
   2148     SSL_LOCK_WRITER(ss);
   2149 
   2150     rv = (PRStatus)(*ss->ops->listen)(ss, backlog);
   2151 
   2152     SSL_UNLOCK_WRITER(ss);
   2153     SSL_UNLOCK_READER(ss);
   2154     return rv;
   2155 }
   2156 
   2157 static PRStatus PR_CALLBACK
   2158 ssl_Shutdown(PRFileDesc *fd, PRIntn how)
   2159 {
   2160     sslSocket * ss = ssl_GetPrivate(fd);
   2161     PRStatus    rv;
   2162 
   2163     if (!ss) {
   2164 	SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd));
   2165 	return PR_FAILURE;
   2166     }
   2167     if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
   2168     	SSL_LOCK_READER(ss);
   2169     }
   2170     if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
   2171     	SSL_LOCK_WRITER(ss);
   2172     }
   2173 
   2174     rv = (PRStatus)(*ss->ops->shutdown)(ss, how);
   2175 
   2176     if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
   2177     	SSL_UNLOCK_WRITER(ss);
   2178     }
   2179     if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
   2180     	SSL_UNLOCK_READER(ss);
   2181     }
   2182     return rv;
   2183 }
   2184 
   2185 static PRStatus PR_CALLBACK
   2186 ssl_Close(PRFileDesc *fd)
   2187 {
   2188     sslSocket *ss;
   2189     PRStatus   rv;
   2190 
   2191     ss = ssl_GetPrivate(fd);
   2192     if (!ss) {
   2193 	SSL_DBG(("%d: SSL[%d]: bad socket in close", SSL_GETPID(), fd));
   2194 	return PR_FAILURE;
   2195     }
   2196 
   2197     /* There must not be any I/O going on */
   2198     SSL_LOCK_READER(ss);
   2199     SSL_LOCK_WRITER(ss);
   2200 
   2201     /* By the time this function returns,
   2202     ** ss is an invalid pointer, and the locks to which it points have
   2203     ** been unlocked and freed.  So, this is the ONE PLACE in all of SSL
   2204     ** where the LOCK calls and the corresponding UNLOCK calls are not in
   2205     ** the same function scope.  The unlock calls are in ssl_FreeSocket().
   2206     */
   2207     rv = (PRStatus)(*ss->ops->close)(ss);
   2208 
   2209     return rv;
   2210 }
   2211 
   2212 static int PR_CALLBACK
   2213 ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
   2214 	 PRIntervalTime timeout)
   2215 {
   2216     sslSocket *ss;
   2217     int        rv;
   2218 
   2219     ss = ssl_GetPrivate(fd);
   2220     if (!ss) {
   2221 	SSL_DBG(("%d: SSL[%d]: bad socket in recv", SSL_GETPID(), fd));
   2222 	return SECFailure;
   2223     }
   2224     SSL_LOCK_READER(ss);
   2225     ss->rTimeout = timeout;
   2226     if (!ss->opt.fdx)
   2227 	ss->wTimeout = timeout;
   2228     rv = (*ss->ops->recv)(ss, (unsigned char*)buf, len, flags);
   2229     SSL_UNLOCK_READER(ss);
   2230     return rv;
   2231 }
   2232 
   2233 static int PR_CALLBACK
   2234 ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
   2235 	 PRIntervalTime timeout)
   2236 {
   2237     sslSocket *ss;
   2238     int        rv;
   2239 
   2240     ss = ssl_GetPrivate(fd);
   2241     if (!ss) {
   2242 	SSL_DBG(("%d: SSL[%d]: bad socket in send", SSL_GETPID(), fd));
   2243 	return SECFailure;
   2244     }
   2245     SSL_LOCK_WRITER(ss);
   2246     ss->wTimeout = timeout;
   2247     if (!ss->opt.fdx)
   2248 	ss->rTimeout = timeout;
   2249     rv = (*ss->ops->send)(ss, (const unsigned char*)buf, len, flags);
   2250     SSL_UNLOCK_WRITER(ss);
   2251     return rv;
   2252 }
   2253 
   2254 static int PR_CALLBACK
   2255 ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len)
   2256 {
   2257     sslSocket *ss;
   2258     int        rv;
   2259 
   2260     ss = ssl_GetPrivate(fd);
   2261     if (!ss) {
   2262 	SSL_DBG(("%d: SSL[%d]: bad socket in read", SSL_GETPID(), fd));
   2263 	return SECFailure;
   2264     }
   2265     SSL_LOCK_READER(ss);
   2266     ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
   2267     if (!ss->opt.fdx)
   2268 	ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
   2269     rv = (*ss->ops->read)(ss, (unsigned char*)buf, len);
   2270     SSL_UNLOCK_READER(ss);
   2271     return rv;
   2272 }
   2273 
   2274 static int PR_CALLBACK
   2275 ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
   2276 {
   2277     sslSocket *ss;
   2278     int        rv;
   2279 
   2280     ss = ssl_GetPrivate(fd);
   2281     if (!ss) {
   2282 	SSL_DBG(("%d: SSL[%d]: bad socket in write", SSL_GETPID(), fd));
   2283 	return SECFailure;
   2284     }
   2285     SSL_LOCK_WRITER(ss);
   2286     ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
   2287     if (!ss->opt.fdx)
   2288 	ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
   2289     rv = (*ss->ops->write)(ss, (const unsigned char*)buf, len);
   2290     SSL_UNLOCK_WRITER(ss);
   2291     return rv;
   2292 }
   2293 
   2294 static PRStatus PR_CALLBACK
   2295 ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
   2296 {
   2297     sslSocket *ss;
   2298 
   2299     ss = ssl_GetPrivate(fd);
   2300     if (!ss) {
   2301 	SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd));
   2302 	return PR_FAILURE;
   2303     }
   2304     return (PRStatus)(*ss->ops->getpeername)(ss, addr);
   2305 }
   2306 
   2307 /*
   2308 */
   2309 SECStatus
   2310 ssl_GetPeerInfo(sslSocket *ss)
   2311 {
   2312     PRFileDesc *      osfd;
   2313     int               rv;
   2314     PRNetAddr         sin;
   2315 
   2316     osfd = ss->fd->lower;
   2317 
   2318     PORT_Memset(&sin, 0, sizeof(sin));
   2319     rv = osfd->methods->getpeername(osfd, &sin);
   2320     if (rv < 0) {
   2321 	return SECFailure;
   2322     }
   2323     ss->TCPconnected = 1;
   2324     if (sin.inet.family == PR_AF_INET) {
   2325         PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer);
   2326 	ss->sec.ci.port = sin.inet.port;
   2327     } else if (sin.ipv6.family == PR_AF_INET6) {
   2328 	ss->sec.ci.peer = sin.ipv6.ip;
   2329 	ss->sec.ci.port = sin.ipv6.port;
   2330     } else {
   2331 	PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR);
   2332     	return SECFailure;
   2333     }
   2334     return SECSuccess;
   2335 }
   2336 
   2337 static PRStatus PR_CALLBACK
   2338 ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name)
   2339 {
   2340     sslSocket *ss;
   2341 
   2342     ss = ssl_GetPrivate(fd);
   2343     if (!ss) {
   2344 	SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd));
   2345 	return PR_FAILURE;
   2346     }
   2347     return (PRStatus)(*ss->ops->getsockname)(ss, name);
   2348 }
   2349 
   2350 SECStatus
   2351 SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses,
   2352 			    SSLKEAType kea)
   2353 {
   2354     sslSocket *ss;
   2355 
   2356     ss = ssl_FindSocket(fd);
   2357     if (!ss) {
   2358 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetStapledOCSPResponses",
   2359 		 SSL_GETPID(), fd));
   2360 	return SECFailure;
   2361     }
   2362 
   2363     if ( kea <= 0 || kea >= kt_kea_size) {
   2364 	SSL_DBG(("%d: SSL[%d]: invalid key in SSL_SetStapledOCSPResponses",
   2365 		 SSL_GETPID(), fd));
   2366 	return SECFailure;
   2367     }
   2368 
   2369     if (ss->certStatusArray[kea]) {
   2370         SECITEM_FreeArray(ss->certStatusArray[kea], PR_TRUE);
   2371         ss->certStatusArray[kea] = NULL;
   2372     }
   2373     if (responses) {
   2374 	ss->certStatusArray[kea] = SECITEM_DupArray(NULL, responses);
   2375     }
   2376     return (ss->certStatusArray[kea] || !responses) ? SECSuccess : SECFailure;
   2377 }
   2378 
   2379 SECStatus
   2380 SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID)
   2381 {
   2382     sslSocket *ss;
   2383 
   2384     ss = ssl_FindSocket(fd);
   2385     if (!ss) {
   2386 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSockPeerID",
   2387 		 SSL_GETPID(), fd));
   2388 	return SECFailure;
   2389     }
   2390 
   2391     if (ss->peerID) {
   2392     	PORT_Free(ss->peerID);
   2393 	ss->peerID = NULL;
   2394     }
   2395     if (peerID)
   2396 	ss->peerID = PORT_Strdup(peerID);
   2397     return (ss->peerID || !peerID) ? SECSuccess : SECFailure;
   2398 }
   2399 
   2400 #define PR_POLL_RW (PR_POLL_WRITE | PR_POLL_READ)
   2401 
   2402 static PRInt16 PR_CALLBACK
   2403 ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags)
   2404 {
   2405     sslSocket *ss;
   2406     PRInt16    new_flags = how_flags;	/* should select on these flags. */
   2407     PRNetAddr  addr;
   2408 
   2409     *p_out_flags = 0;
   2410     ss = ssl_GetPrivate(fd);
   2411     if (!ss) {
   2412 	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll",
   2413 		 SSL_GETPID(), fd));
   2414 	return 0;	/* don't poll on this socket */
   2415     }
   2416 
   2417     if (ss->opt.useSecurity &&
   2418 	ss->handshaking != sslHandshakingUndetermined &&
   2419         !ss->firstHsDone &&
   2420 	(how_flags & PR_POLL_RW)) {
   2421 	if (!ss->TCPconnected) {
   2422 	    ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
   2423 	}
   2424 	/* If it's not connected, then presumably the application is polling
   2425 	** on read or write appropriately, so don't change it.
   2426 	*/
   2427 	if (ss->TCPconnected) {
   2428 	    if (!ss->handshakeBegun) {
   2429 		/* If the handshake has not begun, poll on read or write
   2430 		** based on the local application's role in the handshake,
   2431 		** not based on what the application requested.
   2432 		*/
   2433 		new_flags &= ~PR_POLL_RW;
   2434 		if (ss->handshaking == sslHandshakingAsClient) {
   2435 		    new_flags |= PR_POLL_WRITE;
   2436 		} else { /* handshaking as server */
   2437 		    new_flags |= PR_POLL_READ;
   2438 		}
   2439 	    } else
   2440 	    /* First handshake is in progress */
   2441 	    if (ss->lastWriteBlocked) {
   2442 		if (new_flags & PR_POLL_READ) {
   2443 		    /* The caller is waiting for data to be received,
   2444 		    ** but the initial handshake is blocked on write, or the
   2445 		    ** client's first handshake record has not been written.
   2446 		    ** The code should select on write, not read.
   2447 		    */
   2448 		    new_flags ^=  PR_POLL_READ;	   /* don't select on read. */
   2449 		    new_flags |=  PR_POLL_WRITE;   /* do    select on write. */
   2450 		}
   2451 	    } else if (new_flags & PR_POLL_WRITE) {
   2452 		    /* The caller is trying to write, but the handshake is
   2453 		    ** blocked waiting for data to read, and the first
   2454 		    ** handshake has been sent.  so do NOT to poll on write.
   2455 		    */
   2456 		    new_flags ^=  PR_POLL_WRITE;   /* don't select on write. */
   2457 		    new_flags |=  PR_POLL_READ;	   /* do    select on read. */
   2458 	    }
   2459 	}
   2460     } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) {
   2461 	*p_out_flags = PR_POLL_READ;	/* it's ready already. */
   2462 	return new_flags;
   2463     } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) &&
   2464 	       (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */
   2465 	new_flags |=  PR_POLL_WRITE;   /* also select on write. */
   2466     }
   2467 
   2468     if (ss->version >= SSL_LIBRARY_VERSION_3_0 &&
   2469 	ss->ssl3.hs.restartTarget != NULL) {
   2470 	/* Read and write will block until the asynchronous callback completes
   2471 	 * (e.g. until SSL_AuthCertificateComplete is called), so don't tell
   2472 	 * the caller to poll the socket unless there is pending write data.
   2473 	 */
   2474 	if (ss->lastWriteBlocked && ss->pendingBuf.len != 0) {
   2475 	    /* Ignore any newly-received data on the socket, but do wait for
   2476 	     * the socket to become writable again. Here, it is OK for an error
   2477 	     * to be detected, because our logic for sending pending write data
   2478 	     * will allow us to report the error to the caller without the risk
   2479 	     * of the application spinning.
   2480 	     */
   2481 	    new_flags &= (PR_POLL_WRITE | PR_POLL_EXCEPT);
   2482 	} else {
   2483 	    /* Unfortunately, clearing new_flags will make it impossible for
   2484 	     * the application to detect errors that it would otherwise be
   2485 	     * able to detect with PR_POLL_EXCEPT, until the asynchronous
   2486 	     * callback completes. However, we must clear all the flags to
   2487 	     * prevent the application from spinning (alternating between
   2488 	     * calling PR_Poll that would return PR_POLL_EXCEPT, and send/recv
   2489 	     * which won't actually report the I/O error while we are waiting
   2490 	     * for the asynchronous callback to complete).
   2491 	     */
   2492 	    new_flags = 0;
   2493 	}
   2494     }
   2495 
   2496     if (new_flags && (fd->lower->methods->poll != NULL)) {
   2497 	PRInt16    lower_out_flags = 0;
   2498 	PRInt16    lower_new_flags;
   2499         lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags,
   2500 					           &lower_out_flags);
   2501 	if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) {
   2502 	    PRInt16 out_flags = lower_out_flags & ~PR_POLL_RW;
   2503 	    if (lower_out_flags & PR_POLL_READ)
   2504 		out_flags |= PR_POLL_WRITE;
   2505 	    if (lower_out_flags & PR_POLL_WRITE)
   2506 		out_flags |= PR_POLL_READ;
   2507 	    *p_out_flags = out_flags;
   2508 	    new_flags = how_flags;
   2509 	} else {
   2510 	    *p_out_flags = lower_out_flags;
   2511 	    new_flags    = lower_new_flags;
   2512 	}
   2513     }
   2514 
   2515     return new_flags;
   2516 }
   2517 
   2518 static PRInt32 PR_CALLBACK
   2519 ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd,
   2520 		 const void *headers, PRInt32 hlen,
   2521 		 PRTransmitFileFlags flags, PRIntervalTime timeout)
   2522 {
   2523     PRSendFileData sfd;
   2524 
   2525     sfd.fd = fd;
   2526     sfd.file_offset = 0;
   2527     sfd.file_nbytes = 0;
   2528     sfd.header = headers;
   2529     sfd.hlen = hlen;
   2530     sfd.trailer = NULL;
   2531     sfd.tlen = 0;
   2532 
   2533     return sd->methods->sendfile(sd, &sfd, flags, timeout);
   2534 }
   2535 
   2536 
   2537 PRBool
   2538 ssl_FdIsBlocking(PRFileDesc *fd)
   2539 {
   2540     PRSocketOptionData opt;
   2541     PRStatus           status;
   2542 
   2543     opt.option             = PR_SockOpt_Nonblocking;
   2544     opt.value.non_blocking = PR_FALSE;
   2545     status = PR_GetSocketOption(fd, &opt);
   2546     if (status != PR_SUCCESS)
   2547 	return PR_FALSE;
   2548     return (PRBool)!opt.value.non_blocking;
   2549 }
   2550 
   2551 PRBool
   2552 ssl_SocketIsBlocking(sslSocket *ss)
   2553 {
   2554     return ssl_FdIsBlocking(ss->fd);
   2555 }
   2556 
   2557 PRInt32  sslFirstBufSize = 8 * 1024;
   2558 PRInt32  sslCopyLimit    = 1024;
   2559 
   2560 static PRInt32 PR_CALLBACK
   2561 ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors,
   2562            PRIntervalTime timeout)
   2563 {
   2564     PRInt32            bufLen;
   2565     PRInt32            left;
   2566     PRInt32            rv;
   2567     PRInt32            sent      =  0;
   2568     const PRInt32      first_len = sslFirstBufSize;
   2569     const PRInt32      limit     = sslCopyLimit;
   2570     PRBool             blocking;
   2571     PRIOVec            myIov	 = { 0, 0 };
   2572     char               buf[MAX_FRAGMENT_LENGTH];
   2573 
   2574     if (vectors > PR_MAX_IOVECTOR_SIZE) {
   2575     	PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
   2576 	return -1;
   2577     }
   2578     blocking = ssl_FdIsBlocking(fd);
   2579 
   2580 #define K16 sizeof(buf)
   2581 #define KILL_VECTORS while (vectors && !iov->iov_len) { ++iov; --vectors; }
   2582 #define GET_VECTOR   do { myIov = *iov++; --vectors; KILL_VECTORS } while (0)
   2583 #define HANDLE_ERR(rv, len) \
   2584     if (rv != len) { \
   2585 	if (rv < 0) { \
   2586 	    if (!blocking \
   2587 		&& (PR_GetError() == PR_WOULD_BLOCK_ERROR) \
   2588 		&& (sent > 0)) { \
   2589 		return sent; \
   2590 	    } else { \
   2591 		return -1; \
   2592 	    } \
   2593 	} \
   2594 	/* Only a nonblocking socket can have partial sends */ \
   2595 	PR_ASSERT(!blocking); \
   2596 	return sent + rv; \
   2597     }
   2598 #define SEND(bfr, len) \
   2599     do { \
   2600 	rv = ssl_Send(fd, bfr, len, 0, timeout); \
   2601 	HANDLE_ERR(rv, len) \
   2602 	sent += len; \
   2603     } while (0)
   2604 
   2605     /* Make sure the first write is at least 8 KB, if possible. */
   2606     KILL_VECTORS
   2607     if (!vectors)
   2608 	return ssl_Send(fd, 0, 0, 0, timeout);
   2609     GET_VECTOR;
   2610     if (!vectors) {
   2611 	return ssl_Send(fd, myIov.iov_base, myIov.iov_len, 0, timeout);
   2612     }
   2613     if (myIov.iov_len < first_len) {
   2614 	PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
   2615 	bufLen = myIov.iov_len;
   2616 	left = first_len - bufLen;
   2617 	while (vectors && left) {
   2618 	    int toCopy;
   2619 	    GET_VECTOR;
   2620 	    toCopy = PR_MIN(left, myIov.iov_len);
   2621 	    PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy);
   2622 	    bufLen         += toCopy;
   2623 	    left           -= toCopy;
   2624 	    myIov.iov_base += toCopy;
   2625 	    myIov.iov_len  -= toCopy;
   2626 	}
   2627 	SEND( buf, bufLen );
   2628     }
   2629 
   2630     while (vectors || myIov.iov_len) {
   2631 	PRInt32   addLen;
   2632 	if (!myIov.iov_len) {
   2633 	    GET_VECTOR;
   2634 	}
   2635 	while (myIov.iov_len >= K16) {
   2636 	    SEND(myIov.iov_base, K16);
   2637 	    myIov.iov_base += K16;
   2638 	    myIov.iov_len  -= K16;
   2639 	}
   2640 	if (!myIov.iov_len)
   2641 	    continue;
   2642 
   2643 	if (!vectors || myIov.iov_len > limit) {
   2644 	    addLen = 0;
   2645 	} else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) {
   2646 	    /* Addlen is already computed. */;
   2647 	} else if (vectors > 1 &&
   2648 	     iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) {
   2649 	     addLen = limit - myIov.iov_len;
   2650 	} else
   2651 	    addLen = 0;
   2652 
   2653 	if (!addLen) {
   2654 	    SEND( myIov.iov_base, myIov.iov_len );
   2655 	    myIov.iov_len = 0;
   2656 	    continue;
   2657 	}
   2658 	PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
   2659 	bufLen = myIov.iov_len;
   2660 	do {
   2661 	    GET_VECTOR;
   2662 	    PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen);
   2663 	    myIov.iov_base += addLen;
   2664 	    myIov.iov_len  -= addLen;
   2665 	    bufLen         += addLen;
   2666 
   2667 	    left = PR_MIN( limit, K16 - bufLen);
   2668 	    if (!vectors 		/* no more left */
   2669 	    ||  myIov.iov_len > 0	/* we didn't use that one all up */
   2670 	    ||  bufLen >= K16		/* it's full. */
   2671 	    ) {
   2672 		addLen = 0;
   2673 	    } else if ((addLen = iov->iov_len % K16) <= left) {
   2674 		/* Addlen is already computed. */;
   2675 	    } else if (vectors > 1 &&
   2676 		 iov[1].iov_len % K16 + addLen <= left + limit) {
   2677 		 addLen = left;
   2678 	    } else
   2679 		addLen = 0;
   2680 
   2681 	} while (addLen);
   2682 	SEND( buf, bufLen );
   2683     }
   2684     return sent;
   2685 }
   2686 
   2687 /*
   2688  * These functions aren't implemented.
   2689  */
   2690 
   2691 static PRInt32 PR_CALLBACK
   2692 ssl_Available(PRFileDesc *fd)
   2693 {
   2694     PORT_Assert(0);
   2695     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2696     return SECFailure;
   2697 }
   2698 
   2699 static PRInt64 PR_CALLBACK
   2700 ssl_Available64(PRFileDesc *fd)
   2701 {
   2702     PRInt64 res;
   2703 
   2704     PORT_Assert(0);
   2705     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2706     LL_I2L(res, -1L);
   2707     return res;
   2708 }
   2709 
   2710 static PRStatus PR_CALLBACK
   2711 ssl_FSync(PRFileDesc *fd)
   2712 {
   2713     PORT_Assert(0);
   2714     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2715     return PR_FAILURE;
   2716 }
   2717 
   2718 static PRInt32 PR_CALLBACK
   2719 ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) {
   2720     PORT_Assert(0);
   2721     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2722     return SECFailure;
   2723 }
   2724 
   2725 static PRInt64 PR_CALLBACK
   2726 ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) {
   2727     PRInt64 res;
   2728 
   2729     PORT_Assert(0);
   2730     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2731     LL_I2L(res, -1L);
   2732     return res;
   2733 }
   2734 
   2735 static PRStatus PR_CALLBACK
   2736 ssl_FileInfo(PRFileDesc *fd, PRFileInfo *info)
   2737 {
   2738     PORT_Assert(0);
   2739     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2740     return PR_FAILURE;
   2741 }
   2742 
   2743 static PRStatus PR_CALLBACK
   2744 ssl_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
   2745 {
   2746     PORT_Assert(0);
   2747     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2748     return PR_FAILURE;
   2749 }
   2750 
   2751 static PRInt32 PR_CALLBACK
   2752 ssl_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
   2753 	     PRNetAddr *addr, PRIntervalTime timeout)
   2754 {
   2755     PORT_Assert(0);
   2756     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2757     return SECFailure;
   2758 }
   2759 
   2760 static PRInt32 PR_CALLBACK
   2761 ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
   2762 	   const PRNetAddr *addr, PRIntervalTime timeout)
   2763 {
   2764     PORT_Assert(0);
   2765     PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
   2766     return SECFailure;
   2767 }
   2768 
   2769 static const PRIOMethods ssl_methods = {
   2770     PR_DESC_LAYERED,
   2771     ssl_Close,           	/* close        */
   2772     ssl_Read,            	/* read         */
   2773     ssl_Write,           	/* write        */
   2774     ssl_Available,       	/* available    */
   2775     ssl_Available64,     	/* available64  */
   2776     ssl_FSync,           	/* fsync        */
   2777     ssl_Seek,            	/* seek         */
   2778     ssl_Seek64,          	/* seek64       */
   2779     ssl_FileInfo,        	/* fileInfo     */
   2780     ssl_FileInfo64,      	/* fileInfo64   */
   2781     ssl_WriteV,          	/* writev       */
   2782     ssl_Connect,         	/* connect      */
   2783     ssl_Accept,          	/* accept       */
   2784     ssl_Bind,            	/* bind         */
   2785     ssl_Listen,          	/* listen       */
   2786     ssl_Shutdown,        	/* shutdown     */
   2787     ssl_Recv,            	/* recv         */
   2788     ssl_Send,            	/* send         */
   2789     ssl_RecvFrom,        	/* recvfrom     */
   2790     ssl_SendTo,          	/* sendto       */
   2791     ssl_Poll,            	/* poll         */
   2792     PR_EmulateAcceptRead,       /* acceptread   */
   2793     ssl_TransmitFile,           /* transmitfile */
   2794     ssl_GetSockName,     	/* getsockname  */
   2795     ssl_GetPeerName,     	/* getpeername  */
   2796     NULL,                	/* getsockopt   OBSOLETE */
   2797     NULL,                	/* setsockopt   OBSOLETE */
   2798     NULL,                	/* getsocketoption   */
   2799     NULL,                	/* setsocketoption   */
   2800     PR_EmulateSendFile, 	/* Send a (partial) file with header/trailer*/
   2801     NULL,                	/* reserved for future use */
   2802     NULL,                	/* reserved for future use */
   2803     NULL,                	/* reserved for future use */
   2804     NULL,                	/* reserved for future use */
   2805     NULL                 	/* reserved for future use */
   2806 };
   2807 
   2808 
   2809 static PRIOMethods combined_methods;
   2810 
   2811 static void
   2812 ssl_SetupIOMethods(void)
   2813 {
   2814           PRIOMethods *new_methods  = &combined_methods;
   2815     const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods();
   2816     const PRIOMethods *my_methods   = &ssl_methods;
   2817 
   2818     *new_methods = *nspr_methods;
   2819 
   2820     new_methods->file_type         = my_methods->file_type;
   2821     new_methods->close             = my_methods->close;
   2822     new_methods->read              = my_methods->read;
   2823     new_methods->write             = my_methods->write;
   2824     new_methods->available         = my_methods->available;
   2825     new_methods->available64       = my_methods->available64;
   2826     new_methods->fsync             = my_methods->fsync;
   2827     new_methods->seek              = my_methods->seek;
   2828     new_methods->seek64            = my_methods->seek64;
   2829     new_methods->fileInfo          = my_methods->fileInfo;
   2830     new_methods->fileInfo64        = my_methods->fileInfo64;
   2831     new_methods->writev            = my_methods->writev;
   2832     new_methods->connect           = my_methods->connect;
   2833     new_methods->accept            = my_methods->accept;
   2834     new_methods->bind              = my_methods->bind;
   2835     new_methods->listen            = my_methods->listen;
   2836     new_methods->shutdown          = my_methods->shutdown;
   2837     new_methods->recv              = my_methods->recv;
   2838     new_methods->send              = my_methods->send;
   2839     new_methods->recvfrom          = my_methods->recvfrom;
   2840     new_methods->sendto            = my_methods->sendto;
   2841     new_methods->poll              = my_methods->poll;
   2842     new_methods->acceptread        = my_methods->acceptread;
   2843     new_methods->transmitfile      = my_methods->transmitfile;
   2844     new_methods->getsockname       = my_methods->getsockname;
   2845     new_methods->getpeername       = my_methods->getpeername;
   2846 /*  new_methods->getsocketoption   = my_methods->getsocketoption;	*/
   2847 /*  new_methods->setsocketoption   = my_methods->setsocketoption;	*/
   2848     new_methods->sendfile          = my_methods->sendfile;
   2849 
   2850 }
   2851 
   2852 static PRCallOnceType initIoLayerOnce;
   2853 
   2854 static PRStatus
   2855 ssl_InitIOLayer(void)
   2856 {
   2857     ssl_layer_id = PR_GetUniqueIdentity("SSL");
   2858     ssl_SetupIOMethods();
   2859     ssl_inited = PR_TRUE;
   2860     return PR_SUCCESS;
   2861 }
   2862 
   2863 static PRStatus
   2864 ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id)
   2865 {
   2866     PRFileDesc *layer	= NULL;
   2867     PRStatus    status;
   2868 
   2869     if (!ssl_inited) {
   2870 	status = PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer);
   2871 	if (status != PR_SUCCESS)
   2872 	    goto loser;
   2873     }
   2874 
   2875     if (ns == NULL)
   2876 	goto loser;
   2877 
   2878     layer = PR_CreateIOLayerStub(ssl_layer_id, &combined_methods);
   2879     if (layer == NULL)
   2880 	goto loser;
   2881     layer->secret = (PRFilePrivate *)ns;
   2882 
   2883     /* Here, "stack" points to the PRFileDesc on the top of the stack.
   2884     ** "layer" points to a new FD that is to be inserted into the stack.
   2885     ** If layer is being pushed onto the top of the stack, then
   2886     ** PR_PushIOLayer switches the contents of stack and layer, and then
   2887     ** puts stack on top of layer, so that after it is done, the top of
   2888     ** stack is the same "stack" as it was before, and layer is now the
   2889     ** FD for the former top of stack.
   2890     ** After this call, stack always points to the top PRFD on the stack.
   2891     ** If this function fails, the contents of stack and layer are as
   2892     ** they were before the call.
   2893     */
   2894     status = PR_PushIOLayer(stack, id, layer);
   2895     if (status != PR_SUCCESS)
   2896 	goto loser;
   2897 
   2898     ns->fd = (id == PR_TOP_IO_LAYER) ? stack : layer;
   2899     return PR_SUCCESS;
   2900 
   2901 loser:
   2902     if (layer) {
   2903 	layer->dtor(layer); /* free layer */
   2904     }
   2905     return PR_FAILURE;
   2906 }
   2907 
   2908 /* if this fails, caller must destroy socket. */
   2909 static SECStatus
   2910 ssl_MakeLocks(sslSocket *ss)
   2911 {
   2912     ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL);
   2913     if (!ss->firstHandshakeLock)
   2914 	goto loser;
   2915     ss->ssl3HandshakeLock  = PZ_NewMonitor(nssILockSSL);
   2916     if (!ss->ssl3HandshakeLock)
   2917 	goto loser;
   2918     ss->specLock           = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL);
   2919     if (!ss->specLock)
   2920 	goto loser;
   2921     ss->recvBufLock        = PZ_NewMonitor(nssILockSSL);
   2922     if (!ss->recvBufLock)
   2923 	goto loser;
   2924     ss->xmitBufLock        = PZ_NewMonitor(nssILockSSL);
   2925     if (!ss->xmitBufLock)
   2926 	goto loser;
   2927     ss->writerThread       = NULL;
   2928     if (ssl_lock_readers) {
   2929 	ss->recvLock       = PZ_NewLock(nssILockSSL);
   2930 	if (!ss->recvLock)
   2931 	    goto loser;
   2932 	ss->sendLock       = PZ_NewLock(nssILockSSL);
   2933 	if (!ss->sendLock)
   2934 	    goto loser;
   2935     }
   2936     return SECSuccess;
   2937 loser:
   2938     ssl_DestroyLocks(ss);
   2939     return SECFailure;
   2940 }
   2941 
   2942 #if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS)
   2943 #define NSS_HAVE_GETENV 1
   2944 #endif
   2945 
   2946 #define LOWER(x) (x | 0x20)  /* cheap ToLower function ignores LOCALE */
   2947 
   2948 static void
   2949 ssl_SetDefaultsFromEnvironment(void)
   2950 {
   2951 #if defined( NSS_HAVE_GETENV )
   2952     static int firsttime = 1;
   2953 
   2954     if (firsttime) {
   2955 	char * ev;
   2956 	firsttime = 0;
   2957 #ifdef DEBUG
   2958 	ev = getenv("SSLDEBUGFILE");
   2959 	if (ev && ev[0]) {
   2960 	    ssl_trace_iob = fopen(ev, "w");
   2961 	}
   2962 	if (!ssl_trace_iob) {
   2963 	    ssl_trace_iob = stderr;
   2964 	}
   2965 #ifdef TRACE
   2966 	ev = getenv("SSLTRACE");
   2967 	if (ev && ev[0]) {
   2968 	    ssl_trace = atoi(ev);
   2969 	    SSL_TRACE(("SSL: tracing set to %d", ssl_trace));
   2970 	}
   2971 #endif /* TRACE */
   2972 	ev = getenv("SSLDEBUG");
   2973 	if (ev && ev[0]) {
   2974 	    ssl_debug = atoi(ev);
   2975 	    SSL_TRACE(("SSL: debugging set to %d", ssl_debug));
   2976 	}
   2977 #endif /* DEBUG */
   2978 	ev = getenv("SSLKEYLOGFILE");
   2979 	if (ev && ev[0]) {
   2980 	    ssl_keylog_iob = fopen(ev, "a");
   2981 	    if (!ssl_keylog_iob) {
   2982 		SSL_TRACE(("SSL: failed to open key log file"));
   2983 	    } else {
   2984 		if (ftell(ssl_keylog_iob) == 0) {
   2985 		    fputs("# SSL/TLS secrets log file, generated by NSS\n",
   2986 			  ssl_keylog_iob);
   2987 		}
   2988 		SSL_TRACE(("SSL: logging SSL/TLS secrets to %s", ev));
   2989 	    }
   2990 	}
   2991 #ifndef NO_PKCS11_BYPASS
   2992 	ev = getenv("SSLBYPASS");
   2993 	if (ev && ev[0]) {
   2994 	    ssl_defaults.bypassPKCS11 = (ev[0] == '1');
   2995 	    SSL_TRACE(("SSL: bypass default set to %d", \
   2996 		      ssl_defaults.bypassPKCS11));
   2997 	}
   2998 #endif /* NO_PKCS11_BYPASS */
   2999 	ev = getenv("SSLFORCELOCKS");
   3000 	if (ev && ev[0] == '1') {
   3001 	    ssl_force_locks = PR_TRUE;
   3002 	    ssl_defaults.noLocks = 0;
   3003 	    strcpy(lockStatus + LOCKSTATUS_OFFSET, "FORCED.  ");
   3004 	    SSL_TRACE(("SSL: force_locks set to %d", ssl_force_locks));
   3005 	}
   3006 	ev = getenv("NSS_SSL_ENABLE_RENEGOTIATION");
   3007 	if (ev) {
   3008 	    if (ev[0] == '1' || LOWER(ev[0]) == 'u')
   3009 	    	ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_UNRESTRICTED;
   3010 	    else if (ev[0] == '0' || LOWER(ev[0]) == 'n')
   3011 	    	ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
   3012 	    else if (ev[0] == '2' || LOWER(ev[0]) == 'r')
   3013 		ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN;
   3014 	    else if (ev[0] == '3' || LOWER(ev[0]) == 't')
   3015 	    	ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_TRANSITIONAL;
   3016 	    SSL_TRACE(("SSL: enableRenegotiation set to %d",
   3017 	               ssl_defaults.enableRenegotiation));
   3018 	}
   3019 	ev = getenv("NSS_SSL_REQUIRE_SAFE_NEGOTIATION");
   3020 	if (ev && ev[0] == '1') {
   3021 	    ssl_defaults.requireSafeNegotiation = PR_TRUE;
   3022 	    SSL_TRACE(("SSL: requireSafeNegotiation set to %d",
   3023 	                PR_TRUE));
   3024 	}
   3025 	ev = getenv("NSS_SSL_CBC_RANDOM_IV");
   3026 	if (ev && ev[0] == '0') {
   3027 	    ssl_defaults.cbcRandomIV = PR_FALSE;
   3028 	    SSL_TRACE(("SSL: cbcRandomIV set to 0"));
   3029 	}
   3030     }
   3031 #endif /* NSS_HAVE_GETENV */
   3032 }
   3033 
   3034 /*
   3035 ** Create a newsocket structure for a file descriptor.
   3036 */
   3037 static sslSocket *
   3038 ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant)
   3039 {
   3040     sslSocket *ss;
   3041 
   3042     ssl_SetDefaultsFromEnvironment();
   3043 
   3044     if (ssl_force_locks)
   3045 	makeLocks = PR_TRUE;
   3046 
   3047     /* Make a new socket and get it ready */
   3048     ss = (sslSocket*) PORT_ZAlloc(sizeof(sslSocket));
   3049     if (ss) {
   3050         /* This should be of type SSLKEAType, but CC on IRIX
   3051 	 * complains during the for loop.
   3052 	 */
   3053 	int i;
   3054 	SECStatus status;
   3055 
   3056 	ss->opt                = ssl_defaults;
   3057 	ss->opt.useSocks       = PR_FALSE;
   3058 	ss->opt.noLocks        = !makeLocks;
   3059 	ss->vrange             = *VERSIONS_DEFAULTS(protocolVariant);
   3060 	ss->protocolVariant    = protocolVariant;
   3061 
   3062 	ss->peerID             = NULL;
   3063 	ss->rTimeout	       = PR_INTERVAL_NO_TIMEOUT;
   3064 	ss->wTimeout	       = PR_INTERVAL_NO_TIMEOUT;
   3065 	ss->cTimeout	       = PR_INTERVAL_NO_TIMEOUT;
   3066 	ss->cipherSpecs        = NULL;
   3067         ss->sizeCipherSpecs    = 0;  /* produced lazily */
   3068         ss->preferredCipher    = NULL;
   3069         ss->url                = NULL;
   3070 
   3071 	for (i=kt_null; i < kt_kea_size; i++) {
   3072 	    sslServerCerts * sc = ss->serverCerts + i;
   3073 	    sc->serverCert      = NULL;
   3074 	    sc->serverCertChain = NULL;
   3075 	    sc->serverKeyPair   = NULL;
   3076 	    sc->serverKeyBits   = 0;
   3077 	    ss->certStatusArray[i] = NULL;
   3078 	}
   3079 	ss->requestedCertTypes = NULL;
   3080 	ss->stepDownKeyPair    = NULL;
   3081 	ss->dbHandle           = CERT_GetDefaultCertDB();
   3082 
   3083 	/* Provide default implementation of hooks */
   3084 	ss->authCertificate    = SSL_AuthCertificate;
   3085 	ss->authCertificateArg = (void *)ss->dbHandle;
   3086         ss->sniSocketConfig    = NULL;
   3087         ss->sniSocketConfigArg = NULL;
   3088 	ss->getClientAuthData  = NULL;
   3089 #ifdef NSS_PLATFORM_CLIENT_AUTH
   3090 	ss->getPlatformClientAuthData = NULL;
   3091 	ss->getPlatformClientAuthDataArg = NULL;
   3092 #endif   /* NSS_PLATFORM_CLIENT_AUTH */
   3093 	ss->handleBadCert      = NULL;
   3094 	ss->badCertArg         = NULL;
   3095 	ss->pkcs11PinArg       = NULL;
   3096 	ss->ephemeralECDHKeyPair = NULL;
   3097 	ss->getChannelID       = NULL;
   3098 	ss->getChannelIDArg    = NULL;
   3099 
   3100 	ssl_ChooseOps(ss);
   3101 	ssl2_InitSocketPolicy(ss);
   3102 	ssl3_InitSocketPolicy(ss);
   3103 	PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
   3104 
   3105 	if (makeLocks) {
   3106 	    status = ssl_MakeLocks(ss);
   3107 	    if (status != SECSuccess)
   3108 		goto loser;
   3109 	}
   3110 	status = ssl_CreateSecurityInfo(ss);
   3111 	if (status != SECSuccess)
   3112 	    goto loser;
   3113 	status = ssl_InitGather(&ss->gs);
   3114 	if (status != SECSuccess) {
   3115 loser:
   3116 	    ssl_DestroySocketContents(ss);
   3117 	    ssl_DestroyLocks(ss);
   3118 	    PORT_Free(ss);
   3119 	    ss = NULL;
   3120 	}
   3121     }
   3122     return ss;
   3123 }
   3124 
   3125