1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// OpenSSL binding for SSLClientSocket. The class layout and general principle
// of operation is derived from SSLClientSocketNSS.
#include "net/socket/ssl_client_socket_openssl.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "net/base/cert_verifier.h"
#include "base/histogram.h"
#include "net/base/net_errors.h"
#include "net/base/ssl_connection_status_flags.h"
#include "net/base/ssl_info.h"
#include "net/base/test_certificate_data.h" // TODO(joth): Remove!!
namespace net {
namespace {
// Enable this to see logging for state machine state transitions.
#if 0
#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
" jump to state " << s; \
next_handshake_state_ = s; } while (0)
#else
#define GotoState(s) next_handshake_state_ = s
#endif
const size_t kMaxRecvBufferSize = 4096;
static SSL_CTX* g_ctx = NULL;
static int g_app_data_index = -1;
void MaybeLogSSLError() {
int error_num;
while ((error_num = ERR_get_error()) != 0) {
char buf[128]; // this buffer must be at least 120 chars long.
ERR_error_string_n(error_num, buf, arraysize(buf));
DVLOG(1) << "SSL error " << error_num << ": " << buf;
}
}
int MapOpenSSLError(int err) {
switch (err) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return ERR_IO_PENDING;
case SSL_ERROR_SYSCALL:
DVLOG(1) << "OpenSSL SYSVCALL error, errno " << errno;
MaybeLogSSLError();
return ERR_SSL_PROTOCOL_ERROR;
default:
// TODO(joth): Implement full mapping.
LOG(WARNING) << "Unknown OpenSSL error " << err;
MaybeLogSSLError();
return ERR_SSL_PROTOCOL_ERROR;
}
}
// Registered with |g_ctx| as global verify callback handler; we unpack the
// SSLClientSocketOpenSSL instance associated with this callback and delegate
// the handling to it.
int VerifyCallback(int preverify_ok, X509_STORE_CTX* x509_ctx) {
DCHECK_GE(g_app_data_index, 0);
// Retrieve the pointer to the SSL of the connection currently treated
// and from there, the application specific data stored in the SSL object.
SSL* ssl = static_cast<SSL*>(X509_STORE_CTX_get_ex_data(
x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
DCHECK(ssl);
SSLClientSocketOpenSSL* self = static_cast<SSLClientSocketOpenSSL*>(
SSL_get_ex_data(ssl, g_app_data_index));
DCHECK(self);
return self->SSLVerifyCallback(preverify_ok, ssl, x509_ctx);
}
} // namespace
SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
ClientSocketHandle* transport_socket,
const std::string& hostname,
const SSLConfig& ssl_config)
: ALLOW_THIS_IN_INITIALIZER_LIST(buffer_send_callback_(
this, &SSLClientSocketOpenSSL::BufferSendComplete)),
ALLOW_THIS_IN_INITIALIZER_LIST(buffer_recv_callback_(
this, &SSLClientSocketOpenSSL::BufferRecvComplete)),
transport_send_busy_(false),
transport_recv_busy_(false),
user_connect_callback_(NULL),
user_read_callback_(NULL),
user_write_callback_(NULL),
client_auth_cert_needed_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(handshake_io_callback_(
this, &SSLClientSocketOpenSSL::OnHandshakeIOComplete)),
ssl_(NULL),
transport_bio_(NULL),
transport_(transport_socket),
hostname_(hostname),
ssl_config_(ssl_config),
completed_handshake_(false),
net_log_(transport_socket->socket()->NetLog()) {
}
SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
Disconnect();
}
// TODO(joth): This method needs to be thread-safe.
bool SSLClientSocketOpenSSL::InitOpenSSL() {
if (g_ctx)
return true;
SSL_load_error_strings();
MaybeLogSSLError();
SSL_library_init();
MaybeLogSSLError();
// Allow all versions here; we disable the unneeded ones according to the
// SSL config options in Init().
g_ctx = SSL_CTX_new(SSLv23_client_method());
if (!g_ctx) {
MaybeLogSSLError();
return false;
}
g_app_data_index = SSL_get_ex_new_index(__LINE__, g_ctx, NULL, NULL, NULL);
DCHECK_GE(g_app_data_index, 0);
SSL_CTX_set_verify(g_ctx, SSL_VERIFY_PEER, VerifyCallback);
// For now, just let OpenSSL load CA certs directly from the filesystem.
if (!SSL_CTX_set_default_verify_paths(g_ctx)) {
MaybeLogSSLError();
return false;
}
return true;
}
bool SSLClientSocketOpenSSL::Init() {
DCHECK(g_ctx);
DCHECK(!ssl_);
DCHECK(!transport_bio_);
ssl_ = SSL_new(g_ctx);
if (!ssl_) {
MaybeLogSSLError();
return false;
}
if (!SSL_set_ex_data(ssl_, g_app_data_index, this)) {
MaybeLogSSLError();
return false;
}
if (!SSL_set_tlsext_host_name(ssl_, hostname_.c_str())) {
MaybeLogSSLError();
return false;
}
BIO* ssl_bio = NULL;
// TODO(joth): Provide explicit write buffer sizes, rather than use defaults?
if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0)) {
MaybeLogSSLError();
return false;
}
DCHECK(ssl_bio);
DCHECK(transport_bio_);
SSL_set_bio(ssl_, ssl_bio, ssl_bio);
#define SET_SSL_CONFIG_OPTION(option, value) \
(((value) ? set_mask : clear_mask) |= (option))
// OpenSSL defaults some options to on, others to off. To avoid ambiguity,
// set everything we care about to an absolute value.
long set_mask = 0;
long clear_mask = 0;
SET_SSL_CONFIG_OPTION(SSL_OP_NO_SSLv2, !ssl_config_.ssl2_enabled);
SET_SSL_CONFIG_OPTION(SSL_OP_NO_SSLv3, !ssl_config_.ssl3_enabled);
SET_SSL_CONFIG_OPTION(SSL_OP_NO_TLSv1, !ssl_config_.tls1_enabled);
// TODO(joth): Set this conditionally, see http://crbug.com/55410
SET_SSL_CONFIG_OPTION(SSL_OP_LEGACY_SERVER_CONNECT, true);
// Make sure we haven't got any intersection in the set & clear options.
DCHECK_EQ(0, set_mask & clear_mask);
SSL_set_options(ssl_, set_mask);
SSL_clear_options(ssl_, clear_mask);
#undef SET_SSL_CONFIG_OPTION
return true;
}
int SSLClientSocketOpenSSL::SSLVerifyCallback(int preverify_ok,
SSL* ssl,
X509_STORE_CTX* x509_ctx) {
DCHECK_EQ(ssl_, ssl);
int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
DVLOG(preverify_ok ? 3 : 1) << "SSLVerifyCallback " << preverify_ok
<< " depth " << depth;
MaybeLogSSLError();
return preverify_ok;
}
// SSLClientSocket methods
void SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
ssl_info->Reset();
if (!server_cert_)
return;
// Chrome DCHECKs that https pages provide a valid cert. For now (whilst in
// early dev) we just create a spoof cert.
// TODO(joth): implement X509Certificate for OpenSSL and remove this hack.
LOG(WARNING) << "Filling in certificate with bogus content";
ssl_info->cert = server_cert_;
ssl_info->cert_status = server_cert_verify_result_.cert_status;
ssl_info->security_bits = 56;
ssl_info->connection_status =
((TLS1_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA) &
SSL_CONNECTION_CIPHERSUITE_MASK) << SSL_CONNECTION_CIPHERSUITE_SHIFT;
bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
if (!peer_supports_renego_ext)
ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
(int)peer_supports_renego_ext, 2);
if (ssl_config_.ssl3_fallback)
ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
}
void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) {
NOTREACHED();
}
SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
std::string* proto) {
proto->clear();
return kNextProtoUnsupported;
}
void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
// Since Run may result in Read being called, clear |user_read_callback_|
// up front.
CompletionCallback* c = user_read_callback_;
user_read_callback_ = NULL;
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
c->Run(rv);
}
void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
// Since Run may result in Write being called, clear |user_write_callback_|
// up front.
CompletionCallback* c = user_write_callback_;
user_write_callback_ = NULL;
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
c->Run(rv);
}
// ClientSocket methods
int SSLClientSocketOpenSSL::Connect(CompletionCallback* callback) {
net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
if (!InitOpenSSL()) {
net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
return ERR_UNEXPECTED;
}
// Set up new ssl object.
if (!Init()) {
net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
return ERR_UNEXPECTED;
}
// Set SSL to client mode. Handshake happens in the loop below.
SSL_set_connect_state(ssl_);
GotoState(STATE_HANDSHAKE);
int rv = DoHandshakeLoop(net::OK);
if (rv == ERR_IO_PENDING) {
user_connect_callback_ = callback;
} else {
net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
}
return rv > OK ? OK : rv;
}
void SSLClientSocketOpenSSL::Disconnect() {
if (ssl_) {
SSL_free(ssl_);
ssl_ = NULL;
}
if (transport_bio_) {
BIO_free_all(transport_bio_);
transport_bio_ = NULL;
}
// Shut down anything that may call us back (through buffer_send_callback_,
// buffer_recv_callback, or handshake_io_callback_).
verifier_.reset();
transport_->socket()->Disconnect();
// Null all callbacks, delete all buffers.
transport_send_busy_ = false;
send_buffer_ = NULL;
transport_recv_busy_ = false;
recv_buffer_ = NULL;
user_connect_callback_ = NULL;
user_read_callback_ = NULL;
user_write_callback_ = NULL;
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
client_certs_.clear();
client_auth_cert_needed_ = false;
server_cert_verify_result_.Reset();
completed_handshake_ = false;
}
int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
bool network_moved;
int rv = last_io_result;
do {
// Default to STATE_NONE for next state.
// (This is a quirk carried over from the windows
// implementation. It makes reading the logs a bit harder.)
// State handlers can and often do call GotoState just
// to stay in the current state.
State state = next_handshake_state_;
GotoState(STATE_NONE);
switch (state) {
case STATE_NONE:
// we're just pumping data between the buffer and the network
break;
case STATE_HANDSHAKE:
rv = DoHandshake();
break;
case STATE_VERIFY_CERT:
DCHECK(rv == OK);
rv = DoVerifyCert(rv);
break;
case STATE_VERIFY_CERT_COMPLETE:
rv = DoVerifyCertComplete(rv);
break;
default:
rv = ERR_UNEXPECTED;
NOTREACHED() << "unexpected state" << state;
break;
}
// To avoid getting an ERR_IO_PENDING here after handshake complete.
if (next_handshake_state_ == STATE_NONE)
break;
// Do the actual network I/O.
network_moved = DoTransportIO();
} while ((rv != ERR_IO_PENDING || network_moved) &&
next_handshake_state_ != STATE_NONE);
return rv;
}
int SSLClientSocketOpenSSL::DoHandshake() {
int net_error = net::OK;
int rv = SSL_do_handshake(ssl_);
if (rv == 1) {
// SSL handshake is completed. Let's verify the certificate.
if (UpdateServerCert() == NULL) {
net_error = ERR_SSL_PROTOCOL_ERROR;
} else {
GotoState(STATE_VERIFY_CERT);
// TODO(joth): Remove this check when X509Certificate::Verify is
// implemented for OpenSSL
long verify_result = SSL_get_verify_result(ssl_);
LOG_IF(WARNING, verify_result != X509_V_OK)
<< "Built in verify failed: " << verify_result;
}
} else {
int ssl_error = SSL_get_error(ssl_, rv);
net_error = MapOpenSSLError(ssl_error);
// If not done, stay in this state
if (net_error == ERR_IO_PENDING) {
GotoState(STATE_HANDSHAKE);
} else {
LOG(ERROR) << "handshake failed; returned " << rv
<< ", SSL error code " << ssl_error
<< ", net_error " << net_error;
MaybeLogSSLError();
}
}
return net_error;
}
int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
DCHECK(server_cert_);
GotoState(STATE_VERIFY_CERT_COMPLETE);
int flags = 0;
if (ssl_config_.rev_checking_enabled)
flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
if (ssl_config_.verify_ev_cert)
flags |= X509Certificate::VERIFY_EV_CERT;
verifier_.reset(new CertVerifier);
return verifier_->Verify(server_cert_, hostname_, flags,
&server_cert_verify_result_,
&handshake_io_callback_);
}
int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
verifier_.reset();
if (result == OK) {
// TODO(joth): Work out if we need to remember the intermediate CA certs
// when the server sends them to us, and do so here.
}
// If we have been explicitly told to accept this certificate, override the
// result of verifier_.Verify.
// Eventually, we should cache the cert verification results so that we don't
// need to call verifier_.Verify repeatedly. But for now we need to do this.
// Alternatively, we could use the cert's status that we stored along with
// the cert in the allowed_bad_certs vector.
if (IsCertificateError(result) &&
ssl_config_.IsAllowedBadCert(server_cert_)) {
LOG(INFO) << "accepting bad SSL certificate, as user told us to";
result = OK;
}
completed_handshake_ = true;
// The NSS version has a comment that we may not need this call because it is
// now harmless to have a session with a bad cert.
// This may or may not apply here, but let's invalidate it anyway.
InvalidateSessionIfBadCertificate();
// Exit DoHandshakeLoop and return the result to the caller to Connect.
DCHECK_EQ(STATE_NONE, next_handshake_state_);
return result;
}
void SSLClientSocketOpenSSL::InvalidateSessionIfBadCertificate() {
if (UpdateServerCert() != NULL &&
ssl_config_.IsAllowedBadCert(server_cert_)) {
// Remove from session cache but don't clear this connection.
// TODO(joth): This should be a no-op until we enable session caching,
// see SSL_CTX_set_session_cache_mode(SSL_SESS_CACHE_CLIENT).
SSL_SESSION* session = SSL_get_session(ssl_);
LOG_IF(ERROR, session) << "Connection has a session?? " << session;
int rv = SSL_CTX_remove_session(g_ctx, session);
LOG_IF(ERROR, rv) << "Session was cached?? " << rv;
}
}
X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
if (server_cert_)
return server_cert_;
X509* cert = SSL_get_peer_certificate(ssl_);
if (cert == NULL) {
LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
return NULL;
}
// TODO(joth): Get |server_cert_| from |cert|.
server_cert_ = X509Certificate::CreateFromBytes(
reinterpret_cast<const char*>(google_der), sizeof(google_der));
X509_free(cert);
DCHECK(server_cert_);
// Silence compiler about unused vars.
(void)google_der; (void)webkit_der; (void)thawte_der; (void)paypal_null_der;
return server_cert_;
}
bool SSLClientSocketOpenSSL::DoTransportIO() {
bool network_moved = false;
int nsent = BufferSend();
int nreceived = BufferRecv();
network_moved = (nsent > 0 || nreceived >= 0);
return network_moved;
}
int SSLClientSocketOpenSSL::BufferSend(void) {
if (transport_send_busy_)
return ERR_IO_PENDING;
if (!send_buffer_) {
// Get a fresh send buffer out of the send BIO.
size_t max_read = BIO_ctrl_pending(transport_bio_);
if (max_read > 0) {
send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
DCHECK_GT(read_bytes, 0);
CHECK_EQ(static_cast<int>(max_read), read_bytes);
}
}
int rv = 0;
while (send_buffer_) {
rv = transport_->socket()->Write(send_buffer_,
send_buffer_->BytesRemaining(),
&buffer_send_callback_);
if (rv == ERR_IO_PENDING) {
transport_send_busy_ = true;
return rv;
}
TransportWriteComplete(rv);
}
return rv;
}
void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
transport_send_busy_ = false;
TransportWriteComplete(result);
OnSendComplete(result);
}
void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
if (result < 0) {
// Got a socket write error; close the BIO to indicate this upward.
(void)BIO_shutdown_wr(transport_bio_);
send_buffer_ = NULL;
} else {
DCHECK(send_buffer_);
send_buffer_->DidConsume(result);
DCHECK_GE(send_buffer_->BytesRemaining(), 0);
if (send_buffer_->BytesRemaining() <= 0)
send_buffer_ = NULL;
}
}
int SSLClientSocketOpenSSL::BufferRecv(void) {
if (transport_recv_busy_)
return ERR_IO_PENDING;
size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
if (max_write > kMaxRecvBufferSize)
max_write = kMaxRecvBufferSize;
if (!max_write)
return ERR_IO_PENDING;
recv_buffer_ = new IOBuffer(max_write);
int rv = transport_->socket()->Read(recv_buffer_, max_write,
&buffer_recv_callback_);
if (rv == ERR_IO_PENDING) {
transport_recv_busy_ = true;
} else {
TransportReadComplete(rv);
}
return rv;
}
void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
TransportReadComplete(result);
OnRecvComplete(result);
}
void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
if (result > 0) {
int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
// A write into a memory BIO should always succeed.
CHECK_EQ(result, ret);
} else {
// Received end of file: bubble it up to the SSL layer via the BIO.
BIO_set_mem_eof_return(transport_bio_, 0);
(void)BIO_shutdown_wr(transport_bio_);
}
recv_buffer_ = NULL;
transport_recv_busy_ = false;
}
void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
CompletionCallback* c = user_connect_callback_;
user_connect_callback_ = NULL;
c->Run(rv > OK ? OK : rv);
}
void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
int rv = DoHandshakeLoop(result);
if (rv != ERR_IO_PENDING) {
net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
DoConnectCallback(rv);
}
}
void SSLClientSocketOpenSSL::OnSendComplete(int result) {
if (next_handshake_state_ != STATE_NONE) {
// In handshake phase.
OnHandshakeIOComplete(result);
return;
}
// OnSendComplete may need to call DoPayloadRead while the renegotiation
// handshake is in progress.
int rv_read = ERR_IO_PENDING;
int rv_write = ERR_IO_PENDING;
bool network_moved;
do {
if (user_read_buf_)
rv_read = DoPayloadRead();
if (user_write_buf_)
rv_write = DoPayloadWrite();
network_moved = DoTransportIO();
} while (rv_read == ERR_IO_PENDING &&
rv_write == ERR_IO_PENDING &&
network_moved);
if (user_read_buf_ && rv_read != ERR_IO_PENDING)
DoReadCallback(rv_read);
if (user_write_buf_ && rv_write != ERR_IO_PENDING)
DoWriteCallback(rv_write);
}
void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
if (next_handshake_state_ != STATE_NONE) {
// In handshake phase.
OnHandshakeIOComplete(result);
return;
}
// Network layer received some data, check if client requested to read
// decrypted data.
if (!user_read_buf_)
return;
int rv = DoReadLoop(result);
if (rv != ERR_IO_PENDING)
DoReadCallback(rv);
}
bool SSLClientSocketOpenSSL::IsConnected() const {
bool ret = completed_handshake_ && transport_->socket()->IsConnected();
return ret;
}
bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
return ret;
}
int SSLClientSocketOpenSSL::GetPeerAddress(AddressList* addressList) const {
return transport_->socket()->GetPeerAddress(addressList);
}
const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
return net_log_;
}
void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
if (transport_.get() && transport_->socket()) {
transport_->socket()->SetSubresourceSpeculation();
} else {
NOTREACHED();
}
}
void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
if (transport_.get() && transport_->socket()) {
transport_->socket()->SetOmniboxSpeculation();
} else {
NOTREACHED();
}
}
bool SSLClientSocketOpenSSL::WasEverUsed() const {
if (transport_.get() && transport_->socket())
return transport_->socket()->WasEverUsed();
NOTREACHED();
return false;
}
// Socket methods
int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
int buf_len,
CompletionCallback* callback) {
user_read_buf_ = buf;
user_read_buf_len_ = buf_len;
int rv = DoReadLoop(OK);
if (rv == ERR_IO_PENDING) {
user_read_callback_ = callback;
} else {
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
}
return rv;
}
int SSLClientSocketOpenSSL::DoReadLoop(int result) {
if (result < 0)
return result;
bool network_moved;
int rv;
do {
rv = DoPayloadRead();
network_moved = DoTransportIO();
} while (rv == ERR_IO_PENDING && network_moved);
return rv;
}
int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
int buf_len,
CompletionCallback* callback) {
user_write_buf_ = buf;
user_write_buf_len_ = buf_len;
int rv = DoWriteLoop(OK);
if (rv == ERR_IO_PENDING) {
user_write_callback_ = callback;
} else {
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
}
return rv;
}
int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
if (result < 0)
return result;
bool network_moved;
int rv;
do {
rv = DoPayloadWrite();
network_moved = DoTransportIO();
} while (rv == ERR_IO_PENDING && network_moved);
return rv;
}
bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
return transport_->socket()->SetReceiveBufferSize(size);
}
bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
return transport_->socket()->SetSendBufferSize(size);
}
int SSLClientSocketOpenSSL::DoPayloadRead() {
int rv = SSL_read(ssl_, user_read_buf_->data(), user_read_buf_len_);
// We don't need to invalidate the non-client-authenticated SSL session
// because the server will renegotiate anyway.
if (client_auth_cert_needed_)
return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
if (rv >= 0)
return rv;
int err = SSL_get_error(ssl_, rv);
return MapOpenSSLError(err);
}
int SSLClientSocketOpenSSL::DoPayloadWrite() {
int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
if (rv >= 0)
return rv;
int err = SSL_get_error(ssl_, rv);
return MapOpenSSLError(err);
}
} // namespace net
|