Bug 460926 A11y hierachy is broken on Ubuntu 8.10 (GNOME 2.24), r=Evan.Yan sr=roc
[wine-gecko.git] / security / nss / lib / ssl / sslsock.c
bloba71bec85bd81503fe17fc1069e4421d40cb110a4
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.
6 * ***** BEGIN LICENSE BLOCK *****
7 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
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/
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.
19 * The Original Code is the Netscape security libraries.
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.
26 * Contributor(s):
27 * Dr Stephen Henson <stephen.henson@gemplus.com>
28 * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
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.
42 * ***** END LICENSE BLOCK ***** */
43 /* $Id: sslsock.c,v 1.55 2008/03/06 20:16:22 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"
55 #define SET_ERROR_CODE /* reminder */
57 struct cipherPolicyStr {
58 int cipher;
59 unsigned char export; /* policy value for export policy */
60 unsigned char france; /* policy value for france policy */
63 typedef struct cipherPolicyStr cipherPolicy;
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.
70 static 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_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, SSL_NOT_ALLOWED },
105 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, SSL_NOT_ALLOWED },
106 #ifdef NSS_ENABLE_ECC
107 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
108 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
109 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
110 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
111 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
112 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
113 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
114 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
115 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
116 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
117 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
118 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
119 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
120 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
121 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
122 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
123 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
124 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
125 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
126 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
127 #endif /* NSS_ENABLE_ECC */
128 { 0, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }
131 static const sslSocketOps ssl_default_ops = { /* No SSL. */
132 ssl_DefConnect,
133 NULL,
134 ssl_DefBind,
135 ssl_DefListen,
136 ssl_DefShutdown,
137 ssl_DefClose,
138 ssl_DefRecv,
139 ssl_DefSend,
140 ssl_DefRead,
141 ssl_DefWrite,
142 ssl_DefGetpeername,
143 ssl_DefGetsockname
146 static const sslSocketOps ssl_secure_ops = { /* SSL. */
147 ssl_SecureConnect,
148 NULL,
149 ssl_DefBind,
150 ssl_DefListen,
151 ssl_SecureShutdown,
152 ssl_SecureClose,
153 ssl_SecureRecv,
154 ssl_SecureSend,
155 ssl_SecureRead,
156 ssl_SecureWrite,
157 ssl_DefGetpeername,
158 ssl_DefGetsockname
162 ** default settings for socket enables
164 static sslOptions ssl_defaults = {
165 PR_TRUE, /* useSecurity */
166 PR_FALSE, /* useSocks */
167 PR_FALSE, /* requestCertificate */
168 2, /* requireCertificate */
169 PR_FALSE, /* handshakeAsClient */
170 PR_FALSE, /* handshakeAsServer */
171 PR_TRUE, /* enableSSL2 */
172 PR_TRUE, /* enableSSL3 */
173 PR_TRUE, /* enableTLS */ /* now defaults to on in NSS 3.0 */
174 PR_FALSE, /* noCache */
175 PR_FALSE, /* fdx */
176 PR_TRUE, /* v2CompatibleHello */
177 PR_TRUE, /* detectRollBack */
178 PR_FALSE, /* noStepDown */
179 PR_FALSE, /* bypassPKCS11 */
180 PR_FALSE, /* noLocks */
181 PR_FALSE, /* enableSessionTickets */
184 sslSessionIDLookupFunc ssl_sid_lookup;
185 sslSessionIDCacheFunc ssl_sid_cache;
186 sslSessionIDUncacheFunc ssl_sid_uncache;
188 static PRBool ssl_inited = PR_FALSE;
189 static PRDescIdentity ssl_layer_id;
191 PRBool locksEverDisabled; /* implicitly PR_FALSE */
192 PRBool ssl_force_locks; /* implicitly PR_FALSE */
193 int ssl_lock_readers = 1; /* default true. */
194 char ssl_debug;
195 char ssl_trace;
196 FILE * ssl_trace_iob;
197 char lockStatus[] = "Locks are ENABLED. ";
198 #define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */
200 /* forward declarations. */
201 static sslSocket *ssl_NewSocket(PRBool makeLocks);
202 static SECStatus ssl_MakeLocks(sslSocket *ss);
203 static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack,
204 PRDescIdentity id);
206 /************************************************************************/
209 ** Lookup a socket structure from a file descriptor.
210 ** Only functions called through the PRIOMethods table should use this.
211 ** Other app-callable functions should use ssl_FindSocket.
213 static sslSocket *
214 ssl_GetPrivate(PRFileDesc *fd)
216 sslSocket *ss;
218 PORT_Assert(fd != NULL);
219 PORT_Assert(fd->methods->file_type == PR_DESC_LAYERED);
220 PORT_Assert(fd->identity == ssl_layer_id);
222 if (fd->methods->file_type != PR_DESC_LAYERED ||
223 fd->identity != ssl_layer_id) {
224 PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
225 return NULL;
228 ss = (sslSocket *)fd->secret;
229 ss->fd = fd;
230 return ss;
233 /* This function tries to find the SSL layer in the stack.
234 * It searches for the first SSL layer at or below the argument fd,
235 * and failing that, it searches for the nearest SSL layer above the
236 * argument fd. It returns the private sslSocket from the found layer.
238 sslSocket *
239 ssl_FindSocket(PRFileDesc *fd)
241 PRFileDesc *layer;
242 sslSocket *ss;
244 PORT_Assert(fd != NULL);
245 PORT_Assert(ssl_layer_id != 0);
247 layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
248 if (layer == NULL) {
249 PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
250 return NULL;
253 ss = (sslSocket *)layer->secret;
254 ss->fd = layer;
255 return ss;
258 sslSocket *
259 ssl_DupSocket(sslSocket *os)
261 sslSocket *ss;
262 SECStatus rv;
264 ss = ssl_NewSocket((PRBool)(!os->opt.noLocks));
265 if (ss) {
266 ss->opt = os->opt;
267 ss->opt.useSocks = PR_FALSE;
269 ss->peerID = !os->peerID ? NULL : PORT_Strdup(os->peerID);
270 ss->url = !os->url ? NULL : PORT_Strdup(os->url);
272 ss->ops = os->ops;
273 ss->rTimeout = os->rTimeout;
274 ss->wTimeout = os->wTimeout;
275 ss->cTimeout = os->cTimeout;
276 ss->dbHandle = os->dbHandle;
278 /* copy ssl2&3 policy & prefs, even if it's not selected (yet) */
279 ss->allowedByPolicy = os->allowedByPolicy;
280 ss->maybeAllowedByPolicy= os->maybeAllowedByPolicy;
281 ss->chosenPreference = os->chosenPreference;
282 PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites);
284 if (os->cipherSpecs) {
285 ss->cipherSpecs = (unsigned char*)PORT_Alloc(os->sizeCipherSpecs);
286 if (ss->cipherSpecs)
287 PORT_Memcpy(ss->cipherSpecs, os->cipherSpecs,
288 os->sizeCipherSpecs);
289 ss->sizeCipherSpecs = os->sizeCipherSpecs;
290 ss->preferredCipher = os->preferredCipher;
291 } else {
292 ss->cipherSpecs = NULL; /* produced lazily */
293 ss->sizeCipherSpecs = 0;
294 ss->preferredCipher = NULL;
296 if (ss->opt.useSecurity) {
297 /* This int should be SSLKEAType, but CC on Irix complains,
298 * during the for loop.
300 int i;
301 sslServerCerts * oc = os->serverCerts;
302 sslServerCerts * sc = ss->serverCerts;
304 for (i=kt_null; i < kt_kea_size; i++, oc++, sc++) {
305 if (oc->serverCert && oc->serverCertChain) {
306 sc->serverCert = CERT_DupCertificate(oc->serverCert);
307 sc->serverCertChain = CERT_DupCertList(oc->serverCertChain);
308 if (!sc->serverCertChain)
309 goto loser;
310 } else {
311 sc->serverCert = NULL;
312 sc->serverCertChain = NULL;
314 sc->serverKeyPair = oc->serverKeyPair ?
315 ssl3_GetKeyPairRef(oc->serverKeyPair) : NULL;
316 if (oc->serverKeyPair && !sc->serverKeyPair)
317 goto loser;
318 sc->serverKeyBits = oc->serverKeyBits;
320 ss->stepDownKeyPair = !os->stepDownKeyPair ? NULL :
321 ssl3_GetKeyPairRef(os->stepDownKeyPair);
322 ss->ephemeralECDHKeyPair = !os->ephemeralECDHKeyPair ? NULL :
323 ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair);
325 * XXX the preceeding CERT_ and SECKEY_ functions can fail and return NULL.
326 * XXX We should detect this, and not just march on with NULL pointers.
328 ss->authCertificate = os->authCertificate;
329 ss->authCertificateArg = os->authCertificateArg;
330 ss->getClientAuthData = os->getClientAuthData;
331 ss->getClientAuthDataArg = os->getClientAuthDataArg;
332 ss->handleBadCert = os->handleBadCert;
333 ss->badCertArg = os->badCertArg;
334 ss->handshakeCallback = os->handshakeCallback;
335 ss->handshakeCallbackData = os->handshakeCallbackData;
336 ss->pkcs11PinArg = os->pkcs11PinArg;
338 /* Create security data */
339 rv = ssl_CopySecurityInfo(ss, os);
340 if (rv != SECSuccess) {
341 goto loser;
345 return ss;
347 loser:
348 ssl_FreeSocket(ss);
349 return NULL;
352 static void
353 ssl_DestroyLocks(sslSocket *ss)
355 /* Destroy locks. */
356 if (ss->firstHandshakeLock) {
357 PZ_DestroyMonitor(ss->firstHandshakeLock);
358 ss->firstHandshakeLock = NULL;
360 if (ss->ssl3HandshakeLock) {
361 PZ_DestroyMonitor(ss->ssl3HandshakeLock);
362 ss->ssl3HandshakeLock = NULL;
364 if (ss->specLock) {
365 NSSRWLock_Destroy(ss->specLock);
366 ss->specLock = NULL;
369 if (ss->recvLock) {
370 PZ_DestroyLock(ss->recvLock);
371 ss->recvLock = NULL;
373 if (ss->sendLock) {
374 PZ_DestroyLock(ss->sendLock);
375 ss->sendLock = NULL;
377 if (ss->xmitBufLock) {
378 PZ_DestroyMonitor(ss->xmitBufLock);
379 ss->xmitBufLock = NULL;
381 if (ss->recvBufLock) {
382 PZ_DestroyMonitor(ss->recvBufLock);
383 ss->recvBufLock = NULL;
387 /* Caller holds any relevant locks */
388 static void
389 ssl_DestroySocketContents(sslSocket *ss)
391 /* "i" should be of type SSLKEAType, but CC on IRIX complains during
392 * the for loop.
394 int i;
396 /* Free up socket */
397 ssl_DestroySecurityInfo(&ss->sec);
399 ssl3_DestroySSL3Info(ss);
401 PORT_Free(ss->saveBuf.buf);
402 PORT_Free(ss->pendingBuf.buf);
403 ssl_DestroyGather(&ss->gs);
405 if (ss->peerID != NULL)
406 PORT_Free(ss->peerID);
407 if (ss->url != NULL)
408 PORT_Free((void *)ss->url); /* CONST */
409 if (ss->cipherSpecs) {
410 PORT_Free(ss->cipherSpecs);
411 ss->cipherSpecs = NULL;
412 ss->sizeCipherSpecs = 0;
415 /* Clean up server configuration */
416 for (i=kt_null; i < kt_kea_size; i++) {
417 sslServerCerts * sc = ss->serverCerts + i;
418 if (sc->serverCert != NULL)
419 CERT_DestroyCertificate(sc->serverCert);
420 if (sc->serverCertChain != NULL)
421 CERT_DestroyCertificateList(sc->serverCertChain);
422 if (sc->serverKeyPair != NULL)
423 ssl3_FreeKeyPair(sc->serverKeyPair);
425 if (ss->stepDownKeyPair) {
426 ssl3_FreeKeyPair(ss->stepDownKeyPair);
427 ss->stepDownKeyPair = NULL;
429 if (ss->ephemeralECDHKeyPair) {
430 ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
431 ss->ephemeralECDHKeyPair = NULL;
436 * free an sslSocket struct, and all the stuff that hangs off of it
438 void
439 ssl_FreeSocket(sslSocket *ss)
441 #ifdef DEBUG
442 sslSocket *fs;
443 sslSocket lSock;
444 #endif
446 /* Get every lock you can imagine!
447 ** Caller already holds these:
448 ** SSL_LOCK_READER(ss);
449 ** SSL_LOCK_WRITER(ss);
451 ssl_Get1stHandshakeLock(ss);
452 ssl_GetRecvBufLock(ss);
453 ssl_GetSSL3HandshakeLock(ss);
454 ssl_GetXmitBufLock(ss);
455 ssl_GetSpecWriteLock(ss);
457 #ifdef DEBUG
458 fs = &lSock;
459 *fs = *ss; /* Copy the old socket structure, */
460 PORT_Memset(ss, 0x1f, sizeof *ss); /* then blast the old struct ASAP. */
461 #else
462 #define fs ss
463 #endif
465 ssl_DestroySocketContents(fs);
467 /* Release all the locks acquired above. */
468 SSL_UNLOCK_READER(fs);
469 SSL_UNLOCK_WRITER(fs);
470 ssl_Release1stHandshakeLock(fs);
471 ssl_ReleaseRecvBufLock(fs);
472 ssl_ReleaseSSL3HandshakeLock(fs);
473 ssl_ReleaseXmitBufLock(fs);
474 ssl_ReleaseSpecWriteLock(fs);
476 ssl_DestroyLocks(fs);
478 PORT_Free(ss); /* free the caller's copy, not ours. */
479 return;
481 #undef fs
483 /************************************************************************/
484 SECStatus
485 ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled)
487 PRFileDesc * osfd = ss->fd->lower;
488 SECStatus rv = SECFailure;
489 PRSocketOptionData opt;
491 opt.option = PR_SockOpt_NoDelay;
492 opt.value.no_delay = (PRBool)!enabled;
494 if (osfd->methods->setsocketoption) {
495 rv = (SECStatus) osfd->methods->setsocketoption(osfd, &opt);
496 } else {
497 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
500 return rv;
503 static void
504 ssl_ChooseOps(sslSocket *ss)
506 ss->ops = ss->opt.useSecurity ? &ssl_secure_ops : &ssl_default_ops;
509 /* Called from SSL_Enable (immediately below) */
510 static SECStatus
511 PrepareSocket(sslSocket *ss)
513 SECStatus rv = SECSuccess;
515 ssl_ChooseOps(ss);
516 return rv;
519 SECStatus
520 SSL_Enable(PRFileDesc *fd, int which, PRBool on)
522 return SSL_OptionSet(fd, which, on);
525 static const PRCallOnceType pristineCallOnce;
526 static PRCallOnceType setupBypassOnce;
528 static SECStatus SSL_BypassShutdown(void* appData, void* nssData)
530 /* unload freeBL shared library from memory */
531 BL_Unload();
532 setupBypassOnce = pristineCallOnce;
533 return SECSuccess;
536 static PRStatus SSL_BypassRegisterShutdown(void)
538 SECStatus rv = NSS_RegisterShutdown(SSL_BypassShutdown, NULL);
539 PORT_Assert(SECSuccess == rv);
540 return SECSuccess == rv ? PR_SUCCESS : PR_FAILURE;
543 static PRStatus SSL_BypassSetup(void)
545 return PR_CallOnce(&setupBypassOnce, &SSL_BypassRegisterShutdown);
548 SECStatus
549 SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on)
551 sslSocket *ss = ssl_FindSocket(fd);
552 SECStatus rv = SECSuccess;
553 PRBool holdingLocks;
555 if (!ss) {
556 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
557 return SECFailure;
560 holdingLocks = (!ss->opt.noLocks);
561 ssl_Get1stHandshakeLock(ss);
562 ssl_GetSSL3HandshakeLock(ss);
564 switch (which) {
565 case SSL_SOCKS:
566 ss->opt.useSocks = PR_FALSE;
567 rv = PrepareSocket(ss);
568 if (on) {
569 PORT_SetError(SEC_ERROR_INVALID_ARGS);
570 rv = SECFailure;
572 break;
574 case SSL_SECURITY:
575 ss->opt.useSecurity = on;
576 rv = PrepareSocket(ss);
577 break;
579 case SSL_REQUEST_CERTIFICATE:
580 ss->opt.requestCertificate = on;
581 break;
583 case SSL_REQUIRE_CERTIFICATE:
584 ss->opt.requireCertificate = on;
585 break;
587 case SSL_HANDSHAKE_AS_CLIENT:
588 if ( ss->opt.handshakeAsServer && on ) {
589 PORT_SetError(SEC_ERROR_INVALID_ARGS);
590 rv = SECFailure;
591 break;
593 ss->opt.handshakeAsClient = on;
594 break;
596 case SSL_HANDSHAKE_AS_SERVER:
597 if ( ss->opt.handshakeAsClient && on ) {
598 PORT_SetError(SEC_ERROR_INVALID_ARGS);
599 rv = SECFailure;
600 break;
602 ss->opt.handshakeAsServer = on;
603 break;
605 case SSL_ENABLE_TLS:
606 ss->opt.enableTLS = on;
607 ss->preferredCipher = NULL;
608 if (ss->cipherSpecs) {
609 PORT_Free(ss->cipherSpecs);
610 ss->cipherSpecs = NULL;
611 ss->sizeCipherSpecs = 0;
613 break;
615 case SSL_ENABLE_SSL3:
616 ss->opt.enableSSL3 = on;
617 ss->preferredCipher = NULL;
618 if (ss->cipherSpecs) {
619 PORT_Free(ss->cipherSpecs);
620 ss->cipherSpecs = NULL;
621 ss->sizeCipherSpecs = 0;
623 break;
625 case SSL_ENABLE_SSL2:
626 ss->opt.enableSSL2 = on;
627 if (on) {
628 ss->opt.v2CompatibleHello = on;
630 ss->preferredCipher = NULL;
631 if (ss->cipherSpecs) {
632 PORT_Free(ss->cipherSpecs);
633 ss->cipherSpecs = NULL;
634 ss->sizeCipherSpecs = 0;
636 break;
638 case SSL_NO_CACHE:
639 ss->opt.noCache = on;
640 break;
642 case SSL_ENABLE_FDX:
643 if (on && ss->opt.noLocks) {
644 PORT_SetError(SEC_ERROR_INVALID_ARGS);
645 rv = SECFailure;
647 ss->opt.fdx = on;
648 break;
650 case SSL_V2_COMPATIBLE_HELLO:
651 ss->opt.v2CompatibleHello = on;
652 if (!on) {
653 ss->opt.enableSSL2 = on;
655 break;
657 case SSL_ROLLBACK_DETECTION:
658 ss->opt.detectRollBack = on;
659 break;
661 case SSL_NO_STEP_DOWN:
662 ss->opt.noStepDown = on;
663 if (on)
664 SSL_DisableExportCipherSuites(fd);
665 break;
667 case SSL_BYPASS_PKCS11:
668 if (ss->handshakeBegun) {
669 PORT_SetError(PR_INVALID_STATE_ERROR);
670 rv = SECFailure;
671 } else {
672 if (PR_FALSE != on) {
673 if (PR_SUCCESS == SSL_BypassSetup() ) {
674 ss->opt.bypassPKCS11 = on;
675 } else {
676 rv = SECFailure;
678 } else {
679 ss->opt.bypassPKCS11 = PR_FALSE;
682 break;
684 case SSL_NO_LOCKS:
685 if (on && ss->opt.fdx) {
686 PORT_SetError(SEC_ERROR_INVALID_ARGS);
687 rv = SECFailure;
689 if (on && ssl_force_locks)
690 on = PR_FALSE; /* silent override */
691 ss->opt.noLocks = on;
692 if (on) {
693 locksEverDisabled = PR_TRUE;
694 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
695 } else if (!holdingLocks) {
696 rv = ssl_MakeLocks(ss);
697 if (rv != SECSuccess) {
698 ss->opt.noLocks = PR_TRUE;
701 break;
703 case SSL_ENABLE_SESSION_TICKETS:
704 ss->opt.enableSessionTickets = on;
705 break;
707 default:
708 PORT_SetError(SEC_ERROR_INVALID_ARGS);
709 rv = SECFailure;
712 /* We can't use the macros for releasing the locks here,
713 * because ss->opt.noLocks might have changed just above.
714 * We must release these locks (monitors) here, if we aquired them above,
715 * regardless of the current value of ss->opt.noLocks.
717 if (holdingLocks) {
718 PZ_ExitMonitor((ss)->ssl3HandshakeLock);
719 PZ_ExitMonitor((ss)->firstHandshakeLock);
722 return rv;
725 SECStatus
726 SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn)
728 sslSocket *ss = ssl_FindSocket(fd);
729 SECStatus rv = SECSuccess;
730 PRBool on = PR_FALSE;
732 if (!pOn) {
733 PORT_SetError(SEC_ERROR_INVALID_ARGS);
734 return SECFailure;
736 if (!ss) {
737 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
738 *pOn = PR_FALSE;
739 return SECFailure;
742 ssl_Get1stHandshakeLock(ss);
743 ssl_GetSSL3HandshakeLock(ss);
745 switch (which) {
746 case SSL_SOCKS: on = PR_FALSE; break;
747 case SSL_SECURITY: on = ss->opt.useSecurity; break;
748 case SSL_REQUEST_CERTIFICATE: on = ss->opt.requestCertificate; break;
749 case SSL_REQUIRE_CERTIFICATE: on = ss->opt.requireCertificate; break;
750 case SSL_HANDSHAKE_AS_CLIENT: on = ss->opt.handshakeAsClient; break;
751 case SSL_HANDSHAKE_AS_SERVER: on = ss->opt.handshakeAsServer; break;
752 case SSL_ENABLE_TLS: on = ss->opt.enableTLS; break;
753 case SSL_ENABLE_SSL3: on = ss->opt.enableSSL3; break;
754 case SSL_ENABLE_SSL2: on = ss->opt.enableSSL2; break;
755 case SSL_NO_CACHE: on = ss->opt.noCache; break;
756 case SSL_ENABLE_FDX: on = ss->opt.fdx; break;
757 case SSL_V2_COMPATIBLE_HELLO: on = ss->opt.v2CompatibleHello; break;
758 case SSL_ROLLBACK_DETECTION: on = ss->opt.detectRollBack; break;
759 case SSL_NO_STEP_DOWN: on = ss->opt.noStepDown; break;
760 case SSL_BYPASS_PKCS11: on = ss->opt.bypassPKCS11; break;
761 case SSL_NO_LOCKS: on = ss->opt.noLocks; break;
762 case SSL_ENABLE_SESSION_TICKETS:
763 on = ss->opt.enableSessionTickets;
764 break;
766 default:
767 PORT_SetError(SEC_ERROR_INVALID_ARGS);
768 rv = SECFailure;
771 ssl_ReleaseSSL3HandshakeLock(ss);
772 ssl_Release1stHandshakeLock(ss);
774 *pOn = on;
775 return rv;
778 SECStatus
779 SSL_OptionGetDefault(PRInt32 which, PRBool *pOn)
781 SECStatus rv = SECSuccess;
782 PRBool on = PR_FALSE;
784 if (!pOn) {
785 PORT_SetError(SEC_ERROR_INVALID_ARGS);
786 return SECFailure;
789 switch (which) {
790 case SSL_SOCKS: on = PR_FALSE; break;
791 case SSL_SECURITY: on = ssl_defaults.useSecurity; break;
792 case SSL_REQUEST_CERTIFICATE: on = ssl_defaults.requestCertificate; break;
793 case SSL_REQUIRE_CERTIFICATE: on = ssl_defaults.requireCertificate; break;
794 case SSL_HANDSHAKE_AS_CLIENT: on = ssl_defaults.handshakeAsClient; break;
795 case SSL_HANDSHAKE_AS_SERVER: on = ssl_defaults.handshakeAsServer; break;
796 case SSL_ENABLE_TLS: on = ssl_defaults.enableTLS; break;
797 case SSL_ENABLE_SSL3: on = ssl_defaults.enableSSL3; break;
798 case SSL_ENABLE_SSL2: on = ssl_defaults.enableSSL2; break;
799 case SSL_NO_CACHE: on = ssl_defaults.noCache; break;
800 case SSL_ENABLE_FDX: on = ssl_defaults.fdx; break;
801 case SSL_V2_COMPATIBLE_HELLO: on = ssl_defaults.v2CompatibleHello; break;
802 case SSL_ROLLBACK_DETECTION: on = ssl_defaults.detectRollBack; break;
803 case SSL_NO_STEP_DOWN: on = ssl_defaults.noStepDown; break;
804 case SSL_BYPASS_PKCS11: on = ssl_defaults.bypassPKCS11; break;
805 case SSL_NO_LOCKS: on = ssl_defaults.noLocks; break;
806 case SSL_ENABLE_SESSION_TICKETS:
807 on = ssl_defaults.enableSessionTickets;
808 break;
810 default:
811 PORT_SetError(SEC_ERROR_INVALID_ARGS);
812 rv = SECFailure;
815 *pOn = on;
816 return rv;
819 /* XXX Use Global Lock to protect this stuff. */
820 SECStatus
821 SSL_EnableDefault(int which, PRBool on)
823 return SSL_OptionSetDefault(which, on);
826 SECStatus
827 SSL_OptionSetDefault(PRInt32 which, PRBool on)
829 switch (which) {
830 case SSL_SOCKS:
831 ssl_defaults.useSocks = PR_FALSE;
832 if (on) {
833 PORT_SetError(SEC_ERROR_INVALID_ARGS);
834 return SECFailure;
836 break;
838 case SSL_SECURITY:
839 ssl_defaults.useSecurity = on;
840 break;
842 case SSL_REQUEST_CERTIFICATE:
843 ssl_defaults.requestCertificate = on;
844 break;
846 case SSL_REQUIRE_CERTIFICATE:
847 ssl_defaults.requireCertificate = on;
848 break;
850 case SSL_HANDSHAKE_AS_CLIENT:
851 if ( ssl_defaults.handshakeAsServer && on ) {
852 PORT_SetError(SEC_ERROR_INVALID_ARGS);
853 return SECFailure;
855 ssl_defaults.handshakeAsClient = on;
856 break;
858 case SSL_HANDSHAKE_AS_SERVER:
859 if ( ssl_defaults.handshakeAsClient && on ) {
860 PORT_SetError(SEC_ERROR_INVALID_ARGS);
861 return SECFailure;
863 ssl_defaults.handshakeAsServer = on;
864 break;
866 case SSL_ENABLE_TLS:
867 ssl_defaults.enableTLS = on;
868 break;
870 case SSL_ENABLE_SSL3:
871 ssl_defaults.enableSSL3 = on;
872 break;
874 case SSL_ENABLE_SSL2:
875 ssl_defaults.enableSSL2 = on;
876 if (on) {
877 ssl_defaults.v2CompatibleHello = on;
879 break;
881 case SSL_NO_CACHE:
882 ssl_defaults.noCache = on;
883 break;
885 case SSL_ENABLE_FDX:
886 if (on && ssl_defaults.noLocks) {
887 PORT_SetError(SEC_ERROR_INVALID_ARGS);
888 return SECFailure;
890 ssl_defaults.fdx = on;
891 break;
893 case SSL_V2_COMPATIBLE_HELLO:
894 ssl_defaults.v2CompatibleHello = on;
895 if (!on) {
896 ssl_defaults.enableSSL2 = on;
898 break;
900 case SSL_ROLLBACK_DETECTION:
901 ssl_defaults.detectRollBack = on;
902 break;
904 case SSL_NO_STEP_DOWN:
905 ssl_defaults.noStepDown = on;
906 if (on)
907 SSL_DisableDefaultExportCipherSuites();
908 break;
910 case SSL_BYPASS_PKCS11:
911 if (PR_FALSE != on) {
912 if (PR_SUCCESS == SSL_BypassSetup()) {
913 ssl_defaults.bypassPKCS11 = on;
914 } else {
915 return SECFailure;
917 } else {
918 ssl_defaults.bypassPKCS11 = PR_FALSE;
920 break;
922 case SSL_NO_LOCKS:
923 if (on && ssl_defaults.fdx) {
924 PORT_SetError(SEC_ERROR_INVALID_ARGS);
925 return SECFailure;
927 if (on && ssl_force_locks)
928 on = PR_FALSE; /* silent override */
929 ssl_defaults.noLocks = on;
930 if (on) {
931 locksEverDisabled = PR_TRUE;
932 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
934 break;
936 case SSL_ENABLE_SESSION_TICKETS:
937 ssl_defaults.enableSessionTickets = on;
938 break;
940 default:
941 PORT_SetError(SEC_ERROR_INVALID_ARGS);
942 return SECFailure;
944 return SECSuccess;
947 /* function tells us if the cipher suite is one that we no longer support. */
948 static PRBool
949 ssl_IsRemovedCipherSuite(PRInt32 suite)
951 switch (suite) {
952 case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
953 case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
954 case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA:
955 return PR_TRUE;
956 default:
957 return PR_FALSE;
961 /* Part of the public NSS API.
962 * Since this is a global (not per-socket) setting, we cannot use the
963 * HandshakeLock to protect this. Probably want a global lock.
965 SECStatus
966 SSL_SetPolicy(long which, int policy)
968 if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
969 /* one of the two old FIPS ciphers */
970 if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
971 which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
972 else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
973 which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
975 if (ssl_IsRemovedCipherSuite(which))
976 return SECSuccess;
977 return SSL_CipherPolicySet(which, policy);
980 SECStatus
981 SSL_CipherPolicySet(PRInt32 which, PRInt32 policy)
983 SECStatus rv;
985 if (ssl_IsRemovedCipherSuite(which)) {
986 rv = SECSuccess;
987 } else if (SSL_IS_SSL2_CIPHER(which)) {
988 rv = ssl2_SetPolicy(which, policy);
989 } else {
990 rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy);
992 return rv;
995 SECStatus
996 SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy)
998 SECStatus rv;
1000 if (!oPolicy) {
1001 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1002 return SECFailure;
1004 if (ssl_IsRemovedCipherSuite(which)) {
1005 *oPolicy = SSL_NOT_ALLOWED;
1006 rv = SECSuccess;
1007 } else if (SSL_IS_SSL2_CIPHER(which)) {
1008 rv = ssl2_GetPolicy(which, oPolicy);
1009 } else {
1010 rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy);
1012 return rv;
1015 /* Part of the public NSS API.
1016 * Since this is a global (not per-socket) setting, we cannot use the
1017 * HandshakeLock to protect this. Probably want a global lock.
1018 * These changes have no effect on any sslSockets already created.
1020 SECStatus
1021 SSL_EnableCipher(long which, PRBool enabled)
1023 if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
1024 /* one of the two old FIPS ciphers */
1025 if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
1026 which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
1027 else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
1028 which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
1030 if (ssl_IsRemovedCipherSuite(which))
1031 return SECSuccess;
1032 return SSL_CipherPrefSetDefault(which, enabled);
1035 SECStatus
1036 SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
1038 SECStatus rv;
1040 if (ssl_IsRemovedCipherSuite(which))
1041 return SECSuccess;
1042 if (enabled && ssl_defaults.noStepDown && SSL_IsExportCipherSuite(which)) {
1043 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1044 return SECFailure;
1046 if (SSL_IS_SSL2_CIPHER(which)) {
1047 rv = ssl2_CipherPrefSetDefault(which, enabled);
1048 } else {
1049 rv = ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled);
1051 return rv;
1054 SECStatus
1055 SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
1057 SECStatus rv;
1059 if (!enabled) {
1060 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1061 return SECFailure;
1063 if (ssl_IsRemovedCipherSuite(which)) {
1064 *enabled = PR_FALSE;
1065 rv = SECSuccess;
1066 } else if (SSL_IS_SSL2_CIPHER(which)) {
1067 rv = ssl2_CipherPrefGetDefault(which, enabled);
1068 } else {
1069 rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled);
1071 return rv;
1074 SECStatus
1075 SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled)
1077 SECStatus rv;
1078 sslSocket *ss = ssl_FindSocket(fd);
1080 if (!ss) {
1081 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefSet", SSL_GETPID(), fd));
1082 return SECFailure;
1084 if (ssl_IsRemovedCipherSuite(which))
1085 return SECSuccess;
1086 if (enabled && ss->opt.noStepDown && SSL_IsExportCipherSuite(which)) {
1087 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1088 return SECFailure;
1090 if (SSL_IS_SSL2_CIPHER(which)) {
1091 rv = ssl2_CipherPrefSet(ss, which, enabled);
1092 } else {
1093 rv = ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled);
1095 return rv;
1098 SECStatus
1099 SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled)
1101 SECStatus rv;
1102 sslSocket *ss = ssl_FindSocket(fd);
1104 if (!enabled) {
1105 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1106 return SECFailure;
1108 if (!ss) {
1109 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefGet", SSL_GETPID(), fd));
1110 *enabled = PR_FALSE;
1111 return SECFailure;
1113 if (ssl_IsRemovedCipherSuite(which)) {
1114 *enabled = PR_FALSE;
1115 rv = SECSuccess;
1116 } else if (SSL_IS_SSL2_CIPHER(which)) {
1117 rv = ssl2_CipherPrefGet(ss, which, enabled);
1118 } else {
1119 rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled);
1121 return rv;
1124 SECStatus
1125 NSS_SetDomesticPolicy(void)
1127 #ifndef EXPORT_VERSION
1128 SECStatus status = SECSuccess;
1129 cipherPolicy * policy;
1131 for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
1132 status = SSL_SetPolicy(policy->cipher, SSL_ALLOWED);
1133 if (status != SECSuccess)
1134 break;
1136 return status;
1137 #else
1138 return NSS_SetExportPolicy();
1139 #endif
1142 SECStatus
1143 NSS_SetExportPolicy(void)
1145 SECStatus status = SECSuccess;
1146 cipherPolicy * policy;
1148 for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
1149 status = SSL_SetPolicy(policy->cipher, policy->export);
1150 if (status != SECSuccess)
1151 break;
1153 return status;
1156 SECStatus
1157 NSS_SetFrancePolicy(void)
1159 SECStatus status = SECSuccess;
1160 cipherPolicy * policy;
1162 for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
1163 status = SSL_SetPolicy(policy->cipher, policy->france);
1164 if (status != SECSuccess)
1165 break;
1167 return status;
1172 /* LOCKS ??? XXX */
1173 PRFileDesc *
1174 SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd)
1176 sslSocket * ns = NULL;
1177 PRStatus rv;
1178 PRNetAddr addr;
1180 if (model == NULL) {
1181 /* Just create a default socket if we're given NULL for the model */
1182 ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks));
1183 } else {
1184 sslSocket * ss = ssl_FindSocket(model);
1185 if (ss == NULL) {
1186 SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD",
1187 SSL_GETPID(), model));
1188 return NULL;
1190 ns = ssl_DupSocket(ss);
1192 if (ns == NULL)
1193 return NULL;
1195 rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER);
1196 if (rv != PR_SUCCESS) {
1197 ssl_FreeSocket(ns);
1198 SET_ERROR_CODE
1199 return NULL;
1201 #ifdef _WIN32
1202 PR_Sleep(PR_INTERVAL_NO_WAIT); /* workaround NT winsock connect bug. */
1203 #endif
1204 ns = ssl_FindSocket(fd);
1205 PORT_Assert(ns);
1206 if (ns)
1207 ns->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ns, &addr));
1208 return fd;
1211 /************************************************************************/
1212 /* The following functions are the TOP LEVEL SSL functions.
1213 ** They all get called through the NSPRIOMethods table below.
1216 static PRFileDesc * PR_CALLBACK
1217 ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout)
1219 sslSocket *ss;
1220 sslSocket *ns = NULL;
1221 PRFileDesc *newfd = NULL;
1222 PRFileDesc *osfd;
1223 PRStatus status;
1225 ss = ssl_GetPrivate(fd);
1226 if (!ss) {
1227 SSL_DBG(("%d: SSL[%d]: bad socket in accept", SSL_GETPID(), fd));
1228 return NULL;
1231 /* IF this is a listen socket, there shouldn't be any I/O going on */
1232 SSL_LOCK_READER(ss);
1233 SSL_LOCK_WRITER(ss);
1234 ssl_Get1stHandshakeLock(ss);
1235 ssl_GetSSL3HandshakeLock(ss);
1237 ss->cTimeout = timeout;
1239 osfd = ss->fd->lower;
1241 /* First accept connection */
1242 newfd = osfd->methods->accept(osfd, sockaddr, timeout);
1243 if (newfd == NULL) {
1244 SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d",
1245 SSL_GETPID(), ss->fd, PORT_GetError()));
1246 } else {
1247 /* Create ssl module */
1248 ns = ssl_DupSocket(ss);
1251 ssl_ReleaseSSL3HandshakeLock(ss);
1252 ssl_Release1stHandshakeLock(ss);
1253 SSL_UNLOCK_WRITER(ss);
1254 SSL_UNLOCK_READER(ss); /* ss isn't used below here. */
1256 if (ns == NULL)
1257 goto loser;
1259 /* push ssl module onto the new socket */
1260 status = ssl_PushIOLayer(ns, newfd, PR_TOP_IO_LAYER);
1261 if (status != PR_SUCCESS)
1262 goto loser;
1264 /* Now start server connection handshake with client.
1265 ** Don't need locks here because nobody else has a reference to ns yet.
1267 if ( ns->opt.useSecurity ) {
1268 if ( ns->opt.handshakeAsClient ) {
1269 ns->handshake = ssl2_BeginClientHandshake;
1270 ss->handshaking = sslHandshakingAsClient;
1271 } else {
1272 ns->handshake = ssl2_BeginServerHandshake;
1273 ss->handshaking = sslHandshakingAsServer;
1276 ns->TCPconnected = 1;
1277 return newfd;
1279 loser:
1280 if (ns != NULL)
1281 ssl_FreeSocket(ns);
1282 if (newfd != NULL)
1283 PR_Close(newfd);
1284 return NULL;
1287 static PRStatus PR_CALLBACK
1288 ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout)
1290 sslSocket *ss;
1291 PRStatus rv;
1293 ss = ssl_GetPrivate(fd);
1294 if (!ss) {
1295 SSL_DBG(("%d: SSL[%d]: bad socket in connect", SSL_GETPID(), fd));
1296 return PR_FAILURE;
1299 /* IF this is a listen socket, there shouldn't be any I/O going on */
1300 SSL_LOCK_READER(ss);
1301 SSL_LOCK_WRITER(ss);
1303 ss->cTimeout = timeout;
1304 rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr);
1305 #ifdef _WIN32
1306 PR_Sleep(PR_INTERVAL_NO_WAIT); /* workaround NT winsock connect bug. */
1307 #endif
1309 SSL_UNLOCK_WRITER(ss);
1310 SSL_UNLOCK_READER(ss);
1312 return rv;
1315 static PRStatus PR_CALLBACK
1316 ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr)
1318 sslSocket * ss = ssl_GetPrivate(fd);
1319 PRStatus rv;
1321 if (!ss) {
1322 SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd));
1323 return PR_FAILURE;
1325 SSL_LOCK_READER(ss);
1326 SSL_LOCK_WRITER(ss);
1328 rv = (PRStatus)(*ss->ops->bind)(ss, addr);
1330 SSL_UNLOCK_WRITER(ss);
1331 SSL_UNLOCK_READER(ss);
1332 return rv;
1335 static PRStatus PR_CALLBACK
1336 ssl_Listen(PRFileDesc *fd, PRIntn backlog)
1338 sslSocket * ss = ssl_GetPrivate(fd);
1339 PRStatus rv;
1341 if (!ss) {
1342 SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd));
1343 return PR_FAILURE;
1345 SSL_LOCK_READER(ss);
1346 SSL_LOCK_WRITER(ss);
1348 rv = (PRStatus)(*ss->ops->listen)(ss, backlog);
1350 SSL_UNLOCK_WRITER(ss);
1351 SSL_UNLOCK_READER(ss);
1352 return rv;
1355 static PRStatus PR_CALLBACK
1356 ssl_Shutdown(PRFileDesc *fd, PRIntn how)
1358 sslSocket * ss = ssl_GetPrivate(fd);
1359 PRStatus rv;
1361 if (!ss) {
1362 SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd));
1363 return PR_FAILURE;
1365 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
1366 SSL_LOCK_READER(ss);
1368 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
1369 SSL_LOCK_WRITER(ss);
1372 rv = (PRStatus)(*ss->ops->shutdown)(ss, how);
1374 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
1375 SSL_UNLOCK_WRITER(ss);
1377 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
1378 SSL_UNLOCK_READER(ss);
1380 return rv;
1383 static PRStatus PR_CALLBACK
1384 ssl_Close(PRFileDesc *fd)
1386 sslSocket *ss;
1387 PRStatus rv;
1389 ss = ssl_GetPrivate(fd);
1390 if (!ss) {
1391 SSL_DBG(("%d: SSL[%d]: bad socket in close", SSL_GETPID(), fd));
1392 return PR_FAILURE;
1395 /* There must not be any I/O going on */
1396 SSL_LOCK_READER(ss);
1397 SSL_LOCK_WRITER(ss);
1399 /* By the time this function returns,
1400 ** ss is an invalid pointer, and the locks to which it points have
1401 ** been unlocked and freed. So, this is the ONE PLACE in all of SSL
1402 ** where the LOCK calls and the corresponding UNLOCK calls are not in
1403 ** the same function scope. The unlock calls are in ssl_FreeSocket().
1405 rv = (PRStatus)(*ss->ops->close)(ss);
1407 return rv;
1410 static int PR_CALLBACK
1411 ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
1412 PRIntervalTime timeout)
1414 sslSocket *ss;
1415 int rv;
1417 ss = ssl_GetPrivate(fd);
1418 if (!ss) {
1419 SSL_DBG(("%d: SSL[%d]: bad socket in recv", SSL_GETPID(), fd));
1420 return SECFailure;
1422 SSL_LOCK_READER(ss);
1423 ss->rTimeout = timeout;
1424 if (!ss->opt.fdx)
1425 ss->wTimeout = timeout;
1426 rv = (*ss->ops->recv)(ss, (unsigned char*)buf, len, flags);
1427 SSL_UNLOCK_READER(ss);
1428 return rv;
1431 static int PR_CALLBACK
1432 ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
1433 PRIntervalTime timeout)
1435 sslSocket *ss;
1436 int rv;
1438 ss = ssl_GetPrivate(fd);
1439 if (!ss) {
1440 SSL_DBG(("%d: SSL[%d]: bad socket in send", SSL_GETPID(), fd));
1441 return SECFailure;
1443 SSL_LOCK_WRITER(ss);
1444 ss->wTimeout = timeout;
1445 if (!ss->opt.fdx)
1446 ss->rTimeout = timeout;
1447 rv = (*ss->ops->send)(ss, (const unsigned char*)buf, len, flags);
1448 SSL_UNLOCK_WRITER(ss);
1449 return rv;
1452 static int PR_CALLBACK
1453 ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len)
1455 sslSocket *ss;
1456 int rv;
1458 ss = ssl_GetPrivate(fd);
1459 if (!ss) {
1460 SSL_DBG(("%d: SSL[%d]: bad socket in read", SSL_GETPID(), fd));
1461 return SECFailure;
1463 SSL_LOCK_READER(ss);
1464 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
1465 if (!ss->opt.fdx)
1466 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
1467 rv = (*ss->ops->read)(ss, (unsigned char*)buf, len);
1468 SSL_UNLOCK_READER(ss);
1469 return rv;
1472 static int PR_CALLBACK
1473 ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
1475 sslSocket *ss;
1476 int rv;
1478 ss = ssl_GetPrivate(fd);
1479 if (!ss) {
1480 SSL_DBG(("%d: SSL[%d]: bad socket in write", SSL_GETPID(), fd));
1481 return SECFailure;
1483 SSL_LOCK_WRITER(ss);
1484 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
1485 if (!ss->opt.fdx)
1486 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
1487 rv = (*ss->ops->write)(ss, (const unsigned char*)buf, len);
1488 SSL_UNLOCK_WRITER(ss);
1489 return rv;
1492 static PRStatus PR_CALLBACK
1493 ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
1495 sslSocket *ss;
1497 ss = ssl_GetPrivate(fd);
1498 if (!ss) {
1499 SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd));
1500 return PR_FAILURE;
1502 return (PRStatus)(*ss->ops->getpeername)(ss, addr);
1507 SECStatus
1508 ssl_GetPeerInfo(sslSocket *ss)
1510 PRFileDesc * osfd;
1511 int rv;
1512 PRNetAddr sin;
1514 osfd = ss->fd->lower;
1516 PORT_Memset(&sin, 0, sizeof(sin));
1517 rv = osfd->methods->getpeername(osfd, &sin);
1518 if (rv < 0) {
1519 return SECFailure;
1521 ss->TCPconnected = 1;
1522 if (sin.inet.family == PR_AF_INET) {
1523 PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer);
1524 ss->sec.ci.port = sin.inet.port;
1525 } else if (sin.ipv6.family == PR_AF_INET6) {
1526 ss->sec.ci.peer = sin.ipv6.ip;
1527 ss->sec.ci.port = sin.ipv6.port;
1528 } else {
1529 PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR);
1530 return SECFailure;
1532 return SECSuccess;
1535 static PRStatus PR_CALLBACK
1536 ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name)
1538 sslSocket *ss;
1540 ss = ssl_GetPrivate(fd);
1541 if (!ss) {
1542 SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd));
1543 return PR_FAILURE;
1545 return (PRStatus)(*ss->ops->getsockname)(ss, name);
1548 SECStatus PR_CALLBACK
1549 SSL_SetSockPeerID(PRFileDesc *fd, char *peerID)
1551 sslSocket *ss;
1553 ss = ssl_FindSocket(fd);
1554 if (!ss) {
1555 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetCacheIndex",
1556 SSL_GETPID(), fd));
1557 return SECFailure;
1560 ss->peerID = PORT_Strdup(peerID);
1561 return SECSuccess;
1564 #define PR_POLL_RW (PR_POLL_WRITE | PR_POLL_READ)
1566 static PRInt16 PR_CALLBACK
1567 ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags)
1569 sslSocket *ss;
1570 PRInt16 new_flags = how_flags; /* should select on these flags. */
1571 PRNetAddr addr;
1573 *p_out_flags = 0;
1574 ss = ssl_GetPrivate(fd);
1575 if (!ss) {
1576 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll",
1577 SSL_GETPID(), fd));
1578 return 0; /* don't poll on this socket */
1581 if (ss->opt.useSecurity &&
1582 ss->handshaking != sslHandshakingUndetermined &&
1583 !ss->firstHsDone &&
1584 (how_flags & PR_POLL_RW)) {
1585 if (!ss->TCPconnected) {
1586 ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
1588 /* If it's not connected, then presumably the application is polling
1589 ** on read or write appropriately, so don't change it.
1591 if (ss->TCPconnected) {
1592 if (!ss->handshakeBegun) {
1593 /* If the handshake has not begun, poll on read or write
1594 ** based on the local application's role in the handshake,
1595 ** not based on what the application requested.
1597 new_flags &= ~PR_POLL_RW;
1598 if (ss->handshaking == sslHandshakingAsClient) {
1599 new_flags |= PR_POLL_WRITE;
1600 } else { /* handshaking as server */
1601 new_flags |= PR_POLL_READ;
1603 } else
1604 /* First handshake is in progress */
1605 if (ss->lastWriteBlocked) {
1606 if (new_flags & PR_POLL_READ) {
1607 /* The caller is waiting for data to be received,
1608 ** but the initial handshake is blocked on write, or the
1609 ** client's first handshake record has not been written.
1610 ** The code should select on write, not read.
1612 new_flags ^= PR_POLL_READ; /* don't select on read. */
1613 new_flags |= PR_POLL_WRITE; /* do select on write. */
1615 } else if (new_flags & PR_POLL_WRITE) {
1616 /* The caller is trying to write, but the handshake is
1617 ** blocked waiting for data to read, and the first
1618 ** handshake has been sent. so do NOT to poll on write.
1620 new_flags ^= PR_POLL_WRITE; /* don't select on write. */
1621 new_flags |= PR_POLL_READ; /* do select on read. */
1624 } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) {
1625 *p_out_flags = PR_POLL_READ; /* it's ready already. */
1626 return new_flags;
1627 } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) &&
1628 (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */
1629 new_flags |= PR_POLL_WRITE; /* also select on write. */
1631 if (new_flags && (fd->lower->methods->poll != NULL)) {
1632 PRInt16 lower_out_flags = 0;
1633 PRInt16 lower_new_flags;
1634 lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags,
1635 &lower_out_flags);
1636 if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) {
1637 PRInt16 out_flags = lower_out_flags & ~PR_POLL_RW;
1638 if (lower_out_flags & PR_POLL_READ)
1639 out_flags |= PR_POLL_WRITE;
1640 if (lower_out_flags & PR_POLL_WRITE)
1641 out_flags |= PR_POLL_READ;
1642 *p_out_flags = out_flags;
1643 new_flags = how_flags;
1644 } else {
1645 *p_out_flags = lower_out_flags;
1646 new_flags = lower_new_flags;
1650 return new_flags;
1653 static PRInt32 PR_CALLBACK
1654 ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd,
1655 const void *headers, PRInt32 hlen,
1656 PRTransmitFileFlags flags, PRIntervalTime timeout)
1658 PRSendFileData sfd;
1660 sfd.fd = fd;
1661 sfd.file_offset = 0;
1662 sfd.file_nbytes = 0;
1663 sfd.header = headers;
1664 sfd.hlen = hlen;
1665 sfd.trailer = NULL;
1666 sfd.tlen = 0;
1668 return sd->methods->sendfile(sd, &sfd, flags, timeout);
1672 PRBool
1673 ssl_FdIsBlocking(PRFileDesc *fd)
1675 PRSocketOptionData opt;
1676 PRStatus status;
1678 opt.option = PR_SockOpt_Nonblocking;
1679 opt.value.non_blocking = PR_FALSE;
1680 status = PR_GetSocketOption(fd, &opt);
1681 if (status != PR_SUCCESS)
1682 return PR_FALSE;
1683 return (PRBool)!opt.value.non_blocking;
1686 PRBool
1687 ssl_SocketIsBlocking(sslSocket *ss)
1689 return ssl_FdIsBlocking(ss->fd);
1692 PRInt32 sslFirstBufSize = 8 * 1024;
1693 PRInt32 sslCopyLimit = 1024;
1695 static PRInt32 PR_CALLBACK
1696 ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors,
1697 PRIntervalTime timeout)
1699 PRInt32 bufLen;
1700 PRInt32 left;
1701 PRInt32 rv;
1702 PRInt32 sent = 0;
1703 const PRInt32 first_len = sslFirstBufSize;
1704 const PRInt32 limit = sslCopyLimit;
1705 PRBool blocking;
1706 PRIOVec myIov = { 0, 0 };
1707 char buf[MAX_FRAGMENT_LENGTH];
1709 if (vectors > PR_MAX_IOVECTOR_SIZE) {
1710 PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
1711 return -1;
1713 blocking = ssl_FdIsBlocking(fd);
1715 #define K16 sizeof(buf)
1716 #define KILL_VECTORS while (vectors && !iov->iov_len) { ++iov; --vectors; }
1717 #define GET_VECTOR do { myIov = *iov++; --vectors; KILL_VECTORS } while (0)
1718 #define HANDLE_ERR(rv, len) \
1719 if (rv != len) { \
1720 if (rv < 0) { \
1721 if (!blocking \
1722 && (PR_GetError() == PR_WOULD_BLOCK_ERROR) \
1723 && (sent > 0)) { \
1724 return sent; \
1725 } else { \
1726 return -1; \
1729 /* Only a nonblocking socket can have partial sends */ \
1730 PR_ASSERT(!blocking); \
1731 return sent + rv; \
1733 #define SEND(bfr, len) \
1734 do { \
1735 rv = ssl_Send(fd, bfr, len, 0, timeout); \
1736 HANDLE_ERR(rv, len) \
1737 sent += len; \
1738 } while (0)
1740 /* Make sure the first write is at least 8 KB, if possible. */
1741 KILL_VECTORS
1742 if (!vectors)
1743 return ssl_Send(fd, 0, 0, 0, timeout);
1744 GET_VECTOR;
1745 if (!vectors) {
1746 return ssl_Send(fd, myIov.iov_base, myIov.iov_len, 0, timeout);
1748 if (myIov.iov_len < first_len) {
1749 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
1750 bufLen = myIov.iov_len;
1751 left = first_len - bufLen;
1752 while (vectors && left) {
1753 int toCopy;
1754 GET_VECTOR;
1755 toCopy = PR_MIN(left, myIov.iov_len);
1756 PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy);
1757 bufLen += toCopy;
1758 left -= toCopy;
1759 myIov.iov_base += toCopy;
1760 myIov.iov_len -= toCopy;
1762 SEND( buf, bufLen );
1765 while (vectors || myIov.iov_len) {
1766 PRInt32 addLen;
1767 if (!myIov.iov_len) {
1768 GET_VECTOR;
1770 while (myIov.iov_len >= K16) {
1771 SEND(myIov.iov_base, K16);
1772 myIov.iov_base += K16;
1773 myIov.iov_len -= K16;
1775 if (!myIov.iov_len)
1776 continue;
1778 if (!vectors || myIov.iov_len > limit) {
1779 addLen = 0;
1780 } else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) {
1781 /* Addlen is already computed. */;
1782 } else if (vectors > 1 &&
1783 iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) {
1784 addLen = limit - myIov.iov_len;
1785 } else
1786 addLen = 0;
1788 if (!addLen) {
1789 SEND( myIov.iov_base, myIov.iov_len );
1790 myIov.iov_len = 0;
1791 continue;
1793 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
1794 bufLen = myIov.iov_len;
1795 do {
1796 GET_VECTOR;
1797 PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen);
1798 myIov.iov_base += addLen;
1799 myIov.iov_len -= addLen;
1800 bufLen += addLen;
1802 left = PR_MIN( limit, K16 - bufLen);
1803 if (!vectors /* no more left */
1804 || myIov.iov_len > 0 /* we didn't use that one all up */
1805 || bufLen >= K16 /* it's full. */
1807 addLen = 0;
1808 } else if ((addLen = iov->iov_len % K16) <= left) {
1809 /* Addlen is already computed. */;
1810 } else if (vectors > 1 &&
1811 iov[1].iov_len % K16 + addLen <= left + limit) {
1812 addLen = left;
1813 } else
1814 addLen = 0;
1816 } while (addLen);
1817 SEND( buf, bufLen );
1819 return sent;
1823 * These functions aren't implemented.
1826 static PRInt32 PR_CALLBACK
1827 ssl_Available(PRFileDesc *fd)
1829 PORT_Assert(0);
1830 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1831 return SECFailure;
1834 static PRInt64 PR_CALLBACK
1835 ssl_Available64(PRFileDesc *fd)
1837 PRInt64 res;
1839 PORT_Assert(0);
1840 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1841 LL_I2L(res, -1L);
1842 return res;
1845 static PRStatus PR_CALLBACK
1846 ssl_FSync(PRFileDesc *fd)
1848 PORT_Assert(0);
1849 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1850 return PR_FAILURE;
1853 static PRInt32 PR_CALLBACK
1854 ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) {
1855 PORT_Assert(0);
1856 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1857 return SECFailure;
1860 static PRInt64 PR_CALLBACK
1861 ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) {
1862 PRInt64 res;
1864 PORT_Assert(0);
1865 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1866 LL_I2L(res, -1L);
1867 return res;
1870 static PRStatus PR_CALLBACK
1871 ssl_FileInfo(PRFileDesc *fd, PRFileInfo *info)
1873 PORT_Assert(0);
1874 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1875 return PR_FAILURE;
1878 static PRStatus PR_CALLBACK
1879 ssl_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
1881 PORT_Assert(0);
1882 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1883 return PR_FAILURE;
1886 static PRInt32 PR_CALLBACK
1887 ssl_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
1888 PRNetAddr *addr, PRIntervalTime timeout)
1890 PORT_Assert(0);
1891 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1892 return SECFailure;
1895 static PRInt32 PR_CALLBACK
1896 ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
1897 const PRNetAddr *addr, PRIntervalTime timeout)
1899 PORT_Assert(0);
1900 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1901 return SECFailure;
1904 static const PRIOMethods ssl_methods = {
1905 PR_DESC_LAYERED,
1906 ssl_Close, /* close */
1907 ssl_Read, /* read */
1908 ssl_Write, /* write */
1909 ssl_Available, /* available */
1910 ssl_Available64, /* available64 */
1911 ssl_FSync, /* fsync */
1912 ssl_Seek, /* seek */
1913 ssl_Seek64, /* seek64 */
1914 ssl_FileInfo, /* fileInfo */
1915 ssl_FileInfo64, /* fileInfo64 */
1916 ssl_WriteV, /* writev */
1917 ssl_Connect, /* connect */
1918 ssl_Accept, /* accept */
1919 ssl_Bind, /* bind */
1920 ssl_Listen, /* listen */
1921 ssl_Shutdown, /* shutdown */
1922 ssl_Recv, /* recv */
1923 ssl_Send, /* send */
1924 ssl_RecvFrom, /* recvfrom */
1925 ssl_SendTo, /* sendto */
1926 ssl_Poll, /* poll */
1927 PR_EmulateAcceptRead, /* acceptread */
1928 ssl_TransmitFile, /* transmitfile */
1929 ssl_GetSockName, /* getsockname */
1930 ssl_GetPeerName, /* getpeername */
1931 NULL, /* getsockopt OBSOLETE */
1932 NULL, /* setsockopt OBSOLETE */
1933 NULL, /* getsocketoption */
1934 NULL, /* setsocketoption */
1935 PR_EmulateSendFile, /* Send a (partial) file with header/trailer*/
1936 NULL, /* reserved for future use */
1937 NULL, /* reserved for future use */
1938 NULL, /* reserved for future use */
1939 NULL, /* reserved for future use */
1940 NULL /* reserved for future use */
1944 static PRIOMethods combined_methods;
1946 static void
1947 ssl_SetupIOMethods(void)
1949 PRIOMethods *new_methods = &combined_methods;
1950 const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods();
1951 const PRIOMethods *my_methods = &ssl_methods;
1953 *new_methods = *nspr_methods;
1955 new_methods->file_type = my_methods->file_type;
1956 new_methods->close = my_methods->close;
1957 new_methods->read = my_methods->read;
1958 new_methods->write = my_methods->write;
1959 new_methods->available = my_methods->available;
1960 new_methods->available64 = my_methods->available64;
1961 new_methods->fsync = my_methods->fsync;
1962 new_methods->seek = my_methods->seek;
1963 new_methods->seek64 = my_methods->seek64;
1964 new_methods->fileInfo = my_methods->fileInfo;
1965 new_methods->fileInfo64 = my_methods->fileInfo64;
1966 new_methods->writev = my_methods->writev;
1967 new_methods->connect = my_methods->connect;
1968 new_methods->accept = my_methods->accept;
1969 new_methods->bind = my_methods->bind;
1970 new_methods->listen = my_methods->listen;
1971 new_methods->shutdown = my_methods->shutdown;
1972 new_methods->recv = my_methods->recv;
1973 new_methods->send = my_methods->send;
1974 new_methods->recvfrom = my_methods->recvfrom;
1975 new_methods->sendto = my_methods->sendto;
1976 new_methods->poll = my_methods->poll;
1977 new_methods->acceptread = my_methods->acceptread;
1978 new_methods->transmitfile = my_methods->transmitfile;
1979 new_methods->getsockname = my_methods->getsockname;
1980 new_methods->getpeername = my_methods->getpeername;
1981 /* new_methods->getsocketoption = my_methods->getsocketoption; */
1982 /* new_methods->setsocketoption = my_methods->setsocketoption; */
1983 new_methods->sendfile = my_methods->sendfile;
1987 static PRCallOnceType initIoLayerOnce;
1989 static PRStatus
1990 ssl_InitIOLayer(void)
1992 ssl_layer_id = PR_GetUniqueIdentity("SSL");
1993 ssl_SetupIOMethods();
1994 ssl_inited = PR_TRUE;
1995 return PR_SUCCESS;
1998 static PRStatus
1999 ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id)
2001 PRFileDesc *layer = NULL;
2002 PRStatus status;
2004 if (!ssl_inited) {
2005 PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer);
2008 if (ns == NULL)
2009 goto loser;
2011 layer = PR_CreateIOLayerStub(ssl_layer_id, &combined_methods);
2012 if (layer == NULL)
2013 goto loser;
2014 layer->secret = (PRFilePrivate *)ns;
2016 /* Here, "stack" points to the PRFileDesc on the top of the stack.
2017 ** "layer" points to a new FD that is to be inserted into the stack.
2018 ** If layer is being pushed onto the top of the stack, then
2019 ** PR_PushIOLayer switches the contents of stack and layer, and then
2020 ** puts stack on top of layer, so that after it is done, the top of
2021 ** stack is the same "stack" as it was before, and layer is now the
2022 ** FD for the former top of stack.
2023 ** After this call, stack always points to the top PRFD on the stack.
2024 ** If this function fails, the contents of stack and layer are as
2025 ** they were before the call.
2027 status = PR_PushIOLayer(stack, id, layer);
2028 if (status != PR_SUCCESS)
2029 goto loser;
2031 ns->fd = (id == PR_TOP_IO_LAYER) ? stack : layer;
2032 return PR_SUCCESS;
2034 loser:
2035 if (layer) {
2036 layer->dtor(layer); /* free layer */
2038 return PR_FAILURE;
2041 /* if this fails, caller must destroy socket. */
2042 static SECStatus
2043 ssl_MakeLocks(sslSocket *ss)
2045 ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL);
2046 if (!ss->firstHandshakeLock)
2047 goto loser;
2048 ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL);
2049 if (!ss->ssl3HandshakeLock)
2050 goto loser;
2051 ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL);
2052 if (!ss->specLock)
2053 goto loser;
2054 ss->recvBufLock = PZ_NewMonitor(nssILockSSL);
2055 if (!ss->recvBufLock)
2056 goto loser;
2057 ss->xmitBufLock = PZ_NewMonitor(nssILockSSL);
2058 if (!ss->xmitBufLock)
2059 goto loser;
2060 ss->writerThread = NULL;
2061 if (ssl_lock_readers) {
2062 ss->recvLock = PZ_NewLock(nssILockSSL);
2063 if (!ss->recvLock)
2064 goto loser;
2065 ss->sendLock = PZ_NewLock(nssILockSSL);
2066 if (!ss->sendLock)
2067 goto loser;
2069 return SECSuccess;
2070 loser:
2071 ssl_DestroyLocks(ss);
2072 return SECFailure;
2075 #if (defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS)) && !defined(_WIN32_WCE)
2076 #define NSS_HAVE_GETENV 1
2077 #endif
2080 ** Create a newsocket structure for a file descriptor.
2082 static sslSocket *
2083 ssl_NewSocket(PRBool makeLocks)
2085 sslSocket *ss;
2086 #if defined( NSS_HAVE_GETENV )
2087 static int firsttime = 1;
2089 if (firsttime) {
2090 char * ev;
2091 firsttime = 0;
2092 #ifdef DEBUG
2093 ev = getenv("SSLDEBUGFILE");
2094 if (ev && ev[0]) {
2095 ssl_trace_iob = fopen(ev, "w");
2097 if (!ssl_trace_iob) {
2098 ssl_trace_iob = stderr;
2100 #ifdef TRACE
2101 ev = getenv("SSLTRACE");
2102 if (ev && ev[0]) {
2103 ssl_trace = atoi(ev);
2104 SSL_TRACE(("SSL: tracing set to %d", ssl_trace));
2106 #endif /* TRACE */
2107 ev = getenv("SSLDEBUG");
2108 if (ev && ev[0]) {
2109 ssl_debug = atoi(ev);
2110 SSL_TRACE(("SSL: debugging set to %d", ssl_debug));
2112 #endif /* DEBUG */
2113 ev = getenv("SSLBYPASS");
2114 if (ev && ev[0]) {
2115 ssl_defaults.bypassPKCS11 = (ev[0] == '1');
2116 SSL_TRACE(("SSL: bypass default set to %d", \
2117 ssl_defaults.bypassPKCS11));
2119 ev = getenv("SSLFORCELOCKS");
2120 if (ev && ev[0] == '1') {
2121 ssl_force_locks = PR_TRUE;
2122 ssl_defaults.noLocks = 0;
2123 strcpy(lockStatus + LOCKSTATUS_OFFSET, "FORCED. ");
2124 SSL_TRACE(("SSL: force_locks set to %d", ssl_force_locks));
2127 #endif /* NSS_HAVE_GETENV */
2128 if (ssl_force_locks)
2129 makeLocks = PR_TRUE;
2131 /* Make a new socket and get it ready */
2132 ss = (sslSocket*) PORT_ZAlloc(sizeof(sslSocket));
2133 if (ss) {
2134 /* This should be of type SSLKEAType, but CC on IRIX
2135 * complains during the for loop.
2137 int i;
2138 SECStatus status;
2140 ss->opt = ssl_defaults;
2141 ss->opt.useSocks = PR_FALSE;
2142 ss->opt.noLocks = !makeLocks;
2144 ss->peerID = NULL;
2145 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
2146 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
2147 ss->cTimeout = PR_INTERVAL_NO_TIMEOUT;
2148 ss->cipherSpecs = NULL;
2149 ss->sizeCipherSpecs = 0; /* produced lazily */
2150 ss->preferredCipher = NULL;
2151 ss->url = NULL;
2153 for (i=kt_null; i < kt_kea_size; i++) {
2154 sslServerCerts * sc = ss->serverCerts + i;
2155 sc->serverCert = NULL;
2156 sc->serverCertChain = NULL;
2157 sc->serverKeyPair = NULL;
2158 sc->serverKeyBits = 0;
2160 ss->stepDownKeyPair = NULL;
2161 ss->dbHandle = CERT_GetDefaultCertDB();
2163 /* Provide default implementation of hooks */
2164 ss->authCertificate = SSL_AuthCertificate;
2165 ss->authCertificateArg = (void *)ss->dbHandle;
2166 ss->getClientAuthData = NULL;
2167 ss->handleBadCert = NULL;
2168 ss->badCertArg = NULL;
2169 ss->pkcs11PinArg = NULL;
2171 ssl_ChooseOps(ss);
2172 ssl2_InitSocketPolicy(ss);
2173 ssl3_InitSocketPolicy(ss);
2175 if (makeLocks) {
2176 status = ssl_MakeLocks(ss);
2177 if (status != SECSuccess)
2178 goto loser;
2180 status = ssl_CreateSecurityInfo(ss);
2181 if (status != SECSuccess)
2182 goto loser;
2183 status = ssl_InitGather(&ss->gs);
2184 if (status != SECSuccess) {
2185 loser:
2186 ssl_DestroySocketContents(ss);
2187 ssl_DestroyLocks(ss);
2188 PORT_Free(ss);
2189 ss = NULL;
2192 return ss;