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