1 use crate::msgs::enums::CipherSuite; 2 use crate::msgs::enums::{AlertDescription, HandshakeType}; 3 use crate::session::{Session, SessionCommon}; 4 use crate::keylog::{KeyLog, NoKeyLog}; 5 use crate::suites::{SupportedCipherSuite, ALL_CIPHERSUITES}; 6 use crate::msgs::handshake::CertificatePayload; 7 use crate::msgs::enums::SignatureScheme; 8 use crate::msgs::enums::{ContentType, ProtocolVersion}; 9 use crate::msgs::handshake::ClientExtension; 10 use crate::msgs::message::Message; 11 use crate::verify; 12 use crate::anchors; 13 use crate::sign; 14 use crate::error::TLSError; 15 use crate::key; 16 use crate::vecbuf::WriteV; 17 #[cfg(feature = "logging")] 18 use crate::log::trace; 19 20 use std::sync::Arc; 21 use std::io; 22 use std::fmt; 23 use std::mem; 24 25 use sct; 26 use webpki; 27 28 #[macro_use] 29 mod hs; 30 mod tls12; 31 mod tls13; 32 mod common; 33 pub mod handy; 34 35 /// A trait for the ability to store client session data. 36 /// The keys and values are opaque. 37 /// 38 /// Both the keys and values should be treated as 39 /// **highly sensitive data**, containing enough key material 40 /// to break all security of the corresponding session. 41 /// 42 /// `put` is a mutating operation; this isn't expressed 43 /// in the type system to allow implementations freedom in 44 /// how to achieve interior mutability. `Mutex` is a common 45 /// choice. 46 pub trait StoresClientSessions : Send + Sync { 47 /// Stores a new `value` for `key`. Returns `true` 48 /// if the value was stored. put(&self, key: Vec<u8>, value: Vec<u8>) -> bool49 fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool; 50 51 /// Returns the latest value for `key`. Returns `None` 52 /// if there's no such value. get(&self, key: &[u8]) -> Option<Vec<u8>>53 fn get(&self, key: &[u8]) -> Option<Vec<u8>>; 54 } 55 56 /// A trait for the ability to choose a certificate chain and 57 /// private key for the purposes of client authentication. 58 pub trait ResolvesClientCert : Send + Sync { 59 /// With the server-supplied acceptable issuers in `acceptable_issuers`, 60 /// the server's supported signature schemes in `sigschemes`, 61 /// return a certificate chain and signing key to authenticate. 62 /// 63 /// `acceptable_issuers` is undecoded and unverified by the rustls 64 /// library, but it should be expected to contain a DER encodings 65 /// of X501 NAMEs. 66 /// 67 /// Return None to continue the handshake without any client 68 /// authentication. The server may reject the handshake later 69 /// if it requires authentication. resolve(&self, acceptable_issuers: &[&[u8]], sigschemes: &[SignatureScheme]) -> Option<sign::CertifiedKey>70 fn resolve(&self, 71 acceptable_issuers: &[&[u8]], 72 sigschemes: &[SignatureScheme]) 73 -> Option<sign::CertifiedKey>; 74 75 /// Return true if any certificates at all are available. has_certs(&self) -> bool76 fn has_certs(&self) -> bool; 77 } 78 79 /// Common configuration for (typically) all connections made by 80 /// a program. 81 /// 82 /// Making one of these can be expensive, and should be 83 /// once per process rather than once per connection. 84 #[derive(Clone)] 85 pub struct ClientConfig { 86 /// List of ciphersuites, in preference order. 87 pub ciphersuites: Vec<&'static SupportedCipherSuite>, 88 89 /// Collection of root certificates. 90 pub root_store: anchors::RootCertStore, 91 92 /// Which ALPN protocols we include in our client hello. 93 /// If empty, no ALPN extension is sent. 94 pub alpn_protocols: Vec<Vec<u8>>, 95 96 /// How we store session data or tickets. 97 pub session_persistence: Arc<dyn StoresClientSessions>, 98 99 /// Our MTU. If None, we don't limit TLS message sizes. 100 pub mtu: Option<usize>, 101 102 /// How to decide what client auth certificate/keys to use. 103 pub client_auth_cert_resolver: Arc<dyn ResolvesClientCert>, 104 105 /// Whether to support RFC5077 tickets. You must provide a working 106 /// `session_persistence` member for this to have any meaningful 107 /// effect. 108 /// 109 /// The default is true. 110 pub enable_tickets: bool, 111 112 /// Supported versions, in no particular order. The default 113 /// is all supported versions. 114 pub versions: Vec<ProtocolVersion>, 115 116 /// Collection of certificate transparency logs. 117 /// If this collection is empty, then certificate transparency 118 /// checking is disabled. 119 pub ct_logs: Option<&'static [&'static sct::Log<'static>]>, 120 121 /// Whether to send the Server Name Indication (SNI) extension 122 /// during the client handshake. 123 /// 124 /// The default is true. 125 pub enable_sni: bool, 126 127 /// How to verify the server certificate chain. 128 verifier: Arc<dyn verify::ServerCertVerifier>, 129 130 /// How to output key material for debugging. The default 131 /// does nothing. 132 pub key_log: Arc<dyn KeyLog>, 133 134 /// Whether to send data on the first flight ("early data") in 135 /// TLS 1.3 handshakes. 136 /// 137 /// The default is false. 138 pub enable_early_data: bool, 139 } 140 141 impl Default for ClientConfig { default() -> Self142 fn default() -> Self { Self::new() } 143 } 144 145 impl ClientConfig { 146 /// Make a `ClientConfig` with a default set of ciphersuites, 147 /// no root certificates, no ALPN protocols, and no client auth. 148 /// 149 /// The default session persistence provider stores up to 32 150 /// items in memory. new() -> ClientConfig151 pub fn new() -> ClientConfig { 152 ClientConfig { 153 ciphersuites: ALL_CIPHERSUITES.to_vec(), 154 root_store: anchors::RootCertStore::empty(), 155 alpn_protocols: Vec::new(), 156 session_persistence: handy::ClientSessionMemoryCache::new(32), 157 mtu: None, 158 client_auth_cert_resolver: Arc::new(handy::FailResolveClientCert {}), 159 enable_tickets: true, 160 versions: vec![ProtocolVersion::TLSv1_3, ProtocolVersion::TLSv1_2], 161 ct_logs: None, 162 enable_sni: true, 163 verifier: Arc::new(verify::WebPKIVerifier::new()), 164 key_log: Arc::new(NoKeyLog {}), 165 enable_early_data: false, 166 } 167 } 168 169 #[doc(hidden)] 170 /// We support a given TLS version if it's quoted in the configured 171 /// versions *and* at least one ciphersuite for this version is 172 /// also configured. supports_version(&self, v: ProtocolVersion) -> bool173 pub fn supports_version(&self, v: ProtocolVersion) -> bool { 174 self.versions.contains(&v) && self.ciphersuites.iter().any(|cs| cs.usable_for_version(v)) 175 } 176 177 #[doc(hidden)] get_verifier(&self) -> &dyn verify::ServerCertVerifier178 pub fn get_verifier(&self) -> &dyn verify::ServerCertVerifier { 179 self.verifier.as_ref() 180 } 181 182 /// Set the ALPN protocol list to the given protocol names. 183 /// Overwrites any existing configured protocols. 184 /// The first element in the `protocols` list is the most 185 /// preferred, the last is the least preferred. set_protocols(&mut self, protocols: &[Vec<u8>])186 pub fn set_protocols(&mut self, protocols: &[Vec<u8>]) { 187 self.alpn_protocols.clear(); 188 self.alpn_protocols.extend_from_slice(protocols); 189 } 190 191 /// Sets persistence layer to `persist`. set_persistence(&mut self, persist: Arc<dyn StoresClientSessions>)192 pub fn set_persistence(&mut self, persist: Arc<dyn StoresClientSessions>) { 193 self.session_persistence = persist; 194 } 195 196 /// Sets MTU to `mtu`. If None, the default is used. 197 /// If Some(x) then x must be greater than 5 bytes. set_mtu(&mut self, mtu: &Option<usize>)198 pub fn set_mtu(&mut self, mtu: &Option<usize>) { 199 // Internally our MTU relates to fragment size, and does 200 // not include the TLS header overhead. 201 // 202 // Externally the MTU is the whole packet size. The difference 203 // is PACKET_OVERHEAD. 204 if let Some(x) = *mtu { 205 use crate::msgs::fragmenter; 206 debug_assert!(x > fragmenter::PACKET_OVERHEAD); 207 self.mtu = Some(x - fragmenter::PACKET_OVERHEAD); 208 } else { 209 self.mtu = None; 210 } 211 } 212 213 /// Sets a single client authentication certificate and private key. 214 /// This is blindly used for all servers that ask for client auth. 215 /// 216 /// `cert_chain` is a vector of DER-encoded certificates, 217 /// `key_der` is a DER-encoded RSA or ECDSA private key. set_single_client_cert(&mut self, cert_chain: Vec<key::Certificate>, key_der: key::PrivateKey) -> Result<(), TLSError>218 pub fn set_single_client_cert(&mut self, 219 cert_chain: Vec<key::Certificate>, 220 key_der: key::PrivateKey) -> Result<(), TLSError> { 221 let resolver = handy::AlwaysResolvesClientCert::new(cert_chain, &key_der)?; 222 self.client_auth_cert_resolver = Arc::new(resolver); 223 Ok(()) 224 } 225 226 /// Access configuration options whose use is dangerous and requires 227 /// extra care. 228 #[cfg(feature = "dangerous_configuration")] dangerous(&mut self) -> danger::DangerousClientConfig229 pub fn dangerous(&mut self) -> danger::DangerousClientConfig { 230 danger::DangerousClientConfig { cfg: self } 231 } 232 } 233 234 /// Container for unsafe APIs 235 #[cfg(feature = "dangerous_configuration")] 236 pub mod danger { 237 use std::sync::Arc; 238 239 use super::ClientConfig; 240 use super::verify::ServerCertVerifier; 241 242 /// Accessor for dangerous configuration options. 243 pub struct DangerousClientConfig<'a> { 244 /// The underlying ClientConfig 245 pub cfg: &'a mut ClientConfig 246 } 247 248 impl<'a> DangerousClientConfig<'a> { 249 /// Overrides the default `ServerCertVerifier` with something else. set_certificate_verifier(&mut self, verifier: Arc<dyn ServerCertVerifier>)250 pub fn set_certificate_verifier(&mut self, 251 verifier: Arc<dyn ServerCertVerifier>) { 252 self.cfg.verifier = verifier; 253 } 254 } 255 } 256 257 #[derive(Debug, PartialEq)] 258 enum EarlyDataState { 259 Disabled, 260 Ready, 261 Accepted, 262 AcceptedFinished, 263 Rejected, 264 } 265 266 pub struct EarlyData { 267 state: EarlyDataState, 268 left: usize, 269 } 270 271 impl EarlyData { new() -> EarlyData272 fn new() -> EarlyData { 273 EarlyData { 274 left: 0, 275 state: EarlyDataState::Disabled, 276 } 277 } 278 is_enabled(&self) -> bool279 fn is_enabled(&self) -> bool { 280 match self.state { 281 EarlyDataState::Ready | EarlyDataState::Accepted => true, 282 _ => false 283 } 284 } 285 is_accepted(&self) -> bool286 fn is_accepted(&self) -> bool { 287 match self.state { 288 EarlyDataState::Accepted | EarlyDataState::AcceptedFinished => true, 289 _ => false 290 } 291 } 292 enable(&mut self, max_data: usize)293 fn enable(&mut self, max_data: usize) { 294 assert_eq!(self.state, EarlyDataState::Disabled); 295 self.state = EarlyDataState::Ready; 296 self.left = max_data; 297 } 298 rejected(&mut self)299 fn rejected(&mut self) { 300 trace!("EarlyData rejected"); 301 self.state = EarlyDataState::Rejected; 302 } 303 accepted(&mut self)304 fn accepted(&mut self) { 305 trace!("EarlyData accepted"); 306 assert_eq!(self.state, EarlyDataState::Ready); 307 self.state = EarlyDataState::Accepted; 308 } 309 finished(&mut self)310 fn finished(&mut self) { 311 trace!("EarlyData finished"); 312 self.state = match self.state { 313 EarlyDataState::Accepted => EarlyDataState::AcceptedFinished, 314 _ => panic!("bad EarlyData state"), 315 } 316 } 317 check_write(&mut self, sz: usize) -> io::Result<usize>318 fn check_write(&mut self, sz: usize) -> io::Result<usize> { 319 match self.state { 320 EarlyDataState::Disabled => unreachable!(), 321 EarlyDataState::Ready | EarlyDataState::Accepted => { 322 let take = if self.left < sz { 323 mem::replace(&mut self.left, 0) 324 } else { 325 self.left -= sz; 326 sz 327 }; 328 329 Ok(take) 330 }, 331 EarlyDataState::Rejected 332 | EarlyDataState::AcceptedFinished => { 333 Err(io::Error::from(io::ErrorKind::InvalidInput)) 334 }, 335 } 336 } 337 bytes_left(&self) -> usize338 fn bytes_left(&self) -> usize { 339 self.left 340 } 341 } 342 343 /// Stub that implements io::Write and dispatches to `write_early_data`. 344 pub struct WriteEarlyData<'a> { 345 sess: &'a mut ClientSessionImpl, 346 } 347 348 impl<'a> WriteEarlyData<'a> { new(sess: &'a mut ClientSessionImpl) -> WriteEarlyData<'a>349 fn new(sess: &'a mut ClientSessionImpl) -> WriteEarlyData<'a> { 350 WriteEarlyData { sess } 351 } 352 353 /// How many bytes you may send. Writes will become short 354 /// once this reaches zero. bytes_left(&self) -> usize355 pub fn bytes_left(&self) -> usize { 356 self.sess.early_data.bytes_left() 357 } 358 } 359 360 impl<'a> io::Write for WriteEarlyData<'a> { write(&mut self, buf: &[u8]) -> io::Result<usize>361 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 362 self.sess.write_early_data(buf) 363 } 364 flush(&mut self) -> io::Result<()>365 fn flush(&mut self) -> io::Result<()> { 366 Ok(()) 367 } 368 } 369 370 pub struct ClientSessionImpl { 371 pub config: Arc<ClientConfig>, 372 pub alpn_protocol: Option<Vec<u8>>, 373 pub common: SessionCommon, 374 pub error: Option<TLSError>, 375 pub state: Option<Box<dyn hs::State + Send + Sync>>, 376 pub server_cert_chain: CertificatePayload, 377 pub early_data: EarlyData, 378 pub resumption_ciphersuite: Option<&'static SupportedCipherSuite>, 379 } 380 381 impl fmt::Debug for ClientSessionImpl { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result382 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 383 f.debug_struct("ClientSessionImpl").finish() 384 } 385 } 386 387 impl ClientSessionImpl { new(config: &Arc<ClientConfig>) -> ClientSessionImpl388 pub fn new(config: &Arc<ClientConfig>) -> ClientSessionImpl { 389 ClientSessionImpl { 390 config: config.clone(), 391 alpn_protocol: None, 392 common: SessionCommon::new(config.mtu, true), 393 error: None, 394 state: None, 395 server_cert_chain: Vec::new(), 396 early_data: EarlyData::new(), 397 resumption_ciphersuite: None, 398 } 399 } 400 start_handshake(&mut self, hostname: webpki::DNSName, extra_exts: Vec<ClientExtension>)401 pub fn start_handshake(&mut self, hostname: webpki::DNSName, extra_exts: Vec<ClientExtension>) { 402 self.state = Some(hs::start_handshake(self, hostname, extra_exts)); 403 } 404 get_cipher_suites(&self) -> Vec<CipherSuite>405 pub fn get_cipher_suites(&self) -> Vec<CipherSuite> { 406 let mut ret = Vec::new(); 407 408 for cs in &self.config.ciphersuites { 409 ret.push(cs.suite); 410 } 411 412 // We don't do renegotation at all, in fact. 413 ret.push(CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV); 414 415 ret 416 } 417 find_cipher_suite(&self, suite: CipherSuite) -> Option<&'static SupportedCipherSuite>418 pub fn find_cipher_suite(&self, suite: CipherSuite) -> Option<&'static SupportedCipherSuite> { 419 for scs in &self.config.ciphersuites { 420 if scs.suite == suite { 421 return Some(scs); 422 } 423 } 424 425 None 426 } 427 wants_read(&self) -> bool428 pub fn wants_read(&self) -> bool { 429 // We want to read more data all the time, except when we 430 // have unprocessed plaintext. This provides back-pressure 431 // to the TCP buffers. 432 // 433 // This also covers the handshake case, because we don't have 434 // readable plaintext before handshake has completed. 435 !self.common.has_readable_plaintext() 436 } 437 wants_write(&self) -> bool438 pub fn wants_write(&self) -> bool { 439 !self.common.sendable_tls.is_empty() 440 } 441 is_handshaking(&self) -> bool442 pub fn is_handshaking(&self) -> bool { 443 !self.common.traffic 444 } 445 set_buffer_limit(&mut self, len: usize)446 pub fn set_buffer_limit(&mut self, len: usize) { 447 self.common.set_buffer_limit(len) 448 } 449 process_msg(&mut self, mut msg: Message) -> Result<(), TLSError>450 pub fn process_msg(&mut self, mut msg: Message) -> Result<(), TLSError> { 451 // TLS1.3: drop CCS at any time during handshaking 452 if self.common.is_tls13() 453 && msg.is_content_type(ContentType::ChangeCipherSpec) 454 && self.is_handshaking() { 455 trace!("Dropping CCS"); 456 return Ok(()); 457 } 458 459 // Decrypt if demanded by current state. 460 if self.common.record_layer.is_decrypting() { 461 let dm = self.common.decrypt_incoming(msg)?; 462 msg = dm; 463 } 464 465 // For handshake messages, we need to join them before parsing 466 // and processing. 467 if self.common.handshake_joiner.want_message(&msg) { 468 self.common 469 .handshake_joiner 470 .take_message(msg) 471 .ok_or_else(|| { 472 self.common.send_fatal_alert(AlertDescription::DecodeError); 473 TLSError::CorruptMessagePayload(ContentType::Handshake) 474 })?; 475 return self.process_new_handshake_messages(); 476 } 477 478 // Now we can fully parse the message payload. 479 if !msg.decode_payload() { 480 return Err(TLSError::CorruptMessagePayload(msg.typ)); 481 } 482 483 // For alerts, we have separate logic. 484 if msg.is_content_type(ContentType::Alert) { 485 return self.common.process_alert(msg); 486 } 487 488 self.process_main_protocol(msg) 489 } 490 process_new_handshake_messages(&mut self) -> Result<(), TLSError>491 pub fn process_new_handshake_messages(&mut self) -> Result<(), TLSError> { 492 while let Some(msg) = self.common.handshake_joiner.frames.pop_front() { 493 self.process_main_protocol(msg)?; 494 } 495 496 Ok(()) 497 } 498 queue_unexpected_alert(&mut self)499 fn queue_unexpected_alert(&mut self) { 500 self.common.send_fatal_alert(AlertDescription::UnexpectedMessage); 501 } 502 reject_renegotiation_attempt(&mut self) -> Result<(), TLSError>503 fn reject_renegotiation_attempt(&mut self) -> Result<(), TLSError> { 504 self.common.send_warning_alert(AlertDescription::NoRenegotiation); 505 Ok(()) 506 } 507 508 /// Process `msg`. First, we get the current state. Then we ask what messages 509 /// that state expects, enforced via `check_message`. Finally, we ask the handler 510 /// to handle the message. process_main_protocol(&mut self, msg: Message) -> Result<(), TLSError>511 fn process_main_protocol(&mut self, msg: Message) -> Result<(), TLSError> { 512 // For TLS1.2, outside of the handshake, send rejection alerts for 513 // renegotation requests. These can occur any time. 514 if msg.is_handshake_type(HandshakeType::HelloRequest) && 515 !self.common.is_tls13() && 516 !self.is_handshaking() { 517 return self.reject_renegotiation_attempt(); 518 } 519 520 let state = self.state.take().unwrap(); 521 state 522 .check_message(&msg) 523 .map_err(|err| { 524 self.queue_unexpected_alert(); 525 err 526 })?; 527 self.state = Some(state.handle(self, msg)?); 528 529 Ok(()) 530 } 531 process_new_packets(&mut self) -> Result<(), TLSError>532 pub fn process_new_packets(&mut self) -> Result<(), TLSError> { 533 if let Some(ref err) = self.error { 534 return Err(err.clone()); 535 } 536 537 if self.common.message_deframer.desynced { 538 return Err(TLSError::CorruptMessage); 539 } 540 541 while let Some(msg) = self.common.message_deframer.frames.pop_front() { 542 match self.process_msg(msg) { 543 Ok(_) => {} 544 Err(err) => { 545 self.error = Some(err.clone()); 546 return Err(err); 547 } 548 } 549 } 550 551 Ok(()) 552 } 553 get_peer_certificates(&self) -> Option<Vec<key::Certificate>>554 pub fn get_peer_certificates(&self) -> Option<Vec<key::Certificate>> { 555 if self.server_cert_chain.is_empty() { 556 return None; 557 } 558 559 let mut r = Vec::new(); 560 for cert in &self.server_cert_chain { 561 r.push(cert.clone()); 562 } 563 564 Some(r) 565 } 566 get_alpn_protocol(&self) -> Option<&[u8]>567 pub fn get_alpn_protocol(&self) -> Option<&[u8]> { 568 self.alpn_protocol.as_ref().map(AsRef::as_ref) 569 } 570 get_protocol_version(&self) -> Option<ProtocolVersion>571 pub fn get_protocol_version(&self) -> Option<ProtocolVersion> { 572 self.common.negotiated_version 573 } 574 get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite>575 pub fn get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite> { 576 self.common.get_suite() 577 } 578 write_early_data(&mut self, data: &[u8]) -> io::Result<usize>579 pub fn write_early_data(&mut self, data: &[u8]) -> io::Result<usize> { 580 self.early_data.check_write(data.len()) 581 .and_then(|sz| { 582 self.common.send_early_plaintext(&data[..sz]) 583 }) 584 } 585 export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) -> Result<(), TLSError>586 fn export_keying_material(&self, 587 output: &mut [u8], 588 label: &[u8], 589 context: Option<&[u8]>) -> Result<(), TLSError> { 590 self.state 591 .as_ref() 592 .ok_or_else(|| TLSError::HandshakeNotComplete) 593 .and_then(|st| st.export_keying_material(output, label, context)) 594 } 595 send_some_plaintext(&mut self, buf: &[u8]) -> io::Result<usize>596 fn send_some_plaintext(&mut self, buf: &[u8]) -> io::Result<usize> { 597 let mut st = self.state.take(); 598 st.as_mut() 599 .map(|st| st.perhaps_write_key_update(self)); 600 self.state = st; 601 602 self.common.send_some_plaintext(buf) 603 } 604 } 605 606 /// This represents a single TLS client session. 607 #[derive(Debug)] 608 pub struct ClientSession { 609 // We use the pimpl idiom to hide unimportant details. 610 pub(crate) imp: ClientSessionImpl, 611 } 612 613 impl ClientSession { 614 /// Make a new ClientSession. `config` controls how 615 /// we behave in the TLS protocol, `hostname` is the 616 /// hostname of who we want to talk to. new(config: &Arc<ClientConfig>, hostname: webpki::DNSNameRef) -> ClientSession617 pub fn new(config: &Arc<ClientConfig>, hostname: webpki::DNSNameRef) -> ClientSession { 618 let mut imp = ClientSessionImpl::new(config); 619 imp.start_handshake(hostname.into(), vec![]); 620 ClientSession { imp } 621 } 622 623 /// Returns an `io::Write` implementor you can write bytes to 624 /// to send TLS1.3 early data (a.k.a. "0-RTT data") to the server. 625 /// 626 /// This returns None in many circumstances when the capability to 627 /// send early data is not available, including but not limited to: 628 /// 629 /// - The server hasn't been talked to previously. 630 /// - The server does not support resumption. 631 /// - The server does not support early data. 632 /// - The resumption data for the server has expired. 633 /// 634 /// The server specifies a maximum amount of early data. You can 635 /// learn this limit through the returned object, and writes through 636 /// it will process only this many bytes. 637 /// 638 /// The server can choose not to accept any sent early data -- 639 /// in this case the data is lost but the connection continues. You 640 /// can tell this happened using `is_early_data_accepted`. early_data(&mut self) -> Option<WriteEarlyData>641 pub fn early_data(&mut self) -> Option<WriteEarlyData> { 642 if self.imp.early_data.is_enabled() { 643 Some(WriteEarlyData::new(&mut self.imp)) 644 } else { 645 None 646 } 647 } 648 649 /// Returns True if the server signalled it will process early data. 650 /// 651 /// If you sent early data and this returns false at the end of the 652 /// handshake then the server will not process the data. This 653 /// is not an error, but you may wish to resend the data. is_early_data_accepted(&self) -> bool654 pub fn is_early_data_accepted(&self) -> bool { 655 self.imp.early_data.is_accepted() 656 } 657 } 658 659 impl Session for ClientSession { read_tls(&mut self, rd: &mut dyn io::Read) -> io::Result<usize>660 fn read_tls(&mut self, rd: &mut dyn io::Read) -> io::Result<usize> { 661 self.imp.common.read_tls(rd) 662 } 663 664 /// Writes TLS messages to `wr`. write_tls(&mut self, wr: &mut dyn io::Write) -> io::Result<usize>665 fn write_tls(&mut self, wr: &mut dyn io::Write) -> io::Result<usize> { 666 self.imp.common.write_tls(wr) 667 } 668 writev_tls(&mut self, wr: &mut dyn WriteV) -> io::Result<usize>669 fn writev_tls(&mut self, wr: &mut dyn WriteV) -> io::Result<usize> { 670 self.imp.common.writev_tls(wr) 671 } 672 process_new_packets(&mut self) -> Result<(), TLSError>673 fn process_new_packets(&mut self) -> Result<(), TLSError> { 674 self.imp.process_new_packets() 675 } 676 wants_read(&self) -> bool677 fn wants_read(&self) -> bool { 678 self.imp.wants_read() 679 } 680 wants_write(&self) -> bool681 fn wants_write(&self) -> bool { 682 self.imp.wants_write() 683 } 684 is_handshaking(&self) -> bool685 fn is_handshaking(&self) -> bool { 686 self.imp.is_handshaking() 687 } 688 set_buffer_limit(&mut self, len: usize)689 fn set_buffer_limit(&mut self, len: usize) { 690 self.imp.set_buffer_limit(len) 691 } 692 send_close_notify(&mut self)693 fn send_close_notify(&mut self) { 694 self.imp.common.send_close_notify() 695 } 696 get_peer_certificates(&self) -> Option<Vec<key::Certificate>>697 fn get_peer_certificates(&self) -> Option<Vec<key::Certificate>> { 698 self.imp.get_peer_certificates() 699 } 700 get_alpn_protocol(&self) -> Option<&[u8]>701 fn get_alpn_protocol(&self) -> Option<&[u8]> { 702 self.imp.get_alpn_protocol() 703 } 704 get_protocol_version(&self) -> Option<ProtocolVersion>705 fn get_protocol_version(&self) -> Option<ProtocolVersion> { 706 self.imp.get_protocol_version() 707 } 708 export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) -> Result<(), TLSError>709 fn export_keying_material(&self, 710 output: &mut [u8], 711 label: &[u8], 712 context: Option<&[u8]>) -> Result<(), TLSError> { 713 self.imp.export_keying_material(output, label, context) 714 } 715 get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite>716 fn get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite> { 717 self.imp.get_negotiated_ciphersuite().or(self.imp.resumption_ciphersuite) 718 } 719 720 } 721 722 impl io::Read for ClientSession { 723 /// Obtain plaintext data received from the peer over 724 /// this TLS connection. read(&mut self, buf: &mut [u8]) -> io::Result<usize>725 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { 726 self.imp.common.read(buf) 727 } 728 } 729 730 impl io::Write for ClientSession { 731 /// Send the plaintext `buf` to the peer, encrypting 732 /// and authenticating it. Once this function succeeds 733 /// you should call `write_tls` which will output the 734 /// corresponding TLS records. 735 /// 736 /// This function buffers plaintext sent before the 737 /// TLS handshake completes, and sends it as soon 738 /// as it can. This buffer is of *unlimited size* so 739 /// writing much data before it can be sent will 740 /// cause excess memory usage. write(&mut self, buf: &[u8]) -> io::Result<usize>741 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 742 self.imp.send_some_plaintext(buf) 743 } 744 flush(&mut self) -> io::Result<()>745 fn flush(&mut self) -> io::Result<()> { 746 self.imp.common.flush_plaintext(); 747 Ok(()) 748 } 749 } 750