• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 fsyncd, Berlin, Germany.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 use rand::RngCore;
18 use sha2::{Digest, Sha256};
19 use std::io::{Read, Write};
20 use vsock::{get_local_cid, SockAddr, VsockAddr, VsockStream, VMADDR_CID_HOST};
21 
22 const TEST_BLOB_SIZE: usize = 1_000_000;
23 const TEST_BLOCK_SIZE: usize = 5_000;
24 
25 /// A simple test for the vsock implementation.
26 /// Generate a large random blob of binary data, and transfer it in chunks over the VsockStream
27 /// interface. The vm enpoint is running a simple echo server, so for each chunk we will read
28 /// it's reply and compute a checksum. Comparing the data sent and received confirms that the
29 /// vsock implementation does not introduce corruption and properly implements the interface
30 /// semantics.
31 #[test]
test_vsock()32 fn test_vsock() {
33     let mut rng = rand::thread_rng();
34     let mut blob: Vec<u8> = vec![];
35     let mut rx_blob = vec![];
36     let mut tx_pos = 0;
37 
38     blob.resize(TEST_BLOB_SIZE, 0);
39     rx_blob.resize(TEST_BLOB_SIZE, 0);
40     rng.fill_bytes(&mut blob);
41 
42     let mut stream =
43         VsockStream::connect(&SockAddr::Vsock(VsockAddr::new(3, 8000))).expect("connection failed");
44 
45     while tx_pos < TEST_BLOB_SIZE {
46         let written_bytes = stream
47             .write(&blob[tx_pos..tx_pos + TEST_BLOCK_SIZE])
48             .expect("write failed");
49         if written_bytes == 0 {
50             panic!("stream unexpectedly closed");
51         }
52 
53         let mut rx_pos = tx_pos;
54         while rx_pos < (tx_pos + written_bytes) {
55             let read_bytes = stream.read(&mut rx_blob[rx_pos..]).expect("read failed");
56             if read_bytes == 0 {
57                 panic!("stream unexpectedly closed");
58             }
59             rx_pos += read_bytes;
60         }
61 
62         tx_pos += written_bytes;
63     }
64 
65     let expected = Sha256::digest(&blob);
66     let actual = Sha256::digest(&rx_blob);
67 
68     assert_eq!(expected, actual);
69 }
70 
71 #[test]
test_get_local_cid()72 fn test_get_local_cid() {
73     assert_eq!(get_local_cid().unwrap(), VMADDR_CID_HOST);
74 }
75