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 * ***** BEGIN LICENSE BLOCK *****
7 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
8 *
9 * The contents of this file are subject to the Mozilla Public License Version
10 * 1.1 (the "License"); you may not use this file except in compliance with
11 * the License. You may obtain a copy of the License at
12 * http://www.mozilla.org/MPL/
13 *
14 * Software distributed under the License is distributed on an "AS IS" basis,
15 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
16 * for the specific language governing rights and limitations under the
17 * License.
18 *
19 * The Original Code is the Netscape security libraries.
20 *
21 * The Initial Developer of the Original Code is
22 * Netscape Communications Corporation.
23 * Portions created by the Initial Developer are Copyright (C) 1994-2000
24 * the Initial Developer. All Rights Reserved.
25 *
26 * Contributor(s):
27 *   Dr Stephen Henson <stephen.henson@gemplus.com>
28 *   Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
29 *
30 * Alternatively, the contents of this file may be used under the terms of
31 * either the GNU General Public License Version 2 or later (the "GPL"), or
32 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
33 * in which case the provisions of the GPL or the LGPL are applicable instead
34 * of those above. If you wish to allow use of your version of this file only
35 * under the terms of either the GPL or the LGPL, and not to allow others to
36 * use your version of this file under the terms of the MPL, indicate your
37 * decision by deleting the provisions above and replace them with the notice
38 * and other provisions required by the GPL or the LGPL. If you do not delete
39 * the provisions above, a recipient may use your version of this file under
40 * the terms of any one of the MPL, the GPL or the LGPL.
41 *
42 * ***** END LICENSE BLOCK ***** */
43/* $Id: sslsock.c,v 1.60 2009/11/25 05:24:25 wtc%google.com Exp $ */
44#include "seccomon.h"
45#include "cert.h"
46#include "keyhi.h"
47#include "ssl.h"
48#include "sslimpl.h"
49#include "sslproto.h"
50#include "nspr.h"
51#include "private/pprio.h"
52#include "blapi.h"
53#include "nss.h"
54
55#define SET_ERROR_CODE   /* reminder */
56
57struct cipherPolicyStr {
58	int		cipher;
59	unsigned char 	export;	/* policy value for export policy */
60	unsigned char 	france;	/* policy value for france policy */
61};
62
63typedef struct cipherPolicyStr cipherPolicy;
64
65/* This table contains two preconfigured policies: Export and France.
66** It is used only by the functions SSL_SetDomesticPolicy,
67** SSL_SetExportPolicy, and SSL_SetFrancyPolicy.
68** Order of entries is not important.
69*/
70static cipherPolicy ssl_ciphers[] = {	   /*   Export           France   */
71 {  SSL_EN_RC4_128_WITH_MD5,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
72 {  SSL_EN_RC4_128_EXPORT40_WITH_MD5,	    SSL_ALLOWED,     SSL_ALLOWED },
73 {  SSL_EN_RC2_128_CBC_WITH_MD5,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
74 {  SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5,   SSL_ALLOWED,     SSL_ALLOWED },
75 {  SSL_EN_DES_64_CBC_WITH_MD5,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
76 {  SSL_EN_DES_192_EDE3_CBC_WITH_MD5,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
77 {  SSL_RSA_WITH_RC4_128_MD5,		    SSL_RESTRICTED,  SSL_NOT_ALLOWED },
78 {  SSL_RSA_WITH_RC4_128_SHA,		    SSL_RESTRICTED,  SSL_NOT_ALLOWED },
79 {  SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
80 {  SSL_RSA_WITH_3DES_EDE_CBC_SHA,	    SSL_RESTRICTED,  SSL_NOT_ALLOWED },
81 {  SSL_RSA_FIPS_WITH_DES_CBC_SHA,	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
82 {  SSL_RSA_WITH_DES_CBC_SHA,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
83 {  SSL_RSA_EXPORT_WITH_RC4_40_MD5,	    SSL_ALLOWED,     SSL_ALLOWED },
84 {  SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,	    SSL_ALLOWED,     SSL_ALLOWED },
85 {  SSL_DHE_RSA_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
86 {  SSL_DHE_DSS_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
87 {  SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
88 {  SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
89 {  TLS_DHE_DSS_WITH_RC4_128_SHA,           SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
90 {  SSL_RSA_WITH_NULL_SHA,		    SSL_ALLOWED,     SSL_ALLOWED },
91 {  SSL_RSA_WITH_NULL_MD5,		    SSL_ALLOWED,     SSL_ALLOWED },
92 {  TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
93 {  TLS_DHE_RSA_WITH_AES_128_CBC_SHA,       SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
94 {  TLS_RSA_WITH_AES_128_CBC_SHA,     	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
95 {  TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
96 {  TLS_DHE_RSA_WITH_AES_256_CBC_SHA,       SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
97 {  TLS_RSA_WITH_AES_256_CBC_SHA,     	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
98 {  TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
99 {  TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
100 {  TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
101 {  TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
102 {  TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
103 {  TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, 	    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
104 {  TLS_RSA_WITH_SEED_CBC_SHA,		    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
105 {  TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,    SSL_ALLOWED,     SSL_NOT_ALLOWED },
106 {  TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,     SSL_ALLOWED,     SSL_NOT_ALLOWED },
107#ifdef NSS_ENABLE_ECC
108 {  TLS_ECDH_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED,     SSL_ALLOWED },
109 {  TLS_ECDH_ECDSA_WITH_RC4_128_SHA,        SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
110 {  TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
111 {  TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
112 {  TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
113 {  TLS_ECDHE_ECDSA_WITH_NULL_SHA,          SSL_ALLOWED,     SSL_ALLOWED },
114 {  TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,       SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
115 {  TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,  SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
116 {  TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,   SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
117 {  TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,   SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
118 {  TLS_ECDH_RSA_WITH_NULL_SHA,             SSL_ALLOWED,     SSL_ALLOWED },
119 {  TLS_ECDH_RSA_WITH_RC4_128_SHA,          SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
120 {  TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
121 {  TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
122 {  TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,      SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
123 {  TLS_ECDHE_RSA_WITH_NULL_SHA,            SSL_ALLOWED,     SSL_ALLOWED },
124 {  TLS_ECDHE_RSA_WITH_RC4_128_SHA,         SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
125 {  TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
126 {  TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,     SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
127 {  TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,     SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
128#endif /* NSS_ENABLE_ECC */
129 {  0,					    SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }
130};
131
132static const sslSocketOps ssl_default_ops = {	/* No SSL. */
133    ssl_DefConnect,
134    NULL,
135    ssl_DefBind,
136    ssl_DefListen,
137    ssl_DefShutdown,
138    ssl_DefClose,
139    ssl_DefRecv,
140    ssl_DefSend,
141    ssl_DefRead,
142    ssl_DefWrite,
143    ssl_DefGetpeername,
144    ssl_DefGetsockname
145};
146
147static const sslSocketOps ssl_secure_ops = {	/* SSL. */
148    ssl_SecureConnect,
149    NULL,
150    ssl_DefBind,
151    ssl_DefListen,
152    ssl_SecureShutdown,
153    ssl_SecureClose,
154    ssl_SecureRecv,
155    ssl_SecureSend,
156    ssl_SecureRead,
157    ssl_SecureWrite,
158    ssl_DefGetpeername,
159    ssl_DefGetsockname
160};
161
162/*
163** default settings for socket enables
164*/
165static sslOptions ssl_defaults = {
166    { siBuffer, NULL, 0 },	/* nextProtoNego */
167    PR_TRUE, 	/* useSecurity        */
168    PR_FALSE,	/* useSocks           */
169    PR_FALSE,	/* requestCertificate */
170    2,	        /* requireCertificate */
171    PR_FALSE,	/* handshakeAsClient  */
172    PR_FALSE,	/* handshakeAsServer  */
173    PR_TRUE,	/* enableSSL2         */
174    PR_TRUE,	/* enableSSL3         */
175    PR_TRUE, 	/* enableTLS          */ /* now defaults to on in NSS 3.0 */
176    PR_FALSE,	/* noCache            */
177    PR_FALSE,	/* fdx                */
178    PR_TRUE,	/* v2CompatibleHello  */
179    PR_TRUE,	/* detectRollBack     */
180    PR_FALSE,   /* noStepDown         */
181    PR_FALSE,   /* bypassPKCS11       */
182    PR_FALSE,   /* noLocks            */
183    PR_FALSE,   /* enableSessionTickets */
184    PR_FALSE,   /* enableDeflate      */
185    0,          /* enableRenegotiation (default: never) */
186    PR_FALSE,   /* requireSafeNegotiation */
187};
188
189sslSessionIDLookupFunc  ssl_sid_lookup;
190sslSessionIDCacheFunc   ssl_sid_cache;
191sslSessionIDUncacheFunc ssl_sid_uncache;
192
193static PRBool ssl_inited = PR_FALSE;
194static PRDescIdentity ssl_layer_id;
195
196PRBool                  locksEverDisabled; 	/* implicitly PR_FALSE */
197PRBool			ssl_force_locks;  	/* implicitly PR_FALSE */
198int                     ssl_lock_readers	= 1;	/* default true. */
199char                    ssl_debug;
200char                    ssl_trace;
201FILE *                  ssl_trace_iob;
202char lockStatus[] = "Locks are ENABLED.  ";
203#define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */
204
205/* forward declarations. */
206static sslSocket *ssl_NewSocket(PRBool makeLocks);
207static SECStatus  ssl_MakeLocks(sslSocket *ss);
208static PRStatus   ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack,
209                                  PRDescIdentity id);
210
211/************************************************************************/
212
213/*
214** Lookup a socket structure from a file descriptor.
215** Only functions called through the PRIOMethods table should use this.
216** Other app-callable functions should use ssl_FindSocket.
217*/
218static sslSocket *
219ssl_GetPrivate(PRFileDesc *fd)
220{
221    sslSocket *ss;
222
223    PORT_Assert(fd != NULL);
224    PORT_Assert(fd->methods->file_type == PR_DESC_LAYERED);
225    PORT_Assert(fd->identity == ssl_layer_id);
226
227    if (fd->methods->file_type != PR_DESC_LAYERED ||
228        fd->identity != ssl_layer_id) {
229	PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
230	return NULL;
231    }
232
233    ss = (sslSocket *)fd->secret;
234    ss->fd = fd;
235    return ss;
236}
237
238/* This function tries to find the SSL layer in the stack.
239 * It searches for the first SSL layer at or below the argument fd,
240 * and failing that, it searches for the nearest SSL layer above the
241 * argument fd.  It returns the private sslSocket from the found layer.
242 */
243sslSocket *
244ssl_FindSocket(PRFileDesc *fd)
245{
246    PRFileDesc *layer;
247    sslSocket *ss;
248
249    PORT_Assert(fd != NULL);
250    PORT_Assert(ssl_layer_id != 0);
251
252    layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
253    if (layer == NULL) {
254	PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
255	return NULL;
256    }
257
258    ss = (sslSocket *)layer->secret;
259    ss->fd = layer;
260    return ss;
261}
262
263sslSocket *
264ssl_DupSocket(sslSocket *os)
265{
266    sslSocket *ss;
267    SECStatus rv;
268
269    ss = ssl_NewSocket((PRBool)(!os->opt.noLocks));
270    if (ss) {
271	ss->opt                = os->opt;
272	ss->opt.useSocks       = PR_FALSE;
273
274	ss->peerID             = !os->peerID ? NULL : PORT_Strdup(os->peerID);
275	ss->url                = !os->url    ? NULL : PORT_Strdup(os->url);
276
277	ss->ops      = os->ops;
278	ss->rTimeout = os->rTimeout;
279	ss->wTimeout = os->wTimeout;
280	ss->cTimeout = os->cTimeout;
281	ss->dbHandle = os->dbHandle;
282
283	/* copy ssl2&3 policy & prefs, even if it's not selected (yet) */
284	ss->allowedByPolicy	= os->allowedByPolicy;
285	ss->maybeAllowedByPolicy= os->maybeAllowedByPolicy;
286	ss->chosenPreference 	= os->chosenPreference;
287	PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites);
288
289	if (os->cipherSpecs) {
290	    ss->cipherSpecs  = (unsigned char*)PORT_Alloc(os->sizeCipherSpecs);
291	    if (ss->cipherSpecs)
292	    	PORT_Memcpy(ss->cipherSpecs, os->cipherSpecs,
293		            os->sizeCipherSpecs);
294	    ss->sizeCipherSpecs    = os->sizeCipherSpecs;
295	    ss->preferredCipher    = os->preferredCipher;
296	} else {
297	    ss->cipherSpecs        = NULL;  /* produced lazily */
298	    ss->sizeCipherSpecs    = 0;
299	    ss->preferredCipher    = NULL;
300	}
301	if (ss->opt.useSecurity) {
302	    /* This int should be SSLKEAType, but CC on Irix complains,
303	     * during the for loop.
304	     */
305	    int i;
306	    sslServerCerts * oc = os->serverCerts;
307	    sslServerCerts * sc = ss->serverCerts;
308
309	    for (i=kt_null; i < kt_kea_size; i++, oc++, sc++) {
310		if (oc->serverCert && oc->serverCertChain) {
311		    sc->serverCert      = CERT_DupCertificate(oc->serverCert);
312		    sc->serverCertChain = CERT_DupCertList(oc->serverCertChain);
313		    if (!sc->serverCertChain)
314		    	goto loser;
315		} else {
316		    sc->serverCert      = NULL;
317		    sc->serverCertChain = NULL;
318		}
319		sc->serverKeyPair = oc->serverKeyPair ?
320				ssl3_GetKeyPairRef(oc->serverKeyPair) : NULL;
321		if (oc->serverKeyPair && !sc->serverKeyPair)
322		    goto loser;
323	        sc->serverKeyBits = oc->serverKeyBits;
324	    }
325	    ss->stepDownKeyPair = !os->stepDownKeyPair ? NULL :
326		                  ssl3_GetKeyPairRef(os->stepDownKeyPair);
327	    ss->ephemeralECDHKeyPair = !os->ephemeralECDHKeyPair ? NULL :
328		                  ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair);
329/*
330 * XXX the preceeding CERT_ and SECKEY_ functions can fail and return NULL.
331 * XXX We should detect this, and not just march on with NULL pointers.
332 */
333	    ss->authCertificate       = os->authCertificate;
334	    ss->authCertificateArg    = os->authCertificateArg;
335	    ss->getClientAuthData     = os->getClientAuthData;
336	    ss->getClientAuthDataArg  = os->getClientAuthDataArg;
337	    ss->handleBadCert         = os->handleBadCert;
338	    ss->badCertArg            = os->badCertArg;
339	    ss->handshakeCallback     = os->handshakeCallback;
340	    ss->handshakeCallbackData = os->handshakeCallbackData;
341	    ss->pkcs11PinArg          = os->pkcs11PinArg;
342
343	    /* Create security data */
344	    rv = ssl_CopySecurityInfo(ss, os);
345	    if (rv != SECSuccess) {
346		goto loser;
347	    }
348	}
349    }
350    return ss;
351
352loser:
353    ssl_FreeSocket(ss);
354    return NULL;
355}
356
357static void
358ssl_DestroyLocks(sslSocket *ss)
359{
360    /* Destroy locks. */
361    if (ss->firstHandshakeLock) {
362    	PZ_DestroyMonitor(ss->firstHandshakeLock);
363	ss->firstHandshakeLock = NULL;
364    }
365    if (ss->ssl3HandshakeLock) {
366    	PZ_DestroyMonitor(ss->ssl3HandshakeLock);
367	ss->ssl3HandshakeLock = NULL;
368    }
369    if (ss->specLock) {
370    	NSSRWLock_Destroy(ss->specLock);
371	ss->specLock = NULL;
372    }
373
374    if (ss->recvLock) {
375    	PZ_DestroyLock(ss->recvLock);
376	ss->recvLock = NULL;
377    }
378    if (ss->sendLock) {
379    	PZ_DestroyLock(ss->sendLock);
380	ss->sendLock = NULL;
381    }
382    if (ss->xmitBufLock) {
383    	PZ_DestroyMonitor(ss->xmitBufLock);
384	ss->xmitBufLock = NULL;
385    }
386    if (ss->recvBufLock) {
387    	PZ_DestroyMonitor(ss->recvBufLock);
388	ss->recvBufLock = NULL;
389    }
390}
391
392/* Caller holds any relevant locks */
393static void
394ssl_DestroySocketContents(sslSocket *ss)
395{
396    /* "i" should be of type SSLKEAType, but CC on IRIX complains during
397     * the for loop.
398     */
399    int        i;
400
401    /* Free up socket */
402    ssl_DestroySecurityInfo(&ss->sec);
403
404    ssl3_DestroySSL3Info(ss);
405
406    PORT_Free(ss->saveBuf.buf);
407    PORT_Free(ss->pendingBuf.buf);
408    ssl_DestroyGather(&ss->gs);
409
410    if (ss->peerID != NULL)
411	PORT_Free(ss->peerID);
412    if (ss->url != NULL)
413	PORT_Free((void *)ss->url);	/* CONST */
414    if (ss->cipherSpecs) {
415	PORT_Free(ss->cipherSpecs);
416	ss->cipherSpecs     = NULL;
417	ss->sizeCipherSpecs = 0;
418    }
419
420    /* Clean up server configuration */
421    for (i=kt_null; i < kt_kea_size; i++) {
422	sslServerCerts * sc = ss->serverCerts + i;
423	if (sc->serverCert != NULL)
424	    CERT_DestroyCertificate(sc->serverCert);
425	if (sc->serverCertChain != NULL)
426	    CERT_DestroyCertificateList(sc->serverCertChain);
427	if (sc->serverKeyPair != NULL)
428	    ssl3_FreeKeyPair(sc->serverKeyPair);
429    }
430    if (ss->stepDownKeyPair) {
431	ssl3_FreeKeyPair(ss->stepDownKeyPair);
432	ss->stepDownKeyPair = NULL;
433    }
434    if (ss->ephemeralECDHKeyPair) {
435	ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
436	ss->ephemeralECDHKeyPair = NULL;
437    }
438    if (ss->opt.nextProtoNego.data) {
439	PORT_Free(ss->opt.nextProtoNego.data);
440	ss->opt.nextProtoNego.data = NULL;
441    }
442}
443
444/*
445 * free an sslSocket struct, and all the stuff that hangs off of it
446 */
447void
448ssl_FreeSocket(sslSocket *ss)
449{
450#ifdef DEBUG
451    sslSocket *fs;
452    sslSocket  lSock;
453#endif
454
455/* Get every lock you can imagine!
456** Caller already holds these:
457**  SSL_LOCK_READER(ss);
458**  SSL_LOCK_WRITER(ss);
459*/
460    ssl_Get1stHandshakeLock(ss);
461    ssl_GetRecvBufLock(ss);
462    ssl_GetSSL3HandshakeLock(ss);
463    ssl_GetXmitBufLock(ss);
464    ssl_GetSpecWriteLock(ss);
465
466#ifdef DEBUG
467    fs = &lSock;
468    *fs = *ss;				/* Copy the old socket structure, */
469    PORT_Memset(ss, 0x1f, sizeof *ss);  /* then blast the old struct ASAP. */
470#else
471#define fs ss
472#endif
473
474    ssl_DestroySocketContents(fs);
475
476    /* Release all the locks acquired above.  */
477    SSL_UNLOCK_READER(fs);
478    SSL_UNLOCK_WRITER(fs);
479    ssl_Release1stHandshakeLock(fs);
480    ssl_ReleaseRecvBufLock(fs);
481    ssl_ReleaseSSL3HandshakeLock(fs);
482    ssl_ReleaseXmitBufLock(fs);
483    ssl_ReleaseSpecWriteLock(fs);
484
485    ssl_DestroyLocks(fs);
486
487    PORT_Free(ss);	/* free the caller's copy, not ours. */
488    return;
489}
490#undef fs
491
492/************************************************************************/
493SECStatus
494ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled)
495{
496    PRFileDesc *       osfd = ss->fd->lower;
497    SECStatus         rv = SECFailure;
498    PRSocketOptionData opt;
499
500    opt.option         = PR_SockOpt_NoDelay;
501    opt.value.no_delay = (PRBool)!enabled;
502
503    if (osfd->methods->setsocketoption) {
504        rv = (SECStatus) osfd->methods->setsocketoption(osfd, &opt);
505    } else {
506        PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
507    }
508
509    return rv;
510}
511
512static void
513ssl_ChooseOps(sslSocket *ss)
514{
515    ss->ops = ss->opt.useSecurity ? &ssl_secure_ops : &ssl_default_ops;
516}
517
518/* Called from SSL_Enable (immediately below) */
519static SECStatus
520PrepareSocket(sslSocket *ss)
521{
522    SECStatus     rv = SECSuccess;
523
524    ssl_ChooseOps(ss);
525    return rv;
526}
527
528SECStatus
529SSL_Enable(PRFileDesc *fd, int which, PRBool on)
530{
531    return SSL_OptionSet(fd, which, on);
532}
533
534static const PRCallOnceType pristineCallOnce;
535static PRCallOnceType setupBypassOnce;
536
537static SECStatus SSL_BypassShutdown(void* appData, void* nssData)
538{
539    /* unload freeBL shared library from memory */
540    BL_Unload();
541    setupBypassOnce = pristineCallOnce;
542    return SECSuccess;
543}
544
545static PRStatus SSL_BypassRegisterShutdown(void)
546{
547    SECStatus rv = NSS_RegisterShutdown(SSL_BypassShutdown, NULL);
548    PORT_Assert(SECSuccess == rv);
549    return SECSuccess == rv ? PR_SUCCESS : PR_FAILURE;
550}
551
552static PRStatus SSL_BypassSetup(void)
553{
554    return PR_CallOnce(&setupBypassOnce, &SSL_BypassRegisterShutdown);
555}
556
557SECStatus
558SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on)
559{
560    sslSocket *ss = ssl_FindSocket(fd);
561    SECStatus  rv = SECSuccess;
562    PRBool     holdingLocks;
563
564    if (!ss) {
565	SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
566	return SECFailure;
567    }
568
569    holdingLocks = (!ss->opt.noLocks);
570    ssl_Get1stHandshakeLock(ss);
571    ssl_GetSSL3HandshakeLock(ss);
572
573    switch (which) {
574      case SSL_SOCKS:
575	ss->opt.useSocks = PR_FALSE;
576	rv = PrepareSocket(ss);
577	if (on) {
578	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
579	    rv = SECFailure;
580	}
581	break;
582
583      case SSL_SECURITY:
584	ss->opt.useSecurity = on;
585	rv = PrepareSocket(ss);
586	break;
587
588      case SSL_REQUEST_CERTIFICATE:
589	ss->opt.requestCertificate = on;
590	break;
591
592      case SSL_REQUIRE_CERTIFICATE:
593	ss->opt.requireCertificate = on;
594	break;
595
596      case SSL_HANDSHAKE_AS_CLIENT:
597	if ( ss->opt.handshakeAsServer && on ) {
598	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
599	    rv = SECFailure;
600	    break;
601	}
602	ss->opt.handshakeAsClient = on;
603	break;
604
605      case SSL_HANDSHAKE_AS_SERVER:
606	if ( ss->opt.handshakeAsClient && on ) {
607	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
608	    rv = SECFailure;
609	    break;
610	}
611	ss->opt.handshakeAsServer = on;
612	break;
613
614      case SSL_ENABLE_TLS:
615	ss->opt.enableTLS       = on;
616	ss->preferredCipher     = NULL;
617	if (ss->cipherSpecs) {
618	    PORT_Free(ss->cipherSpecs);
619	    ss->cipherSpecs     = NULL;
620	    ss->sizeCipherSpecs = 0;
621	}
622	break;
623
624      case SSL_ENABLE_SSL3:
625	ss->opt.enableSSL3      = on;
626	ss->preferredCipher     = NULL;
627	if (ss->cipherSpecs) {
628	    PORT_Free(ss->cipherSpecs);
629	    ss->cipherSpecs     = NULL;
630	    ss->sizeCipherSpecs = 0;
631	}
632	break;
633
634      case SSL_ENABLE_SSL2:
635	ss->opt.enableSSL2       = on;
636	if (on) {
637	    ss->opt.v2CompatibleHello = on;
638	}
639	ss->preferredCipher     = NULL;
640	if (ss->cipherSpecs) {
641	    PORT_Free(ss->cipherSpecs);
642	    ss->cipherSpecs     = NULL;
643	    ss->sizeCipherSpecs = 0;
644	}
645	break;
646
647      case SSL_NO_CACHE:
648	ss->opt.noCache = on;
649	break;
650
651      case SSL_ENABLE_FDX:
652	if (on && ss->opt.noLocks) {
653	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
654	    rv = SECFailure;
655	}
656      	ss->opt.fdx = on;
657	break;
658
659      case SSL_V2_COMPATIBLE_HELLO:
660      	ss->opt.v2CompatibleHello = on;
661	if (!on) {
662	    ss->opt.enableSSL2    = on;
663	}
664	break;
665
666      case SSL_ROLLBACK_DETECTION:
667	ss->opt.detectRollBack = on;
668        break;
669
670      case SSL_NO_STEP_DOWN:
671	ss->opt.noStepDown     = on;
672	if (on)
673	    SSL_DisableExportCipherSuites(fd);
674	break;
675
676      case SSL_BYPASS_PKCS11:
677	if (ss->handshakeBegun) {
678	    PORT_SetError(PR_INVALID_STATE_ERROR);
679	    rv = SECFailure;
680	} else {
681            if (PR_FALSE != on) {
682                if (PR_SUCCESS == SSL_BypassSetup() ) {
683                    ss->opt.bypassPKCS11   = on;
684                } else {
685                    rv = SECFailure;
686                }
687            } else {
688                ss->opt.bypassPKCS11   = PR_FALSE;
689            }
690	}
691	break;
692
693      case SSL_NO_LOCKS:
694	if (on && ss->opt.fdx) {
695	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
696	    rv = SECFailure;
697	}
698	if (on && ssl_force_locks)
699	    on = PR_FALSE;	/* silent override */
700	ss->opt.noLocks   = on;
701	if (on) {
702	    locksEverDisabled = PR_TRUE;
703	    strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
704	} else if (!holdingLocks) {
705	    rv = ssl_MakeLocks(ss);
706	    if (rv != SECSuccess) {
707		ss->opt.noLocks   = PR_TRUE;
708	    }
709	}
710	break;
711
712      case SSL_ENABLE_SESSION_TICKETS:
713	ss->opt.enableSessionTickets = on;
714	break;
715
716      case SSL_ENABLE_DEFLATE:
717	ss->opt.enableDeflate = on;
718	break;
719
720      case SSL_ENABLE_RENEGOTIATION:
721	ss->opt.enableRenegotiation = on;
722	break;
723
724      case SSL_REQUIRE_SAFE_NEGOTIATION:
725	ss->opt.requireSafeNegotiation = on;
726	break;
727
728      default:
729	PORT_SetError(SEC_ERROR_INVALID_ARGS);
730	rv = SECFailure;
731    }
732
733    /* We can't use the macros for releasing the locks here,
734     * because ss->opt.noLocks might have changed just above.
735     * We must release these locks (monitors) here, if we aquired them above,
736     * regardless of the current value of ss->opt.noLocks.
737     */
738    if (holdingLocks) {
739	PZ_ExitMonitor((ss)->ssl3HandshakeLock);
740	PZ_ExitMonitor((ss)->firstHandshakeLock);
741    }
742
743    return rv;
744}
745
746SECStatus
747SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn)
748{
749    sslSocket *ss = ssl_FindSocket(fd);
750    SECStatus  rv = SECSuccess;
751    PRBool     on = PR_FALSE;
752
753    if (!pOn) {
754	PORT_SetError(SEC_ERROR_INVALID_ARGS);
755	return SECFailure;
756    }
757    if (!ss) {
758	SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
759	*pOn = PR_FALSE;
760	return SECFailure;
761    }
762
763    ssl_Get1stHandshakeLock(ss);
764    ssl_GetSSL3HandshakeLock(ss);
765
766    switch (which) {
767    case SSL_SOCKS:               on = PR_FALSE;               break;
768    case SSL_SECURITY:            on = ss->opt.useSecurity;        break;
769    case SSL_REQUEST_CERTIFICATE: on = ss->opt.requestCertificate; break;
770    case SSL_REQUIRE_CERTIFICATE: on = ss->opt.requireCertificate; break;
771    case SSL_HANDSHAKE_AS_CLIENT: on = ss->opt.handshakeAsClient;  break;
772    case SSL_HANDSHAKE_AS_SERVER: on = ss->opt.handshakeAsServer;  break;
773    case SSL_ENABLE_TLS:          on = ss->opt.enableTLS;          break;
774    case SSL_ENABLE_SSL3:         on = ss->opt.enableSSL3;         break;
775    case SSL_ENABLE_SSL2:         on = ss->opt.enableSSL2;         break;
776    case SSL_NO_CACHE:            on = ss->opt.noCache;            break;
777    case SSL_ENABLE_FDX:          on = ss->opt.fdx;                break;
778    case SSL_V2_COMPATIBLE_HELLO: on = ss->opt.v2CompatibleHello;  break;
779    case SSL_ROLLBACK_DETECTION:  on = ss->opt.detectRollBack;     break;
780    case SSL_NO_STEP_DOWN:        on = ss->opt.noStepDown;         break;
781    case SSL_BYPASS_PKCS11:       on = ss->opt.bypassPKCS11;       break;
782    case SSL_NO_LOCKS:            on = ss->opt.noLocks;            break;
783    case SSL_ENABLE_SESSION_TICKETS:
784	on = ss->opt.enableSessionTickets;
785	break;
786    case SSL_ENABLE_DEFLATE:      on = ss->opt.enableDeflate;      break;
787    case SSL_ENABLE_RENEGOTIATION:
788                                  on = ss->opt.enableRenegotiation; break;
789    case SSL_REQUIRE_SAFE_NEGOTIATION:
790                                  on = ss->opt.requireSafeNegotiation; break;
791
792    default:
793	PORT_SetError(SEC_ERROR_INVALID_ARGS);
794	rv = SECFailure;
795    }
796
797    ssl_ReleaseSSL3HandshakeLock(ss);
798    ssl_Release1stHandshakeLock(ss);
799
800    *pOn = on;
801    return rv;
802}
803
804SECStatus
805SSL_OptionGetDefault(PRInt32 which, PRBool *pOn)
806{
807    SECStatus  rv = SECSuccess;
808    PRBool     on = PR_FALSE;
809
810    if (!pOn) {
811	PORT_SetError(SEC_ERROR_INVALID_ARGS);
812	return SECFailure;
813    }
814
815    switch (which) {
816    case SSL_SOCKS:               on = PR_FALSE;                        break;
817    case SSL_SECURITY:            on = ssl_defaults.useSecurity;        break;
818    case SSL_REQUEST_CERTIFICATE: on = ssl_defaults.requestCertificate; break;
819    case SSL_REQUIRE_CERTIFICATE: on = ssl_defaults.requireCertificate; break;
820    case SSL_HANDSHAKE_AS_CLIENT: on = ssl_defaults.handshakeAsClient;  break;
821    case SSL_HANDSHAKE_AS_SERVER: on = ssl_defaults.handshakeAsServer;  break;
822    case SSL_ENABLE_TLS:          on = ssl_defaults.enableTLS;          break;
823    case SSL_ENABLE_SSL3:         on = ssl_defaults.enableSSL3;         break;
824    case SSL_ENABLE_SSL2:         on = ssl_defaults.enableSSL2;         break;
825    case SSL_NO_CACHE:            on = ssl_defaults.noCache;		break;
826    case SSL_ENABLE_FDX:          on = ssl_defaults.fdx;                break;
827    case SSL_V2_COMPATIBLE_HELLO: on = ssl_defaults.v2CompatibleHello;  break;
828    case SSL_ROLLBACK_DETECTION:  on = ssl_defaults.detectRollBack;     break;
829    case SSL_NO_STEP_DOWN:        on = ssl_defaults.noStepDown;         break;
830    case SSL_BYPASS_PKCS11:       on = ssl_defaults.bypassPKCS11;       break;
831    case SSL_NO_LOCKS:            on = ssl_defaults.noLocks;            break;
832    case SSL_ENABLE_SESSION_TICKETS:
833	on = ssl_defaults.enableSessionTickets;
834	break;
835    case SSL_ENABLE_DEFLATE:      on = ssl_defaults.enableDeflate;      break;
836    case SSL_ENABLE_RENEGOTIATION:
837                                  on = ssl_defaults.enableRenegotiation; break;
838    case SSL_REQUIRE_SAFE_NEGOTIATION:
839                                  on = ssl_defaults.requireSafeNegotiation;
840				  break;
841
842    default:
843	PORT_SetError(SEC_ERROR_INVALID_ARGS);
844	rv = SECFailure;
845    }
846
847    *pOn = on;
848    return rv;
849}
850
851/* XXX Use Global Lock to protect this stuff. */
852SECStatus
853SSL_EnableDefault(int which, PRBool on)
854{
855    return SSL_OptionSetDefault(which, on);
856}
857
858SECStatus
859SSL_OptionSetDefault(PRInt32 which, PRBool on)
860{
861    switch (which) {
862      case SSL_SOCKS:
863	ssl_defaults.useSocks = PR_FALSE;
864	if (on) {
865	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
866	    return SECFailure;
867	}
868	break;
869
870      case SSL_SECURITY:
871	ssl_defaults.useSecurity = on;
872	break;
873
874      case SSL_REQUEST_CERTIFICATE:
875	ssl_defaults.requestCertificate = on;
876	break;
877
878      case SSL_REQUIRE_CERTIFICATE:
879	ssl_defaults.requireCertificate = on;
880	break;
881
882      case SSL_HANDSHAKE_AS_CLIENT:
883	if ( ssl_defaults.handshakeAsServer && on ) {
884	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
885	    return SECFailure;
886	}
887	ssl_defaults.handshakeAsClient = on;
888	break;
889
890      case SSL_HANDSHAKE_AS_SERVER:
891	if ( ssl_defaults.handshakeAsClient && on ) {
892	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
893	    return SECFailure;
894	}
895	ssl_defaults.handshakeAsServer = on;
896	break;
897
898      case SSL_ENABLE_TLS:
899	ssl_defaults.enableTLS = on;
900	break;
901
902      case SSL_ENABLE_SSL3:
903	ssl_defaults.enableSSL3 = on;
904	break;
905
906      case SSL_ENABLE_SSL2:
907	ssl_defaults.enableSSL2 = on;
908	if (on) {
909	    ssl_defaults.v2CompatibleHello = on;
910	}
911	break;
912
913      case SSL_NO_CACHE:
914	ssl_defaults.noCache = on;
915	break;
916
917      case SSL_ENABLE_FDX:
918	if (on && ssl_defaults.noLocks) {
919	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
920	    return SECFailure;
921	}
922      	ssl_defaults.fdx = on;
923	break;
924
925      case SSL_V2_COMPATIBLE_HELLO:
926      	ssl_defaults.v2CompatibleHello = on;
927	if (!on) {
928	    ssl_defaults.enableSSL2    = on;
929	}
930	break;
931
932      case SSL_ROLLBACK_DETECTION:
933	ssl_defaults.detectRollBack = on;
934	break;
935
936      case SSL_NO_STEP_DOWN:
937	ssl_defaults.noStepDown     = on;
938	if (on)
939	    SSL_DisableDefaultExportCipherSuites();
940	break;
941
942      case SSL_BYPASS_PKCS11:
943        if (PR_FALSE != on) {
944            if (PR_SUCCESS == SSL_BypassSetup()) {
945                ssl_defaults.bypassPKCS11   = on;
946            } else {
947                return SECFailure;
948            }
949        } else {
950            ssl_defaults.bypassPKCS11   = PR_FALSE;
951        }
952	break;
953
954      case SSL_NO_LOCKS:
955	if (on && ssl_defaults.fdx) {
956	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
957	    return SECFailure;
958	}
959	if (on && ssl_force_locks)
960	    on = PR_FALSE;		/* silent override */
961	ssl_defaults.noLocks        = on;
962	if (on) {
963	    locksEverDisabled = PR_TRUE;
964	    strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
965	}
966	break;
967
968      case SSL_ENABLE_SESSION_TICKETS:
969	ssl_defaults.enableSessionTickets = on;
970	break;
971
972      case SSL_ENABLE_DEFLATE:
973	ssl_defaults.enableDeflate = on;
974	break;
975
976      case SSL_ENABLE_RENEGOTIATION:
977	ssl_defaults.enableRenegotiation = on;
978	break;
979
980      case SSL_REQUIRE_SAFE_NEGOTIATION:
981	ssl_defaults.requireSafeNegotiation = on;
982	break;
983
984      default:
985	PORT_SetError(SEC_ERROR_INVALID_ARGS);
986	return SECFailure;
987    }
988    return SECSuccess;
989}
990
991/* function tells us if the cipher suite is one that we no longer support. */
992static PRBool
993ssl_IsRemovedCipherSuite(PRInt32 suite)
994{
995    switch (suite) {
996    case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
997    case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
998    case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA:
999    	return PR_TRUE;
1000    default:
1001    	return PR_FALSE;
1002    }
1003}
1004
1005/* Part of the public NSS API.
1006 * Since this is a global (not per-socket) setting, we cannot use the
1007 * HandshakeLock to protect this.  Probably want a global lock.
1008 */
1009SECStatus
1010SSL_SetPolicy(long which, int policy)
1011{
1012    if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
1013    	/* one of the two old FIPS ciphers */
1014	if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
1015	    which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
1016	else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
1017	    which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
1018    }
1019    if (ssl_IsRemovedCipherSuite(which))
1020    	return SECSuccess;
1021    return SSL_CipherPolicySet(which, policy);
1022}
1023
1024SECStatus
1025SSL_CipherPolicySet(PRInt32 which, PRInt32 policy)
1026{
1027    SECStatus rv;
1028
1029    if (ssl_IsRemovedCipherSuite(which)) {
1030    	rv = SECSuccess;
1031    } else if (SSL_IS_SSL2_CIPHER(which)) {
1032	rv = ssl2_SetPolicy(which, policy);
1033    } else {
1034	rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy);
1035    }
1036    return rv;
1037}
1038
1039SECStatus
1040SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy)
1041{
1042    SECStatus rv;
1043
1044    if (!oPolicy) {
1045	PORT_SetError(SEC_ERROR_INVALID_ARGS);
1046	return SECFailure;
1047    }
1048    if (ssl_IsRemovedCipherSuite(which)) {
1049	*oPolicy = SSL_NOT_ALLOWED;
1050    	rv = SECSuccess;
1051    } else if (SSL_IS_SSL2_CIPHER(which)) {
1052	rv = ssl2_GetPolicy(which, oPolicy);
1053    } else {
1054	rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy);
1055    }
1056    return rv;
1057}
1058
1059/* Part of the public NSS API.
1060 * Since this is a global (not per-socket) setting, we cannot use the
1061 * HandshakeLock to protect this.  Probably want a global lock.
1062 * These changes have no effect on any sslSockets already created.
1063 */
1064SECStatus
1065SSL_EnableCipher(long which, PRBool enabled)
1066{
1067    if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
1068    	/* one of the two old FIPS ciphers */
1069	if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
1070	    which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
1071	else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
1072	    which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
1073    }
1074    if (ssl_IsRemovedCipherSuite(which))
1075    	return SECSuccess;
1076    return SSL_CipherPrefSetDefault(which, enabled);
1077}
1078
1079SECStatus
1080SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
1081{
1082    SECStatus rv;
1083
1084    if (ssl_IsRemovedCipherSuite(which))
1085    	return SECSuccess;
1086    if (enabled && ssl_defaults.noStepDown && SSL_IsExportCipherSuite(which)) {
1087    	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1088	return SECFailure;
1089    }
1090    if (SSL_IS_SSL2_CIPHER(which)) {
1091	rv = ssl2_CipherPrefSetDefault(which, enabled);
1092    } else {
1093	rv = ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled);
1094    }
1095    return rv;
1096}
1097
1098SECStatus
1099SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
1100{
1101    SECStatus  rv;
1102
1103    if (!enabled) {
1104	PORT_SetError(SEC_ERROR_INVALID_ARGS);
1105	return SECFailure;
1106    }
1107    if (ssl_IsRemovedCipherSuite(which)) {
1108	*enabled = PR_FALSE;
1109    	rv = SECSuccess;
1110    } else if (SSL_IS_SSL2_CIPHER(which)) {
1111	rv = ssl2_CipherPrefGetDefault(which, enabled);
1112    } else {
1113	rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled);
1114    }
1115    return rv;
1116}
1117
1118SECStatus
1119SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled)
1120{
1121    SECStatus rv;
1122    sslSocket *ss = ssl_FindSocket(fd);
1123
1124    if (!ss) {
1125	SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefSet", SSL_GETPID(), fd));
1126	return SECFailure;
1127    }
1128    if (ssl_IsRemovedCipherSuite(which))
1129    	return SECSuccess;
1130    if (enabled && ss->opt.noStepDown && SSL_IsExportCipherSuite(which)) {
1131    	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1132	return SECFailure;
1133    }
1134    if (SSL_IS_SSL2_CIPHER(which)) {
1135	rv = ssl2_CipherPrefSet(ss, which, enabled);
1136    } else {
1137	rv = ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled);
1138    }
1139    return rv;
1140}
1141
1142SECStatus
1143SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled)
1144{
1145    SECStatus  rv;
1146    sslSocket *ss = ssl_FindSocket(fd);
1147
1148    if (!enabled) {
1149	PORT_SetError(SEC_ERROR_INVALID_ARGS);
1150	return SECFailure;
1151    }
1152    if (!ss) {
1153	SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefGet", SSL_GETPID(), fd));
1154	*enabled = PR_FALSE;
1155	return SECFailure;
1156    }
1157    if (ssl_IsRemovedCipherSuite(which)) {
1158	*enabled = PR_FALSE;
1159    	rv = SECSuccess;
1160    } else if (SSL_IS_SSL2_CIPHER(which)) {
1161	rv = ssl2_CipherPrefGet(ss, which, enabled);
1162    } else {
1163	rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled);
1164    }
1165    return rv;
1166}
1167
1168SECStatus
1169NSS_SetDomesticPolicy(void)
1170{
1171#ifndef EXPORT_VERSION
1172    SECStatus      status = SECSuccess;
1173    cipherPolicy * policy;
1174
1175    for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
1176	status = SSL_SetPolicy(policy->cipher, SSL_ALLOWED);
1177	if (status != SECSuccess)
1178	    break;
1179    }
1180    return status;
1181#else
1182    return NSS_SetExportPolicy();
1183#endif
1184}
1185
1186SECStatus
1187NSS_SetExportPolicy(void)
1188{
1189    SECStatus      status = SECSuccess;
1190    cipherPolicy * policy;
1191
1192    for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
1193	status = SSL_SetPolicy(policy->cipher, policy->export);
1194	if (status != SECSuccess)
1195	    break;
1196    }
1197    return status;
1198}
1199
1200SECStatus
1201NSS_SetFrancePolicy(void)
1202{
1203    SECStatus      status = SECSuccess;
1204    cipherPolicy * policy;
1205
1206    for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
1207	status = SSL_SetPolicy(policy->cipher, policy->france);
1208	if (status != SECSuccess)
1209	    break;
1210    }
1211    return status;
1212}
1213
1214
1215
1216/* LOCKS ??? XXX */
1217PRFileDesc *
1218SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd)
1219{
1220    sslSocket * ns = NULL;
1221    PRStatus    rv;
1222    PRNetAddr   addr;
1223
1224    if (model == NULL) {
1225	/* Just create a default socket if we're given NULL for the model */
1226	ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks));
1227    } else {
1228	sslSocket * ss = ssl_FindSocket(model);
1229	if (ss == NULL) {
1230	    SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD",
1231	    	      SSL_GETPID(), model));
1232	    return NULL;
1233	}
1234	ns = ssl_DupSocket(ss);
1235    }
1236    if (ns == NULL)
1237    	return NULL;
1238
1239    rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER);
1240    if (rv != PR_SUCCESS) {
1241	ssl_FreeSocket(ns);
1242	SET_ERROR_CODE
1243	return NULL;
1244    }
1245#ifdef _WIN32
1246    PR_Sleep(PR_INTERVAL_NO_WAIT);     /* workaround NT winsock connect bug. */
1247#endif
1248    ns = ssl_FindSocket(fd);
1249    PORT_Assert(ns);
1250    if (ns)
1251	ns->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ns, &addr));
1252    return fd;
1253}
1254
1255/* SSL_SetNextProtoNego sets the list of supported protocols for the given
1256 * socket. The list is a series of 8-bit, length prefixed strings. */
1257SECStatus
1258SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
1259		     unsigned short length)
1260{
1261    sslSocket *ss = ssl_FindSocket(fd);
1262
1263    if (!ss) {
1264	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoNego", SSL_GETPID(),
1265		fd));
1266	return SECFailure;
1267    }
1268
1269    if (ssl3_ValidateNextProtoNego(data, length) != SECSuccess)
1270	return SECFailure;
1271
1272    ssl_GetSSL3HandshakeLock(ss);
1273    if (ss->opt.nextProtoNego.data)
1274	PORT_Free(ss->opt.nextProtoNego.data);
1275    ss->opt.nextProtoNego.data = PORT_Alloc(length);
1276    if (!ss->opt.nextProtoNego.data) {
1277	ssl_ReleaseSSL3HandshakeLock(ss);
1278	return SECFailure;
1279    }
1280    memcpy(ss->opt.nextProtoNego.data, data, length);
1281    ss->opt.nextProtoNego.len = length;
1282    ss->opt.nextProtoNego.type = siBuffer;
1283    ssl_ReleaseSSL3HandshakeLock(ss);
1284
1285    return SECSuccess;
1286}
1287
1288/* SSL_GetNextProto reads the resulting Next Protocol Negotiation result for
1289 * the given socket. It's only valid to call this once the handshake has
1290 * completed.
1291 *
1292 * state is set to one of the SSL_NEXT_PROTO_* constants. The negotiated
1293 * protocol, if any, is written into buf, which must be at least buf_len
1294 * bytes long. If the negotiated protocol is longer than this, it is truncated.
1295 * The number of bytes copied is written into length.
1296 */
1297SECStatus
1298SSL_GetNextProto(PRFileDesc *fd, int *state, unsigned char *buf,
1299		 unsigned int *length, unsigned int buf_len)
1300{
1301    sslSocket *ss = ssl_FindSocket(fd);
1302
1303    if (!ss) {
1304	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNextProto", SSL_GETPID(),
1305		fd));
1306	return SECFailure;
1307    }
1308
1309    *state = ss->ssl3.nextProtoState;
1310
1311    if (ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
1312	ss->ssl3.nextProto.data) {
1313	*length = ss->ssl3.nextProto.len;
1314	if (*length > buf_len)
1315	    *length = buf_len;
1316	PORT_Memcpy(buf, ss->ssl3.nextProto.data, *length);
1317    } else {
1318	*length = 0;
1319    }
1320
1321    return SECSuccess;
1322}
1323
1324/************************************************************************/
1325/* The following functions are the TOP LEVEL SSL functions.
1326** They all get called through the NSPRIOMethods table below.
1327*/
1328
1329static PRFileDesc * PR_CALLBACK
1330ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout)
1331{
1332    sslSocket  *ss;
1333    sslSocket  *ns 	= NULL;
1334    PRFileDesc *newfd 	= NULL;
1335    PRFileDesc *osfd;
1336    PRStatus    status;
1337
1338    ss = ssl_GetPrivate(fd);
1339    if (!ss) {
1340	SSL_DBG(("%d: SSL[%d]: bad socket in accept", SSL_GETPID(), fd));
1341	return NULL;
1342    }
1343
1344    /* IF this is a listen socket, there shouldn't be any I/O going on */
1345    SSL_LOCK_READER(ss);
1346    SSL_LOCK_WRITER(ss);
1347    ssl_Get1stHandshakeLock(ss);
1348    ssl_GetSSL3HandshakeLock(ss);
1349
1350    ss->cTimeout = timeout;
1351
1352    osfd = ss->fd->lower;
1353
1354    /* First accept connection */
1355    newfd = osfd->methods->accept(osfd, sockaddr, timeout);
1356    if (newfd == NULL) {
1357	SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d",
1358		 SSL_GETPID(), ss->fd, PORT_GetError()));
1359    } else {
1360	/* Create ssl module */
1361	ns = ssl_DupSocket(ss);
1362    }
1363
1364    ssl_ReleaseSSL3HandshakeLock(ss);
1365    ssl_Release1stHandshakeLock(ss);
1366    SSL_UNLOCK_WRITER(ss);
1367    SSL_UNLOCK_READER(ss);			/* ss isn't used below here. */
1368
1369    if (ns == NULL)
1370	goto loser;
1371
1372    /* push ssl module onto the new socket */
1373    status = ssl_PushIOLayer(ns, newfd, PR_TOP_IO_LAYER);
1374    if (status != PR_SUCCESS)
1375	goto loser;
1376
1377    /* Now start server connection handshake with client.
1378    ** Don't need locks here because nobody else has a reference to ns yet.
1379    */
1380    if ( ns->opt.useSecurity ) {
1381	if ( ns->opt.handshakeAsClient ) {
1382	    ns->handshake = ssl2_BeginClientHandshake;
1383	    ss->handshaking = sslHandshakingAsClient;
1384	} else {
1385	    ns->handshake = ssl2_BeginServerHandshake;
1386	    ss->handshaking = sslHandshakingAsServer;
1387	}
1388    }
1389    ns->TCPconnected = 1;
1390    return newfd;
1391
1392loser:
1393    if (ns != NULL)
1394	ssl_FreeSocket(ns);
1395    if (newfd != NULL)
1396	PR_Close(newfd);
1397    return NULL;
1398}
1399
1400static PRStatus PR_CALLBACK
1401ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout)
1402{
1403    sslSocket *ss;
1404    PRStatus   rv;
1405
1406    ss = ssl_GetPrivate(fd);
1407    if (!ss) {
1408	SSL_DBG(("%d: SSL[%d]: bad socket in connect", SSL_GETPID(), fd));
1409	return PR_FAILURE;
1410    }
1411
1412    /* IF this is a listen socket, there shouldn't be any I/O going on */
1413    SSL_LOCK_READER(ss);
1414    SSL_LOCK_WRITER(ss);
1415
1416    ss->cTimeout = timeout;
1417    rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr);
1418#ifdef _WIN32
1419    PR_Sleep(PR_INTERVAL_NO_WAIT);     /* workaround NT winsock connect bug. */
1420#endif
1421
1422    SSL_UNLOCK_WRITER(ss);
1423    SSL_UNLOCK_READER(ss);
1424
1425    return rv;
1426}
1427
1428static PRStatus PR_CALLBACK
1429ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr)
1430{
1431    sslSocket * ss = ssl_GetPrivate(fd);
1432    PRStatus    rv;
1433
1434    if (!ss) {
1435	SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd));
1436	return PR_FAILURE;
1437    }
1438    SSL_LOCK_READER(ss);
1439    SSL_LOCK_WRITER(ss);
1440
1441    rv = (PRStatus)(*ss->ops->bind)(ss, addr);
1442
1443    SSL_UNLOCK_WRITER(ss);
1444    SSL_UNLOCK_READER(ss);
1445    return rv;
1446}
1447
1448static PRStatus PR_CALLBACK
1449ssl_Listen(PRFileDesc *fd, PRIntn backlog)
1450{
1451    sslSocket * ss = ssl_GetPrivate(fd);
1452    PRStatus    rv;
1453
1454    if (!ss) {
1455	SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd));
1456	return PR_FAILURE;
1457    }
1458    SSL_LOCK_READER(ss);
1459    SSL_LOCK_WRITER(ss);
1460
1461    rv = (PRStatus)(*ss->ops->listen)(ss, backlog);
1462
1463    SSL_UNLOCK_WRITER(ss);
1464    SSL_UNLOCK_READER(ss);
1465    return rv;
1466}
1467
1468static PRStatus PR_CALLBACK
1469ssl_Shutdown(PRFileDesc *fd, PRIntn how)
1470{
1471    sslSocket * ss = ssl_GetPrivate(fd);
1472    PRStatus    rv;
1473
1474    if (!ss) {
1475	SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd));
1476	return PR_FAILURE;
1477    }
1478    if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
1479    	SSL_LOCK_READER(ss);
1480    }
1481    if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
1482    	SSL_LOCK_WRITER(ss);
1483    }
1484
1485    rv = (PRStatus)(*ss->ops->shutdown)(ss, how);
1486
1487    if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
1488    	SSL_UNLOCK_WRITER(ss);
1489    }
1490    if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
1491    	SSL_UNLOCK_READER(ss);
1492    }
1493    return rv;
1494}
1495
1496static PRStatus PR_CALLBACK
1497ssl_Close(PRFileDesc *fd)
1498{
1499    sslSocket *ss;
1500    PRStatus   rv;
1501
1502    ss = ssl_GetPrivate(fd);
1503    if (!ss) {
1504	SSL_DBG(("%d: SSL[%d]: bad socket in close", SSL_GETPID(), fd));
1505	return PR_FAILURE;
1506    }
1507
1508    /* There must not be any I/O going on */
1509    SSL_LOCK_READER(ss);
1510    SSL_LOCK_WRITER(ss);
1511
1512    /* By the time this function returns,
1513    ** ss is an invalid pointer, and the locks to which it points have
1514    ** been unlocked and freed.  So, this is the ONE PLACE in all of SSL
1515    ** where the LOCK calls and the corresponding UNLOCK calls are not in
1516    ** the same function scope.  The unlock calls are in ssl_FreeSocket().
1517    */
1518    rv = (PRStatus)(*ss->ops->close)(ss);
1519
1520    return rv;
1521}
1522
1523static int PR_CALLBACK
1524ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
1525	 PRIntervalTime timeout)
1526{
1527    sslSocket *ss;
1528    int        rv;
1529
1530    ss = ssl_GetPrivate(fd);
1531    if (!ss) {
1532	SSL_DBG(("%d: SSL[%d]: bad socket in recv", SSL_GETPID(), fd));
1533	return SECFailure;
1534    }
1535    SSL_LOCK_READER(ss);
1536    ss->rTimeout = timeout;
1537    if (!ss->opt.fdx)
1538	ss->wTimeout = timeout;
1539    rv = (*ss->ops->recv)(ss, (unsigned char*)buf, len, flags);
1540    SSL_UNLOCK_READER(ss);
1541    return rv;
1542}
1543
1544static int PR_CALLBACK
1545ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
1546	 PRIntervalTime timeout)
1547{
1548    sslSocket *ss;
1549    int        rv;
1550
1551    ss = ssl_GetPrivate(fd);
1552    if (!ss) {
1553	SSL_DBG(("%d: SSL[%d]: bad socket in send", SSL_GETPID(), fd));
1554	return SECFailure;
1555    }
1556    SSL_LOCK_WRITER(ss);
1557    ss->wTimeout = timeout;
1558    if (!ss->opt.fdx)
1559	ss->rTimeout = timeout;
1560    rv = (*ss->ops->send)(ss, (const unsigned char*)buf, len, flags);
1561    SSL_UNLOCK_WRITER(ss);
1562    return rv;
1563}
1564
1565static int PR_CALLBACK
1566ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len)
1567{
1568    sslSocket *ss;
1569    int        rv;
1570
1571    ss = ssl_GetPrivate(fd);
1572    if (!ss) {
1573	SSL_DBG(("%d: SSL[%d]: bad socket in read", SSL_GETPID(), fd));
1574	return SECFailure;
1575    }
1576    SSL_LOCK_READER(ss);
1577    ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
1578    if (!ss->opt.fdx)
1579	ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
1580    rv = (*ss->ops->read)(ss, (unsigned char*)buf, len);
1581    SSL_UNLOCK_READER(ss);
1582    return rv;
1583}
1584
1585static int PR_CALLBACK
1586ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
1587{
1588    sslSocket *ss;
1589    int        rv;
1590
1591    ss = ssl_GetPrivate(fd);
1592    if (!ss) {
1593	SSL_DBG(("%d: SSL[%d]: bad socket in write", SSL_GETPID(), fd));
1594	return SECFailure;
1595    }
1596    SSL_LOCK_WRITER(ss);
1597    ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
1598    if (!ss->opt.fdx)
1599	ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
1600    rv = (*ss->ops->write)(ss, (const unsigned char*)buf, len);
1601    SSL_UNLOCK_WRITER(ss);
1602    return rv;
1603}
1604
1605static PRStatus PR_CALLBACK
1606ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
1607{
1608    sslSocket *ss;
1609
1610    ss = ssl_GetPrivate(fd);
1611    if (!ss) {
1612	SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd));
1613	return PR_FAILURE;
1614    }
1615    return (PRStatus)(*ss->ops->getpeername)(ss, addr);
1616}
1617
1618/*
1619*/
1620SECStatus
1621ssl_GetPeerInfo(sslSocket *ss)
1622{
1623    PRFileDesc *      osfd;
1624    int               rv;
1625    PRNetAddr         sin;
1626
1627    osfd = ss->fd->lower;
1628
1629    PORT_Memset(&sin, 0, sizeof(sin));
1630    rv = osfd->methods->getpeername(osfd, &sin);
1631    if (rv < 0) {
1632	return SECFailure;
1633    }
1634    ss->TCPconnected = 1;
1635    if (sin.inet.family == PR_AF_INET) {
1636        PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer);
1637	ss->sec.ci.port = sin.inet.port;
1638    } else if (sin.ipv6.family == PR_AF_INET6) {
1639	ss->sec.ci.peer = sin.ipv6.ip;
1640	ss->sec.ci.port = sin.ipv6.port;
1641    } else {
1642	PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR);
1643    	return SECFailure;
1644    }
1645    return SECSuccess;
1646}
1647
1648static PRStatus PR_CALLBACK
1649ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name)
1650{
1651    sslSocket *ss;
1652
1653    ss = ssl_GetPrivate(fd);
1654    if (!ss) {
1655	SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd));
1656	return PR_FAILURE;
1657    }
1658    return (PRStatus)(*ss->ops->getsockname)(ss, name);
1659}
1660
1661SECStatus
1662SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID)
1663{
1664    sslSocket *ss;
1665
1666    ss = ssl_FindSocket(fd);
1667    if (!ss) {
1668	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetCacheIndex",
1669		 SSL_GETPID(), fd));
1670	return SECFailure;
1671    }
1672
1673    if (ss->peerID) {
1674    	PORT_Free(ss->peerID);
1675	ss->peerID = NULL;
1676    }
1677    if (peerID)
1678	ss->peerID = PORT_Strdup(peerID);
1679    return (ss->peerID || !peerID) ? SECSuccess : SECFailure;
1680}
1681
1682#define PR_POLL_RW (PR_POLL_WRITE | PR_POLL_READ)
1683
1684static PRInt16 PR_CALLBACK
1685ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags)
1686{
1687    sslSocket *ss;
1688    PRInt16    new_flags = how_flags;	/* should select on these flags. */
1689    PRNetAddr  addr;
1690
1691    *p_out_flags = 0;
1692    ss = ssl_GetPrivate(fd);
1693    if (!ss) {
1694	SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll",
1695		 SSL_GETPID(), fd));
1696	return 0;	/* don't poll on this socket */
1697    }
1698
1699    if (ss->opt.useSecurity &&
1700	ss->handshaking != sslHandshakingUndetermined &&
1701        !ss->firstHsDone &&
1702	(how_flags & PR_POLL_RW)) {
1703	if (!ss->TCPconnected) {
1704	    ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
1705	}
1706	/* If it's not connected, then presumably the application is polling
1707	** on read or write appropriately, so don't change it.
1708	*/
1709	if (ss->TCPconnected) {
1710	    if (!ss->handshakeBegun) {
1711		/* If the handshake has not begun, poll on read or write
1712		** based on the local application's role in the handshake,
1713		** not based on what the application requested.
1714		*/
1715		new_flags &= ~PR_POLL_RW;
1716		if (ss->handshaking == sslHandshakingAsClient) {
1717		    new_flags |= PR_POLL_WRITE;
1718		} else { /* handshaking as server */
1719		    new_flags |= PR_POLL_READ;
1720		}
1721	    } else
1722	    /* First handshake is in progress */
1723	    if (ss->lastWriteBlocked) {
1724		if (new_flags & PR_POLL_READ) {
1725		    /* The caller is waiting for data to be received,
1726		    ** but the initial handshake is blocked on write, or the
1727		    ** client's first handshake record has not been written.
1728		    ** The code should select on write, not read.
1729		    */
1730		    new_flags ^=  PR_POLL_READ;	   /* don't select on read. */
1731		    new_flags |=  PR_POLL_WRITE;   /* do    select on write. */
1732		}
1733	    } else if (new_flags & PR_POLL_WRITE) {
1734		    /* The caller is trying to write, but the handshake is
1735		    ** blocked waiting for data to read, and the first
1736		    ** handshake has been sent.  so do NOT to poll on write.
1737		    */
1738		    new_flags ^=  PR_POLL_WRITE;   /* don't select on write. */
1739		    new_flags |=  PR_POLL_READ;	   /* do    select on read. */
1740	    }
1741	}
1742    } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) {
1743	*p_out_flags = PR_POLL_READ;	/* it's ready already. */
1744	return new_flags;
1745    } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) &&
1746	       (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */
1747	new_flags |=  PR_POLL_WRITE;   /* also select on write. */
1748    }
1749    if (new_flags && (fd->lower->methods->poll != NULL)) {
1750	PRInt16    lower_out_flags = 0;
1751	PRInt16    lower_new_flags;
1752        lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags,
1753					           &lower_out_flags);
1754	if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) {
1755	    PRInt16 out_flags = lower_out_flags & ~PR_POLL_RW;
1756	    if (lower_out_flags & PR_POLL_READ)
1757		out_flags |= PR_POLL_WRITE;
1758	    if (lower_out_flags & PR_POLL_WRITE)
1759		out_flags |= PR_POLL_READ;
1760	    *p_out_flags = out_flags;
1761	    new_flags = how_flags;
1762	} else {
1763	    *p_out_flags = lower_out_flags;
1764	    new_flags    = lower_new_flags;
1765	}
1766    }
1767
1768    return new_flags;
1769}
1770
1771static PRInt32 PR_CALLBACK
1772ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd,
1773		 const void *headers, PRInt32 hlen,
1774		 PRTransmitFileFlags flags, PRIntervalTime timeout)
1775{
1776    PRSendFileData sfd;
1777
1778    sfd.fd = fd;
1779    sfd.file_offset = 0;
1780    sfd.file_nbytes = 0;
1781    sfd.header = headers;
1782    sfd.hlen = hlen;
1783    sfd.trailer = NULL;
1784    sfd.tlen = 0;
1785
1786    return sd->methods->sendfile(sd, &sfd, flags, timeout);
1787}
1788
1789
1790PRBool
1791ssl_FdIsBlocking(PRFileDesc *fd)
1792{
1793    PRSocketOptionData opt;
1794    PRStatus           status;
1795
1796    opt.option             = PR_SockOpt_Nonblocking;
1797    opt.value.non_blocking = PR_FALSE;
1798    status = PR_GetSocketOption(fd, &opt);
1799    if (status != PR_SUCCESS)
1800	return PR_FALSE;
1801    return (PRBool)!opt.value.non_blocking;
1802}
1803
1804PRBool
1805ssl_SocketIsBlocking(sslSocket *ss)
1806{
1807    return ssl_FdIsBlocking(ss->fd);
1808}
1809
1810PRInt32  sslFirstBufSize = 8 * 1024;
1811PRInt32  sslCopyLimit    = 1024;
1812
1813static PRInt32 PR_CALLBACK
1814ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors,
1815           PRIntervalTime timeout)
1816{
1817    PRInt32            bufLen;
1818    PRInt32            left;
1819    PRInt32            rv;
1820    PRInt32            sent      =  0;
1821    const PRInt32      first_len = sslFirstBufSize;
1822    const PRInt32      limit     = sslCopyLimit;
1823    PRBool             blocking;
1824    PRIOVec            myIov	 = { 0, 0 };
1825    char               buf[MAX_FRAGMENT_LENGTH];
1826
1827    if (vectors > PR_MAX_IOVECTOR_SIZE) {
1828    	PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
1829	return -1;
1830    }
1831    blocking = ssl_FdIsBlocking(fd);
1832
1833#define K16 sizeof(buf)
1834#define KILL_VECTORS while (vectors && !iov->iov_len) { ++iov; --vectors; }
1835#define GET_VECTOR   do { myIov = *iov++; --vectors; KILL_VECTORS } while (0)
1836#define HANDLE_ERR(rv, len) \
1837    if (rv != len) { \
1838	if (rv < 0) { \
1839	    if (!blocking \
1840		&& (PR_GetError() == PR_WOULD_BLOCK_ERROR) \
1841		&& (sent > 0)) { \
1842		return sent; \
1843	    } else { \
1844		return -1; \
1845	    } \
1846	} \
1847	/* Only a nonblocking socket can have partial sends */ \
1848	PR_ASSERT(!blocking); \
1849	return sent + rv; \
1850    }
1851#define SEND(bfr, len) \
1852    do { \
1853	rv = ssl_Send(fd, bfr, len, 0, timeout); \
1854	HANDLE_ERR(rv, len) \
1855	sent += len; \
1856    } while (0)
1857
1858    /* Make sure the first write is at least 8 KB, if possible. */
1859    KILL_VECTORS
1860    if (!vectors)
1861	return ssl_Send(fd, 0, 0, 0, timeout);
1862    GET_VECTOR;
1863    if (!vectors) {
1864	return ssl_Send(fd, myIov.iov_base, myIov.iov_len, 0, timeout);
1865    }
1866    if (myIov.iov_len < first_len) {
1867	PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
1868	bufLen = myIov.iov_len;
1869	left = first_len - bufLen;
1870	while (vectors && left) {
1871	    int toCopy;
1872	    GET_VECTOR;
1873	    toCopy = PR_MIN(left, myIov.iov_len);
1874	    PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy);
1875	    bufLen         += toCopy;
1876	    left           -= toCopy;
1877	    myIov.iov_base += toCopy;
1878	    myIov.iov_len  -= toCopy;
1879	}
1880	SEND( buf, bufLen );
1881    }
1882
1883    while (vectors || myIov.iov_len) {
1884	PRInt32   addLen;
1885	if (!myIov.iov_len) {
1886	    GET_VECTOR;
1887	}
1888	while (myIov.iov_len >= K16) {
1889	    SEND(myIov.iov_base, K16);
1890	    myIov.iov_base += K16;
1891	    myIov.iov_len  -= K16;
1892	}
1893	if (!myIov.iov_len)
1894	    continue;
1895
1896	if (!vectors || myIov.iov_len > limit) {
1897	    addLen = 0;
1898	} else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) {
1899	    /* Addlen is already computed. */;
1900	} else if (vectors > 1 &&
1901	     iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) {
1902	     addLen = limit - myIov.iov_len;
1903	} else
1904	    addLen = 0;
1905
1906	if (!addLen) {
1907	    SEND( myIov.iov_base, myIov.iov_len );
1908	    myIov.iov_len = 0;
1909	    continue;
1910	}
1911	PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
1912	bufLen = myIov.iov_len;
1913	do {
1914	    GET_VECTOR;
1915	    PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen);
1916	    myIov.iov_base += addLen;
1917	    myIov.iov_len  -= addLen;
1918	    bufLen         += addLen;
1919
1920	    left = PR_MIN( limit, K16 - bufLen);
1921	    if (!vectors 		/* no more left */
1922	    ||  myIov.iov_len > 0	/* we didn't use that one all up */
1923	    ||  bufLen >= K16		/* it's full. */
1924	    ) {
1925		addLen = 0;
1926	    } else if ((addLen = iov->iov_len % K16) <= left) {
1927		/* Addlen is already computed. */;
1928	    } else if (vectors > 1 &&
1929		 iov[1].iov_len % K16 + addLen <= left + limit) {
1930		 addLen = left;
1931	    } else
1932		addLen = 0;
1933
1934	} while (addLen);
1935	SEND( buf, bufLen );
1936    }
1937    return sent;
1938}
1939
1940/*
1941 * These functions aren't implemented.
1942 */
1943
1944static PRInt32 PR_CALLBACK
1945ssl_Available(PRFileDesc *fd)
1946{
1947    PORT_Assert(0);
1948    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1949    return SECFailure;
1950}
1951
1952static PRInt64 PR_CALLBACK
1953ssl_Available64(PRFileDesc *fd)
1954{
1955    PRInt64 res;
1956
1957    PORT_Assert(0);
1958    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1959    LL_I2L(res, -1L);
1960    return res;
1961}
1962
1963static PRStatus PR_CALLBACK
1964ssl_FSync(PRFileDesc *fd)
1965{
1966    PORT_Assert(0);
1967    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1968    return PR_FAILURE;
1969}
1970
1971static PRInt32 PR_CALLBACK
1972ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) {
1973    PORT_Assert(0);
1974    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1975    return SECFailure;
1976}
1977
1978static PRInt64 PR_CALLBACK
1979ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) {
1980    PRInt64 res;
1981
1982    PORT_Assert(0);
1983    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1984    LL_I2L(res, -1L);
1985    return res;
1986}
1987
1988static PRStatus PR_CALLBACK
1989ssl_FileInfo(PRFileDesc *fd, PRFileInfo *info)
1990{
1991    PORT_Assert(0);
1992    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1993    return PR_FAILURE;
1994}
1995
1996static PRStatus PR_CALLBACK
1997ssl_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
1998{
1999    PORT_Assert(0);
2000    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2001    return PR_FAILURE;
2002}
2003
2004static PRInt32 PR_CALLBACK
2005ssl_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
2006	     PRNetAddr *addr, PRIntervalTime timeout)
2007{
2008    PORT_Assert(0);
2009    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2010    return SECFailure;
2011}
2012
2013static PRInt32 PR_CALLBACK
2014ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
2015	   const PRNetAddr *addr, PRIntervalTime timeout)
2016{
2017    PORT_Assert(0);
2018    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2019    return SECFailure;
2020}
2021
2022static const PRIOMethods ssl_methods = {
2023    PR_DESC_LAYERED,
2024    ssl_Close,           	/* close        */
2025    ssl_Read,            	/* read         */
2026    ssl_Write,           	/* write        */
2027    ssl_Available,       	/* available    */
2028    ssl_Available64,     	/* available64  */
2029    ssl_FSync,           	/* fsync        */
2030    ssl_Seek,            	/* seek         */
2031    ssl_Seek64,          	/* seek64       */
2032    ssl_FileInfo,        	/* fileInfo     */
2033    ssl_FileInfo64,      	/* fileInfo64   */
2034    ssl_WriteV,          	/* writev       */
2035    ssl_Connect,         	/* connect      */
2036    ssl_Accept,          	/* accept       */
2037    ssl_Bind,            	/* bind         */
2038    ssl_Listen,          	/* listen       */
2039    ssl_Shutdown,        	/* shutdown     */
2040    ssl_Recv,            	/* recv         */
2041    ssl_Send,            	/* send         */
2042    ssl_RecvFrom,        	/* recvfrom     */
2043    ssl_SendTo,          	/* sendto       */
2044    ssl_Poll,            	/* poll         */
2045    PR_EmulateAcceptRead,       /* acceptread   */
2046    ssl_TransmitFile,           /* transmitfile */
2047    ssl_GetSockName,     	/* getsockname  */
2048    ssl_GetPeerName,     	/* getpeername  */
2049    NULL,                	/* getsockopt   OBSOLETE */
2050    NULL,                	/* setsockopt   OBSOLETE */
2051    NULL,                	/* getsocketoption   */
2052    NULL,                	/* setsocketoption   */
2053    PR_EmulateSendFile, 	/* Send a (partial) file with header/trailer*/
2054    NULL,                	/* reserved for future use */
2055    NULL,                	/* reserved for future use */
2056    NULL,                	/* reserved for future use */
2057    NULL,                	/* reserved for future use */
2058    NULL                 	/* reserved for future use */
2059};
2060
2061
2062static PRIOMethods combined_methods;
2063
2064static void
2065ssl_SetupIOMethods(void)
2066{
2067          PRIOMethods *new_methods  = &combined_methods;
2068    const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods();
2069    const PRIOMethods *my_methods   = &ssl_methods;
2070
2071    *new_methods = *nspr_methods;
2072
2073    new_methods->file_type         = my_methods->file_type;
2074    new_methods->close             = my_methods->close;
2075    new_methods->read              = my_methods->read;
2076    new_methods->write             = my_methods->write;
2077    new_methods->available         = my_methods->available;
2078    new_methods->available64       = my_methods->available64;
2079    new_methods->fsync             = my_methods->fsync;
2080    new_methods->seek              = my_methods->seek;
2081    new_methods->seek64            = my_methods->seek64;
2082    new_methods->fileInfo          = my_methods->fileInfo;
2083    new_methods->fileInfo64        = my_methods->fileInfo64;
2084    new_methods->writev            = my_methods->writev;
2085    new_methods->connect           = my_methods->connect;
2086    new_methods->accept            = my_methods->accept;
2087    new_methods->bind              = my_methods->bind;
2088    new_methods->listen            = my_methods->listen;
2089    new_methods->shutdown          = my_methods->shutdown;
2090    new_methods->recv              = my_methods->recv;
2091    new_methods->send              = my_methods->send;
2092    new_methods->recvfrom          = my_methods->recvfrom;
2093    new_methods->sendto            = my_methods->sendto;
2094    new_methods->poll              = my_methods->poll;
2095    new_methods->acceptread        = my_methods->acceptread;
2096    new_methods->transmitfile      = my_methods->transmitfile;
2097    new_methods->getsockname       = my_methods->getsockname;
2098    new_methods->getpeername       = my_methods->getpeername;
2099/*  new_methods->getsocketoption   = my_methods->getsocketoption;	*/
2100/*  new_methods->setsocketoption   = my_methods->setsocketoption;	*/
2101    new_methods->sendfile          = my_methods->sendfile;
2102
2103}
2104
2105static PRCallOnceType initIoLayerOnce;
2106
2107static PRStatus
2108ssl_InitIOLayer(void)
2109{
2110    ssl_layer_id = PR_GetUniqueIdentity("SSL");
2111    ssl_SetupIOMethods();
2112    ssl_inited = PR_TRUE;
2113    return PR_SUCCESS;
2114}
2115
2116static PRStatus
2117ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id)
2118{
2119    PRFileDesc *layer	= NULL;
2120    PRStatus    status;
2121
2122    if (!ssl_inited) {
2123	PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer);
2124    }
2125
2126    if (ns == NULL)
2127	goto loser;
2128
2129    layer = PR_CreateIOLayerStub(ssl_layer_id, &combined_methods);
2130    if (layer == NULL)
2131	goto loser;
2132    layer->secret = (PRFilePrivate *)ns;
2133
2134    /* Here, "stack" points to the PRFileDesc on the top of the stack.
2135    ** "layer" points to a new FD that is to be inserted into the stack.
2136    ** If layer is being pushed onto the top of the stack, then
2137    ** PR_PushIOLayer switches the contents of stack and layer, and then
2138    ** puts stack on top of layer, so that after it is done, the top of
2139    ** stack is the same "stack" as it was before, and layer is now the
2140    ** FD for the former top of stack.
2141    ** After this call, stack always points to the top PRFD on the stack.
2142    ** If this function fails, the contents of stack and layer are as
2143    ** they were before the call.
2144    */
2145    status = PR_PushIOLayer(stack, id, layer);
2146    if (status != PR_SUCCESS)
2147	goto loser;
2148
2149    ns->fd = (id == PR_TOP_IO_LAYER) ? stack : layer;
2150    return PR_SUCCESS;
2151
2152loser:
2153    if (layer) {
2154	layer->dtor(layer); /* free layer */
2155    }
2156    return PR_FAILURE;
2157}
2158
2159/* if this fails, caller must destroy socket. */
2160static SECStatus
2161ssl_MakeLocks(sslSocket *ss)
2162{
2163    ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL);
2164    if (!ss->firstHandshakeLock)
2165	goto loser;
2166    ss->ssl3HandshakeLock  = PZ_NewMonitor(nssILockSSL);
2167    if (!ss->ssl3HandshakeLock)
2168	goto loser;
2169    ss->specLock           = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL);
2170    if (!ss->specLock)
2171	goto loser;
2172    ss->recvBufLock        = PZ_NewMonitor(nssILockSSL);
2173    if (!ss->recvBufLock)
2174	goto loser;
2175    ss->xmitBufLock        = PZ_NewMonitor(nssILockSSL);
2176    if (!ss->xmitBufLock)
2177	goto loser;
2178    ss->writerThread       = NULL;
2179    if (ssl_lock_readers) {
2180	ss->recvLock       = PZ_NewLock(nssILockSSL);
2181	if (!ss->recvLock)
2182	    goto loser;
2183	ss->sendLock       = PZ_NewLock(nssILockSSL);
2184	if (!ss->sendLock)
2185	    goto loser;
2186    }
2187    return SECSuccess;
2188loser:
2189    ssl_DestroyLocks(ss);
2190    return SECFailure;
2191}
2192
2193#if (defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS)) && !defined(_WIN32_WCE)
2194#define NSS_HAVE_GETENV 1
2195#endif
2196
2197#define LOWER(x) (x | 0x20)  /* cheap ToLower function ignores LOCALE */
2198
2199/*
2200** Create a newsocket structure for a file descriptor.
2201*/
2202static sslSocket *
2203ssl_NewSocket(PRBool makeLocks)
2204{
2205    sslSocket *ss;
2206#if defined( NSS_HAVE_GETENV )
2207    static int firsttime = 1;
2208
2209    if (firsttime) {
2210	char * ev;
2211	firsttime = 0;
2212#ifdef DEBUG
2213	ev = getenv("SSLDEBUGFILE");
2214	if (ev && ev[0]) {
2215	    ssl_trace_iob = fopen(ev, "w");
2216	}
2217	if (!ssl_trace_iob) {
2218	    ssl_trace_iob = stderr;
2219	}
2220#ifdef TRACE
2221	ev = getenv("SSLTRACE");
2222	if (ev && ev[0]) {
2223	    ssl_trace = atoi(ev);
2224	    SSL_TRACE(("SSL: tracing set to %d", ssl_trace));
2225	}
2226#endif /* TRACE */
2227	ev = getenv("SSLDEBUG");
2228	if (ev && ev[0]) {
2229	    ssl_debug = atoi(ev);
2230	    SSL_TRACE(("SSL: debugging set to %d", ssl_debug));
2231	}
2232#endif /* DEBUG */
2233	ev = getenv("SSLBYPASS");
2234	if (ev && ev[0]) {
2235	    ssl_defaults.bypassPKCS11 = (ev[0] == '1');
2236	    SSL_TRACE(("SSL: bypass default set to %d", \
2237		      ssl_defaults.bypassPKCS11));
2238	}
2239	ev = getenv("SSLFORCELOCKS");
2240	if (ev && ev[0] == '1') {
2241	    ssl_force_locks = PR_TRUE;
2242	    ssl_defaults.noLocks = 0;
2243	    strcpy(lockStatus + LOCKSTATUS_OFFSET, "FORCED.  ");
2244	    SSL_TRACE(("SSL: force_locks set to %d", ssl_force_locks));
2245	}
2246	ev = getenv("NSS_SSL_ENABLE_RENEGOTIATION");
2247	if (ev) {
2248	    if (ev[0] == '1' || LOWER(ev[0]) == 'u')
2249	    	ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_UNRESTRICTED;
2250#ifdef LATER
2251	    /* When SSL_RENEGOTIATE_REQUIRES_XTN is implemented, it will be
2252	     * the default.  Until then, NEVER will be the default.
2253	     */
2254	    else if (ev[0] == '0' || LOWER(ev[0]) == 'n')
2255	    	ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
2256	    else
2257	    	ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN;
2258#else
2259	    else
2260	    	ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
2261#endif
2262
2263	    SSL_TRACE(("SSL: enableRenegotiation set to %d",
2264	               ssl_defaults.enableRenegotiation));
2265	}
2266	ev = getenv("NSS_SSL_REQUIRE_SAFE_NEGOTIATION");
2267	if (ev && ev[0] == '1') {
2268	    ssl_defaults.requireSafeNegotiation = PR_TRUE;
2269	    SSL_TRACE(("SSL: requireSafeNegotiation set to %d",
2270	                PR_TRUE));
2271	}
2272    }
2273#endif /* NSS_HAVE_GETENV */
2274    if (ssl_force_locks)
2275	makeLocks = PR_TRUE;
2276
2277    /* Make a new socket and get it ready */
2278    ss = (sslSocket*) PORT_ZAlloc(sizeof(sslSocket));
2279    if (ss) {
2280        /* This should be of type SSLKEAType, but CC on IRIX
2281	 * complains during the for loop.
2282	 */
2283	int i;
2284	SECStatus status;
2285
2286	ss->opt                = ssl_defaults;
2287	ss->opt.useSocks       = PR_FALSE;
2288	ss->opt.noLocks        = !makeLocks;
2289
2290	ss->peerID             = NULL;
2291	ss->rTimeout	       = PR_INTERVAL_NO_TIMEOUT;
2292	ss->wTimeout	       = PR_INTERVAL_NO_TIMEOUT;
2293	ss->cTimeout	       = PR_INTERVAL_NO_TIMEOUT;
2294	ss->cipherSpecs        = NULL;
2295        ss->sizeCipherSpecs    = 0;  /* produced lazily */
2296        ss->preferredCipher    = NULL;
2297        ss->url                = NULL;
2298
2299	for (i=kt_null; i < kt_kea_size; i++) {
2300	    sslServerCerts * sc = ss->serverCerts + i;
2301	    sc->serverCert      = NULL;
2302	    sc->serverCertChain = NULL;
2303	    sc->serverKeyPair   = NULL;
2304	    sc->serverKeyBits   = 0;
2305	}
2306	ss->stepDownKeyPair    = NULL;
2307	ss->dbHandle           = CERT_GetDefaultCertDB();
2308
2309	/* Provide default implementation of hooks */
2310	ss->authCertificate    = SSL_AuthCertificate;
2311	ss->authCertificateArg = (void *)ss->dbHandle;
2312	ss->getClientAuthData  = NULL;
2313	ss->handleBadCert      = NULL;
2314	ss->badCertArg         = NULL;
2315	ss->pkcs11PinArg       = NULL;
2316
2317	ssl_ChooseOps(ss);
2318	ssl2_InitSocketPolicy(ss);
2319	ssl3_InitSocketPolicy(ss);
2320
2321	if (makeLocks) {
2322	    status = ssl_MakeLocks(ss);
2323	    if (status != SECSuccess)
2324		goto loser;
2325	}
2326	status = ssl_CreateSecurityInfo(ss);
2327	if (status != SECSuccess)
2328	    goto loser;
2329	status = ssl_InitGather(&ss->gs);
2330	if (status != SECSuccess) {
2331loser:
2332	    ssl_DestroySocketContents(ss);
2333	    ssl_DestroyLocks(ss);
2334	    PORT_Free(ss);
2335	    ss = NULL;
2336	}
2337    }
2338    return ss;
2339}
2340
2341