File: many_connections.rs

package info (click to toggle)
rust-quinn 0.11.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 620 kB
  • sloc: makefile: 2
file content (189 lines) | stat: -rw-r--r-- 6,618 bytes parent folder | download
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
#![cfg(any(feature = "rustls", feature = "rustls-ring"))]
use std::{
    convert::TryInto,
    net::{IpAddr, Ipv4Addr, SocketAddr},
    sync::{Arc, Mutex},
    time::Duration,
};

use crc::Crc;
use quinn::{ConnectionError, ReadError, StoppedError, TransportConfig, WriteError};
use rand::{self, RngCore};
use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
use tokio::runtime::Builder;

struct Shared {
    errors: Vec<ConnectionError>,
}

#[test]
#[ignore]
fn connect_n_nodes_to_1_and_send_1mb_data() {
    /*tracing::subscriber::set_global_default(
        tracing_subscriber::FmtSubscriber::builder()
            .finish(),
    )
    .unwrap();*/

    let runtime = Builder::new_current_thread().enable_all().build().unwrap();
    let _guard = runtime.enter();
    let shared = Arc::new(Mutex::new(Shared { errors: vec![] }));

    let (cfg, listener_cert) = configure_listener();
    let endpoint =
        quinn::Endpoint::server(cfg, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)).unwrap();
    let listener_addr = endpoint.local_addr().unwrap();

    let expected_messages = 50;

    let crc = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
    let shared2 = shared.clone();
    let endpoint2 = endpoint.clone();
    let read_incoming_data = async move {
        for _ in 0..expected_messages {
            let conn = endpoint2.accept().await.unwrap().await.unwrap();

            let shared = shared2.clone();
            let task = async move {
                while let Ok(stream) = conn.accept_uni().await {
                    read_from_peer(stream).await?;
                    conn.close(0u32.into(), &[]);
                }
                Ok(())
            };
            tokio::spawn(async move {
                if let Err(e) = task.await {
                    shared.lock().unwrap().errors.push(e);
                }
            });
        }
    };
    runtime.spawn(read_incoming_data);

    let client_cfg = configure_connector(listener_cert);

    for _ in 0..expected_messages {
        let data = random_data_with_hash(1024 * 1024, &crc);
        let shared = shared.clone();
        let connecting = endpoint
            .connect_with(client_cfg.clone(), listener_addr, "localhost")
            .unwrap();
        let task = async move {
            let conn = connecting.await.map_err(WriteError::ConnectionLost)?;
            write_to_peer(conn, data).await?;
            Ok(())
        };
        runtime.spawn(async move {
            if let Err(e) = task.await {
                use quinn::ConnectionError::*;
                match e {
                    WriteError::ConnectionLost(ApplicationClosed { .. })
                    | WriteError::ConnectionLost(Reset) => {}
                    WriteError::ConnectionLost(e) => shared.lock().unwrap().errors.push(e),
                    _ => panic!("unexpected write error"),
                }
            }
        });
    }

    runtime.block_on(endpoint.wait_idle());
    let shared = shared.lock().unwrap();
    if !shared.errors.is_empty() {
        panic!("some connections failed: {:?}", shared.errors);
    }
}

async fn read_from_peer(mut stream: quinn::RecvStream) -> Result<(), quinn::ConnectionError> {
    let crc = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
    match stream.read_to_end(1024 * 1024 * 5).await {
        Ok(data) => {
            assert!(hash_correct(&data, &crc));
            Ok(())
        }
        Err(e) => {
            use quinn::ReadToEndError::*;
            use ReadError::*;
            match e {
                TooLong | Read(ClosedStream) | Read(ZeroRttRejected) | Read(IllegalOrderedRead) => {
                    unreachable!()
                }
                Read(Reset(error_code)) => panic!("unexpected stream reset: {error_code}"),
                Read(ConnectionLost(e)) => Err(e),
            }
        }
    }
}

async fn write_to_peer(conn: quinn::Connection, data: Vec<u8>) -> Result<(), WriteError> {
    let mut s = conn.open_uni().await.map_err(WriteError::ConnectionLost)?;
    s.write_all(&data).await?;
    s.finish().unwrap();
    // Wait for the stream to be fully received
    match s.stopped().await {
        Ok(_) => Ok(()),
        Err(StoppedError::ConnectionLost(ConnectionError::ApplicationClosed { .. })) => Ok(()),
        Err(e) => Err(e.into()),
    }
}

/// Builds client configuration. Trusts given node certificate.
fn configure_connector(node_cert: CertificateDer<'static>) -> quinn::ClientConfig {
    let mut roots = rustls::RootCertStore::empty();
    roots.add(node_cert).unwrap();

    let mut transport_config = TransportConfig::default();
    transport_config.max_idle_timeout(Some(Duration::from_secs(20).try_into().unwrap()));

    let mut peer_cfg = quinn::ClientConfig::with_root_certificates(Arc::new(roots)).unwrap();
    peer_cfg.transport_config(Arc::new(transport_config));
    peer_cfg
}

/// Builds listener configuration along with its certificate.
fn configure_listener() -> (quinn::ServerConfig, CertificateDer<'static>) {
    let (our_cert, our_priv_key) = gen_cert();
    let mut our_cfg =
        quinn::ServerConfig::with_single_cert(vec![our_cert.clone()], our_priv_key.into()).unwrap();

    let transport_config = Arc::get_mut(&mut our_cfg.transport).unwrap();
    transport_config.max_idle_timeout(Some(Duration::from_secs(20).try_into().unwrap()));

    (our_cfg, our_cert)
}

fn gen_cert() -> (CertificateDer<'static>, PrivatePkcs8KeyDer<'static>) {
    let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
    (
        cert.cert.into(),
        PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der()),
    )
}

/// Constructs a buffer with random bytes of given size prefixed with a hash of this data.
fn random_data_with_hash(size: usize, crc: &Crc<u32>) -> Vec<u8> {
    let mut data = random_vec(size + 4);
    let hash = crc.checksum(&data[4..]);
    // write hash in big endian
    data[0] = (hash >> 24) as u8;
    data[1] = ((hash >> 16) & 0xff) as u8;
    data[2] = ((hash >> 8) & 0xff) as u8;
    data[3] = (hash & 0xff) as u8;
    data
}

/// Checks if given data buffer hash is correct. Hash itself is a 4 byte prefix in the data.
fn hash_correct(data: &[u8], crc: &Crc<u32>) -> bool {
    let encoded_hash = ((data[0] as u32) << 24)
        | ((data[1] as u32) << 16)
        | ((data[2] as u32) << 8)
        | data[3] as u32;
    let actual_hash = crc.checksum(&data[4..]);
    encoded_hash == actual_hash
}

#[allow(unsafe_code)]
fn random_vec(size: usize) -> Vec<u8> {
    let mut ret = vec![0; size];
    rand::thread_rng().fill_bytes(&mut ret[..]);
    ret
}