diff options
Diffstat (limited to 'third_party/rust/mio-uds')
-rw-r--r-- | third_party/rust/mio-uds/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/mio-uds/Cargo.toml | 34 | ||||
-rw-r--r-- | third_party/rust/mio-uds/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | third_party/rust/mio-uds/LICENSE-MIT | 25 | ||||
-rw-r--r-- | third_party/rust/mio-uds/README.md | 49 | ||||
-rw-r--r-- | third_party/rust/mio-uds/src/datagram.rs | 183 | ||||
-rw-r--r-- | third_party/rust/mio-uds/src/lib.rs | 28 | ||||
-rw-r--r-- | third_party/rust/mio-uds/src/listener.rs | 143 | ||||
-rw-r--r-- | third_party/rust/mio-uds/src/socket.rs | 166 | ||||
-rw-r--r-- | third_party/rust/mio-uds/src/stream.rs | 246 |
10 files changed, 1076 insertions, 0 deletions
diff --git a/third_party/rust/mio-uds/.cargo-checksum.json b/third_party/rust/mio-uds/.cargo-checksum.json new file mode 100644 index 0000000000..1c83b1b67c --- /dev/null +++ b/third_party/rust/mio-uds/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"6fb189dd6765ec3be1e2cb65d8733979c48f24df77e0b6fece565fbbc27ae022","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"8de91b1fa2bd5014b42e2b33d8b07e1626ed9715cfd8b8bfd80aa95a114d737c","src/datagram.rs":"b4311804bd4e330905fbf3e47e8c738759bbc039bf6ad2045490080a958d48c2","src/lib.rs":"a827f7a59ddd3c6bc6bd119646493f1c921de48b3ac5d674d5810dff35231dd8","src/listener.rs":"297d73cac8fce225972abb9c8747349d6151e5a61cb8f7fbfb050c336375a61d","src/socket.rs":"f278f62d1f751cae4a0dbfaf507012a99f34eb45b58aee6d70fa1a69e13132c6","src/stream.rs":"31bb65120f6b236a35cfc989c63e06c5e1d4ee9ea1995b150a9a455435f5b1e3"},"package":"afcb699eb26d4332647cc848492bbc15eafb26f08d0304550d5aa1f612e066f0"}
\ No newline at end of file diff --git a/third_party/rust/mio-uds/Cargo.toml b/third_party/rust/mio-uds/Cargo.toml new file mode 100644 index 0000000000..b6501f7abf --- /dev/null +++ b/third_party/rust/mio-uds/Cargo.toml @@ -0,0 +1,34 @@ +# 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] +name = "mio-uds" +version = "0.6.8" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +include = ["Cargo.toml", "LICENSE-APACHE", "LICENSE-MIT", "README.md", "src/**/*.rs"] +description = "Unix domain socket bindings for mio\n" +homepage = "https://github.com/deprecrated/mio-uds" +documentation = "https://docs.rs/mio-uds" +readme = "README.md" +categories = ["asynchronous"] +license = "MIT/Apache-2.0" +repository = "https://github.com/deprecrated/mio-uds" +[dev-dependencies.tempdir] +version = "0.3" +[target."cfg(unix)".dependencies.iovec] +version = "0.1" + +[target."cfg(unix)".dependencies.libc] +version = "0.2.69" + +[target."cfg(unix)".dependencies.mio] +version = "0.6.5" diff --git a/third_party/rust/mio-uds/LICENSE-APACHE b/third_party/rust/mio-uds/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/third_party/rust/mio-uds/LICENSE-APACHE @@ -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/third_party/rust/mio-uds/LICENSE-MIT b/third_party/rust/mio-uds/LICENSE-MIT new file mode 100644 index 0000000000..39e0ed6602 --- /dev/null +++ b/third_party/rust/mio-uds/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/mio-uds/README.md b/third_party/rust/mio-uds/README.md new file mode 100644 index 0000000000..ebbaa706bf --- /dev/null +++ b/third_party/rust/mio-uds/README.md @@ -0,0 +1,49 @@ +# mio-uds + +A library for integrating Unix Domain Sockets with [mio]. Based on the standard +library's [support for Unix sockets][std], except all of the abstractions and +types are nonblocking to conform with the expectations of mio. + +[mio]: https://github.com/tokio-rs/mio +[std]: https://doc.rust-lang.org/std/os/unix/net/ + +[![Build Status](https://github.com/deprecrated/mio-uds/workflows/CI/badge.svg)](https://github.com/deprecrated/mio-uds/actions?query=workflow%3ACI+branch%3Amaster) +[![Documentation](https://docs.rs/mio-uds/badge.svg?version=0.6)](https://docs.rs/mio-uds/~0.6) + +# mio-uds is Deprecated + +With the 0.7 release, `mio` now includes native support for Unix Domain +Sockets. Consumers should switch to that functionality when updating their +`mio` dependency to the 0.7.x series. + + +## Usage + +```toml +# Cargo.toml +[dependencies] +mio-uds = "0.6" +mio = "0.6" +``` + +The three exported types at the top level, `UnixStream`, `UnixListener`, and +`UnixDatagram`, are thin wrappers around the libstd counterparts. They can be +used in similar fashions to mio's TCP and UDP types in terms of registration and +API. + +# License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. diff --git a/third_party/rust/mio-uds/src/datagram.rs b/third_party/rust/mio-uds/src/datagram.rs new file mode 100644 index 0000000000..4fbefd1ceb --- /dev/null +++ b/third_party/rust/mio-uds/src/datagram.rs @@ -0,0 +1,183 @@ +use std::io; +use std::net::Shutdown; +use std::os::unix::net; +use std::os::unix::prelude::*; +use std::path::Path; + +use libc; +use mio::event::Evented; +use mio::unix::EventedFd; +use mio::{Poll, Token, Ready, PollOpt}; + +use cvt; +use socket::{sockaddr_un, Socket}; + +/// A Unix datagram socket. +#[derive(Debug)] +pub struct UnixDatagram { + inner: net::UnixDatagram, +} + +impl UnixDatagram { + /// Creates a Unix datagram socket bound to the given path. + pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> { + UnixDatagram::_bind(path.as_ref()) + } + + fn _bind(path: &Path) -> io::Result<UnixDatagram> { + unsafe { + let (addr, len) = try!(sockaddr_un(path)); + let fd = try!(Socket::new(libc::SOCK_DGRAM)); + + let addr = &addr as *const _ as *const _; + try!(cvt(libc::bind(fd.fd(), addr, len))); + + Ok(UnixDatagram::from_raw_fd(fd.into_fd())) + } + } + + /// Consumes a standard library `UnixDatagram` and returns a wrapped + /// `UnixDatagram` compatible with mio. + /// + /// The returned stream is moved into nonblocking mode and is otherwise + /// ready to get associated with an event loop. + pub fn from_datagram(stream: net::UnixDatagram) -> io::Result<UnixDatagram> { + try!(stream.set_nonblocking(true)); + Ok(UnixDatagram { inner: stream }) + } + + /// Create an unnamed pair of connected sockets. + /// + /// Returns two `UnixDatagrams`s which are connected to each other. + pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> { + unsafe { + let (a, b) = try!(Socket::pair(libc::SOCK_DGRAM)); + Ok((UnixDatagram::from_raw_fd(a.into_fd()), + UnixDatagram::from_raw_fd(b.into_fd()))) + } + } + + /// Creates a Unix Datagram socket which is not bound to any address. + pub fn unbound() -> io::Result<UnixDatagram> { + let stream = try!(net::UnixDatagram::unbound()); + try!(stream.set_nonblocking(true)); + Ok(UnixDatagram { inner: stream }) + } + + /// Connects the socket to the specified address. + /// + /// The `send` method may be used to send data to the specified address. + /// `recv` and `recv_from` will only receive data from that address. + pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> { + self.inner.connect(path) + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `UnixListener` is a reference to the same socket that this + /// object references. Both handles can be used to accept incoming + /// connections and options set on one listener will affect the other. + pub fn try_clone(&self) -> io::Result<UnixDatagram> { + self.inner.try_clone().map(|i| { + UnixDatagram { inner: i } + }) + } + + /// Returns the address of this socket. + pub fn local_addr(&self) -> io::Result<net::SocketAddr> { + self.inner.local_addr() + } + + /// Returns the address of this socket's peer. + /// + /// The `connect` method will connect the socket to a peer. + pub fn peer_addr(&self) -> io::Result<net::SocketAddr> { + self.inner.peer_addr() + } + + /// Receives data from the socket. + /// + /// On success, returns the number of bytes read and the address from + /// whence the data came. + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, net::SocketAddr)> { + self.inner.recv_from(buf) + } + + /// Receives data from the socket. + /// + /// On success, returns the number of bytes read. + pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { + self.inner.recv(buf) + } + + /// Sends data on the socket to the specified address. + /// + /// On success, returns the number of bytes written. + pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> { + self.inner.send_to(buf, path) + } + + /// Sends data on the socket to the socket's peer. + /// + /// The peer address may be set by the `connect` method, and this method + /// will return an error if the socket has not already been connected. + /// + /// On success, returns the number of bytes written. + pub fn send(&self, buf: &[u8]) -> io::Result<usize> { + self.inner.send(buf) + } + + /// Returns the value of the `SO_ERROR` option. + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + self.inner.take_error() + } + + /// Shut down the read, write, or both halves of this connection. + /// + /// This function will cause all pending and future I/O calls on the + /// specified portions to immediately return with an appropriate value + /// (see the documentation of `Shutdown`). + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + self.inner.shutdown(how) + } +} + +impl Evented for UnixDatagram { + fn register(&self, + poll: &Poll, + token: Token, + events: Ready, + opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).register(poll, token, events, opts) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + events: Ready, + opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).deregister(poll) + } +} + +impl AsRawFd for UnixDatagram { + fn as_raw_fd(&self) -> i32 { + self.inner.as_raw_fd() + } +} + +impl IntoRawFd for UnixDatagram { + fn into_raw_fd(self) -> i32 { + self.inner.into_raw_fd() + } +} + +impl FromRawFd for UnixDatagram { + unsafe fn from_raw_fd(fd: i32) -> UnixDatagram { + UnixDatagram { inner: net::UnixDatagram::from_raw_fd(fd) } + } +} diff --git a/third_party/rust/mio-uds/src/lib.rs b/third_party/rust/mio-uds/src/lib.rs new file mode 100644 index 0000000000..ed29e4ac92 --- /dev/null +++ b/third_party/rust/mio-uds/src/lib.rs @@ -0,0 +1,28 @@ +//! MIO bindings for Unix Domain Sockets + +#![cfg(unix)] +#![deny(missing_docs)] +#![doc(html_root_url = "https://docs.rs/mio-uds/0.6")] + +extern crate iovec; +extern crate libc; +extern crate mio; + +use std::io; + +mod datagram; +mod listener; +mod socket; +mod stream; + +pub use stream::UnixStream; +pub use listener::UnixListener; +pub use datagram::UnixDatagram; + +fn cvt(i: libc::c_int) -> io::Result<libc::c_int> { + if i == -1 { + Err(io::Error::last_os_error()) + } else { + Ok(i) + } +} diff --git a/third_party/rust/mio-uds/src/listener.rs b/third_party/rust/mio-uds/src/listener.rs new file mode 100644 index 0000000000..c79830eeb0 --- /dev/null +++ b/third_party/rust/mio-uds/src/listener.rs @@ -0,0 +1,143 @@ +use std::io; +use std::os::unix::net; +use std::os::unix::prelude::*; +use std::path::Path; + +use libc; +use mio::event::Evented; +use mio::unix::EventedFd; +use mio::{Poll, PollOpt, Ready, Token}; + +use UnixStream; +use cvt; +use socket::{sockaddr_un, Socket}; + +/// A structure representing a Unix domain socket server. +/// +/// This listener can be used to accept new streams connected to a remote +/// endpoint, through which the `read` and `write` methods can be used to +/// communicate. +#[derive(Debug)] +pub struct UnixListener { + inner: net::UnixListener, +} + +impl UnixListener { + /// Creates a new `UnixListener` bound to the specified socket. + pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> { + UnixListener::_bind(path.as_ref()) + } + + fn _bind(path: &Path) -> io::Result<UnixListener> { + unsafe { + let (addr, len) = try!(sockaddr_un(path)); + let fd = try!(Socket::new(libc::SOCK_STREAM)); + + let addr = &addr as *const _ as *const _; + try!(cvt(libc::bind(fd.fd(), addr, len))); + try!(cvt(libc::listen(fd.fd(), 128))); + + Ok(UnixListener::from_raw_fd(fd.into_fd())) + } + } + + /// Consumes a standard library `UnixListener` and returns a wrapped + /// `UnixListener` compatible with mio. + /// + /// The returned stream is moved into nonblocking mode and is otherwise + /// ready to get associated with an event loop. + pub fn from_listener(stream: net::UnixListener) -> io::Result<UnixListener> { + try!(stream.set_nonblocking(true)); + Ok(UnixListener { inner: stream }) + } + + /// Accepts a new incoming connection to this listener. + /// + /// When established, the corresponding `UnixStream` and the remote peer's + /// address will be returned as `Ok(Some(...))`. If there is no connection + /// waiting to be accepted, then `Ok(None)` is returned. + /// + /// If an error happens while accepting, `Err` is returned. + pub fn accept(&self) -> io::Result<Option<(UnixStream, net::SocketAddr)>> { + match try!(self.accept_std()) { + Some((stream, addr)) => Ok(Some((UnixStream::from_stream(stream)?, addr))), + None => Ok(None), + } + } + + /// Accepts a new incoming connection to this listener. + /// + /// This method is the same as `accept`, except that it returns a `net::UnixStream` *in blocking mode* + /// which isn't bound to a `mio` type. This can later be converted to a `mio` type, if + /// necessary. + /// + /// If an error happens while accepting, `Err` is returned. + pub fn accept_std(&self) -> io::Result<Option<(net::UnixStream, net::SocketAddr)>> { + match self.inner.accept() { + Ok((socket, addr)) => Ok(Some(unsafe { + (net::UnixStream::from_raw_fd(socket.into_raw_fd()), addr) + })), + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Ok(None), + Err(e) => Err(e), + } + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `UnixListener` is a reference to the same socket that this + /// object references. Both handles can be used to accept incoming + /// connections and options set on one listener will affect the other. + pub fn try_clone(&self) -> io::Result<UnixListener> { + self.inner.try_clone().map(|l| UnixListener { inner: l }) + } + + /// Returns the local socket address of this listener. + pub fn local_addr(&self) -> io::Result<net::SocketAddr> { + self.inner.local_addr() + } + + /// Returns the value of the `SO_ERROR` option. + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + self.inner.take_error() + } +} + +impl Evented for UnixListener { + fn register(&self, poll: &Poll, token: Token, events: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).register(poll, token, events, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + events: Ready, + opts: PollOpt, + ) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).deregister(poll) + } +} + +impl AsRawFd for UnixListener { + fn as_raw_fd(&self) -> i32 { + self.inner.as_raw_fd() + } +} + +impl IntoRawFd for UnixListener { + fn into_raw_fd(self) -> i32 { + self.inner.into_raw_fd() + } +} + +impl FromRawFd for UnixListener { + unsafe fn from_raw_fd(fd: i32) -> UnixListener { + UnixListener { + inner: net::UnixListener::from_raw_fd(fd), + } + } +} diff --git a/third_party/rust/mio-uds/src/socket.rs b/third_party/rust/mio-uds/src/socket.rs new file mode 100644 index 0000000000..820f74dde7 --- /dev/null +++ b/third_party/rust/mio-uds/src/socket.rs @@ -0,0 +1,166 @@ +use std::cmp::Ordering; +use std::io; +use std::mem; +use std::os::unix::prelude::*; +use std::path::Path; + +use libc::{self, c_int, c_ulong}; + +use cvt; + +// See below for the usage of SOCK_CLOEXEC, but this constant is only defined on +// Linux currently (e.g. support doesn't exist on other platforms). In order to +// get name resolution to work and things to compile we just define a dummy +// SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't +// actually ever used (the blocks below are wrapped in `if cfg!` as well. +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris" +))] +use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK}; +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris" +)))] +const SOCK_CLOEXEC: c_int = 0; +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris" +)))] +const SOCK_NONBLOCK: c_int = 0; + +pub struct Socket { + fd: c_int, +} + +impl Socket { + pub fn new(ty: c_int) -> io::Result<Socket> { + unsafe { + // On linux we first attempt to pass the SOCK_CLOEXEC flag to + // atomically create the socket and set it as CLOEXEC. Support for + // this option, however, was added in 2.6.27, and we still support + // 2.6.18 as a kernel, so if the returned error is EINVAL we + // fallthrough to the fallback. + if cfg!(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris" + )) { + let flags = ty | SOCK_CLOEXEC | SOCK_NONBLOCK; + match cvt(libc::socket(libc::AF_UNIX, flags, 0)) { + Ok(fd) => return Ok(Socket { fd: fd }), + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} + Err(e) => return Err(e), + } + } + + let fd = Socket { fd: try!(cvt(libc::socket(libc::AF_UNIX, ty, 0))) }; + try!(cvt(libc::ioctl(fd.fd, libc::FIOCLEX))); + let mut nonblocking = 1 as c_ulong; + try!(cvt(libc::ioctl(fd.fd, libc::FIONBIO, &mut nonblocking))); + Ok(fd) + } + } + + pub fn pair(ty: c_int) -> io::Result<(Socket, Socket)> { + unsafe { + let mut fds = [0, 0]; + + // Like above, see if we can set cloexec atomically + if cfg!(any( + target_os = "linux", + target_os = "android", + target_os = "illumos", + target_os = "solaris" + )) { + let flags = ty | SOCK_CLOEXEC | SOCK_NONBLOCK; + match cvt(libc::socketpair(libc::AF_UNIX, flags, 0, fds.as_mut_ptr())) { + Ok(_) => { + return Ok((Socket { fd: fds[0] }, Socket { fd: fds[1] })) + } + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}, + Err(e) => return Err(e), + } + } + + try!(cvt(libc::socketpair(libc::AF_UNIX, ty, 0, fds.as_mut_ptr()))); + let a = Socket { fd: fds[0] }; + let b = Socket { fd: fds[1] }; + try!(cvt(libc::ioctl(a.fd, libc::FIOCLEX))); + try!(cvt(libc::ioctl(b.fd, libc::FIOCLEX))); + let mut nonblocking = 1 as c_ulong; + try!(cvt(libc::ioctl(a.fd, libc::FIONBIO, &mut nonblocking))); + try!(cvt(libc::ioctl(b.fd, libc::FIONBIO, &mut nonblocking))); + Ok((a, b)) + } + } + + pub fn fd(&self) -> c_int { + self.fd + } + + pub fn into_fd(self) -> c_int { + let ret = self.fd; + mem::forget(self); + ret + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.fd); + } + } +} + +pub unsafe fn sockaddr_un(path: &Path) + -> io::Result<(libc::sockaddr_un, libc::socklen_t)> { + let mut addr: libc::sockaddr_un = mem::zeroed(); + addr.sun_family = libc::AF_UNIX as libc::sa_family_t; + + let bytes = path.as_os_str().as_bytes(); + + match (bytes.get(0), bytes.len().cmp(&addr.sun_path.len())) { + // Abstract paths don't need a null terminator + (Some(&0), Ordering::Greater) => { + return Err(io::Error::new(io::ErrorKind::InvalidInput, + "path must be no longer than SUN_LEN")); + } + (_, Ordering::Greater) | (_, Ordering::Equal) => { + return Err(io::Error::new(io::ErrorKind::InvalidInput, + "path must be shorter than SUN_LEN")); + } + _ => {} + } + for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { + *dst = *src as libc::c_char; + } + // null byte for pathname addresses is already there because we zeroed the + // struct + + let mut len = sun_path_offset() + bytes.len(); + match bytes.get(0) { + Some(&0) | None => {} + Some(_) => len += 1, + } + Ok((addr, len as libc::socklen_t)) +} + +fn sun_path_offset() -> usize { + unsafe { + // Work with an actual instance of the type since using a null pointer is UB + let addr: libc::sockaddr_un = mem::uninitialized(); + let base = &addr as *const _ as usize; + let path = &addr.sun_path as *const _ as usize; + path - base + } +} + diff --git a/third_party/rust/mio-uds/src/stream.rs b/third_party/rust/mio-uds/src/stream.rs new file mode 100644 index 0000000000..82a283492b --- /dev/null +++ b/third_party/rust/mio-uds/src/stream.rs @@ -0,0 +1,246 @@ +use std::cmp; +use std::io::prelude::*; +use std::io; +use std::os::unix::net; +use std::os::unix::prelude::*; +use std::path::Path; +use std::net::Shutdown; + +use iovec::IoVec; +use iovec::unix as iovec; +use libc; +use mio::event::Evented; +use mio::unix::EventedFd; +use mio::{Poll, Token, Ready, PollOpt}; + +use cvt; +use socket::{sockaddr_un, Socket}; + +/// A Unix stream socket. +/// +/// This type represents a `SOCK_STREAM` connection of the `AF_UNIX` family, +/// otherwise known as Unix domain sockets or Unix sockets. This stream is +/// readable/writable and acts similarly to a TCP stream where reads/writes are +/// all in order with respect to the other connected end. +/// +/// Streams can either be connected to paths locally or another ephemeral socket +/// created by the `pair` function. +/// +/// A `UnixStream` implements the `Read`, `Write`, `Evented`, `AsRawFd`, +/// `IntoRawFd`, and `FromRawFd` traits for interoperating with other I/O code. +/// +/// Note that all values of this type are typically in nonblocking mode, so the +/// `read` and `write` methods may return an error with the kind of +/// `WouldBlock`, indicating that it's not ready to read/write just yet. +#[derive(Debug)] +pub struct UnixStream { + inner: net::UnixStream, +} + +impl UnixStream { + /// Connects to the socket named by `path`. + /// + /// The socket returned may not be readable and/or writable yet, as the + /// connection may be in progress. The socket should be registered with an + /// event loop to wait on both of these properties being available. + pub fn connect<P: AsRef<Path>>(p: P) -> io::Result<UnixStream> { + UnixStream::_connect(p.as_ref()) + } + + fn _connect(path: &Path) -> io::Result<UnixStream> { + unsafe { + let (addr, len) = try!(sockaddr_un(path)); + let socket = try!(Socket::new(libc::SOCK_STREAM)); + let addr = &addr as *const _ as *const _; + match cvt(libc::connect(socket.fd(), addr, len)) { + Ok(_) => {} + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} + Err(e) => return Err(e), + } + + Ok(UnixStream::from_raw_fd(socket.into_fd())) + } + } + + /// Consumes a standard library `UnixStream` and returns a wrapped + /// `UnixStream` compatible with mio. + /// + /// The returned stream is moved into nonblocking mode and is otherwise + /// ready to get associated with an event loop. + pub fn from_stream(stream: net::UnixStream) -> io::Result<UnixStream> { + try!(stream.set_nonblocking(true)); + Ok(UnixStream { inner: stream }) + } + + /// Creates an unnamed pair of connected sockets. + /// + /// Returns two `UnixStream`s which are connected to each other. + pub fn pair() -> io::Result<(UnixStream, UnixStream)> { + Socket::pair(libc::SOCK_STREAM).map(|(a, b)| unsafe { + (UnixStream::from_raw_fd(a.into_fd()), + UnixStream::from_raw_fd(b.into_fd())) + }) + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `UnixStream` is a reference to the same stream that this + /// object references. Both handles will read and write the same stream of + /// data, and options set on one stream will be propogated to the other + /// stream. + pub fn try_clone(&self) -> io::Result<UnixStream> { + self.inner.try_clone().map(|s| { + UnixStream { inner: s } + }) + } + + /// Returns the socket address of the local half of this connection. + pub fn local_addr(&self) -> io::Result<net::SocketAddr> { + self.inner.local_addr() + } + + /// Returns the socket address of the remote half of this connection. + pub fn peer_addr(&self) -> io::Result<net::SocketAddr> { + self.inner.peer_addr() + } + + /// Returns the value of the `SO_ERROR` option. + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + self.inner.take_error() + } + + /// Shuts down the read, write, or both halves of this connection. + /// + /// This function will cause all pending and future I/O calls on the + /// specified portions to immediately return with an appropriate value + /// (see the documentation of `Shutdown`). + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + self.inner.shutdown(how) + } + + /// Read in a list of buffers all at once. + /// + /// This operation will attempt to read bytes from this socket and place + /// them into the list of buffers provided. Note that each buffer is an + /// `IoVec` which can be created from a byte slice. + /// + /// The buffers provided will be filled in sequentially. A buffer will be + /// entirely filled up before the next is written to. + /// + /// The number of bytes read is returned, if successful, or an error is + /// returned otherwise. If no bytes are available to be read yet then + /// a "would block" error is returned. This operation does not block. + pub fn read_bufs(&self, bufs: &mut [&mut IoVec]) -> io::Result<usize> { + unsafe { + let slice = iovec::as_os_slice_mut(bufs); + let len = cmp::min(<libc::c_int>::max_value() as usize, slice.len()); + let rc = libc::readv(self.inner.as_raw_fd(), + slice.as_ptr(), + len as libc::c_int); + if rc < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(rc as usize) + } + } + } + + /// Write a list of buffers all at once. + /// + /// This operation will attempt to write a list of byte buffers to this + /// socket. Note that each buffer is an `IoVec` which can be created from a + /// byte slice. + /// + /// The buffers provided will be written sequentially. A buffer will be + /// entirely written before the next is written. + /// + /// The number of bytes written is returned, if successful, or an error is + /// returned otherwise. If the socket is not currently writable then a + /// "would block" error is returned. This operation does not block. + pub fn write_bufs(&self, bufs: &[&IoVec]) -> io::Result<usize> { + unsafe { + let slice = iovec::as_os_slice(bufs); + let len = cmp::min(<libc::c_int>::max_value() as usize, slice.len()); + let rc = libc::writev(self.inner.as_raw_fd(), + slice.as_ptr(), + len as libc::c_int); + if rc < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(rc as usize) + } + } + } +} + +impl Evented for UnixStream { + fn register(&self, + poll: &Poll, + token: Token, + events: Ready, + opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).register(poll, token, events, opts) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + events: Ready, + opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).deregister(poll) + } +} + +impl Read for UnixStream { + fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> { + self.inner.read(bytes) + } +} + +impl<'a> Read for &'a UnixStream { + fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> { + (&self.inner).read(bytes) + } +} + +impl Write for UnixStream { + fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { + self.inner.write(bytes) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } +} + +impl<'a> Write for &'a UnixStream { + fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { + (&self.inner).write(bytes) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.inner).flush() + } +} + +impl AsRawFd for UnixStream { + fn as_raw_fd(&self) -> i32 { + self.inner.as_raw_fd() + } +} + +impl IntoRawFd for UnixStream { + fn into_raw_fd(self) -> i32 { + self.inner.into_raw_fd() + } +} + +impl FromRawFd for UnixStream { + unsafe fn from_raw_fd(fd: i32) -> UnixStream { + UnixStream { inner: net::UnixStream::from_raw_fd(fd) } + } +} |