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