· 8 years ago · Dec 19, 2017, 08:26 PM
1fn handle_connection<H: Handler>(
2 log: &Logger,
3 our_public_key: &PublicKey, our_secret_key: &SecretKey,
4 mut stream: TcpStream, handler: &H
5) ->
6 Result<(), NetworkingError>
7{
8 // Set up the logger for this new connection
9 let connection_log = log.new(o!("peer" => stream.peer_addr()?.to_string()));
10 info!(connection_log, "Starting new connection");
11
12 // Receive the header and decrypt it
13 let header_encrypted = packet::recv(&mut stream)?;
14 let header_data = sealedbox::open(&header_encrypted, our_public_key, our_secret_key)
15 .map_err(|_| NetworkingError::ProtocolError)?;
16
17 // Split the data into parts, making sure it's of valid size
18 let end = box_::PUBLICKEYBYTES + box_::NONCEBYTES;
19 if header_data.len() != end {
20 return Err(NetworkingError::ProtocolError);
21 }
22 let key_raw = &header_data[0..box_::PUBLICKEYBYTES];
23 let nonce_raw = &header_data[box_::PUBLICKEYBYTES..end];
24
25 // Get the client's pkey and nonce from the data
26 let their_public_key = PublicKey::from_slice(&key_raw).unwrap();
27 let precomputed_key = box_::precompute(&their_public_key, &our_secret_key);
28 let nonce = Nonce::from_slice(&nonce_raw).unwrap();
29
30 // Receive the request itself and decrypt it
31 let request_encrypted = packet::recv(&mut stream)?;
32 let request_data = box_::open_precomputed(&request_encrypted, &nonce, &precomputed_key)
33 .map_err(|_| NetworkingError::ProtocolError)?;
34
35 // Pass on the data to the library user's handler
36 let response_data = handler.invoke(connection_log, request_data);
37
38 // Encrypt the response and send it back to the client, incrementing the nonce so the request
39 // can't be replayed as a response
40 let nonce = nonce.increment_le();
41 let response_encrypted = box_::seal_precomputed(&response_data, &nonce, &precomputed_key);
42 packet::send(&mut stream, &response_encrypted)?;
43
44 Ok(())
45}