Delete unused downloads page asset.
[chromium-blink-merge.git] / net / socket / ssl_server_socket_nss.cc
blobc48c04cb0bc713ee5f7ca02577fa83f92df1344a
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/ssl_server_socket_nss.h"
7 #if defined(OS_WIN)
8 #include <winsock2.h>
9 #endif
11 #if defined(USE_SYSTEM_SSL)
12 #include <dlfcn.h>
13 #endif
14 #if defined(OS_MACOSX)
15 #include <Security/Security.h>
16 #endif
17 #include <certdb.h>
18 #include <cryptohi.h>
19 #include <hasht.h>
20 #include <keyhi.h>
21 #include <nspr.h>
22 #include <nss.h>
23 #include <pk11pub.h>
24 #include <secerr.h>
25 #include <sechash.h>
26 #include <ssl.h>
27 #include <sslerr.h>
28 #include <sslproto.h>
30 #include <limits>
32 #include "base/callback_helpers.h"
33 #include "base/lazy_instance.h"
34 #include "base/memory/ref_counted.h"
35 #include "crypto/nss_util_internal.h"
36 #include "crypto/rsa_private_key.h"
37 #include "net/base/io_buffer.h"
38 #include "net/base/net_errors.h"
39 #include "net/log/net_log.h"
40 #include "net/socket/nss_ssl_util.h"
42 // SSL plaintext fragments are shorter than 16KB. Although the record layer
43 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
44 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
45 // entire SSL record.
46 static const int kRecvBufferSize = 17 * 1024;
47 static const int kSendBufferSize = 17 * 1024;
49 #define GotoState(s) next_handshake_state_ = s
51 namespace net {
53 namespace {
55 bool g_nss_server_sockets_init = false;
57 class NSSSSLServerInitSingleton {
58 public:
59 NSSSSLServerInitSingleton() {
60 EnsureNSSSSLInit();
62 SSL_ConfigServerSessionIDCache(64, 28800, 28800, NULL);
63 g_nss_server_sockets_init = true;
66 ~NSSSSLServerInitSingleton() {
67 SSL_ShutdownServerSessionIDCache();
68 g_nss_server_sockets_init = false;
72 static base::LazyInstance<NSSSSLServerInitSingleton>
73 g_nss_ssl_server_init_singleton = LAZY_INSTANCE_INITIALIZER;
75 } // namespace
77 void EnableSSLServerSockets() {
78 g_nss_ssl_server_init_singleton.Get();
81 scoped_ptr<SSLServerSocket> CreateSSLServerSocket(
82 scoped_ptr<StreamSocket> socket,
83 X509Certificate* cert,
84 crypto::RSAPrivateKey* key,
85 const SSLConfig& ssl_config) {
86 DCHECK(g_nss_server_sockets_init) << "EnableSSLServerSockets() has not been"
87 << " called yet!";
89 return scoped_ptr<SSLServerSocket>(
90 new SSLServerSocketNSS(socket.Pass(), cert, key, ssl_config));
93 SSLServerSocketNSS::SSLServerSocketNSS(
94 scoped_ptr<StreamSocket> transport_socket,
95 scoped_refptr<X509Certificate> cert,
96 crypto::RSAPrivateKey* key,
97 const SSLConfig& ssl_config)
98 : transport_send_busy_(false),
99 transport_recv_busy_(false),
100 user_read_buf_len_(0),
101 user_write_buf_len_(0),
102 nss_fd_(NULL),
103 nss_bufs_(NULL),
104 transport_socket_(transport_socket.Pass()),
105 ssl_config_(ssl_config),
106 cert_(cert),
107 next_handshake_state_(STATE_NONE),
108 completed_handshake_(false) {
109 // TODO(hclam): Need a better way to clone a key.
110 std::vector<uint8> key_bytes;
111 CHECK(key->ExportPrivateKey(&key_bytes));
112 key_.reset(crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(key_bytes));
113 CHECK(key_.get());
116 SSLServerSocketNSS::~SSLServerSocketNSS() {
117 if (nss_fd_ != NULL) {
118 PR_Close(nss_fd_);
119 nss_fd_ = NULL;
123 int SSLServerSocketNSS::Handshake(const CompletionCallback& callback) {
124 net_log_.BeginEvent(NetLog::TYPE_SSL_SERVER_HANDSHAKE);
126 int rv = Init();
127 if (rv != OK) {
128 LOG(ERROR) << "Failed to initialize NSS";
129 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_SERVER_HANDSHAKE, rv);
130 return rv;
133 rv = InitializeSSLOptions();
134 if (rv != OK) {
135 LOG(ERROR) << "Failed to initialize SSL options";
136 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_SERVER_HANDSHAKE, rv);
137 return rv;
140 // Set peer address. TODO(hclam): This should be in a separate method.
141 PRNetAddr peername;
142 memset(&peername, 0, sizeof(peername));
143 peername.raw.family = AF_INET;
144 memio_SetPeerName(nss_fd_, &peername);
146 GotoState(STATE_HANDSHAKE);
147 rv = DoHandshakeLoop(OK);
148 if (rv == ERR_IO_PENDING) {
149 user_handshake_callback_ = callback;
150 } else {
151 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_SERVER_HANDSHAKE, rv);
154 return rv > OK ? OK : rv;
157 int SSLServerSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
158 bool has_context,
159 const base::StringPiece& context,
160 unsigned char* out,
161 unsigned int outlen) {
162 if (!IsConnected())
163 return ERR_SOCKET_NOT_CONNECTED;
164 SECStatus result = SSL_ExportKeyingMaterial(
165 nss_fd_, label.data(), label.size(), has_context,
166 reinterpret_cast<const unsigned char*>(context.data()),
167 context.length(), out, outlen);
168 if (result != SECSuccess) {
169 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
170 return MapNSSError(PORT_GetError());
172 return OK;
175 int SSLServerSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
176 if (!IsConnected())
177 return ERR_SOCKET_NOT_CONNECTED;
178 unsigned char buf[64];
179 unsigned int len;
180 SECStatus result = SSL_GetChannelBinding(nss_fd_,
181 SSL_CHANNEL_BINDING_TLS_UNIQUE,
182 buf, &len, arraysize(buf));
183 if (result != SECSuccess) {
184 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
185 return MapNSSError(PORT_GetError());
187 out->assign(reinterpret_cast<char*>(buf), len);
188 return OK;
191 int SSLServerSocketNSS::Connect(const CompletionCallback& callback) {
192 NOTIMPLEMENTED();
193 return ERR_NOT_IMPLEMENTED;
196 int SSLServerSocketNSS::Read(IOBuffer* buf, int buf_len,
197 const CompletionCallback& callback) {
198 DCHECK(user_read_callback_.is_null());
199 DCHECK(user_handshake_callback_.is_null());
200 DCHECK(!user_read_buf_.get());
201 DCHECK(nss_bufs_);
202 DCHECK(!callback.is_null());
204 user_read_buf_ = buf;
205 user_read_buf_len_ = buf_len;
207 DCHECK(completed_handshake_);
209 int rv = DoReadLoop(OK);
211 if (rv == ERR_IO_PENDING) {
212 user_read_callback_ = callback;
213 } else {
214 user_read_buf_ = NULL;
215 user_read_buf_len_ = 0;
217 return rv;
220 int SSLServerSocketNSS::Write(IOBuffer* buf, int buf_len,
221 const CompletionCallback& callback) {
222 DCHECK(user_write_callback_.is_null());
223 DCHECK(!user_write_buf_.get());
224 DCHECK(nss_bufs_);
225 DCHECK(!callback.is_null());
227 user_write_buf_ = buf;
228 user_write_buf_len_ = buf_len;
230 int rv = DoWriteLoop(OK);
232 if (rv == ERR_IO_PENDING) {
233 user_write_callback_ = callback;
234 } else {
235 user_write_buf_ = NULL;
236 user_write_buf_len_ = 0;
238 return rv;
241 int SSLServerSocketNSS::SetReceiveBufferSize(int32 size) {
242 return transport_socket_->SetReceiveBufferSize(size);
245 int SSLServerSocketNSS::SetSendBufferSize(int32 size) {
246 return transport_socket_->SetSendBufferSize(size);
249 bool SSLServerSocketNSS::IsConnected() const {
250 // TODO(wtc): Find out if we should check transport_socket_->IsConnected()
251 // as well.
252 return completed_handshake_;
255 void SSLServerSocketNSS::Disconnect() {
256 transport_socket_->Disconnect();
259 bool SSLServerSocketNSS::IsConnectedAndIdle() const {
260 return completed_handshake_ && transport_socket_->IsConnectedAndIdle();
263 int SSLServerSocketNSS::GetPeerAddress(IPEndPoint* address) const {
264 if (!IsConnected())
265 return ERR_SOCKET_NOT_CONNECTED;
266 return transport_socket_->GetPeerAddress(address);
269 int SSLServerSocketNSS::GetLocalAddress(IPEndPoint* address) const {
270 if (!IsConnected())
271 return ERR_SOCKET_NOT_CONNECTED;
272 return transport_socket_->GetLocalAddress(address);
275 const BoundNetLog& SSLServerSocketNSS::NetLog() const {
276 return net_log_;
279 void SSLServerSocketNSS::SetSubresourceSpeculation() {
280 transport_socket_->SetSubresourceSpeculation();
283 void SSLServerSocketNSS::SetOmniboxSpeculation() {
284 transport_socket_->SetOmniboxSpeculation();
287 bool SSLServerSocketNSS::WasEverUsed() const {
288 return transport_socket_->WasEverUsed();
291 bool SSLServerSocketNSS::UsingTCPFastOpen() const {
292 return transport_socket_->UsingTCPFastOpen();
295 bool SSLServerSocketNSS::WasNpnNegotiated() const {
296 NOTIMPLEMENTED();
297 return false;
300 NextProto SSLServerSocketNSS::GetNegotiatedProtocol() const {
301 // NPN is not supported by this class.
302 return kProtoUnknown;
305 bool SSLServerSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
306 NOTIMPLEMENTED();
307 return false;
310 void SSLServerSocketNSS::GetConnectionAttempts(ConnectionAttempts* out) const {
311 out->clear();
314 int SSLServerSocketNSS::InitializeSSLOptions() {
315 // Transport connected, now hook it up to nss
316 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
317 if (nss_fd_ == NULL) {
318 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
321 // Grab pointer to buffers
322 nss_bufs_ = memio_GetSecret(nss_fd_);
324 /* Create SSL state machine */
325 /* Push SSL onto our fake I/O socket */
326 nss_fd_ = SSL_ImportFD(NULL, nss_fd_);
327 if (nss_fd_ == NULL) {
328 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
329 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
331 // TODO(port): set more ssl options! Check errors!
333 int rv;
335 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
336 if (rv != SECSuccess) {
337 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
338 return ERR_UNEXPECTED;
341 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
342 if (rv != SECSuccess) {
343 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
344 return ERR_UNEXPECTED;
347 SSLVersionRange version_range;
348 version_range.min = ssl_config_.version_min;
349 version_range.max = ssl_config_.version_max;
350 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
351 if (rv != SECSuccess) {
352 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
353 return ERR_NO_SSL_VERSIONS_ENABLED;
356 if (ssl_config_.require_ecdhe) {
357 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
358 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
360 // Iterate over the cipher suites and disable those that don't use ECDHE.
361 for (unsigned i = 0; i < num_ciphers; i++) {
362 SSLCipherSuiteInfo info;
363 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) ==
364 SECSuccess) {
365 if (strcmp(info.keaTypeName, "ECDHE") != 0) {
366 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
372 for (std::vector<uint16>::const_iterator it =
373 ssl_config_.disabled_cipher_suites.begin();
374 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
375 // This will fail if the specified cipher is not implemented by NSS, but
376 // the failure is harmless.
377 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
380 // Server socket doesn't need session tickets.
381 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_FALSE);
382 if (rv != SECSuccess) {
383 LogFailedNSSFunction(
384 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
387 // Doing this will force PR_Accept perform handshake as server.
388 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_FALSE);
389 if (rv != SECSuccess) {
390 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
391 return ERR_UNEXPECTED;
394 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_SERVER, PR_TRUE);
395 if (rv != SECSuccess) {
396 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_SERVER");
397 return ERR_UNEXPECTED;
400 rv = SSL_OptionSet(nss_fd_, SSL_REQUEST_CERTIFICATE, PR_FALSE);
401 if (rv != SECSuccess) {
402 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_REQUEST_CERTIFICATE");
403 return ERR_UNEXPECTED;
406 rv = SSL_OptionSet(nss_fd_, SSL_REQUIRE_CERTIFICATE, PR_FALSE);
407 if (rv != SECSuccess) {
408 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_REQUIRE_CERTIFICATE");
409 return ERR_UNEXPECTED;
412 rv = SSL_AuthCertificateHook(nss_fd_, OwnAuthCertHandler, this);
413 if (rv != SECSuccess) {
414 LogFailedNSSFunction(net_log_, "SSL_AuthCertificateHook", "");
415 return ERR_UNEXPECTED;
418 rv = SSL_HandshakeCallback(nss_fd_, HandshakeCallback, this);
419 if (rv != SECSuccess) {
420 LogFailedNSSFunction(net_log_, "SSL_HandshakeCallback", "");
421 return ERR_UNEXPECTED;
424 // Get a certificate of CERTCertificate structure.
425 std::string der_string;
426 if (!X509Certificate::GetDEREncoded(cert_->os_cert_handle(), &der_string))
427 return ERR_UNEXPECTED;
429 SECItem der_cert;
430 der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(
431 der_string.data()));
432 der_cert.len = der_string.length();
433 der_cert.type = siDERCertBuffer;
435 // Parse into a CERTCertificate structure.
436 CERTCertificate* cert = CERT_NewTempCertificate(
437 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
438 if (!cert) {
439 LogFailedNSSFunction(net_log_, "CERT_NewTempCertificate", "");
440 return MapNSSError(PORT_GetError());
443 // Get a key of SECKEYPrivateKey* structure.
444 std::vector<uint8> key_vector;
445 if (!key_->ExportPrivateKey(&key_vector)) {
446 CERT_DestroyCertificate(cert);
447 return ERR_UNEXPECTED;
450 SECKEYPrivateKeyStr* private_key = NULL;
451 PK11SlotInfo* slot = PK11_GetInternalSlot();
452 if (!slot) {
453 CERT_DestroyCertificate(cert);
454 return ERR_UNEXPECTED;
457 SECItem der_private_key_info;
458 der_private_key_info.data =
459 const_cast<unsigned char*>(&key_vector.front());
460 der_private_key_info.len = key_vector.size();
461 // The server's RSA private key must be imported into NSS with the
462 // following key usage bits:
463 // - KU_KEY_ENCIPHERMENT, required for the RSA key exchange algorithm.
464 // - KU_DIGITAL_SIGNATURE, required for the DHE_RSA and ECDHE_RSA key
465 // exchange algorithms.
466 const unsigned int key_usage = KU_KEY_ENCIPHERMENT | KU_DIGITAL_SIGNATURE;
467 rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(
468 slot, &der_private_key_info, NULL, NULL, PR_FALSE, PR_FALSE,
469 key_usage, &private_key, NULL);
470 PK11_FreeSlot(slot);
471 if (rv != SECSuccess) {
472 CERT_DestroyCertificate(cert);
473 return ERR_UNEXPECTED;
476 // Assign server certificate and private key.
477 SSLKEAType cert_kea = NSS_FindCertKEAType(cert);
478 rv = SSL_ConfigSecureServer(nss_fd_, cert, private_key, cert_kea);
479 CERT_DestroyCertificate(cert);
480 SECKEY_DestroyPrivateKey(private_key);
482 if (rv != SECSuccess) {
483 PRErrorCode prerr = PR_GetError();
484 LOG(ERROR) << "Failed to config SSL server: " << prerr;
485 LogFailedNSSFunction(net_log_, "SSL_ConfigureSecureServer", "");
486 return ERR_UNEXPECTED;
489 // Tell SSL we're a server; needed if not letting NSPR do socket I/O
490 rv = SSL_ResetHandshake(nss_fd_, PR_TRUE);
491 if (rv != SECSuccess) {
492 LogFailedNSSFunction(net_log_, "SSL_ResetHandshake", "");
493 return ERR_UNEXPECTED;
496 return OK;
499 void SSLServerSocketNSS::OnSendComplete(int result) {
500 if (next_handshake_state_ == STATE_HANDSHAKE) {
501 // In handshake phase.
502 OnHandshakeIOComplete(result);
503 return;
506 // TODO(byungchul): This state machine is not correct. Copy the state machine
507 // of SSLClientSocketNSS::OnSendComplete() which handles it better.
508 if (!completed_handshake_)
509 return;
511 if (user_write_buf_.get()) {
512 int rv = DoWriteLoop(result);
513 if (rv != ERR_IO_PENDING)
514 DoWriteCallback(rv);
515 } else {
516 // Ensure that any queued ciphertext is flushed.
517 DoTransportIO();
521 void SSLServerSocketNSS::OnRecvComplete(int result) {
522 if (next_handshake_state_ == STATE_HANDSHAKE) {
523 // In handshake phase.
524 OnHandshakeIOComplete(result);
525 return;
528 // Network layer received some data, check if client requested to read
529 // decrypted data.
530 if (!user_read_buf_.get() || !completed_handshake_)
531 return;
533 int rv = DoReadLoop(result);
534 if (rv != ERR_IO_PENDING)
535 DoReadCallback(rv);
538 void SSLServerSocketNSS::OnHandshakeIOComplete(int result) {
539 int rv = DoHandshakeLoop(result);
540 if (rv == ERR_IO_PENDING)
541 return;
543 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_SERVER_HANDSHAKE, rv);
544 if (!user_handshake_callback_.is_null())
545 DoHandshakeCallback(rv);
548 // Return 0 for EOF,
549 // > 0 for bytes transferred immediately,
550 // < 0 for error (or the non-error ERR_IO_PENDING).
551 int SSLServerSocketNSS::BufferSend(void) {
552 if (transport_send_busy_)
553 return ERR_IO_PENDING;
555 const char* buf1;
556 const char* buf2;
557 unsigned int len1, len2;
558 if (memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2)) {
559 // The error code itself is ignored, so just return ERR_ABORTED.
560 return ERR_ABORTED;
562 const size_t len = len1 + len2;
564 int rv = 0;
565 if (len) {
566 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
567 memcpy(send_buffer->data(), buf1, len1);
568 memcpy(send_buffer->data() + len1, buf2, len2);
569 rv = transport_socket_->Write(
570 send_buffer.get(),
571 len,
572 base::Bind(&SSLServerSocketNSS::BufferSendComplete,
573 base::Unretained(this)));
574 if (rv == ERR_IO_PENDING) {
575 transport_send_busy_ = true;
576 } else {
577 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
581 return rv;
584 void SSLServerSocketNSS::BufferSendComplete(int result) {
585 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
586 transport_send_busy_ = false;
587 OnSendComplete(result);
590 int SSLServerSocketNSS::BufferRecv(void) {
591 if (transport_recv_busy_) return ERR_IO_PENDING;
593 char* buf;
594 int nb = memio_GetReadParams(nss_bufs_, &buf);
595 int rv;
596 if (!nb) {
597 // buffer too full to read into, so no I/O possible at moment
598 rv = ERR_IO_PENDING;
599 } else {
600 recv_buffer_ = new IOBuffer(nb);
601 rv = transport_socket_->Read(
602 recv_buffer_.get(),
604 base::Bind(&SSLServerSocketNSS::BufferRecvComplete,
605 base::Unretained(this)));
606 if (rv == ERR_IO_PENDING) {
607 transport_recv_busy_ = true;
608 } else {
609 if (rv > 0)
610 memcpy(buf, recv_buffer_->data(), rv);
611 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
612 recv_buffer_ = NULL;
615 return rv;
618 void SSLServerSocketNSS::BufferRecvComplete(int result) {
619 if (result > 0) {
620 char* buf;
621 memio_GetReadParams(nss_bufs_, &buf);
622 memcpy(buf, recv_buffer_->data(), result);
624 recv_buffer_ = NULL;
625 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
626 transport_recv_busy_ = false;
627 OnRecvComplete(result);
630 // Do as much network I/O as possible between the buffer and the
631 // transport socket. Return true if some I/O performed, false
632 // otherwise (error or ERR_IO_PENDING).
633 bool SSLServerSocketNSS::DoTransportIO() {
634 bool network_moved = false;
635 if (nss_bufs_ != NULL) {
636 int rv;
637 // Read and write as much data as we can. The loop is neccessary
638 // because Write() may return synchronously.
639 do {
640 rv = BufferSend();
641 if (rv > 0)
642 network_moved = true;
643 } while (rv > 0);
644 if (BufferRecv() >= 0)
645 network_moved = true;
647 return network_moved;
650 int SSLServerSocketNSS::DoPayloadRead() {
651 DCHECK(user_read_buf_.get());
652 DCHECK_GT(user_read_buf_len_, 0);
653 int rv = PR_Read(nss_fd_, user_read_buf_->data(), user_read_buf_len_);
654 if (rv >= 0)
655 return rv;
656 PRErrorCode prerr = PR_GetError();
657 if (prerr == PR_WOULD_BLOCK_ERROR) {
658 return ERR_IO_PENDING;
660 rv = MapNSSError(prerr);
661 net_log_.AddEvent(NetLog::TYPE_SSL_READ_ERROR,
662 CreateNetLogSSLErrorCallback(rv, prerr));
663 return rv;
666 int SSLServerSocketNSS::DoPayloadWrite() {
667 DCHECK(user_write_buf_.get());
668 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
669 if (rv >= 0)
670 return rv;
671 PRErrorCode prerr = PR_GetError();
672 if (prerr == PR_WOULD_BLOCK_ERROR) {
673 return ERR_IO_PENDING;
675 rv = MapNSSError(prerr);
676 net_log_.AddEvent(NetLog::TYPE_SSL_WRITE_ERROR,
677 CreateNetLogSSLErrorCallback(rv, prerr));
678 return rv;
681 int SSLServerSocketNSS::DoHandshakeLoop(int last_io_result) {
682 int rv = last_io_result;
683 do {
684 // Default to STATE_NONE for next state.
685 // (This is a quirk carried over from the windows
686 // implementation. It makes reading the logs a bit harder.)
687 // State handlers can and often do call GotoState just
688 // to stay in the current state.
689 State state = next_handshake_state_;
690 GotoState(STATE_NONE);
691 switch (state) {
692 case STATE_HANDSHAKE:
693 rv = DoHandshake();
694 break;
695 case STATE_NONE:
696 default:
697 rv = ERR_UNEXPECTED;
698 LOG(DFATAL) << "unexpected state " << state;
699 break;
702 // Do the actual network I/O
703 bool network_moved = DoTransportIO();
704 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
705 // In general we exit the loop if rv is ERR_IO_PENDING. In this
706 // special case we keep looping even if rv is ERR_IO_PENDING because
707 // the transport IO may allow DoHandshake to make progress.
708 rv = OK; // This causes us to stay in the loop.
710 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
711 return rv;
714 int SSLServerSocketNSS::DoReadLoop(int result) {
715 DCHECK(completed_handshake_);
716 DCHECK(next_handshake_state_ == STATE_NONE);
718 if (result < 0)
719 return result;
721 if (!nss_bufs_) {
722 LOG(DFATAL) << "!nss_bufs_";
723 int rv = ERR_UNEXPECTED;
724 net_log_.AddEvent(NetLog::TYPE_SSL_READ_ERROR,
725 CreateNetLogSSLErrorCallback(rv, 0));
726 return rv;
729 bool network_moved;
730 int rv;
731 do {
732 rv = DoPayloadRead();
733 network_moved = DoTransportIO();
734 } while (rv == ERR_IO_PENDING && network_moved);
735 return rv;
738 int SSLServerSocketNSS::DoWriteLoop(int result) {
739 DCHECK(completed_handshake_);
740 DCHECK_EQ(next_handshake_state_, STATE_NONE);
742 if (result < 0)
743 return result;
745 if (!nss_bufs_) {
746 LOG(DFATAL) << "!nss_bufs_";
747 int rv = ERR_UNEXPECTED;
748 net_log_.AddEvent(NetLog::TYPE_SSL_WRITE_ERROR,
749 CreateNetLogSSLErrorCallback(rv, 0));
750 return rv;
753 bool network_moved;
754 int rv;
755 do {
756 rv = DoPayloadWrite();
757 network_moved = DoTransportIO();
758 } while (rv == ERR_IO_PENDING && network_moved);
759 return rv;
762 int SSLServerSocketNSS::DoHandshake() {
763 int net_error = OK;
764 SECStatus rv = SSL_ForceHandshake(nss_fd_);
766 if (rv == SECSuccess) {
767 completed_handshake_ = true;
768 } else {
769 PRErrorCode prerr = PR_GetError();
770 net_error = MapNSSError(prerr);
772 // If not done, stay in this state
773 if (net_error == ERR_IO_PENDING) {
774 GotoState(STATE_HANDSHAKE);
775 } else {
776 LOG(ERROR) << "handshake failed; NSS error code " << prerr
777 << ", net_error " << net_error;
778 net_log_.AddEvent(NetLog::TYPE_SSL_HANDSHAKE_ERROR,
779 CreateNetLogSSLErrorCallback(net_error, prerr));
782 return net_error;
785 void SSLServerSocketNSS::DoHandshakeCallback(int rv) {
786 DCHECK_NE(rv, ERR_IO_PENDING);
787 ResetAndReturn(&user_handshake_callback_).Run(rv > OK ? OK : rv);
790 void SSLServerSocketNSS::DoReadCallback(int rv) {
791 DCHECK(rv != ERR_IO_PENDING);
792 DCHECK(!user_read_callback_.is_null());
794 user_read_buf_ = NULL;
795 user_read_buf_len_ = 0;
796 ResetAndReturn(&user_read_callback_).Run(rv);
799 void SSLServerSocketNSS::DoWriteCallback(int rv) {
800 DCHECK(rv != ERR_IO_PENDING);
801 DCHECK(!user_write_callback_.is_null());
803 user_write_buf_ = NULL;
804 user_write_buf_len_ = 0;
805 ResetAndReturn(&user_write_callback_).Run(rv);
808 // static
809 // NSS calls this if an incoming certificate needs to be verified.
810 // Do nothing but return SECSuccess.
811 // This is called only in full handshake mode.
812 // Peer certificate is retrieved in HandshakeCallback() later, which is called
813 // in full handshake mode or in resumption handshake mode.
814 SECStatus SSLServerSocketNSS::OwnAuthCertHandler(void* arg,
815 PRFileDesc* socket,
816 PRBool checksig,
817 PRBool is_server) {
818 // TODO(hclam): Implement.
819 // Tell NSS to not verify the certificate.
820 return SECSuccess;
823 // static
824 // NSS calls this when handshake is completed.
825 // After the SSL handshake is finished we need to verify the certificate.
826 void SSLServerSocketNSS::HandshakeCallback(PRFileDesc* socket,
827 void* arg) {
828 // TODO(hclam): Implement.
831 int SSLServerSocketNSS::Init() {
832 // Initialize the NSS SSL library in a threadsafe way. This also
833 // initializes the NSS base library.
834 EnsureNSSSSLInit();
835 if (!NSS_IsInitialized())
836 return ERR_UNEXPECTED;
838 EnableSSLServerSockets();
839 return OK;
842 } // namespace net