mio-uds-0.6.7/.gitignore010066400017500001750000000000221274376066200133230ustar0000000000000000target Cargo.lock mio-uds-0.6.7/.travis.yml010066400017500001750000000022331321026550300134320ustar0000000000000000language: rust sudo: false matrix: include: - rust: 1.21.0 - rust: stable - os: osx - rust: beta - rust: nightly - rust: nightly before_script: - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - cargo doc --no-deps --all-features after_success: - travis-cargo --only nightly doc-upload script: - cargo test env: global: secure: "V+dRcbwjNbHJxvoEcASMMdXY74YSmQqZXA9P2oa4gzP7lI0fXqM47pBIVfA4Mj4dhZywByywc/EBDc51JOjdORZognENxLUymTlTcTu7zcq+r7woXYPQHmm7BEvrEKBbQTaV/sO+200CN4d5mT1sPNJoFMp8lUL7/QtoczH+vGWSzWBb8F59oxRpNqD1MhaTpo0oWVMp8yskLvylgIjEoCY8E1uKp7rkqgAxUj8RmZt3hnFAr1SIu32tYUhj7STw8Ad++pI+kdx6SH0bslBy7TQcEhsTPQ4Q66u1z5pkVhv/Q0u3QLiJcI8WWEukTa3lwRUusXwZXfuME2Lz6PiKWa7jSGDc0UBc83oy7FOxyY+tutk74MQU0861dh2UlJgzzw+A7NnZHXueNQyT3RaD3K1ce3aPdCMBPM6GcRFkMcm+6llz5weGBhWHo5Uyeuy+Y88OF/ZZS7a5PdmvPfapB3Ir6MRZaDse/bDEWaBd5wO7ZMk8YyFumxJWuksHWxnIYTEjkn+4zHH1doCSr5axjryv9oDa8Agjcd1ePRNUAlgszslUeyU5ACfX2rJi2VlEL+DC01WfUQC0z0M8ISOOaQdoVRnwYOYpw6qQHZDU2Es7f1TihIzAOmzkgnz9wpInzs73EDjHqyROVRnHQO8P/epapbisWlakWWmUn7GJA3Y=" notifications: email: on_success: never mio-uds-0.6.7/Cargo.toml.orig010066400017500001750000000010601334357131000142100ustar0000000000000000[package] name = "mio-uds" version = "0.6.7" authors = ["Alex Crichton "] license = "MIT/Apache-2.0" readme = "README.md" repository = "https://github.com/alexcrichton/mio-uds" homepage = "https://github.com/alexcrichton/mio-uds" documentation = "https://docs.rs/mio-uds" description = """ Unix domain socket bindings for mio """ categories = ["asynchronous"] [badges] travis-ci = { repository = "alexcrichton/mio-uds" } [target."cfg(unix)".dependencies] iovec = "0.1" libc = "0.2.42" mio = "0.6.5" [dev-dependencies] tempdir = "0.3" mio-uds-0.6.7/Cargo.toml0000644000000022250000000000000104610ustar00# 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.7" authors = ["Alex Crichton "] description = "Unix domain socket bindings for mio\n" homepage = "https://github.com/alexcrichton/mio-uds" documentation = "https://docs.rs/mio-uds" readme = "README.md" categories = ["asynchronous"] license = "MIT/Apache-2.0" repository = "https://github.com/alexcrichton/mio-uds" [dev-dependencies.tempdir] version = "0.3" [target."cfg(unix)".dependencies.iovec] version = "0.1" [target."cfg(unix)".dependencies.libc] version = "0.2.42" [target."cfg(unix)".dependencies.mio] version = "0.6.5" [badges.travis-ci] repository = "alexcrichton/mio-uds" mio-uds-0.6.7/LICENSE-APACHE010066400017500001750000000251371274400443700132650ustar0000000000000000 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. mio-uds-0.6.7/LICENSE-MIT010066400017500001750000000020411274400443700127620ustar0000000000000000Copyright (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. mio-uds-0.6.7/README.md010066400017500001750000000024611317571727500126250ustar0000000000000000# mio-uds [![Build Status](https://travis-ci.org/alexcrichton/mio-uds.svg?branch=master)](https://travis-ci.org/alexcrichton/mio-uds) [Documentation](https://docs.rs/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/carllerche/mio [std]: https://doc.rust-lang.org/std/os/unix/net/ ```toml # Cargo.toml [dependencies] mio-uds = "0.6" mio = "0.6" ``` ## Usage 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 Serde by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. mio-uds-0.6.7/src/datagram.rs010066400017500001750000000133621334357130400142510ustar0000000000000000use 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>(path: P) -> io::Result { UnixDatagram::_bind(path.as_ref()) } fn _bind(path: &Path) -> io::Result { 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 { 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 { 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>(&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 { self.inner.try_clone().map(|i| { UnixDatagram { inner: i } }) } /// Returns the address of this socket. pub fn local_addr(&self) -> io::Result { 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 { 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 { 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>(&self, buf: &[u8], path: P) -> io::Result { 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 { self.inner.send(buf) } /// Returns the value of the `SO_ERROR` option. pub fn take_error(&self) -> io::Result> { 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) } } } mio-uds-0.6.7/src/lib.rs010066400017500001750000000007611334357130400132360ustar0000000000000000//! 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 { if i == -1 { Err(io::Error::last_os_error()) } else { Ok(i) } } mio-uds-0.6.7/src/listener.rs010066400017500001750000000111231334357130400143070ustar0000000000000000use 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>(path: P) -> io::Result { UnixListener::_bind(path.as_ref()) } fn _bind(path: &Path) -> io::Result { 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 { 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> { 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 UDP socket *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> { 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 { self.inner.try_clone().map(|l| UnixListener { inner: l }) } /// Returns the local socket address of this listener. pub fn local_addr(&self) -> io::Result { self.inner.local_addr() } /// Returns the value of the `SO_ERROR` option. pub fn take_error(&self) -> io::Result> { 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), } } } mio-uds-0.6.7/src/socket.rs010066400017500001750000000117021327265406600137650ustar0000000000000000use 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"))] use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK}; #[cfg(not(any(target_os = "linux", target_os = "android")))] const SOCK_CLOEXEC: c_int = 0; #[cfg(not(any(target_os = "linux", target_os = "android")))] const SOCK_NONBLOCK: c_int = 0; pub struct Socket { fd: c_int, } impl Socket { pub fn new(ty: c_int) -> io::Result { 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!(target_os = "linux") || cfg!(target_os = "android") { 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!(target_os = "linux") || cfg!(target_os = "android") { 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 } } mio-uds-0.6.7/src/stream.rs010066400017500001750000000203051317571727500137730ustar0000000000000000use 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: P) -> io::Result { UnixStream::_connect(p.as_ref()) } fn _connect(path: &Path) -> io::Result { 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 { 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 { 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 { self.inner.local_addr() } /// Returns the socket address of the remote half of this connection. pub fn peer_addr(&self) -> io::Result { self.inner.peer_addr() } /// Returns the value of the `SO_ERROR` option. pub fn take_error(&self) -> io::Result> { 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 { unsafe { let slice = iovec::as_os_slice_mut(bufs); let len = cmp::min(::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 { unsafe { let slice = iovec::as_os_slice(bufs); let len = cmp::min(::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 { self.inner.read(bytes) } } impl<'a> Read for &'a UnixStream { fn read(&mut self, bytes: &mut [u8]) -> io::Result { (&self.inner).read(bytes) } } impl Write for UnixStream { fn write(&mut self, bytes: &[u8]) -> io::Result { 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 { (&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) } } } mio-uds-0.6.7/tests/echo.rs010066400017500001750000000176241306226530500137660ustar0000000000000000extern crate mio; extern crate tempdir; extern crate mio_uds; use std::io::{self, Write, Read}; use std::io::ErrorKind::WouldBlock; use tempdir::TempDir; use mio::*; use mio_uds::*; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {}", stringify!($e), e), }) } const SERVER: Token = Token(0); const CLIENT: Token = Token(1); struct EchoConn { sock: UnixStream, buf: Vec, token: Option, interest: Ready, } impl EchoConn { fn new(sock: UnixStream) -> EchoConn { EchoConn { sock: sock, buf: Vec::new(), token: None, interest: Ready::readable(), } } fn writable(&mut self, poll: &Poll) -> io::Result<()> { match self.sock.write(&self.buf) { Ok(n) => { assert_eq!(n, self.buf.len()); self.interest.insert(Ready::readable()); self.interest.remove(Ready::writable()); } Err(ref e) if e.kind() == WouldBlock => { self.interest.insert(Ready::writable()); } Err(e) => panic!("not implemented; client err={:?}", e), } assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); poll.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot()) } fn readable(&mut self, poll: &Poll) -> io::Result<()> { let mut buf = [0; 1024]; match self.sock.read(&mut buf) { Ok(r) => { self.buf = buf[..r].to_vec(); self.interest.remove(Ready::readable()); self.interest.insert(Ready::writable()); } Err(ref e) if e.kind() == WouldBlock => {} Err(_e) => { self.interest.remove(Ready::readable()); } } assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); poll.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot()) } } struct EchoServer { sock: UnixListener, conns: Vec>, } impl EchoServer { fn accept(&mut self, poll: &Poll) -> io::Result<()> { let sock = t!(self.sock.accept()).unwrap().0; let conn = EchoConn::new(sock); let tok = Token(self.conns.len() + 2); self.conns.push(Some(conn)); // Register the connection self.conn(tok).token = Some(tok); t!(poll.register(&self.conn(tok).sock, tok, Ready::readable(), PollOpt::edge() | PollOpt::oneshot())); Ok(()) } fn conn_readable(&mut self, poll: &Poll, tok: Token) -> io::Result<()> { self.conn(tok).readable(poll) } fn conn_writable(&mut self, poll: &Poll, tok: Token) -> io::Result<()> { self.conn(tok).writable(poll) } fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn { self.conns[usize::from(tok) - 2].as_mut().unwrap() } } struct EchoClient { sock: UnixStream, msgs: Vec<&'static str>, tx: &'static [u8], rx: &'static [u8], token: Token, interest: Ready, active: bool, } // Sends a message and expects to receive the same exact message, one at a time impl EchoClient { fn new(sock: UnixStream, tok: Token, mut msgs: Vec<&'static str>) -> EchoClient { let curr = msgs.remove(0); EchoClient { sock: sock, msgs: msgs, tx: curr.as_bytes(), rx: curr.as_bytes(), token: tok, interest: Ready::empty(), active: true, } } fn readable(&mut self, poll: &Poll) -> io::Result<()> { let mut buf = [0; 1024]; match self.sock.read(&mut buf) { Ok(n) => { assert_eq!(&self.rx[..n], &buf[..n]); self.rx = &self.rx[n..]; self.interest.remove(Ready::readable()); if self.rx.len() == 0 { self.next_msg(poll).unwrap(); } } Err(ref e) if e.kind() == WouldBlock => {} Err(e) => panic!("error {}", e), } if !self.interest.is_empty() { assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); try!(poll.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot())); } Ok(()) } fn writable(&mut self, poll: &Poll) -> io::Result<()> { match self.sock.write(self.tx) { Ok(r) => { self.tx = &self.tx[r..]; self.interest.insert(Ready::readable()); self.interest.remove(Ready::writable()); } Err(ref e) if e.kind() == WouldBlock => { self.interest.insert(Ready::writable()); } Err(e) => panic!("not implemented; client err={:?}", e) } assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); poll.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) } fn next_msg(&mut self, poll: &Poll) -> io::Result<()> { if self.msgs.is_empty() { self.active = false; return Ok(()); } let curr = self.msgs.remove(0); self.tx = curr.as_bytes(); self.rx = curr.as_bytes(); self.interest.insert(Ready::writable()); assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); poll.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) } } struct Echo { server: EchoServer, client: EchoClient, } impl Echo { fn new(srv: UnixListener, client: UnixStream, msgs: Vec<&'static str>) -> Echo { Echo { server: EchoServer { sock: srv, conns: Vec::new(), }, client: EchoClient::new(client, CLIENT, msgs) } } fn ready(&mut self, poll: &Poll, token: Token, events: Ready) { println!("ready {:?} {:?}", token, events); if events.is_readable() { match token { SERVER => self.server.accept(poll).unwrap(), CLIENT => self.client.readable(poll).unwrap(), i => self.server.conn_readable(poll, i).unwrap() } } if events.is_writable() { match token { SERVER => panic!("received writable for token 0"), CLIENT => self.client.writable(poll).unwrap(), _ => self.server.conn_writable(poll, token).unwrap() } } } } #[test] fn echo_server() { let tmp_dir = t!(TempDir::new("mio-uds")); let addr = tmp_dir.path().join("sock"); let poll = t!(Poll::new()); let mut events = Events::with_capacity(1024); let srv = t!(UnixListener::bind(&addr)); t!(poll.register(&srv, SERVER, Ready::readable(), PollOpt::edge() | PollOpt::oneshot())); let sock = t!(UnixStream::connect(&addr)); t!(poll.register(&sock, CLIENT, Ready::writable(), PollOpt::edge() | PollOpt::oneshot())); let mut echo = Echo::new(srv, sock, vec!["foo", "bar"]); while echo.client.active { t!(poll.poll(&mut events, None)); for i in 0..events.len() { let event = events.get(i).unwrap(); echo.ready(&poll, event.token(), event.readiness()); } } } mio-uds-0.6.7/tests/smoke.rs010066400017500001750000000062401317571727500141730ustar0000000000000000extern crate iovec; extern crate mio; extern crate tempdir; extern crate mio_uds; use std::io::prelude::*; use std::time::Duration; use iovec::IoVec; use mio::*; use mio_uds::*; use tempdir::TempDir; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {}", stringify!($e), e), }) } #[test] fn listener() { let td = t!(TempDir::new("uds")); let a = t!(UnixListener::bind(td.path().join("foo"))); assert!(t!(a.accept()).is_none()); t!(a.local_addr()); assert!(t!(a.take_error()).is_none()); let b = t!(a.try_clone()); assert!(t!(b.accept()).is_none()); let poll = t!(Poll::new()); let mut events = Events::with_capacity(1024); t!(poll.register(&a, Token(1), Ready::readable(), PollOpt::edge())); let s = t!(UnixStream::connect(td.path().join("foo"))); assert_eq!(t!(poll.poll(&mut events, None)), 1); let (s2, addr) = t!(a.accept()).unwrap(); assert_eq!(t!(s.peer_addr()).as_pathname(), t!(s2.local_addr()).as_pathname()); assert_eq!(t!(s.local_addr()).as_pathname(), t!(s2.peer_addr()).as_pathname()); assert_eq!(addr.as_pathname(), t!(s.local_addr()).as_pathname()); } #[test] fn stream() { let poll = t!(Poll::new()); let mut events = Events::with_capacity(1024); let (mut a, mut b) = t!(UnixStream::pair()); let both = Ready::readable() | Ready::writable(); t!(poll.register(&a, Token(1), both, PollOpt::edge())); t!(poll.register(&b, Token(2), both, PollOpt::edge())); assert_eq!(t!(poll.poll(&mut events, Some(Duration::new(0, 0)))), 2); assert_eq!(events.get(0).unwrap().readiness(), Ready::writable()); assert_eq!(events.get(1).unwrap().readiness(), Ready::writable()); assert_eq!(t!(a.write(&[3])), 1); assert_eq!(t!(poll.poll(&mut events, Some(Duration::new(0, 0)))), 1); assert!(events.get(0).unwrap().readiness().is_readable()); assert_eq!(events.get(0).unwrap().token(), Token(2)); assert_eq!(t!(b.read(&mut [0; 1024])), 1); } #[test] fn stream_iovec() { let poll = t!(Poll::new()); let mut events = Events::with_capacity(1024); let (a, b) = t!(UnixStream::pair()); let both = Ready::readable() | Ready::writable(); t!(poll.register(&a, Token(1), both, PollOpt::edge())); t!(poll.register(&b, Token(2), both, PollOpt::edge())); assert_eq!(t!(poll.poll(&mut events, Some(Duration::new(0, 0)))), 2); assert_eq!(events.get(0).unwrap().readiness(), Ready::writable()); assert_eq!(events.get(1).unwrap().readiness(), Ready::writable()); let send = b"Hello, World!"; let vecs: [&IoVec;2] = [ (&send[..6]).into(), (&send[6..]).into() ]; assert_eq!(t!(a.write_bufs(&vecs)), send.len()); assert_eq!(t!(poll.poll(&mut events, Some(Duration::new(0, 0)))), 1); assert!(events.get(0).unwrap().readiness().is_readable()); assert_eq!(events.get(0).unwrap().token(), Token(2)); let mut recv = [0; 13]; { let (mut first, mut last) = recv.split_at_mut(6); let mut vecs: [&mut IoVec;2] = [ first.into(), last.into() ]; assert_eq!(t!(b.read_bufs(&mut vecs)), send.len()); } assert_eq!(&send[..], &recv[..]); }