diff options
author | Andrew Walbran <qwandor@google.com> | 2020-10-23 13:35:05 +0000 |
---|---|---|
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | 2020-10-23 13:35:05 +0000 |
commit | cf9e33f54e411b0dfbddf184446c6900de6e02ee (patch) | |
tree | 42dafdc8ac23493aa189bbf8a0de6dd233e5a9f4 | |
parent | 36c28ee478d2408f6aeab04a9ba2cc3a5d4e06f8 (diff) | |
parent | 9e6fe586d8336735c8c686390331c09a23d240e7 (diff) | |
download | vsock-cf9e33f54e411b0dfbddf184446c6900de6e02ee.tar.gz |
Import vsock crate. am: 641348654d am: 7aa46c1987 am: 9e6fe586d8
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/vsock/+/1466266
Change-Id: I2ea22dff36d37914c9df4397bbc6dab2d8f5e04f
-rw-r--r-- | .cargo/config | 2 | ||||
-rw-r--r-- | .cargo_vcs_info.json | 5 | ||||
-rw-r--r-- | .gitignore | 4 | ||||
-rw-r--r-- | Android.bp | 20 | ||||
-rw-r--r-- | Cargo.toml | 31 | ||||
-rw-r--r-- | Cargo.toml.orig | 17 | ||||
-rw-r--r-- | LICENSE | 201 | ||||
-rw-r--r-- | METADATA | 19 | ||||
-rw-r--r-- | MODULE_LICENSE_APACHE2 | 0 | ||||
-rw-r--r-- | Makefile | 61 | ||||
-rw-r--r-- | OWNERS | 1 | ||||
-rw-r--r-- | README.md | 36 | ||||
-rw-r--r-- | src/lib.rs | 489 | ||||
-rw-r--r-- | tests/vsock.rs | 70 |
14 files changed, 956 insertions, 0 deletions
diff --git a/.cargo/config b/.cargo/config new file mode 100644 index 0000000..c1ca86b --- /dev/null +++ b/.cargo/config @@ -0,0 +1,2 @@ +[build] +target = "x86_64-unknown-linux-musl"
\ No newline at end of file diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..6b5c25e --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,5 @@ +{ + "git": { + "sha1": "7b815b3f50782ea682da1939f208d5dd8cac17bd" + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6678b89 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +target +.idea/ +*.iml +Cargo.lock diff --git a/Android.bp b/Android.bp new file mode 100644 index 0000000..5c792d9 --- /dev/null +++ b/Android.bp @@ -0,0 +1,20 @@ +// This file is generated by cargo2android.py --run --device --dependencies. + +rust_library { + name: "libvsock", + host_supported: true, + crate_name: "vsock", + srcs: ["src/lib.rs"], + edition: "2018", + rustlibs: [ + "liblibc", + "libnix", + ], +} + +// dependent_library ["feature_list"] +// bitflags-1.2.1 "default" +// cfg-if-0.1.10 +// libc-0.2.77 "default,extra_traits,std" +// nix-0.17.0 +// void-1.0.2 "default,std" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3d14676 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,31 @@ +# 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.1" +authors = ["fsyncd"] +exclude = ["test_fixture"] +description = "Virtio socket support for Rust" +license = "Apache-2.0" +repository = "https://github.com/fsyncd/vsock-rs" +[dependencies.libc] +version = "0.2.65" + +[dependencies.nix] +version = "0.17.0" +[dev-dependencies.rand] +version = "0.7.2" + +[dev-dependencies.sha2] +version = ">=0.8.0" diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..d6eaa17 --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,17 @@ +[package] +name = "vsock" +version = "0.2.1" +authors = ["fsyncd"] +description = "Virtio socket support for Rust" +repository = "https://github.com/fsyncd/vsock-rs" +license = "Apache-2.0" +edition = "2018" +exclude = ["test_fixture"] + +[dependencies] +libc = "0.2.65" +nix = "0.17.0" + +[dev-dependencies] +rand = "0.7.2" +sha2 = ">=0.8.0" @@ -0,0 +1,201 @@ + 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. diff --git a/METADATA b/METADATA new file mode 100644 index 0000000..f407b00 --- /dev/null +++ b/METADATA @@ -0,0 +1,19 @@ +name: "vsock" +description: "Vsock support for Rust." +third_party { + url { + type: HOMEPAGE + value: "https://crates.io/crates/vsock" + } + url { + type: ARCHIVE + value: "https://static.crates.io/crates/vsock/vsock-0.2.1.crate" + } + version: "0.2.1" + license_type: NOTICE + last_upgrade_date { + year: 2020 + month: 9 + day: 28 + } +} diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2 new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/MODULE_LICENSE_APACHE2 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cbaf471 --- /dev/null +++ b/Makefile @@ -0,0 +1,61 @@ +# 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 + cargo fmt --all -- --check + cargo clippy --all-targets --all-features -- -D warnings + cargo test --all + +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" + +# 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)
\ No newline at end of file @@ -0,0 +1 @@ +include platform/prebuilts/rust:/OWNERS diff --git a/README.md b/README.md new file mode 100644 index 0000000..e25c4b0 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# 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 +```
\ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..ec059ce --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,489 @@ +/* + * 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::size_of; +use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; + +use libc::*; +use nix::sys::socket::{SockAddr, VsockAddr}; +use std::ffi::c_void; +use std::net::Shutdown; +use std::time::Duration; + +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<VsockStream>; + + fn next(&mut self) -> Option<Result<VsockStream>> { + 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<VsockListener> { + 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::<sockaddr_vm>() as u32, + ) + }; + 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 }) + } + + /// The local socket address of the listener. + pub fn local_addr(&self) -> Result<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::<sockaddr_vm>() 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<Self> { + 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::<sockaddr_vm>() as socklen_t; + let socket = unsafe { + accept( + self.socket, + &mut vsock_addr as *mut _ as *mut sockaddr, + &mut vsock_addr_len, + ) + }; + 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<Option<Error>> { + 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 { + self.socket + } +} + +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<Self> { + 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::<sockaddr_vm>() as u32, + ) + } < 0 + { + Err(Error::last_os_error()) + } else { + Ok(unsafe { VsockStream::from_raw_fd(sock) }) + } + } + + /// Virtio socket address of the remote peer associated with this connection. + pub fn peer_addr(&self) -> Result<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::<sockaddr_vm>() 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<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::<sockaddr_vm>() 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<Self> { + Ok(self.clone()) + } + + /// Set the timeout on read operations. + pub fn set_read_timeout(&self, dur: Option<Duration>) -> 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::<timeval>() as u32, + ) + } < 0 + { + Err(Error::last_os_error()) + } else { + Ok(()) + } + } + + /// Set the timeout on write operations. + pub fn set_write_timeout(&self, dur: Option<Duration>) -> 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::<timeval>() as u32, + ) + } < 0 + { + Err(Error::last_os_error()) + } else { + Ok(()) + } + } + + /// Retrieve the latest error associated with the underlying socket. + pub fn take_error(&self) -> Result<Option<Error>> { + 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<Duration>) -> Result<timeval> { + 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", + )); + } + + 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<usize> { + <&Self>::read(&mut &*self, buf) + } +} + +impl Write for VsockStream { + fn write(&mut self, buf: &[u8]) -> Result<usize> { + <&Self>::write(&mut &*self, buf) + } + + fn flush(&mut self) -> Result<()> { + Ok(()) + } +} + +impl Read for &VsockStream { + fn read(&mut self, buf: &mut [u8]) -> Result<usize> { + 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<usize> { + 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 { + self.socket + } +} + +impl Drop for VsockStream { + fn drop(&mut self) { + unsafe { close(self.socket) }; + } +} diff --git a/tests/vsock.rs b/tests/vsock.rs new file mode 100644 index 0000000..24f4e37 --- /dev/null +++ b/tests/vsock.rs @@ -0,0 +1,70 @@ +/* + * 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 nix::sys::socket::{SockAddr, VsockAddr}; +use rand::RngCore; +use sha2::{Digest, Sha256}; +use std::io::{Read, Write}; +use vsock::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<u8> = 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); +} |