vsock-0.2.4/.cargo/config000064400000000000000000000000540000000000000132710ustar 00000000000000[build] target = "x86_64-unknown-linux-musl"vsock-0.2.4/.cargo_vcs_info.json0000644000000001120000000000000121550ustar { "git": { "sha1": "56852d4006efce337875594e6a21ec49f0fc9c89" } } vsock-0.2.4/.github/workflows/bvt.yaml000064400000000000000000000015260000000000000160110ustar 00000000000000name: BVT on: [pull_request] jobs: bvt: name: BVT runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: install dependencies run: | rustup target add x86_64-unknown-linux-musl rustup component add rustfmt clippy - name: Format Check run: make fmt - name: Clippy Check run: make clippy - name: Build run: make vsock - name: Build echo_server run: make echo_server ## Unfortunately GitHub Acions doesn't support nested virtualization at the moment, ## And the vsock have bugs on qemu + tcg, so we can't run the unit test for now. # - name: Install QEMU # run: | # sudo apt-get install qemu-system-x86 -y # sudo modprobe vhost_vsock # - name: Run Unit Test # run: | # make vm-for-action # make check vsock-0.2.4/.github/workflows/commit-message-check.yaml000064400000000000000000000031270000000000000212020ustar 00000000000000name: Commit Message Check on: pull_request: types: - opened - reopened - synchronize env: error_msg: |+ See the document below for help on formatting commits for the project. https://github.com/kata-containers/community/blob/master/CONTRIBUTING.md#patch-forma jobs: commit-message-check: runs-on: ubuntu-latest name: Commit Message Check steps: - name: Get PR Commits id: 'get-pr-commits' uses: tim-actions/get-pr-commits@v1.0.0 with: token: ${{ secrets.GITHUB_TOKEN }} - name: DCO Check uses: tim-actions/dco@2fd0504dc0d27b33f542867c300c60840c6dcb20 with: commits: ${{ steps.get-pr-commits.outputs.commits }} - name: Commit Body Missing Check if: ${{ success() || failure() }} uses: tim-actions/commit-body-check@v1.0.2 with: commits: ${{ steps.get-pr-commits.outputs.commits }} - name: Check Subject Line Length if: ${{ success() || failure() }} uses: tim-actions/commit-message-checker-with-regex@v0.3.1 with: commits: ${{ steps.get-pr-commits.outputs.commits }} pattern: '^.{0,75}(\n.*)*$' error: 'Subject too long (max 75)' post_error: ${{ env.error_msg }} - name: Check Body Line Length if: ${{ success() || failure() }} uses: tim-actions/commit-message-checker-with-regex@v0.3.1 with: commits: ${{ steps.get-pr-commits.outputs.commits }} pattern: '^.+(\n.{0,72})*$|^.+\n\s*[^a-zA-Z\s\n]|^.+\n\S+$' error: 'Body line too long (max 72)' post_error: ${{ env.error_msg }} vsock-0.2.4/.gitignore000064400000000000000000000000660000000000000127230ustar 00000000000000target .idea/ *.iml Cargo.lock echo_server/Cargo.lock vsock-0.2.4/Cargo.toml0000644000000017610000000000000101660ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "vsock" version = "0.2.4" authors = ["fsyncd", "rust-vsock"] exclude = ["test_fixture"] description = "Virtio socket support for Rust" homepage = "https://github.com/rust-vsock/vsock-rs" readme = "README.md" license = "Apache-2.0" repository = "https://github.com/rust-vsock/vsock-rs" [dependencies.libc] version = "0.2.79" [dependencies.nix] version = "0.19.1" [dev-dependencies.rand] version = "0.8.3" [dev-dependencies.sha2] version = ">=0.8.0" vsock-0.2.4/Cargo.toml.orig000064400000000000000000000006420000000000000136220ustar 00000000000000[package] name = "vsock" version = "0.2.4" authors = ["fsyncd", "rust-vsock"] description = "Virtio socket support for Rust" repository = "https://github.com/rust-vsock/vsock-rs" homepage = "https://github.com/rust-vsock/vsock-rs" readme = "README.md" license = "Apache-2.0" edition = "2018" exclude = ["test_fixture"] [dependencies] libc = "0.2.79" nix = "0.19.1" [dev-dependencies] rand = "0.8.3" sha2 = ">=0.8.0" vsock-0.2.4/LICENSE000064400000000000000000000261350000000000000117450ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. vsock-0.2.4/Makefile000064400000000000000000000046440000000000000124010ustar 00000000000000# Copyright 2019 fsyncd, Berlin, Germany. # Additional material, copyright of the containerd authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. TOOLCHAIN := x86_64-unknown-linux-musl VPATH = target/system target/$(TOOLCHAIN)/debug target/$(TOOLCHAIN)/release SRCS := $(shell find . -type f -name '*.rs' | grep -v 'tests') ID := $(shell date +%s) .PHONY: all check clean vsock kmod vm all: vsock echo_server check: vsock echo_server test test: cargo test --all fmt: cargo fmt --all -- --check clippy: cargo clippy --all-targets --all-features -- -D warnings clean: cargo clean vsock: $(SRCS) cargo build --lib echo_server: vsock echo_server/src/main.rs cargo build --manifest-path=echo_server/Cargo.toml # Set up required host kernel modules kmod: sudo /sbin/modprobe -r vmw_vsock_vmci_transport sudo /sbin/modprobe -r vmw_vsock_virtio_transport_common sudo /sbin/modprobe -r vsock sudo /sbin/modprobe vhost_vsock # Start a virtio socket enabled vm vm: initrd.cpio sudo qemu-system-x86_64 -kernel test_fixture/bzImage -initrd target/$(TOOLCHAIN)/debug/initrd.cpio \ -enable-kvm -m 256 -device vhost-vsock-pci,id=vhost-vsock-pci0,guest-cid=3 -nographic -append "console=ttyS0" # Start a virtio socket enabled vm in background vm-for-action: initrd.cpio sudo qemu-system-x86_64 -kernel test_fixture/bzImage -initrd target/$(TOOLCHAIN)/debug/initrd.cpio \ -m 256 -device vhost-vsock-pci,id=vhost-vsock-pci0,guest-cid=3 -display none -daemonize -append "console=ttyS0" # Create a simple operating system image for the vm initrd.cpio: echo_server -rm -f target/$(TOOLCHAIN)/debug/initrd.cpio mkdir -p /tmp/$(ID) cp test_fixture/busybox.cpio /tmp/$(ID)/initrd.cpio cp test_fixture/init /tmp/$(ID)/init cp echo_server/target/$(TOOLCHAIN)/debug/echo_server /tmp/$(ID)/ (cd '/tmp/$(ID)' && find . | grep -v 'initrd.cpio' | cpio -H newc -o --append -F initrd.cpio) mv /tmp/$(ID)/initrd.cpio target/$(TOOLCHAIN)/debug/ rm -Rf /tmp/$(ID) vsock-0.2.4/README.md000064400000000000000000000011050000000000000122050ustar 00000000000000# vsock-rs Virtio socket support for Rust. Implements VsockListener and VsockStream which are analogous to the `std::net::TcpListener` and `std::net::TcpStream` types. ## Usage Refer to the crate [documentation](https://docs.rs/vsock). ## Testing ### Prerequisites You will need a recent qemu-system-x86_64 build in your path. ### Host Setup the required virtio kernel modules: ``` make kmod ``` Start the test vm, you can shutdown the vm with the keyboard shortcut ```Ctrl+A``` and then ```x```: ``` make vm ``` ### Tests Run the test suite with: ``` make check ```vsock-0.2.4/src/lib.rs000064400000000000000000000341500000000000000126370ustar 00000000000000/* * Copyright 2019 fsyncd, Berlin, Germany. * Additional material Copyright the Rust project and it's contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //! Virtio socket support for Rust. use std::io::{Error, ErrorKind, Read, Result, Write}; use std::mem::{self, size_of}; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use libc::*; use std::ffi::c_void; use std::net::Shutdown; use std::time::Duration; pub use nix::sys::socket::{SockAddr, VsockAddr}; fn new_socket() -> libc::c_int { unsafe { socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC, 0) } } /// An iterator that infinitely accepts connections on a VsockListener. #[derive(Debug)] pub struct Incoming<'a> { listener: &'a VsockListener, } impl<'a> Iterator for Incoming<'a> { type Item = Result; fn next(&mut self) -> Option> { Some(self.listener.accept().map(|p| p.0)) } } /// A virtio socket server, listening for connections. #[derive(Debug, Clone)] pub struct VsockListener { socket: RawFd, } impl VsockListener { /// Create a new VsockListener which is bound and listening on the socket address. pub fn bind(addr: &SockAddr) -> Result { let mut vsock_addr = if let SockAddr::Vsock(addr) = addr { addr.0 } else { return Err(Error::new( ErrorKind::Other, "requires a virtio socket address", )); }; let socket = new_socket(); if socket < 0 { return Err(Error::last_os_error()); } let res = unsafe { bind( socket, &mut vsock_addr as *mut _ as *mut sockaddr, size_of::() as socklen_t, ) }; if res < 0 { return Err(Error::last_os_error()); } // rust stdlib uses a 128 connection backlog let res = unsafe { listen(socket, 128) }; if res < 0 { return Err(Error::last_os_error()); } Ok(Self { socket }) } /// Create a new VsockListener with specified cid and port. pub fn bind_with_cid_port(cid: u32, port: u32) -> Result { Self::bind(&SockAddr::Vsock(VsockAddr::new(cid, port))) } /// The local socket address of the listener. pub fn local_addr(&self) -> Result { let mut vsock_addr = sockaddr_vm { svm_family: AF_VSOCK as sa_family_t, svm_reserved1: 0, svm_port: 0, svm_cid: 0, svm_zero: [0u8; 4], }; let mut vsock_addr_len = size_of::() as socklen_t; if unsafe { getsockname( self.socket, &mut vsock_addr as *mut _ as *mut sockaddr, &mut vsock_addr_len, ) } < 0 { Err(Error::last_os_error()) } else { Ok(SockAddr::Vsock(VsockAddr(vsock_addr))) } } /// Create a new independently owned handle to the underlying socket. pub fn try_clone(&self) -> Result { Ok(self.clone()) } /// Accept a new incoming connection from this listener. pub fn accept(&self) -> Result<(VsockStream, SockAddr)> { let mut vsock_addr = sockaddr_vm { svm_family: AF_VSOCK as sa_family_t, svm_reserved1: 0, svm_port: 0, svm_cid: 0, svm_zero: [0u8; 4], }; let mut vsock_addr_len = size_of::() as socklen_t; let socket = unsafe { accept4( self.socket, &mut vsock_addr as *mut _ as *mut sockaddr, &mut vsock_addr_len, SOCK_CLOEXEC, ) }; if socket < 0 { Err(Error::last_os_error()) } else { Ok(( unsafe { VsockStream::from_raw_fd(socket as RawFd) }, SockAddr::Vsock(VsockAddr::new(vsock_addr.svm_cid, vsock_addr.svm_port)), )) } } /// An iterator over the connections being received on this listener. pub fn incoming(&self) -> Incoming { Incoming { listener: self } } /// Retrieve the latest error associated with the underlying socket. pub fn take_error(&self) -> Result> { let mut error: i32 = 0; let mut error_len: socklen_t = 0; if unsafe { getsockopt( self.socket, SOL_SOCKET, SO_ERROR, &mut error as *mut _ as *mut c_void, &mut error_len, ) } < 0 { Err(Error::last_os_error()) } else { Ok(if error == 0 { None } else { Some(Error::from_raw_os_error(error)) }) } } /// Move this stream in and out of nonblocking mode. pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()> { let mut nonblocking: i32 = if nonblocking { 1 } else { 0 }; if unsafe { ioctl(self.socket, FIONBIO, &mut nonblocking) } < 0 { Err(Error::last_os_error()) } else { Ok(()) } } } impl AsRawFd for VsockListener { fn as_raw_fd(&self) -> RawFd { self.socket } } impl FromRawFd for VsockListener { unsafe fn from_raw_fd(socket: RawFd) -> Self { Self { socket } } } impl IntoRawFd for VsockListener { fn into_raw_fd(self) -> RawFd { let fd = self.socket; mem::forget(self); fd } } impl Drop for VsockListener { fn drop(&mut self) { unsafe { close(self.socket) }; } } /// A virtio stream between a local and a remote socket. #[derive(Debug, Clone)] pub struct VsockStream { socket: RawFd, } impl VsockStream { /// Open a connection to a remote host. pub fn connect(addr: &SockAddr) -> Result { let vsock_addr = if let SockAddr::Vsock(addr) = addr { addr.0 } else { return Err(Error::new( ErrorKind::Other, "requires a virtio socket address", )); }; let sock = new_socket(); if sock < 0 { return Err(Error::last_os_error()); } if unsafe { connect( sock, &vsock_addr as *const _ as *const sockaddr, size_of::() as socklen_t, ) } < 0 { Err(Error::last_os_error()) } else { Ok(unsafe { VsockStream::from_raw_fd(sock) }) } } /// Open a connection to a remote host with specified cid and port. pub fn connect_with_cid_port(cid: u32, port: u32) -> Result { Self::connect(&SockAddr::Vsock(VsockAddr::new(cid, port))) } /// Virtio socket address of the remote peer associated with this connection. pub fn peer_addr(&self) -> Result { let mut vsock_addr = sockaddr_vm { svm_family: AF_VSOCK as sa_family_t, svm_reserved1: 0, svm_port: 0, svm_cid: 0, svm_zero: [0u8; 4], }; let mut vsock_addr_len = size_of::() as socklen_t; if unsafe { getpeername( self.socket, &mut vsock_addr as *mut _ as *mut sockaddr, &mut vsock_addr_len, ) } < 0 { Err(Error::last_os_error()) } else { Ok(SockAddr::Vsock(VsockAddr(vsock_addr))) } } /// Virtio socket address of the local address associated with this connection. pub fn local_addr(&self) -> Result { let mut vsock_addr = sockaddr_vm { svm_family: AF_VSOCK as sa_family_t, svm_reserved1: 0, svm_port: 0, svm_cid: 0, svm_zero: [0u8; 4], }; let mut vsock_addr_len = size_of::() as socklen_t; if unsafe { getsockname( self.socket, &mut vsock_addr as *mut _ as *mut sockaddr, &mut vsock_addr_len, ) } < 0 { Err(Error::last_os_error()) } else { Ok(SockAddr::Vsock(VsockAddr(vsock_addr))) } } /// Shutdown the read, write, or both halves of this connection. pub fn shutdown(&self, how: Shutdown) -> Result<()> { let how = match how { Shutdown::Write => SHUT_WR, Shutdown::Read => SHUT_RD, Shutdown::Both => SHUT_RDWR, }; if unsafe { shutdown(self.socket, how) } < 0 { Err(Error::last_os_error()) } else { Ok(()) } } /// Create a new independently owned handle to the underlying socket. pub fn try_clone(&self) -> Result { Ok(self.clone()) } /// Set the timeout on read operations. pub fn set_read_timeout(&self, dur: Option) -> Result<()> { let timeout = Self::timeval_from_duration(dur)?; if unsafe { setsockopt( self.socket, SOL_SOCKET, SO_SNDTIMEO, &timeout as *const _ as *const c_void, size_of::() as socklen_t, ) } < 0 { Err(Error::last_os_error()) } else { Ok(()) } } /// Set the timeout on write operations. pub fn set_write_timeout(&self, dur: Option) -> Result<()> { let timeout = Self::timeval_from_duration(dur)?; if unsafe { setsockopt( self.socket, SOL_SOCKET, SO_RCVTIMEO, &timeout as *const _ as *const c_void, size_of::() as socklen_t, ) } < 0 { Err(Error::last_os_error()) } else { Ok(()) } } /// Retrieve the latest error associated with the underlying socket. pub fn take_error(&self) -> Result> { let mut error: i32 = 0; let mut error_len: socklen_t = 0; if unsafe { getsockopt( self.socket, SOL_SOCKET, SO_ERROR, &mut error as *mut _ as *mut c_void, &mut error_len, ) } < 0 { Err(Error::last_os_error()) } else { Ok(if error == 0 { None } else { Some(Error::from_raw_os_error(error)) }) } } /// Move this stream in and out of nonblocking mode. pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()> { let mut nonblocking: i32 = if nonblocking { 1 } else { 0 }; if unsafe { ioctl(self.socket, FIONBIO, &mut nonblocking) } < 0 { Err(Error::last_os_error()) } else { Ok(()) } } fn timeval_from_duration(dur: Option) -> Result { match dur { Some(dur) => { if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { return Err(Error::new( ErrorKind::InvalidInput, "cannot set a zero duration timeout", )); } // https://github.com/rust-lang/libc/issues/1848 #[cfg_attr(target_env = "musl", allow(deprecated))] let secs = if dur.as_secs() > time_t::max_value() as u64 { time_t::max_value() } else { dur.as_secs() as time_t }; let mut timeout = timeval { tv_sec: secs, tv_usec: i64::from(dur.subsec_micros()) as suseconds_t, }; if timeout.tv_sec == 0 && timeout.tv_usec == 0 { timeout.tv_usec = 1; } Ok(timeout) } None => Ok(timeval { tv_sec: 0, tv_usec: 0, }), } } } impl Read for VsockStream { fn read(&mut self, buf: &mut [u8]) -> Result { <&Self>::read(&mut &*self, buf) } } impl Write for VsockStream { fn write(&mut self, buf: &[u8]) -> Result { <&Self>::write(&mut &*self, buf) } fn flush(&mut self) -> Result<()> { Ok(()) } } impl Read for &VsockStream { fn read(&mut self, buf: &mut [u8]) -> Result { let ret = unsafe { recv(self.socket, buf.as_mut_ptr() as *mut c_void, buf.len(), 0) }; if ret < 0 { Err(Error::last_os_error()) } else { Ok(ret as usize) } } } impl Write for &VsockStream { fn write(&mut self, buf: &[u8]) -> Result { let ret = unsafe { send( self.socket, buf.as_ptr() as *const c_void, buf.len(), MSG_NOSIGNAL, ) }; if ret < 0 { Err(Error::last_os_error()) } else { Ok(ret as usize) } } fn flush(&mut self) -> Result<()> { Ok(()) } } impl AsRawFd for VsockStream { fn as_raw_fd(&self) -> RawFd { self.socket } } impl FromRawFd for VsockStream { unsafe fn from_raw_fd(socket: RawFd) -> Self { Self { socket } } } impl IntoRawFd for VsockStream { fn into_raw_fd(self) -> RawFd { let fd = self.socket; mem::forget(self); fd } } impl Drop for VsockStream { fn drop(&mut self) { unsafe { close(self.socket) }; } } vsock-0.2.4/tests/vsock.rs000064400000000000000000000045110000000000000135670ustar 00000000000000/* * Copyright 2019 fsyncd, Berlin, Germany. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use rand::RngCore; use sha2::{Digest, Sha256}; use std::io::{Read, Write}; use vsock::{SockAddr, VsockAddr, VsockStream}; const TEST_BLOB_SIZE: usize = 1_000_000; const TEST_BLOCK_SIZE: usize = 5_000; /// A simple test for the vsock implementation. /// Generate a large random blob of binary data, and transfer it in chunks over the VsockStream /// interface. The vm enpoint is running a simple echo server, so for each chunk we will read /// it's reply and compute a checksum. Comparing the data sent and received confirms that the /// vsock implementation does not introduce corruption and properly implements the interface /// semantics. #[test] fn test_vsock() { let mut rng = rand::thread_rng(); let mut blob: Vec = vec![]; let mut rx_blob = vec![]; let mut tx_pos = 0; blob.resize(TEST_BLOB_SIZE, 0); rx_blob.resize(TEST_BLOB_SIZE, 0); rng.fill_bytes(&mut blob); let mut stream = VsockStream::connect(&SockAddr::Vsock(VsockAddr::new(3, 8000))).expect("connection failed"); while tx_pos < TEST_BLOB_SIZE { let written_bytes = stream .write(&blob[tx_pos..tx_pos + TEST_BLOCK_SIZE]) .expect("write failed"); if written_bytes == 0 { panic!("stream unexpectedly closed"); } let mut rx_pos = tx_pos; while rx_pos < (tx_pos + written_bytes) { let read_bytes = stream.read(&mut rx_blob[rx_pos..]).expect("read failed"); if read_bytes == 0 { panic!("stream unexpectedly closed"); } rx_pos += read_bytes; } tx_pos += written_bytes; } let expected = Sha256::digest(&blob); let actual = Sha256::digest(&rx_blob); assert_eq!(expected, actual); }