1
1
//! TLS support.
2
+ use std:: collections:: HashMap ;
2
3
use std:: sync:: Arc ;
3
4
4
5
use anyhow:: Result ;
6
+ use once_cell:: sync:: Lazy ;
7
+ use parking_lot:: Mutex ;
5
8
6
9
use crate :: net:: session:: SessionStream ;
7
10
11
+ use tokio_rustls:: rustls:: client:: ClientSessionStore ;
12
+
8
13
pub async fn wrap_tls (
9
14
strict_tls : bool ,
10
15
hostname : & str ,
16
+ port : u16 ,
11
17
alpn : & str ,
12
18
stream : impl SessionStream + ' static ,
13
19
) -> Result < impl SessionStream > {
14
20
if strict_tls {
15
- let tls_stream = wrap_rustls ( hostname, alpn, stream) . await ?;
21
+ let tls_stream = wrap_rustls ( hostname, port , alpn, stream) . await ?;
16
22
let boxed_stream: Box < dyn SessionStream > = Box :: new ( tls_stream) ;
17
23
Ok ( boxed_stream)
18
24
} else {
@@ -35,8 +41,12 @@ pub async fn wrap_tls(
35
41
}
36
42
}
37
43
44
+ static RESUMPTION_STORE : Lazy < Mutex < HashMap < ( u16 , String ) , Arc < dyn ClientSessionStore > > > > =
45
+ Lazy :: new ( Default :: default) ;
46
+
38
47
pub async fn wrap_rustls (
39
48
hostname : & str ,
49
+ port : u16 ,
40
50
alpn : & str ,
41
51
stream : impl SessionStream ,
42
52
) -> Result < impl SessionStream > {
@@ -52,6 +62,27 @@ pub async fn wrap_rustls(
52
62
vec ! [ alpn. as_bytes( ) . to_vec( ) ]
53
63
} ;
54
64
65
+ // Enable TLS 1.3 session resumption.
66
+ //
67
+ // TLS 1.2 has worse security,
68
+ // not risking it: <https://words.filippo.io/we-need-to-talk-about-session-tickets/>
69
+ let resumption_store;
70
+ {
71
+ let mut lock = RESUMPTION_STORE . lock ( ) ;
72
+ let entry = lock. entry ( ( port, alpn. to_string ( ) ) ) ;
73
+ let store = entry. or_insert_with ( || {
74
+ // This is the default as of version 0.23.16, but make it shared between clients.
75
+ Arc :: new ( tokio_rustls:: rustls:: client:: ClientSessionMemoryCache :: new (
76
+ 256 ,
77
+ ) )
78
+ } ) ;
79
+ resumption_store = Arc :: clone ( store) ;
80
+ }
81
+
82
+ let resumption = tokio_rustls:: rustls:: client:: Resumption :: store ( resumption_store)
83
+ . tls12_resumption ( tokio_rustls:: rustls:: client:: Tls12Resumption :: Disabled ) ;
84
+ config. resumption = resumption;
85
+
55
86
let tls = tokio_rustls:: TlsConnector :: from ( Arc :: new ( config) ) ;
56
87
let name = rustls_pki_types:: ServerName :: try_from ( hostname) ?. to_owned ( ) ;
57
88
let tls_stream = tls. connect ( name, stream) . await ?;
0 commit comments