├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── 01_socket.rs └── src ├── bt └── mod.rs ├── lib.rs ├── sys ├── mod.rs ├── unix │ ├── bt.rs │ ├── c.rs │ ├── fd.rs │ └── mod.rs └── windows │ ├── bt.rs │ ├── c.rs │ └── mod.rs └── sys_common ├── bt.rs └── mod.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [pull_request, push] 4 | 5 | jobs: 6 | test: 7 | name: Test 8 | runs-on: ${{ matrix.config.os }} 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | config: 13 | - { os: "ubuntu-latest", target: "i686-unknown-linux-gnu", toolchain: "stable"} 14 | - { os: "ubuntu-latest", target: "x86_64-unknown-linux-gnu", toolchain: "stable"} 15 | - { os: "ubuntu-latest", target: "x86_64-unknown-linux-gnu", toolchain: "beta"} 16 | - { os: "ubuntu-latest", target: "x86_64-unknown-linux-gnu", toolchain: "nightly"} 17 | - { os: "windows-2016", target: "i686-pc-windows-msvc", toolchain: "stable"} 18 | - { os: "windows-2016", target: "x86_64-pc-windows-msvc", toolchain: "stable"} 19 | steps: 20 | - uses: actions/checkout@v2 21 | 22 | - name: Install ${{ matrix.config.toolchain }} toolchain 23 | uses: actions-rs/toolchain@v1 24 | with: 25 | profile: minimal 26 | toolchain: ${{ matrix.config.toolchain }} 27 | target: ${{ matrix.config.target }} 28 | override: true 29 | components: clippy, rustfmt 30 | 31 | - name: Install libbluetooth-dev (Linux only) 32 | if: runner.os == 'Linux' 33 | run: sudo apt-get install libbluetooth-dev 34 | 35 | - name: Run cargo test 36 | uses: actions-rs/cargo@v1 37 | continue-on-error: ${{ matrix.config.toolchain == 'nightly' }} 38 | with: 39 | command: test 40 | 41 | - name: Run cargo fmt 42 | uses: actions-rs/cargo@v1 43 | with: 44 | command: fmt 45 | args: --all -- --check 46 | 47 | - name: Run cargo clippy 48 | uses: actions-rs/clippy-check@v1 49 | with: 50 | token: ${{ secrets.GITHUB_TOKEN }} 51 | args: --all-features 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | .vscode/ 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to IO Bluetooth 2 | 3 | IO Bluetooth welcomes contributions from everyone in the form of suggestions, bug reports, pull requests, and feedback. This document gives some guidance if you are thinking of helping us. 4 | 5 | Please reach out here in a GitHub issue if we can do anything to help you contribute. 6 | 7 | ## Submitting bug reports and feature requests 8 | 9 | When reporting a bug or asking for help, please include enough details so that the people helping you can reproduce the behavior you are seeing. For some tips on how to approach this, read about how to produce a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). 10 | 11 | When making a feature request, please make it clear what problem you intend to solve with the feature, any ideas for how IO Bluetooth could support solving that problem, any possible alternatives, and any disadvantages. 12 | 13 | ## Conduct 14 | 15 | In all IO Bluetooth-related forums, we follow the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct). 16 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "io_bluetooth" 3 | version = "0.2.0" 4 | authors = ["Wodann "] 5 | license = "MIT OR Apache-2.0" 6 | description = "A cross-platform library for Bluetooth" 7 | keywords = ["bluetooth", "io", "unix", "windows"] 8 | categories = ["network-programming"] 9 | repository = "https://github.com/Wodann/io-bluetooth-rs/" 10 | readme = "README.md" 11 | include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] 12 | edition = "2018" 13 | 14 | [dependencies] 15 | cfg-if = "0.1" 16 | 17 | [target.'cfg(unix)'.dependencies] 18 | libbluetooth = { version = "0.1", features = ["impl-default"] } 19 | libc = "0.2" 20 | 21 | [target.'cfg(windows)'.dependencies] 22 | winapi = { version = "0.3.8", features = ["impl-default", "guiddef", "handleapi", "processthreadsapi", "winbase", "winerror", "winnt", "winsock2", "ws2def","bthdef","ws2bth"] } 23 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy 2 | of this software and associated documentation files (the "Software"), to deal 3 | in the Software without restriction, including without limitation the rights 4 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 5 | copies of the Software, and to permit persons to whom the Software is 6 | furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all 9 | copies or substantial portions of the Software. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 17 | SOFTWARE. 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # IO Bluetooth 2 | 3 | **IO Bluetooth is a Rust library that provides cross-platform support for Bluetooth communication.** 4 | 5 | [![Build Status](https://github.com/Wodann/io-bluetooth-rs/workflows/CI/badge.svg?branch=master)](https://github.com/wodann/io-bluetooth-rs/actions) 6 | [![Documentation][docs-badge]][docs-url] 7 | [![MIT OR Apache license][license-badge]][license-url] 8 | ![Lines of Code][loc-url] 9 | 10 | [docs-badge]: https://img.shields.io/badge/docs-website-blue.svg 11 | [docs-url]: https://docs.rs/io_bluetooth 12 | [license-badge]: https://img.shields.io/crates/l/io_bluetooth 13 | [license-url]: README.md 14 | [loc-url]: https://tokei.rs/b1/github/wodann/io-bluetooth-rs?category=code 15 | 16 | ## Usage 17 | 18 | Add the following to your `cargo.toml`: 19 | 20 | ```toml 21 | [dependencies] 22 | io_bluetooth = "0.2" 23 | ``` 24 | 25 | Examples of how to use the IO Bluetooth API are provided [here](examples/). 26 | 27 | ## No-std support 28 | 29 | This crate currently requires the Rust standard library. 30 | 31 | ## Platform support 32 | 33 | IO Bluetooth is guaranteed to build for the following platforms: 34 | 35 | * x86_64-pc-windows-msvc 36 | * x86_64-unknown-linux-gnu 37 | 38 | ## License 39 | 40 | IO Bluetooth is licensed under either of 41 | 42 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 43 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 44 | 45 | at your option. 46 | 47 | ### Contribution 48 | 49 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in IO Bluetooth by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 50 | 51 | To contribute to IO Bluetooth, please see [CONTRIBUTING](CONTRIBUTING.md). 52 | -------------------------------------------------------------------------------- /examples/01_socket.rs: -------------------------------------------------------------------------------- 1 | extern crate io_bluetooth; 2 | 3 | use std::io; 4 | use std::iter; 5 | 6 | use io_bluetooth::bt::{self, BtStream}; 7 | 8 | fn main() -> io::Result<()> { 9 | let devices = bt::discover_devices()?; 10 | println!("Devices:"); 11 | for (idx, device) in devices.iter().enumerate() { 12 | println!("{}: {}", idx, *device); 13 | } 14 | 15 | if devices.len() == 0 { 16 | return Err(io::Error::new( 17 | io::ErrorKind::NotFound, 18 | "No Bluetooth devices found.", 19 | )); 20 | } 21 | 22 | let device_idx = request_device_idx(devices.len())?; 23 | 24 | let socket = BtStream::connect(iter::once(&devices[device_idx]), bt::BtProtocol::RFCOMM)?; 25 | 26 | match socket.peer_addr() { 27 | Ok(name) => println!("Peername: {}.", name.to_string()), 28 | Err(err) => println!("An error occured while retrieving the peername: {:?}", err), 29 | } 30 | 31 | match socket.local_addr() { 32 | Ok(name) => println!("Socket name: {}", name.to_string()), 33 | Err(err) => println!("An error occured while retrieving the sockname: {:?}", err), 34 | } 35 | 36 | let mut buffer = vec![0; 1024]; 37 | loop { 38 | match socket.recv(&mut buffer[..]) { 39 | Ok(len) => println!("Received {} bytes.", len), 40 | Err(err) => return Err(err), 41 | } 42 | } 43 | } 44 | 45 | fn request_device_idx(len: usize) -> io::Result { 46 | println!("Please specify the index of the Bluetooth device you want to connect to:"); 47 | 48 | let mut buffer = String::new(); 49 | loop { 50 | io::stdin().read_line(&mut buffer)?; 51 | if let Ok(idx) = buffer.trim_end().parse::() { 52 | if idx < len { 53 | return Ok(idx); 54 | } 55 | } 56 | buffer.clear(); 57 | println!("Invalid index. Please try again."); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/bt/mod.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::io; 3 | use std::net::Shutdown; 4 | use std::time::Duration; 5 | 6 | use crate::sys_common::bt as bt_imp; 7 | use crate::sys_common::{AsInner, FromInner, IntoInner}; 8 | 9 | /// A Bluetooth address, consisting of 6 bytes. 10 | #[derive(Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)] 11 | pub struct BtAddr(pub [u8; 6]); 12 | 13 | impl BtAddr { 14 | pub fn nap_sap(nap: u16, sap: u32) -> BtAddr { 15 | let nap = nap.to_le_bytes(); 16 | let sap = sap.to_le_bytes(); 17 | Self([sap[0], sap[1], sap[2], sap[3], nap[0], nap[1]]) 18 | } 19 | } 20 | 21 | impl fmt::Debug for BtAddr { 22 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 23 | write!( 24 | f, 25 | "BtAddr({:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x})", 26 | self.0[5], self.0[4], self.0[3], self.0[2], self.0[1], self.0[0] 27 | ) 28 | } 29 | } 30 | 31 | impl fmt::Display for BtAddr { 32 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 33 | write!( 34 | f, 35 | "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", 36 | self.0[5], self.0[4], self.0[3], self.0[2], self.0[1], self.0[0] 37 | ) 38 | } 39 | } 40 | 41 | #[derive(Clone, Copy)] 42 | pub enum BtProtocol { 43 | L2CAP, 44 | RFCOMM, 45 | } 46 | 47 | pub use crate::sys::bt::discover_devices; 48 | 49 | /// A Bluetooth socket server, listening for connections. 50 | /// 51 | /// After creating a `BtListener` by [`bind`]ing it to a Bluetooth address, it listens 52 | /// for incoming Bluetooth connections. These can be accepted by calling [`accept`] or by 53 | /// iterating over the [`Incoming`] iterator returned by [`incoming`] 54 | /// [`BtListener::incoming`]. 55 | /// 56 | /// The socket will be closed when the value is dropped. 57 | /// 58 | /// The Bluetooth transport protocols are specified by the 59 | /// [Bluetooth Special Interest Group]. 60 | /// 61 | /// [`accept`]: #method.accept 62 | /// [`bind`]: #method.bind 63 | /// [Bluetooth Special Interest Group]: https://www.bluetooth.com/specifications 64 | /// [`Incoming`]: https://doc.rust-lang.org/std/net/struct.Incoming.html 65 | /// [`BtListener::incoming`]: #method.incoming 66 | pub struct BtListener(bt_imp::BtListener); 67 | 68 | /// A Bluetooth stream between a local and remote socket 69 | /// 70 | /// After creating a `BtStream` by either [`connect`]ing to a remote host or [`accept`]ing 71 | /// a connection on a [`BtListener`], data can be transmitted by [reading] and [writing] 72 | /// to it. 73 | /// 74 | /// The connection will be closed when the value is dropped. The reading and writing 75 | /// portions of the connection can also be shut down individually with the [`shutdown`] 76 | /// method. 77 | /// 78 | /// The Bluetooth transport protocols are specified by the 79 | /// [Bluetooth Special Interest Group]. 80 | /// 81 | /// [`accept`]: ../struct.BtListener.html#method.accept 82 | /// [Bluetooth Special Interest Group]: https://www.bluetooth.com/specifications 83 | /// [`connect`]: #method.connect 84 | /// [reading]: https://doc.rust-lang.org/std/io/trait.Read.html 85 | /// [`shutdown`]: #method.shutdown 86 | /// [`BtListener`]: ../struct.BtListener.html 87 | /// [writing]: https://doc.rust-lang.org/std/io/trait.Write.html 88 | pub struct BtStream(bt_imp::BtStream); 89 | 90 | impl BtListener { 91 | /// Creates a new `BtListener` which will be bound to the specified address. 92 | /// 93 | /// The returned listener is ready for accepting connections. 94 | /// 95 | /// Binding with a port number of 0 will request that the OS assigns a port to this 96 | /// listener. The port allocated can be queried via the [`local_addr`] method. 97 | /// 98 | /// If `addrs` yields multiple addresses, `bind` will be attempted with each of the 99 | /// addresses until one succeeds and returns the socket. If none of the addresses 100 | /// succeed in creating a socket, the error returned from the last attempt (the last 101 | /// address) is returned. 102 | /// 103 | /// [`local_addr`]: #method.local_addr 104 | pub fn bind<'a, I>(addrs: I, protocol: BtProtocol) -> io::Result 105 | where 106 | I: Iterator, 107 | { 108 | each_addr(addrs, |addr| bt_imp::BtListener::bind(addr, protocol)).map(BtListener) 109 | } 110 | 111 | /// Accept a new incoming connection from this listener. 112 | /// 113 | /// This function will block the calling thread until a new Bluetooth connection is 114 | /// established. When established, the corresponding [`BtStream`] and the remote 115 | /// peer's address will be returned. 116 | /// 117 | /// [`BtStream`]: bt/struct.BtStream.html 118 | pub fn accept(&self) -> io::Result<(BtStream, BtAddr)> { 119 | // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so 120 | // the `a` variable here is technically unused. 121 | #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] 122 | self.0.accept().map(|(a, b)| (BtStream(a), b)) 123 | } 124 | 125 | /// Returns the local socket address of this listener. 126 | pub fn local_addr(&self) -> io::Result { 127 | self.0.local_addr() 128 | } 129 | 130 | /// Returns the socket protocol of this socket. 131 | pub fn protocol(&self) -> BtProtocol { 132 | self.0.protocol() 133 | } 134 | 135 | /// Get the value of the `SO_ERROR` option on this socket. 136 | /// 137 | /// This will retrieve the stored error in the underlying socket, clearing the field 138 | /// in the process. This can be useful for checking errors between calls. 139 | pub fn take_error(&self) -> io::Result> { 140 | self.0.take_error() 141 | } 142 | 143 | /// Moves this Bluetooth stream into or out of nonblocking mode. 144 | /// 145 | /// This will result in the `accept` operation becoming nonblocking, i.e., immediately 146 | /// returning from their calls. If the IO operation is successful, `Ok` is returned 147 | /// and no further action is required. If the IO operation could not be completed and 148 | /// needs to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is returned. 149 | /// 150 | /// On Unix platforms, calling this method corresponds to calling `fcntl` `FIONBIO`. 151 | /// On Windows calling this method corresponds to calling `ioctlsocket` `FIONBIO`. 152 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 153 | self.0.set_nonblocking(nonblocking) 154 | } 155 | 156 | /// Creates a new independently owned handle to the underlying socket. 157 | /// 158 | /// The returned [`BtListener`] is a reference to the same socket that this 159 | /// object references. Both handles can be used to accept incoming 160 | /// connections and options set on one listener will affect the other. 161 | /// 162 | /// [`BtListener`]: bt/struct.BtListener.html 163 | pub fn try_clone(&self) -> io::Result { 164 | self.0.duplicate().map(BtListener) 165 | } 166 | } 167 | 168 | impl fmt::Debug for BtListener { 169 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 170 | self.0.fmt(f) 171 | } 172 | } 173 | 174 | impl AsInner for BtListener { 175 | fn as_inner(&self) -> &bt_imp::BtListener { 176 | &self.0 177 | } 178 | } 179 | 180 | impl FromInner for BtListener { 181 | fn from_inner(inner: bt_imp::BtListener) -> BtListener { 182 | BtListener(inner) 183 | } 184 | } 185 | 186 | impl IntoInner for BtListener { 187 | fn into_inner(self) -> bt_imp::BtListener { 188 | self.0 189 | } 190 | } 191 | 192 | impl BtStream { 193 | /// Opens a Bluetooth connection to a remote host. 194 | /// 195 | /// If `addrs` yields multiple addresses, `connect` will be attempted with each of the 196 | /// addresses until the underlying OS function returns no error. Note that usually, a 197 | /// successful `connect` call does not specify that there is a remote server listening 198 | /// on the port, rather, such an error would only be detected after the first send. If 199 | /// the OS returns an error for each of the specified addresses, the error returned 200 | /// from the last connection attempt (the last address) is returned. 201 | pub fn connect<'a, I: Iterator>( 202 | addrs: I, 203 | protocol: BtProtocol, 204 | ) -> io::Result { 205 | each_addr(addrs, |addr| bt_imp::BtStream::connect(addr, protocol)).map(BtStream) 206 | } 207 | 208 | /// Opens a Bluetooth connection to a remote host with a timeout. 209 | /// 210 | /// Unlike `connect`, `connect_timeout` takes a single [`BtAddr`] since timeout must 211 | /// be applied to individual addresses. 212 | /// 213 | /// It is an error to pass a zero `Duration` to this function. 214 | /// 215 | /// Unlike other methods on `BtStream`, this does not correspond to a single system 216 | /// call. It instead calls `connect` in nonblocking mode and then uses an OS-specific 217 | /// mechanism to await the completion of the connection request. 218 | /// 219 | /// [`BtAddr`]: https://doc.rust-lang.org/std/net/enum.BtAddr.html 220 | pub fn connect_timeout( 221 | addr: &BtAddr, 222 | protocol: BtProtocol, 223 | timeout: Duration, 224 | ) -> io::Result { 225 | bt_imp::BtStream::connect_timeout(addr, protocol, timeout).map(BtStream) 226 | } 227 | 228 | /// Receives single Bluetooth on the socket from the remote address to which it is 229 | /// connected, without removing the message from input queue. On success, returns the 230 | /// number of bytes peeked. 231 | /// 232 | /// The function must be called with valid byte array `buf` of sufficient size to hold 233 | /// the message bytes. If a message is too long to fit in the supplied buffer, excess 234 | /// bytes may be discarded. 235 | /// 236 | /// Successive calls return the same data. This is accomplished by passing `MSG_PEEK` 237 | /// as a flag to the underlying `recv` system call. 238 | /// 239 | /// Do not use this function to implement busy waiting, instead use `libc::poll` to 240 | /// synchronize IO events on one or more sockets. 241 | /// 242 | /// The [`connect`] method will connect this socket to a remote address. This method 243 | /// will fail if the socket is not connected. 244 | /// 245 | /// [`connect`]: #method.connect 246 | /// 247 | /// # Errors 248 | /// 249 | /// This method will fail if the socket is not connected. The `connect` method will 250 | /// connect this socket to a remote address. 251 | pub fn peek(&self, buf: &mut [u8]) -> io::Result { 252 | self.0.peek(buf) 253 | } 254 | 255 | /// Receives a single Bluetooth message on the socket, without removing it from the 256 | /// queue. On success, returns the number of bytes read and the origin. 257 | /// 258 | /// The function must be called with valid byte array `buf` of sufficient size to hold 259 | /// the message bytes. If a message is too long to fit in the supplied buffer, excess 260 | /// bytes may be discarded. 261 | /// 262 | /// Successive calls return the same data. This is accomplished by passing `MSG_PEEK` 263 | /// as a flag to the underlying `recvfrom` system call. 264 | /// 265 | /// Do not use this function to implement busy waiting, instead use `libc::poll` to 266 | /// synchronize IO events on one or more sockets. 267 | pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 268 | self.0.peek_from(buf) 269 | } 270 | 271 | /// Receives a single Bluetooth message on the socket from the remote address to which 272 | /// it is connected. On success, returns the number of bytes read. 273 | /// 274 | /// The function must be called with valid byte array `buf` of sufficient size to hold 275 | /// the message bytes. If a message is too long to fit in the supplied buffer, excess 276 | /// bytes may be discarded. 277 | /// 278 | /// The [`connect`] method will connect this socket to a remote address. This method 279 | /// will fail if the socket is not connected. 280 | /// 281 | /// [`connect`]: #method.connect 282 | pub fn recv(&self, buf: &mut [u8]) -> io::Result { 283 | self.0.recv(buf) 284 | } 285 | 286 | /// Receives a single Bluetooth message on the socket. On success, returns the number 287 | /// of bytes read and the origin. 288 | /// 289 | /// The function must be called with valid byte array `buf` of sufficient size to hold 290 | /// the message bytes. If a message is too long to fit in the supplied buffer, excess 291 | /// bytes may be discarded. 292 | pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 293 | self.0.recv_from(buf) 294 | } 295 | 296 | /// Sends data on the socket to the remote address to which it is connected. 297 | /// 298 | /// The [`connect`] method will connect this socket to a remote address. This method 299 | /// will fail if the socket is not connected. 300 | /// 301 | /// [`connect`]: #method.connect 302 | pub fn send(&self, buf: &[u8]) -> io::Result { 303 | self.0.send(buf) 304 | } 305 | 306 | /// Sends data on the socket to the given address. On success, returns the number of 307 | /// bytes written. 308 | pub fn send_to(&self, buf: &[u8], dst: &BtAddr) -> io::Result { 309 | self.0.send_to(buf, dst) 310 | } 311 | 312 | /// Shuts down the read, write, or both halves of this connection. 313 | /// 314 | /// This function will cause all pending and future I/O on the specified portions to 315 | /// return immediately with an appropriate value (see the documentation of [`Shutdown`] 316 | /// ). 317 | /// 318 | /// [`Shutdown`]: https://doc.rust-lang.org/std/net/enum.Shutdown.html 319 | /// 320 | /// # Platform-specific behavior 321 | /// 322 | /// Calling this function multiple times may result in different behavior, depending 323 | /// on the operating system. On Linux, the second call will return `Ok(())`, but on 324 | /// macOS, it will return `ErrorKind::NotConnected`. This may change in the future. 325 | pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { 326 | self.0.shutdown(how) 327 | } 328 | 329 | /// Returns the socket address that this socket was created from. 330 | pub fn local_addr(&self) -> io::Result { 331 | self.0.local_addr() 332 | } 333 | 334 | /// Returns the socket address of the remote peer this socket was connected to. 335 | pub fn peer_addr(&self) -> io::Result { 336 | self.0.peer_addr() 337 | } 338 | 339 | /// Returns the socket protocol of this socket. 340 | pub fn protocol(&self) -> BtProtocol { 341 | self.0.protocol() 342 | } 343 | 344 | /// Gets the value of the `SO_ERROR` option on this socket. 345 | /// 346 | /// This will retrieve the stored error in the underlying socket, clearing 347 | /// the field in the process. This can be useful for checking errors between 348 | /// calls. 349 | pub fn take_error(&self) -> io::Result> { 350 | self.0.take_error() 351 | } 352 | 353 | /// Returns the read timeout of this socket. 354 | /// 355 | /// If the timeout is [`None`], then [`read`] calls will block indefinitely. 356 | /// 357 | /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None 358 | /// [`read`]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read 359 | pub fn read_timeout(&self) -> io::Result> { 360 | self.0.read_timeout() 361 | } 362 | 363 | /// Sets the read timeout to the timeout specified. 364 | /// 365 | /// If the value specified is [`None`], then [`read`] calls will block indefinitely. 366 | /// An [`Err`] is returned if the zero [`Duration`] is passed to this method. 367 | /// 368 | /// # Platform-specific behavior 369 | /// 370 | /// Platforms may return a different error code whenever a read times out as a result 371 | /// of setting this option. For example Unix typically returns an error of the kind 372 | /// [`WouldBlock`], but Windows may return [`TimedOut`]. 373 | /// 374 | /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None 375 | /// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err 376 | /// [`read`]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read 377 | /// [`Duration`]: https://doc.rust-lang.org/std/time/struct.Duration.html 378 | /// [`WouldBlock`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.WouldBlock 379 | /// [`TimedOut`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.TimedOut 380 | /// 381 | /// An [`Err`] is returned if the zero [`Duration`] is passed to this method. 382 | pub fn set_read_timeout(&self, dur: Option) -> io::Result<()> { 383 | self.0.set_read_timeout(dur) 384 | } 385 | 386 | /// Returns the write timeout of this socket. 387 | /// 388 | /// If the timeout is [`None`], then [`write`] calls will block indefinitely. 389 | /// 390 | /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None 391 | /// [`write`]: https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.write 392 | pub fn write_timeout(&self) -> io::Result> { 393 | self.0.write_timeout() 394 | } 395 | 396 | /// Sets the write timeout to the timeout specified. 397 | /// 398 | /// If the value specified is [`None`], then [`write`] calls will block indefinitely. 399 | /// An [`Err`] is returned if the zero [`Duration`] is passed to this method. 400 | /// 401 | /// # Platform-specific behavior 402 | /// 403 | /// Platforms may return a different error code whenever a write times out as a result 404 | /// of setting this option. For example Unix typically returns an error of the kind 405 | /// [`WouldBlock`], but Windows may return [`TimedOut`]. 406 | /// 407 | /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None 408 | /// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err 409 | /// [`write`]: https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.write 410 | /// [`Duration`]: https://doc.rust-lang.org/std/time/struct.Duration.html 411 | /// [`WouldBlock`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.WouldBlock 412 | /// [`TimedOut`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.TimedOut 413 | /// 414 | /// An [`Err`] is returned if the zero [`Duration`] is passed to this method. 415 | pub fn set_write_timeout(&self, dur: Option) -> io::Result<()> { 416 | self.0.set_write_timeout(dur) 417 | } 418 | 419 | /// Moves this Bluetooth socket into or out of nonblocking mode. 420 | /// 421 | /// This will result in `recv`, `recv_from`, `send`, and `send_to` operations becoming 422 | /// nonblocking, i.e., immediately returning from their calls. If the IO operation is 423 | /// successful, `Ok` is returned and no further action is required. If the IO 424 | /// operation could not be completed and needs to be retried, an error with kind 425 | /// [`io::ErrorKind::WouldBlock`] is returned. 426 | /// 427 | /// On Unix platforms, calling this method corresponds to calling `fcntl` `FIONBIO`. 428 | /// On Windows calling this method corresponds to calling `ioctlsocket` `FIONBIO`. 429 | /// 430 | /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock 431 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 432 | self.0.set_nonblocking(nonblocking) 433 | } 434 | 435 | /// Creates a new independently owned handle to the underlying socket. 436 | /// 437 | /// The returned `UdpSocket` is a reference to the same socket that this 438 | /// object references. Both handles will read and write the same port, and 439 | /// options set on one socket will be propagated to the other. 440 | pub fn try_clone(&self) -> io::Result { 441 | self.0.duplicate().map(BtStream) 442 | } 443 | } 444 | 445 | impl fmt::Debug for BtStream { 446 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 447 | self.0.fmt(f) 448 | } 449 | } 450 | 451 | impl io::Read for BtStream { 452 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 453 | self.0.recv(buf) 454 | } 455 | } 456 | 457 | impl io::Write for BtStream { 458 | fn write(&mut self, buf: &[u8]) -> io::Result { 459 | self.0.send(buf) 460 | } 461 | 462 | fn flush(&mut self) -> io::Result<()> { 463 | Ok(()) 464 | } 465 | } 466 | 467 | impl AsInner for BtStream { 468 | fn as_inner(&self) -> &bt_imp::BtStream { 469 | &self.0 470 | } 471 | } 472 | 473 | impl FromInner for BtStream { 474 | fn from_inner(inner: bt_imp::BtStream) -> BtStream { 475 | BtStream(inner) 476 | } 477 | } 478 | 479 | impl IntoInner for BtStream { 480 | fn into_inner(self) -> bt_imp::BtStream { 481 | self.0 482 | } 483 | } 484 | 485 | fn each_addr<'a, I, F, T>(addrs: I, mut f: F) -> io::Result 486 | where 487 | F: FnMut(&'a BtAddr) -> io::Result, 488 | I: Iterator, 489 | { 490 | let mut last_err = None; 491 | for addr in addrs { 492 | match f(addr) { 493 | Ok(l) => return Ok(l), 494 | Err(e) => last_err = Some(e), 495 | } 496 | } 497 | Err(last_err.unwrap_or_else(|| { 498 | io::Error::new( 499 | io::ErrorKind::InvalidInput, 500 | "could not resolve to any addresses", 501 | ) 502 | })) 503 | } 504 | 505 | #[cfg(test)] 506 | mod tests {} 507 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate cfg_if; 3 | 4 | #[cfg(windows)] 5 | extern crate winapi; 6 | 7 | pub mod bt; 8 | 9 | mod sys; 10 | mod sys_common; 11 | -------------------------------------------------------------------------------- /src/sys/mod.rs: -------------------------------------------------------------------------------- 1 | cfg_if! { 2 | if #[cfg(unix)] { 3 | mod unix; 4 | pub use self::unix::*; 5 | } else if #[cfg(windows)] { 6 | mod windows; 7 | pub use self::windows::*; 8 | } else { 9 | compile_error!("io_bluetooth doesn't compile for this platform yet"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/sys/unix/bt.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | use std::io; 3 | use std::mem; 4 | use std::net::Shutdown; 5 | use std::os::raw::{c_int, c_void}; 6 | use std::ptr; 7 | use std::time::{Duration, Instant}; 8 | 9 | mod libbt { 10 | pub use libbluetooth::bluetooth::{bdaddr_t, BTPROTO_L2CAP, BTPROTO_RFCOMM}; 11 | pub use libbluetooth::hci::{inquiry_info, IREQ_CACHE_FLUSH}; 12 | pub use libbluetooth::hci_lib::{hci_close_dev, hci_get_route, hci_inquiry, hci_open_dev}; 13 | pub use libbluetooth::rfcomm::sockaddr_rc; 14 | } 15 | 16 | use libc; 17 | 18 | use crate::bt::{BtAddr, BtProtocol}; 19 | use crate::sys::fd::FileDesc; 20 | use crate::sys_common::bt::{getsockopt, setsockopt}; 21 | use crate::sys_common::{AsInner, FromInner, IntoInner}; 22 | 23 | pub use crate::sys::{cvt, cvt_r}; 24 | 25 | pub mod btc { 26 | pub use libc::size_t as wrlen_t; 27 | pub use libc::*; 28 | } 29 | 30 | // Another conditional constant for name resolution: MacOS and iOS use 31 | // SO_NOSIGPIPE as a setsockopt flag to disable SIGPIPE emission on socket. 32 | // Other platforms do otherwise. 33 | #[cfg(not(target_os = "linux"))] 34 | use libc::SO_NOSIGPIPE; 35 | #[cfg(target_os = "linux")] 36 | const SO_NOSIGPIPE: c_int = 0; 37 | 38 | pub struct Socket(FileDesc); 39 | 40 | impl Socket { 41 | pub fn new(protocol: BtProtocol) -> io::Result { 42 | let protocol = match protocol { 43 | BtProtocol::L2CAP => libbt::BTPROTO_L2CAP, 44 | BtProtocol::RFCOMM => libbt::BTPROTO_RFCOMM, 45 | }; 46 | 47 | // On linux we first attempt to pass the SOCK_CLOEXEC flag to 48 | // atomically create the socket and set it as CLOEXEC. Support for 49 | // this option, however, was added in 2.6.27, and we still support 50 | // 2.6.18 as a kernel, so if the returned error is EINVAL we 51 | // fallthrough to the fallback. 52 | if cfg!(target_os = "linux") { 53 | let res = cvt(unsafe { 54 | libc::socket( 55 | libc::AF_BLUETOOTH, 56 | libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 57 | protocol, 58 | ) 59 | }); 60 | match res { 61 | Ok(fd) => return Ok(Socket(FileDesc::new(fd))), 62 | Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} 63 | Err(e) => return Err(e), 64 | } 65 | } 66 | 67 | let fd = cvt(unsafe { libc::socket(libc::AF_BLUETOOTH, libc::SOCK_STREAM, protocol) })?; 68 | let fd = FileDesc::new(fd); 69 | fd.set_cloexec()?; 70 | let socket = Socket(fd); 71 | if cfg!(target_vendor = "apple") { 72 | setsockopt(&socket, libc::SOL_SOCKET, SO_NOSIGPIPE, 1)?; 73 | } 74 | Ok(socket) 75 | } 76 | 77 | pub fn accept(&self) -> io::Result<(Socket, BtAddr)> { 78 | let mut addr: libbt::sockaddr_rc = unsafe { mem::zeroed() }; 79 | let mut len = mem::size_of::() as btc::socklen_t; 80 | 81 | // Unfortunately the only known way right now to accept a socket and 82 | // atomically set the CLOEXEC flag is to use the `accept4` syscall on 83 | // Linux. This was added in 2.6.28, however, and because we support 84 | // 2.6.18 we must detect this support dynamically. 85 | if cfg!(target_os = "linux") { 86 | let res = cvt_r(|| unsafe { 87 | libc::accept4( 88 | self.0.raw(), 89 | &mut addr as *mut _ as *mut _, 90 | &mut len, 91 | libc::SOCK_CLOEXEC, 92 | ) 93 | }); 94 | match res { 95 | Ok(fd) => return Ok((Socket(FileDesc::new(fd)), BtAddr(addr.rc_bdaddr.b))), 96 | Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} 97 | Err(e) => return Err(e), 98 | } 99 | } 100 | 101 | let fd = cvt_r(|| unsafe { 102 | libc::accept(self.0.raw(), &mut addr as *mut _ as *mut _, &mut len) 103 | })?; 104 | let fd = FileDesc::new(fd); 105 | fd.set_cloexec()?; 106 | Ok((Socket(fd), BtAddr(addr.rc_bdaddr.b))) 107 | } 108 | 109 | pub fn connect_timeout(&self, addr: &BtAddr, timeout: Duration) -> io::Result<()> { 110 | self.set_nonblocking(true)?; 111 | let r = { 112 | let addr = libbt::sockaddr_rc { 113 | rc_family: libc::AF_BLUETOOTH as u16, 114 | rc_bdaddr: libbt::bdaddr_t { b: addr.0 }, 115 | rc_channel: 1, 116 | }; 117 | cvt(unsafe { 118 | libc::connect( 119 | self.0.raw(), 120 | &addr as *const _ as *const _, 121 | mem::size_of_val(&addr) as libc::socklen_t, 122 | ) 123 | }) 124 | }; 125 | self.set_nonblocking(false)?; 126 | 127 | match r { 128 | Ok(_) => return Ok(()), 129 | // There's no ErrorKind for EINPROGRESS 130 | Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} 131 | Err(e) => return Err(e), 132 | } 133 | 134 | let mut pollfd = libc::pollfd { 135 | fd: self.0.raw(), 136 | events: libc::POLLOUT, 137 | revents: 0, 138 | }; 139 | 140 | if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { 141 | return Err(io::Error::new( 142 | io::ErrorKind::InvalidInput, 143 | "cannot set a 0 duration timeout", 144 | )); 145 | } 146 | 147 | let start = Instant::now(); 148 | 149 | loop { 150 | let elapsed = start.elapsed(); 151 | if elapsed >= timeout { 152 | return Err(io::Error::new( 153 | io::ErrorKind::TimedOut, 154 | "connection timed out", 155 | )); 156 | } 157 | 158 | let timeout = timeout - elapsed; 159 | let mut timeout = timeout 160 | .as_secs() 161 | .saturating_mul(1_000) 162 | .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000); 163 | if timeout == 0 { 164 | timeout = 1; 165 | } 166 | 167 | let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int; 168 | 169 | match unsafe { libc::poll(&mut pollfd, 1, timeout) } { 170 | -1 => { 171 | let err = io::Error::last_os_error(); 172 | if err.kind() != io::ErrorKind::Interrupted { 173 | return Err(err); 174 | } 175 | } 176 | 0 => {} 177 | _ => { 178 | // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look 179 | // for POLLHUP rather than read readiness 180 | if pollfd.revents & libc::POLLHUP != 0 { 181 | let e = self.take_error()?.unwrap_or_else(|| { 182 | io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") 183 | }); 184 | return Err(e); 185 | } 186 | 187 | return Ok(()); 188 | } 189 | } 190 | } 191 | } 192 | 193 | pub fn peek(&self, buf: &mut [u8]) -> io::Result { 194 | self.recv_with_flags(buf, libc::MSG_PEEK) 195 | } 196 | 197 | pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 198 | self.recv_from_with_flags(buf, libc::MSG_PEEK) 199 | } 200 | 201 | pub fn read(&self, buf: &mut [u8]) -> io::Result { 202 | self.recv_with_flags(buf, 0) 203 | } 204 | 205 | pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 206 | self.recv_from_with_flags(buf, 0) 207 | } 208 | 209 | fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, BtAddr)> { 210 | let mut addr: libbt::sockaddr_rc = unsafe { mem::zeroed() }; 211 | let mut addrlen = mem::size_of_val(&addr) as libc::socklen_t; 212 | 213 | let n = cvt(unsafe { 214 | libc::recvfrom( 215 | self.0.raw(), 216 | buf.as_mut_ptr() as *mut c_void, 217 | buf.len(), 218 | flags, 219 | &mut addr as *mut _ as *mut _, 220 | &mut addrlen, 221 | ) 222 | })?; 223 | Ok((n as usize, BtAddr(addr.rc_bdaddr.b))) 224 | } 225 | 226 | fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result { 227 | let ret = cvt(unsafe { 228 | libc::recv( 229 | self.0.raw(), 230 | buf.as_mut_ptr() as *mut c_void, 231 | buf.len(), 232 | flags, 233 | ) 234 | })?; 235 | Ok(ret as usize) 236 | } 237 | 238 | pub fn set_timeout(&self, dur: Option, kind: c_int) -> io::Result<()> { 239 | let timeout = match dur { 240 | Some(dur) => { 241 | if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { 242 | return Err(io::Error::new( 243 | io::ErrorKind::InvalidInput, 244 | "cannot set a 0 duration timeout", 245 | )); 246 | } 247 | 248 | let secs = if dur.as_secs() > libc::time_t::max_value() as u64 { 249 | libc::time_t::max_value() 250 | } else { 251 | dur.as_secs() as libc::time_t 252 | }; 253 | let mut timeout = libc::timeval { 254 | tv_sec: secs, 255 | tv_usec: dur.subsec_micros() as libc::suseconds_t, 256 | }; 257 | if timeout.tv_sec == 0 && timeout.tv_usec == 0 { 258 | timeout.tv_usec = 1; 259 | } 260 | timeout 261 | } 262 | None => libc::timeval { 263 | tv_sec: 0, 264 | tv_usec: 0, 265 | }, 266 | }; 267 | setsockopt(self, libc::SOL_SOCKET, kind, timeout) 268 | } 269 | 270 | pub fn timeout(&self, kind: c_int) -> io::Result> { 271 | let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?; 272 | if raw.tv_sec == 0 && raw.tv_usec == 0 { 273 | Ok(None) 274 | } else { 275 | let sec = raw.tv_sec as u64; 276 | let nsec = (raw.tv_usec as u32) * 1_000; 277 | Ok(Some(Duration::new(sec, nsec))) 278 | } 279 | } 280 | 281 | pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { 282 | let how = match how { 283 | Shutdown::Write => libc::SHUT_WR, 284 | Shutdown::Read => libc::SHUT_RD, 285 | Shutdown::Both => libc::SHUT_RDWR, 286 | }; 287 | cvt(unsafe { libc::shutdown(self.0.raw(), how) })?; 288 | Ok(()) 289 | } 290 | 291 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 292 | let mut nonblocking = nonblocking as c_int; 293 | cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ()) 294 | } 295 | 296 | pub fn take_error(&self) -> io::Result> { 297 | let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?; 298 | if raw == 0 { 299 | Ok(None) 300 | } else { 301 | Ok(Some(io::Error::from_raw_os_error(raw as i32))) 302 | } 303 | } 304 | 305 | pub fn duplicate(&self) -> io::Result { 306 | self.0.duplicate().map(Socket) 307 | } 308 | } 309 | 310 | impl AsInner for Socket { 311 | fn as_inner(&self) -> &c_int { 312 | self.0.as_inner() 313 | } 314 | } 315 | 316 | impl FromInner for Socket { 317 | fn from_inner(fd: c_int) -> Socket { 318 | Socket(FileDesc::new(fd)) 319 | } 320 | } 321 | 322 | impl IntoInner for Socket { 323 | fn into_inner(self) -> c_int { 324 | self.0.into_raw() 325 | } 326 | } 327 | 328 | pub fn discover_devices() -> io::Result> { 329 | let device_id = unsafe { libbt::hci_get_route(ptr::null_mut()) }; 330 | if device_id == -1 { 331 | return Err(io::Error::last_os_error()); 332 | } 333 | 334 | let local_socket = unsafe { libbt::hci_open_dev(device_id) }; 335 | if local_socket == -1 { 336 | return Err(io::Error::last_os_error()); 337 | } 338 | 339 | let mut inquiry_infos = vec![libbt::inquiry_info::default(); 256]; 340 | 341 | const TIMEOUT: c_int = 4; // 4 * 1.28 seconds 342 | let num_responses = unsafe { 343 | libbt::hci_inquiry( 344 | device_id, 345 | TIMEOUT, 346 | inquiry_infos.len() as c_int, 347 | ptr::null(), 348 | &mut inquiry_infos.as_mut_ptr(), 349 | libbt::IREQ_CACHE_FLUSH, 350 | ) 351 | }; 352 | if num_responses == -1 { 353 | return Err(io::Error::last_os_error()); 354 | } 355 | 356 | inquiry_infos.truncate(num_responses as usize); 357 | let devices = inquiry_infos.iter().map(|ii| BtAddr(ii.bdaddr.b)).collect(); 358 | 359 | if -1 == unsafe { libbt::hci_close_dev(local_socket) } { 360 | Err(io::Error::last_os_error()) 361 | } else { 362 | Ok(devices) 363 | } 364 | } 365 | 366 | impl<'a> Into for &'a btc::sockaddr_storage { 367 | fn into(self) -> BtAddr { 368 | let addr: &'a libbt::sockaddr_rc = unsafe { &*(self as *const _ as *const _) }; 369 | BtAddr(addr.rc_bdaddr.b) 370 | } 371 | } 372 | 373 | impl<'a> Into<(btc::sockaddr_storage, btc::socklen_t)> for &'a BtAddr { 374 | fn into(self) -> (btc::sockaddr_storage, btc::socklen_t) { 375 | let mut addr: btc::sockaddr_storage = unsafe { mem::zeroed() }; 376 | 377 | let sarc: &mut libbt::sockaddr_rc = unsafe { &mut *(&mut addr as *mut _ as *mut _) }; 378 | sarc.rc_family = libc::AF_BLUETOOTH as u16; 379 | sarc.rc_bdaddr.b = self.0; 380 | sarc.rc_channel = 1; 381 | 382 | (addr, mem::size_of::() as btc::socklen_t) 383 | } 384 | } 385 | -------------------------------------------------------------------------------- /src/sys/unix/c.rs: -------------------------------------------------------------------------------- 1 | pub use libbluetooth::{ 2 | bluetooth::{bdaddr_t, BTPROTO_L2CAP, BTPROTO_RFCOMM}, 3 | hci::{inquiry_info, IREQ_CACHE_FLUSH}, 4 | hci_lib::{hci_close_dev, hci_get_route, hci_inquiry, hci_open_dev}, 5 | rfcomm::sockaddr_rc, 6 | }; 7 | pub use libc::{ 8 | accept, bind, connect, getpeername, getsockname, shutdown, sockaddr, socket, socklen_t, 9 | AF_BLUETOOTH, SHUT_RDWR, SOCK_STREAM, 10 | }; 11 | -------------------------------------------------------------------------------- /src/sys/unix/fd.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | use std::io::{self, Read}; 3 | use std::mem; 4 | use std::sync::atomic::{AtomicBool, Ordering}; 5 | 6 | use crate::sys::cvt; 7 | use crate::sys_common::AsInner; 8 | 9 | use libc::{self, c_int, c_void, ssize_t}; 10 | 11 | #[derive(Debug)] 12 | pub struct FileDesc { 13 | fd: c_int, 14 | } 15 | 16 | fn max_len() -> usize { 17 | // The maximum read limit on most posix-like systems is `SSIZE_MAX`, 18 | // with the man page quoting that if the count of bytes to read is 19 | // greater than `SSIZE_MAX` the result is "unspecified". 20 | // 21 | // On macOS, however, apparently the 64-bit libc is either buggy or 22 | // intentionally showing odd behavior by rejecting any read with a size 23 | // larger than or equal to INT_MAX. To handle both of these the read 24 | // size is capped on both platforms. 25 | if cfg!(target_os = "macos") { 26 | ::max_value() as usize - 1 27 | } else { 28 | ::max_value() as usize 29 | } 30 | } 31 | 32 | impl FileDesc { 33 | pub fn new(fd: c_int) -> FileDesc { 34 | FileDesc { fd } 35 | } 36 | 37 | pub fn raw(&self) -> c_int { 38 | self.fd 39 | } 40 | 41 | /// Extracts the actual file descriptor without closing it. 42 | pub fn into_raw(self) -> c_int { 43 | let fd = self.fd; 44 | mem::forget(self); 45 | fd 46 | } 47 | 48 | pub fn read(&self, buf: &mut [u8]) -> io::Result { 49 | let ret = cvt(unsafe { 50 | libc::read( 51 | self.fd, 52 | buf.as_mut_ptr() as *mut c_void, 53 | cmp::min(buf.len(), max_len()), 54 | ) 55 | })?; 56 | Ok(ret as usize) 57 | } 58 | 59 | pub fn read_to_end(&self, buf: &mut Vec) -> io::Result { 60 | let mut me = self; 61 | (&mut me).read_to_end(buf) 62 | } 63 | 64 | pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { 65 | #[cfg(target_os = "android")] 66 | use super::android::cvt_pread64; 67 | 68 | #[cfg(target_os = "emscripten")] 69 | unsafe fn cvt_pread64( 70 | fd: c_int, 71 | buf: *mut c_void, 72 | count: usize, 73 | offset: i64, 74 | ) -> io::Result { 75 | use convert::TryInto; 76 | use libc::pread64; 77 | // pread64 on emscripten actually takes a 32 bit offset 78 | if let Ok(o) = offset.try_into() { 79 | cvt(pread64(fd, buf, count, o)) 80 | } else { 81 | Err(io::Error::new( 82 | io::ErrorKind::InvalidInput, 83 | "cannot pread >2GB", 84 | )) 85 | } 86 | } 87 | 88 | #[cfg(not(any(target_os = "android", target_os = "emscripten")))] 89 | unsafe fn cvt_pread64( 90 | fd: c_int, 91 | buf: *mut c_void, 92 | count: usize, 93 | offset: i64, 94 | ) -> io::Result { 95 | #[cfg(not(target_os = "linux"))] 96 | use libc::pread as pread64; 97 | #[cfg(target_os = "linux")] 98 | use libc::pread64; 99 | cvt(pread64(fd, buf, count, offset)) 100 | } 101 | 102 | unsafe { 103 | cvt_pread64( 104 | self.fd, 105 | buf.as_mut_ptr() as *mut c_void, 106 | cmp::min(buf.len(), max_len()), 107 | offset as i64, 108 | ) 109 | .map(|n| n as usize) 110 | } 111 | } 112 | 113 | pub fn write(&self, buf: &[u8]) -> io::Result { 114 | let ret = cvt(unsafe { 115 | libc::write( 116 | self.fd, 117 | buf.as_ptr() as *const c_void, 118 | cmp::min(buf.len(), max_len()), 119 | ) 120 | })?; 121 | Ok(ret as usize) 122 | } 123 | 124 | pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result { 125 | #[cfg(target_os = "android")] 126 | use super::android::cvt_pwrite64; 127 | 128 | #[cfg(target_os = "emscripten")] 129 | unsafe fn cvt_pwrite64( 130 | fd: c_int, 131 | buf: *const c_void, 132 | count: usize, 133 | offset: i64, 134 | ) -> io::Result { 135 | use convert::TryInto; 136 | use libc::pwrite64; 137 | // pwrite64 on emscripten actually takes a 32 bit offset 138 | if let Ok(o) = offset.try_into() { 139 | cvt(pwrite64(fd, buf, count, o)) 140 | } else { 141 | Err(io::Error::new( 142 | io::ErrorKind::InvalidInput, 143 | "cannot pwrite >2GB", 144 | )) 145 | } 146 | } 147 | 148 | #[cfg(not(any(target_os = "android", target_os = "emscripten")))] 149 | unsafe fn cvt_pwrite64( 150 | fd: c_int, 151 | buf: *const c_void, 152 | count: usize, 153 | offset: i64, 154 | ) -> io::Result { 155 | #[cfg(not(target_os = "linux"))] 156 | use libc::pwrite as pwrite64; 157 | #[cfg(target_os = "linux")] 158 | use libc::pwrite64; 159 | cvt(pwrite64(fd, buf, count, offset)) 160 | } 161 | 162 | unsafe { 163 | cvt_pwrite64( 164 | self.fd, 165 | buf.as_ptr() as *const c_void, 166 | cmp::min(buf.len(), max_len()), 167 | offset as i64, 168 | ) 169 | .map(|n| n as usize) 170 | } 171 | } 172 | 173 | #[cfg(target_os = "linux")] 174 | pub fn get_cloexec(&self) -> io::Result { 175 | unsafe { Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) } 176 | } 177 | 178 | #[cfg(not(any( 179 | target_env = "newlib", 180 | target_os = "solaris", 181 | target_os = "emscripten", 182 | target_os = "fuchsia", 183 | target_os = "l4re", 184 | target_os = "haiku" 185 | )))] 186 | pub fn set_cloexec(&self) -> io::Result<()> { 187 | unsafe { 188 | cvt(libc::ioctl(self.fd, libc::FIOCLEX))?; 189 | Ok(()) 190 | } 191 | } 192 | #[cfg(any( 193 | target_env = "newlib", 194 | target_os = "solaris", 195 | target_os = "emscripten", 196 | target_os = "fuchsia", 197 | target_os = "l4re", 198 | target_os = "haiku" 199 | ))] 200 | pub fn set_cloexec(&self) -> io::Result<()> { 201 | unsafe { 202 | let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?; 203 | let new = previous | libc::FD_CLOEXEC; 204 | if new != previous { 205 | cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?; 206 | } 207 | Ok(()) 208 | } 209 | } 210 | 211 | #[cfg(target_os = "linux")] 212 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 213 | unsafe { 214 | let v = nonblocking as c_int; 215 | cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?; 216 | Ok(()) 217 | } 218 | } 219 | 220 | #[cfg(not(target_os = "linux"))] 221 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 222 | unsafe { 223 | let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?; 224 | let new = if nonblocking { 225 | previous | libc::O_NONBLOCK 226 | } else { 227 | previous & !libc::O_NONBLOCK 228 | }; 229 | if new != previous { 230 | cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?; 231 | } 232 | Ok(()) 233 | } 234 | } 235 | 236 | pub fn duplicate(&self) -> io::Result { 237 | // We want to atomically duplicate this file descriptor and set the 238 | // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This 239 | // flag, however, isn't supported on older Linux kernels (earlier than 240 | // 2.6.24). 241 | // 242 | // To detect this and ensure that CLOEXEC is still set, we 243 | // follow a strategy similar to musl [1] where if passing 244 | // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not 245 | // supported (the third parameter, 0, is always valid), so we stop 246 | // trying that. 247 | // 248 | // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to 249 | // resolve so we at least compile this. 250 | // 251 | // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963 252 | #[cfg(any(target_os = "android", target_os = "haiku"))] 253 | use libc::F_DUPFD as F_DUPFD_CLOEXEC; 254 | #[cfg(not(any(target_os = "android", target_os = "haiku")))] 255 | use libc::F_DUPFD_CLOEXEC; 256 | 257 | let make_filedesc = |fd| { 258 | let fd = FileDesc::new(fd); 259 | fd.set_cloexec()?; 260 | Ok(fd) 261 | }; 262 | static TRY_CLOEXEC: AtomicBool = AtomicBool::new(!cfg!(target_os = "android")); 263 | let fd = self.raw(); 264 | if TRY_CLOEXEC.load(Ordering::Relaxed) { 265 | match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) { 266 | // We *still* call the `set_cloexec` method as apparently some 267 | // linux kernel at some point stopped setting CLOEXEC even 268 | // though it reported doing so on F_DUPFD_CLOEXEC. 269 | Ok(fd) => { 270 | return Ok(if cfg!(target_os = "linux") { 271 | make_filedesc(fd)? 272 | } else { 273 | FileDesc::new(fd) 274 | }); 275 | } 276 | Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => { 277 | TRY_CLOEXEC.store(false, Ordering::Relaxed); 278 | } 279 | Err(e) => return Err(e), 280 | } 281 | } 282 | cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc) 283 | } 284 | } 285 | 286 | impl<'a> Read for &'a FileDesc { 287 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 288 | (**self).read(buf) 289 | } 290 | } 291 | 292 | impl AsInner for FileDesc { 293 | fn as_inner(&self) -> &c_int { 294 | &self.fd 295 | } 296 | } 297 | 298 | impl Drop for FileDesc { 299 | fn drop(&mut self) { 300 | // Note that errors are ignored when closing a file descriptor. The 301 | // reason for this is that if an error occurs we don't actually know if 302 | // the file descriptor was closed or not, and if we retried (for 303 | // something like EINTR), we might close another valid file descriptor 304 | // opened after we closed ours. 305 | let _ = unsafe { libc::close(self.fd) }; 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /src/sys/unix/mod.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | pub mod bt; 4 | pub mod c; 5 | pub mod fd; 6 | 7 | #[doc(hidden)] 8 | pub trait IsMinusOne { 9 | fn is_minus_one(&self) -> bool; 10 | } 11 | 12 | macro_rules! impl_is_minus_one { 13 | ($($t:ident)*) => ($(impl IsMinusOne for $t { 14 | fn is_minus_one(&self) -> bool { 15 | *self == -1 16 | } 17 | })*) 18 | } 19 | 20 | impl_is_minus_one! { i8 i16 i32 i64 isize } 21 | 22 | pub fn cvt(t: T) -> io::Result { 23 | if t.is_minus_one() { 24 | Err(io::Error::last_os_error()) 25 | } else { 26 | Ok(t) 27 | } 28 | } 29 | 30 | pub fn cvt_r(mut f: F) -> io::Result 31 | where 32 | T: IsMinusOne, 33 | F: FnMut() -> T, 34 | { 35 | loop { 36 | match cvt(f()) { 37 | Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} 38 | other => return other, 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/sys/windows/bt.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | use std::io; 3 | use std::mem::{self, MaybeUninit}; 4 | use std::net::{self, Shutdown}; 5 | use std::os::raw::{c_char, c_int, c_long, c_ulong}; 6 | use std::ptr; 7 | use std::sync::Once; 8 | use std::time::Duration; 9 | 10 | use crate::sys::{self, c}; 11 | use crate::sys_common::bt; 12 | use crate::sys_common::{AsInner, FromInner, IntoInner}; 13 | 14 | use crate::bt::{BtAddr, BtProtocol}; 15 | 16 | pub mod btc { 17 | pub use crate::sys::c::SOCKADDR as sockaddr; 18 | pub use crate::sys::c::SOCKADDR_STORAGE_LH as sockaddr_storage; 19 | pub use crate::sys::c::*; 20 | pub use std::os::raw::c_int as socklen_t; 21 | pub use std::os::raw::c_int as wrlen_t; 22 | } 23 | 24 | pub struct Socket(c::SOCKET); 25 | 26 | fn init() { 27 | static START: Once = Once::new(); 28 | 29 | START.call_once(|| { 30 | // Initialize winsock through the standard library by just creating a 31 | // dummy socket. Whether this is successful or not we drop the result as 32 | // libstd will be sure to have initialized winsock. 33 | let _ = net::UdpSocket::bind("127.0.0.1:34254"); 34 | }); 35 | } 36 | 37 | /// Returns the last error from the Windows socket interface. 38 | fn last_error() -> io::Error { 39 | io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() }) 40 | } 41 | 42 | #[doc(hidden)] 43 | pub trait IsMinusOne { 44 | fn is_minus_one(&self) -> bool; 45 | } 46 | 47 | macro_rules! impl_is_minus_one { 48 | ($($t:ident)*) => ($(impl IsMinusOne for $t { 49 | fn is_minus_one(&self) -> bool { 50 | *self == -1 51 | } 52 | })*) 53 | } 54 | 55 | impl_is_minus_one! { i8 i16 i32 i64 isize } 56 | 57 | /// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1) 58 | /// and if so, returns the last error from the Windows socket interface. This 59 | /// function must be called before another call to the socket API is made. 60 | pub fn cvt(t: T) -> io::Result { 61 | if t.is_minus_one() { 62 | Err(last_error()) 63 | } else { 64 | Ok(t) 65 | } 66 | } 67 | 68 | /// Just to provide the same interface as sys/unix/bt.rs 69 | pub fn cvt_r(mut f: F) -> io::Result 70 | where 71 | T: IsMinusOne, 72 | F: FnMut() -> T, 73 | { 74 | cvt(f()) 75 | } 76 | 77 | impl Socket { 78 | pub fn new(protocol: BtProtocol) -> io::Result { 79 | init(); 80 | 81 | let protocol = match protocol { 82 | BtProtocol::L2CAP => { 83 | return Err(io::Error::new( 84 | io::ErrorKind::InvalidData, 85 | "L2CAP is currently not supported on Windows", 86 | )) 87 | } //c::BTHPROTO_L2CAP, 88 | BtProtocol::RFCOMM => c::BTHPROTO_RFCOMM, 89 | }; 90 | let socket = unsafe { 91 | match c::WSASocketW( 92 | c::AF_BTH as c_int, 93 | c::SOCK_STREAM, 94 | protocol as c_int, 95 | ptr::null_mut(), 96 | 0, 97 | c::WSA_FLAG_OVERLAPPED, 98 | ) { 99 | c::INVALID_SOCKET => Err(last_error()), 100 | n => Ok(Socket(n)), 101 | } 102 | }?; 103 | socket.set_no_inherit()?; 104 | Ok(socket) 105 | } 106 | 107 | pub fn accept(&self) -> io::Result<(Socket, BtAddr)> { 108 | let mut addr_storage = c::SOCKADDR_STORAGE_LH::default(); 109 | let mut len = mem::size_of::() as c_int; 110 | 111 | let socket = unsafe { 112 | match c::accept(self.0, &mut addr_storage as *mut _ as *mut _, &mut len) { 113 | c::INVALID_SOCKET => Err(last_error()), 114 | n => Ok(Socket(n)), 115 | } 116 | }?; 117 | socket.set_no_inherit()?; 118 | 119 | let addr = unsafe { &*(&addr_storage as *const _ as *const c::SOCKADDR_BTH) }; 120 | Ok(( 121 | socket, 122 | BtAddr::nap_sap(c::GET_NAP(addr.btAddr), c::GET_SAP(addr.btAddr)), 123 | )) 124 | } 125 | 126 | pub fn connect_timeout(&self, addr: &BtAddr, timeout: Duration) -> io::Result<()> { 127 | self.set_nonblocking(true)?; 128 | let r = { 129 | let addr = { 130 | fn init_bt_addr(storage: *mut c::SOCKADDR_STORAGE_LH, addr: &BtAddr) { 131 | let storage = storage as *mut c::SOCKADDR_BTH; 132 | unsafe { 133 | *storage = c::SOCKADDR_BTH { 134 | addressFamily: c::AF_BTH, 135 | btAddr: addr.into(), 136 | // serviceClassId: protocol_guid(self.protocol), 137 | ..Default::default() 138 | }; 139 | } 140 | } 141 | let mut storage = MaybeUninit::::uninit(); 142 | init_bt_addr(storage.as_mut_ptr(), addr); 143 | unsafe { storage.assume_init() } 144 | }; 145 | 146 | cvt(unsafe { 147 | c::connect( 148 | self.0, 149 | &addr as *const _ as *const c::SOCKADDR, 150 | mem::size_of::() as i32, 151 | ) 152 | }) 153 | }; 154 | self.set_nonblocking(false)?; 155 | 156 | match r { 157 | Ok(_) => return Ok(()), 158 | Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} 159 | Err(e) => return Err(e), 160 | } 161 | 162 | if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { 163 | return Err(io::Error::new( 164 | io::ErrorKind::InvalidInput, 165 | "cannot set a 0 duration timeout", 166 | )); 167 | } 168 | 169 | let timeout = { 170 | let tv_sec = timeout.as_secs() as c_long; 171 | let mut tv_usec = (timeout.subsec_micros()) as c_long; 172 | if tv_sec == 0 && tv_usec == 0 { 173 | tv_usec = 1; 174 | } 175 | c::timeval { tv_sec, tv_usec } 176 | }; 177 | 178 | let fds = { 179 | let mut fds = c::fd_set::default(); 180 | fds.fd_count = 1; 181 | fds.fd_array[0] = self.0; 182 | fds 183 | }; 184 | 185 | let mut writefds = fds; 186 | let mut errorfds = fds; 187 | 188 | let n = 189 | cvt(unsafe { c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout) })?; 190 | 191 | match n { 192 | 0 => Err(io::Error::new( 193 | io::ErrorKind::TimedOut, 194 | "connection timed out", 195 | )), 196 | _ => { 197 | if writefds.fd_count != 1 { 198 | if let Some(e) = self.take_error()? { 199 | return Err(e); 200 | } 201 | } 202 | Ok(()) 203 | } 204 | } 205 | } 206 | 207 | pub fn duplicate(&self) -> io::Result { 208 | let socket = { 209 | let mut info = c::WSAPROTOCOL_INFOW::default(); 210 | cvt(unsafe { c::WSADuplicateSocketW(self.0, c::GetCurrentProcessId(), &mut info) })?; 211 | match unsafe { 212 | c::WSASocketW( 213 | info.iAddressFamily, 214 | info.iSocketType, 215 | info.iProtocol, 216 | &mut info, 217 | 0, 218 | c::WSA_FLAG_OVERLAPPED, 219 | ) 220 | } { 221 | c::INVALID_SOCKET => Err(last_error()), 222 | n => Ok(Socket(n)), 223 | } 224 | }?; 225 | socket.set_no_inherit()?; 226 | Ok(socket) 227 | } 228 | 229 | pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 230 | self.recv_from_with_flags(buf, c::MSG_PEEK) 231 | } 232 | 233 | pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 234 | self.recv_from_with_flags(buf, 0) 235 | } 236 | 237 | fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, BtAddr)> { 238 | let mut addr_storage = c::SOCKADDR_STORAGE_LH::default(); 239 | let mut addrlen = mem::size_of::() as c_int; 240 | let len = cmp::min(buf.len(), ::max_value() as usize) as c_int; 241 | 242 | match unsafe { 243 | c::recvfrom( 244 | self.0, 245 | buf.as_mut_ptr() as *mut c_char, 246 | len, 247 | flags, 248 | &mut addr_storage as *mut _ as *mut _, 249 | &mut addrlen, 250 | ) 251 | } { 252 | -1 if unsafe { c::WSAGetLastError() } == c::WSAESHUTDOWN => { 253 | let addr = unsafe { &*(&addr_storage as *const _ as *const c::SOCKADDR_BTH) }; 254 | Ok(( 255 | 0, 256 | BtAddr::nap_sap(c::GET_NAP(addr.btAddr), c::GET_SAP(addr.btAddr)), 257 | )) 258 | } 259 | -1 => Err(last_error()), 260 | n => { 261 | let addr = unsafe { &*(&addr_storage as *const _ as *const c::SOCKADDR_BTH) }; 262 | Ok(( 263 | n as usize, 264 | BtAddr::nap_sap(c::GET_NAP(addr.btAddr), c::GET_SAP(addr.btAddr)), 265 | )) 266 | } 267 | } 268 | } 269 | 270 | pub fn peek(&self, buf: &mut [u8]) -> io::Result { 271 | self.recv_with_flags(buf, c::MSG_PEEK) 272 | } 273 | 274 | pub fn read(&self, buf: &mut [u8]) -> io::Result { 275 | self.recv_with_flags(buf, 0) 276 | } 277 | 278 | fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result { 279 | // On unix when a socket is shut down all further reads return 0, so we 280 | // do the same on windows to map a shut down to return EOF. 281 | let len = cmp::min(buf.len(), ::max_value() as usize) as c_int; 282 | match unsafe { c::recv(self.0, buf.as_mut_ptr() as *mut c_char, len, flags) } { 283 | -1 if unsafe { c::WSAGetLastError() } == c::WSAESHUTDOWN => Ok(0), 284 | -1 => Err(last_error()), 285 | n => Ok(n as usize), 286 | } 287 | } 288 | 289 | pub fn set_timeout(&self, dur: Option, kind: c_int) -> io::Result<()> { 290 | let timeout = match dur { 291 | Some(dur) => { 292 | let timeout = sys::dur2timeout(dur); 293 | if timeout == 0 { 294 | return Err(io::Error::new( 295 | io::ErrorKind::InvalidData, 296 | "cannot set a 0 duration timeout", 297 | )); 298 | } 299 | timeout 300 | } 301 | None => 0, 302 | }; 303 | bt::setsockopt(self, c::SOL_SOCKET, kind, timeout) 304 | } 305 | 306 | pub fn timeout(&self, kind: c_int) -> io::Result> { 307 | let raw: c_ulong = bt::getsockopt(self, c::SOL_SOCKET, kind)?; 308 | if raw == 0 { 309 | Ok(None) 310 | } else { 311 | let secs = raw / 1_000; 312 | let nsec = (raw % 1_000) * 1_000_000; 313 | Ok(Some(Duration::new(secs as u64, nsec as u32))) 314 | } 315 | } 316 | 317 | fn set_no_inherit(&self) -> io::Result<()> { 318 | sys::cvt(unsafe { 319 | c::SetHandleInformation(self.0 as c::HANDLE, c::HANDLE_FLAG_INHERIT, 0) 320 | })?; 321 | Ok(()) 322 | } 323 | 324 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 325 | let mut nonblocking = nonblocking as c_ulong; 326 | cvt(unsafe { c::ioctlsocket(self.0, c::FIONBIO as c_int, &mut nonblocking) })?; 327 | Ok(()) 328 | } 329 | 330 | pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { 331 | let how = match how { 332 | Shutdown::Write => c::SD_SEND, 333 | Shutdown::Read => c::SD_RECEIVE, 334 | Shutdown::Both => c::SD_BOTH, 335 | }; 336 | cvt(unsafe { c::shutdown(self.0, how) })?; 337 | Ok(()) 338 | } 339 | 340 | pub fn take_error(&self) -> io::Result> { 341 | let raw: c_int = bt::getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)?; 342 | if raw == 0 { 343 | Ok(None) 344 | } else { 345 | Ok(Some(io::Error::from_raw_os_error(raw as i32))) 346 | } 347 | } 348 | } 349 | 350 | impl Drop for Socket { 351 | fn drop(&mut self) { 352 | unsafe { c::closesocket(self.0) }; 353 | } 354 | } 355 | 356 | impl AsInner for Socket { 357 | fn as_inner(&self) -> &c::SOCKET { 358 | &self.0 359 | } 360 | } 361 | 362 | impl FromInner for Socket { 363 | fn from_inner(socket: c::SOCKET) -> Socket { 364 | Socket(socket) 365 | } 366 | } 367 | 368 | impl IntoInner for Socket { 369 | fn into_inner(self) -> c::SOCKET { 370 | let ret = self.0; 371 | mem::forget(self); 372 | ret 373 | } 374 | } 375 | 376 | pub fn discover_devices() -> io::Result> { 377 | init(); 378 | 379 | let handle: c::HANDLE = { 380 | let mut query: c::WSAQUERYSETW = Default::default(); 381 | query.dwSize = mem::size_of::() as u32; 382 | query.dwNameSpace = c::NS_BTH; 383 | 384 | let mut handle: c::HANDLE = std::ptr::null_mut(); 385 | if 0 != unsafe { 386 | c::WSALookupServiceBeginW( 387 | &mut query, 388 | c::LUP_CONTAINERS | c::LUP_FLUSHCACHE, 389 | &mut handle, 390 | ) 391 | } { 392 | Err(last_error()) 393 | } else { 394 | Ok(handle) 395 | } 396 | }?; 397 | 398 | // Use `usize` to guarantee matching alignment with `WSAQUERYSETW` 399 | let mut buffer: Vec = 400 | vec![0; mem::size_of::() / mem::size_of::()]; 401 | 402 | let mut addresses = Vec::new(); 403 | loop { 404 | let (query, mut len) = { 405 | let slice = &mut buffer[..]; 406 | ( 407 | slice.as_mut_ptr() as *mut c::WSAQUERYSETW, 408 | (slice.len() * mem::size_of::()) as u32, 409 | ) 410 | }; 411 | 412 | unsafe { 413 | if 0 == c::WSALookupServiceNextW( 414 | handle, 415 | c::LUP_CONTAINERS | c::LUP_RETURN_ADDR, 416 | &mut len, 417 | query, 418 | ) { 419 | let query: c::WSAQUERYSETW = *query; 420 | let addr_info: c::CSADDR_INFO = *query.lpcsaBuffer; 421 | let addr = *(addr_info.RemoteAddr.lpSockaddr as *mut c::SOCKADDR_BTH); 422 | addresses.push(BtAddr::nap_sap( 423 | c::GET_NAP(addr.btAddr), 424 | c::GET_SAP(addr.btAddr), 425 | )); 426 | } else { 427 | let err = last_error(); 428 | match err.raw_os_error().unwrap() as u32 { 429 | c::WSA_E_NO_MORE => break, 430 | c::WSAEFAULT => buffer.resize_with( 431 | 1 + (len as usize) / mem::size_of::(), 432 | Default::default, 433 | ), 434 | _ => return Err(err), 435 | } 436 | } 437 | }; 438 | } 439 | 440 | if 0 != unsafe { c::WSALookupServiceEnd(handle) } { 441 | Err(last_error()) 442 | } else { 443 | Ok(addresses) 444 | } 445 | } 446 | 447 | fn protocol_guid(protocol: BtProtocol) -> c::GUID { 448 | match protocol { 449 | BtProtocol::L2CAP => c::L2CAP_PROTOCOL_UUID, 450 | BtProtocol::RFCOMM => c::RFCOMM_PROTOCOL_UUID, 451 | } 452 | } 453 | 454 | impl<'a> Into for &'a BtAddr { 455 | fn into(self) -> u64 { 456 | let sap = u32::from_le_bytes([self.0[0], self.0[1], self.0[2], self.0[3]]); 457 | let nap = u16::from_le_bytes([self.0[4], self.0[5]]); 458 | c::SET_NAP_SAP(nap, sap) 459 | } 460 | } 461 | 462 | impl<'a> Into for &'a btc::sockaddr_storage { 463 | fn into(self) -> BtAddr { 464 | let sab: &'a c::SOCKADDR_BTH = unsafe { &*(self as *const _ as *const _) }; 465 | BtAddr::nap_sap(c::GET_NAP(sab.btAddr), c::GET_SAP(sab.btAddr)) 466 | } 467 | } 468 | 469 | impl<'a> Into<(btc::sockaddr_storage, btc::socklen_t)> for &'a BtAddr { 470 | fn into(self) -> (btc::sockaddr_storage, btc::socklen_t) { 471 | let mut addr = btc::sockaddr_storage { 472 | ss_family: c::AF_BTH, 473 | ..Default::default() 474 | }; 475 | 476 | let sab: &mut c::SOCKADDR_BTH = unsafe { &mut *(&mut addr as *mut _ as *mut _) }; 477 | sab.btAddr = self.into(); 478 | sab.serviceClassId = c::RFCOMM_PROTOCOL_UUID; 479 | 480 | (addr, mem::size_of::() as c_int) 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /src/sys/windows/c.rs: -------------------------------------------------------------------------------- 1 | pub use winapi::shared::bthdef::{ 2 | GET_NAP, GET_SAP, L2CAP_PROTOCOL_UUID, RFCOMM_PROTOCOL_UUID, SET_NAP_SAP, 3 | }; 4 | pub use winapi::shared::guiddef::GUID; 5 | pub use winapi::shared::winerror::{WSAEFAULT, WSA_E_NO_MORE}; 6 | pub use winapi::shared::ws2def::{CSADDR_INFO, SOCKADDR, SOCKADDR_STORAGE_LH}; 7 | pub use winapi::um::handleapi::SetHandleInformation; 8 | pub use winapi::um::processthreadsapi::GetCurrentProcessId; 9 | pub use winapi::um::winbase::{HANDLE_FLAG_INHERIT, INFINITE}; 10 | pub use winapi::um::winnt::HANDLE; 11 | pub use winapi::um::winsock2::{ 12 | accept, bind, closesocket, connect, fd_set, getpeername, getsockname, getsockopt, ioctlsocket, 13 | listen, recv, recvfrom, select, send, sendto, setsockopt, shutdown, timeval, WSACleanup, 14 | WSADuplicateSocketW, WSAGetLastError, WSALookupServiceBeginW, WSALookupServiceEnd, 15 | WSALookupServiceNextW, WSASocketW, WSAStartup, FIONBIO, INVALID_SOCKET, LUP_CONTAINERS, 16 | LUP_FLUSHCACHE, LUP_RETURN_ADDR, MSG_PEEK, NS_BTH, SD_BOTH, SD_RECEIVE, SD_SEND, SOCKET, 17 | SOCKET_ERROR, SOCK_STREAM, SOL_SOCKET, SO_ERROR, SO_RCVTIMEO, SO_REUSEADDR, SO_SNDTIMEO, 18 | WSADATA, WSAESHUTDOWN, WSAPROTOCOL_INFOW, WSAQUERYSETW, WSA_FLAG_OVERLAPPED, 19 | }; 20 | pub use winapi::um::ws2bth::{AF_BTH, BTHPROTO_L2CAP, BTHPROTO_RFCOMM, BT_PORT_ANY, SOCKADDR_BTH}; 21 | -------------------------------------------------------------------------------- /src/sys/windows/mod.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::os::raw::c_ulong; 3 | use std::time::Duration; 4 | 5 | pub mod bt; 6 | pub mod c; 7 | 8 | pub trait IsZero { 9 | fn is_zero(&self) -> bool; 10 | } 11 | 12 | macro_rules! impl_is_zero { 13 | ($($t:ident)*) => ($(impl IsZero for $t { 14 | fn is_zero(&self) -> bool { 15 | *self == 0 16 | } 17 | })*) 18 | } 19 | 20 | impl_is_zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } 21 | 22 | pub fn cvt(i: I) -> io::Result { 23 | if i.is_zero() { 24 | Err(io::Error::last_os_error()) 25 | } else { 26 | Ok(i) 27 | } 28 | } 29 | 30 | pub fn dur2timeout(dur: Duration) -> c_ulong { 31 | // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the 32 | // timeouts in windows APIs are typically u32 milliseconds. To translate, we 33 | // have two pieces to take care of: 34 | // 35 | // * Nanosecond precision is rounded up 36 | // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE 37 | // (never time out). 38 | dur.as_secs() 39 | .checked_mul(1000) 40 | .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) 41 | .and_then(|ms| { 42 | ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 { 43 | 1 44 | } else { 45 | 0 46 | }) 47 | }) 48 | .map(|ms| { 49 | if ms > ::max_value() as u64 { 50 | c::INFINITE 51 | } else { 52 | ms as c_ulong 53 | } 54 | }) 55 | .unwrap_or(c::INFINITE) 56 | } 57 | -------------------------------------------------------------------------------- /src/sys_common/bt.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | use std::fmt; 3 | use std::io; 4 | use std::mem; 5 | use std::net::Shutdown; 6 | use std::os::raw::c_int; 7 | use std::time::Duration; 8 | 9 | use crate::sys::bt::btc as c; 10 | use crate::sys::bt::Socket; 11 | use crate::sys::bt::{cvt, cvt_r}; 12 | use crate::sys_common::AsInner; 13 | 14 | use crate::bt::{BtAddr, BtProtocol}; 15 | 16 | cfg_if! { 17 | if #[cfg(any( 18 | target_os = "linux", target_os = "android", 19 | target_os = "dragonfly", target_os = "freebsd", 20 | target_os = "openbsd", target_os = "netbsd", 21 | target_os = "haiku", target_os = "bitrig" 22 | ))] { 23 | use libc::MSG_NOSIGNAL; 24 | } else { 25 | const MSG_NOSIGNAL: c_int = 0x0; 26 | } 27 | } 28 | 29 | //////////////////////////////////////////////////////////////////////////////// 30 | // sockaddr and misc bindings 31 | //////////////////////////////////////////////////////////////////////////////// 32 | 33 | pub fn setsockopt(sock: &Socket, opt: c_int, val: c_int, payload: T) -> io::Result<()> { 34 | let payload = &payload as *const T as *const _; 35 | cvt(unsafe { 36 | c::setsockopt( 37 | *sock.as_inner(), 38 | opt, 39 | val, 40 | payload, 41 | mem::size_of::() as c::socklen_t, 42 | ) 43 | })?; 44 | Ok(()) 45 | } 46 | 47 | pub fn getsockopt(sock: &Socket, opt: c_int, val: c_int) -> io::Result { 48 | unsafe { 49 | let mut slot: T = mem::zeroed(); 50 | let mut len = mem::size_of::() as c::socklen_t; 51 | cvt(c::getsockopt( 52 | *sock.as_inner(), 53 | opt, 54 | val, 55 | &mut slot as *mut _ as *mut _, 56 | &mut len, 57 | ))?; 58 | assert_eq!(len as usize, mem::size_of::()); 59 | Ok(slot) 60 | } 61 | } 62 | 63 | fn sockname(f: F) -> io::Result 64 | where 65 | F: FnOnce(*mut c::sockaddr_storage, *mut c::socklen_t) -> c_int, 66 | { 67 | let mut addr: c::sockaddr_storage = unsafe { mem::zeroed() }; 68 | let mut len = mem::size_of_val(&addr) as c::socklen_t; 69 | cvt(f(&mut addr, &mut len))?; 70 | Ok((&addr).into()) 71 | } 72 | 73 | //////////////////////////////////////////////////////////////////////////////// 74 | // Bluetooth listeners 75 | //////////////////////////////////////////////////////////////////////////////// 76 | 77 | pub struct BtListener { 78 | inner: Socket, 79 | protocol: BtProtocol, 80 | } 81 | 82 | impl BtListener { 83 | pub fn bind(addr: &BtAddr, protocol: BtProtocol) -> io::Result { 84 | let socket = Socket::new(protocol)?; 85 | 86 | // On platforms with Berkeley-derived sockets, this allows 87 | // to quickly rebind a socket, without needing to wait for 88 | // the OS to clean up the previous one. 89 | if !cfg!(windows) { 90 | setsockopt(&socket, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?; 91 | } 92 | 93 | let (addr, len) = addr.into(); 94 | cvt(unsafe { c::bind(*socket.as_inner(), &addr as *const _ as *const _, len) })?; 95 | cvt(unsafe { c::listen(*socket.as_inner(), 128) })?; 96 | Ok(Self { 97 | inner: socket, 98 | protocol, 99 | }) 100 | } 101 | 102 | pub fn accept(&self) -> io::Result<(BtStream, BtAddr)> { 103 | self.inner.accept().map(|(socket, addr)| { 104 | ( 105 | BtStream { 106 | inner: socket, 107 | protocol: self.protocol, 108 | }, 109 | addr, 110 | ) 111 | }) 112 | } 113 | 114 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 115 | self.inner.set_nonblocking(nonblocking) 116 | } 117 | 118 | pub fn local_addr(&self) -> io::Result { 119 | sockname(|addr, len| unsafe { c::getsockname(*self.inner.as_inner(), addr as *mut _, len) }) 120 | } 121 | 122 | pub fn take_error(&self) -> io::Result> { 123 | self.inner.take_error() 124 | } 125 | 126 | pub fn protocol(&self) -> BtProtocol { 127 | self.protocol 128 | } 129 | 130 | pub fn socket(&self) -> &Socket { 131 | &self.inner 132 | } 133 | 134 | pub fn into_socket(self) -> Socket { 135 | self.inner 136 | } 137 | 138 | pub fn duplicate(&self) -> io::Result { 139 | self.inner.duplicate().map(|s| Self { 140 | inner: s, 141 | protocol: self.protocol, 142 | }) 143 | } 144 | } 145 | 146 | impl fmt::Debug for BtListener { 147 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 148 | let mut res = f.debug_struct("BtListener"); 149 | 150 | if let Ok(addr) = self.local_addr() { 151 | res.field("addr", &addr); 152 | } 153 | 154 | let name = if cfg!(windows) { "socket" } else { "fd" }; 155 | res.field(name, &self.inner.as_inner()).finish() 156 | } 157 | } 158 | 159 | //////////////////////////////////////////////////////////////////////////////// 160 | // Bluetooth streams 161 | //////////////////////////////////////////////////////////////////////////////// 162 | 163 | pub struct BtStream { 164 | inner: Socket, 165 | protocol: BtProtocol, 166 | } 167 | 168 | impl BtStream { 169 | pub fn connect(addr: &BtAddr, protocol: BtProtocol) -> io::Result { 170 | let (addr, len) = addr.into(); 171 | 172 | let socket = Socket::new(protocol)?; 173 | cvt_r(|| unsafe { c::connect(*socket.as_inner(), &addr as *const _ as *const _, len) })?; 174 | Ok(Self { 175 | inner: socket, 176 | protocol, 177 | }) 178 | } 179 | 180 | pub fn connect_timeout( 181 | addr: &BtAddr, 182 | protocol: BtProtocol, 183 | timeout: Duration, 184 | ) -> io::Result { 185 | let socket = Socket::new(protocol)?; 186 | socket.connect_timeout(addr, timeout)?; 187 | Ok(Self { 188 | inner: socket, 189 | protocol, 190 | }) 191 | } 192 | 193 | pub fn peek(&self, buf: &mut [u8]) -> io::Result { 194 | self.inner.peek(buf) 195 | } 196 | 197 | pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 198 | self.inner.peek_from(buf) 199 | } 200 | 201 | pub fn recv(&self, buf: &mut [u8]) -> io::Result { 202 | self.inner.read(buf) 203 | } 204 | 205 | pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, BtAddr)> { 206 | self.inner.recv_from(buf) 207 | } 208 | 209 | pub fn send(&self, buf: &[u8]) -> io::Result { 210 | cvt(unsafe { 211 | c::send( 212 | *self.inner.as_inner(), 213 | buf.as_ptr() as *const _, 214 | cmp::min(buf.len(), ::max_value() as usize) as c::wrlen_t, 215 | MSG_NOSIGNAL, 216 | ) 217 | }) 218 | .map(|ret| ret as usize) 219 | } 220 | 221 | pub fn send_to(&self, buf: &[u8], dst: &BtAddr) -> io::Result { 222 | let (addr, addrlen) = dst.into(); 223 | cvt(unsafe { 224 | c::sendto( 225 | *self.inner.as_inner(), 226 | buf.as_ptr() as *const _, 227 | cmp::min(buf.len(), ::max_value() as usize) as c::wrlen_t, 228 | MSG_NOSIGNAL, 229 | &addr as *const _ as *const _, 230 | addrlen, 231 | ) 232 | }) 233 | .map(|ret| ret as usize) 234 | } 235 | 236 | pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { 237 | self.inner.shutdown(how) 238 | } 239 | 240 | pub fn read_timeout(&self) -> io::Result> { 241 | self.inner.timeout(c::SO_RCVTIMEO) 242 | } 243 | 244 | pub fn set_read_timeout(&self, dur: Option) -> io::Result<()> { 245 | self.inner.set_timeout(dur, c::SO_RCVTIMEO) 246 | } 247 | 248 | pub fn write_timeout(&self) -> io::Result> { 249 | self.inner.timeout(c::SO_SNDTIMEO) 250 | } 251 | 252 | pub fn set_write_timeout(&self, dur: Option) -> io::Result<()> { 253 | self.inner.set_timeout(dur, c::SO_SNDTIMEO) 254 | } 255 | 256 | pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { 257 | self.inner.set_nonblocking(nonblocking) 258 | } 259 | 260 | pub fn local_addr(&self) -> io::Result { 261 | sockname(|addr, len| unsafe { c::getsockname(*self.inner.as_inner(), addr as *mut _, len) }) 262 | } 263 | 264 | pub fn peer_addr(&self) -> io::Result { 265 | sockname(|addr, len| unsafe { c::getpeername(*self.inner.as_inner(), addr as *mut _, len) }) 266 | } 267 | 268 | pub fn take_error(&self) -> io::Result> { 269 | self.inner.take_error() 270 | } 271 | 272 | pub fn protocol(&self) -> BtProtocol { 273 | self.protocol 274 | } 275 | 276 | pub fn socket(&self) -> &Socket { 277 | &self.inner 278 | } 279 | 280 | pub fn into_socket(self) -> Socket { 281 | self.inner 282 | } 283 | 284 | pub fn duplicate(&self) -> io::Result { 285 | self.inner.duplicate().map(|s| Self { 286 | inner: s, 287 | protocol: self.protocol, 288 | }) 289 | } 290 | } 291 | 292 | impl fmt::Debug for BtStream { 293 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 294 | let mut res = f.debug_struct("BtStream"); 295 | 296 | if let Ok(addr) = self.local_addr() { 297 | res.field("addr", &addr); 298 | } 299 | 300 | let name = if cfg!(windows) { "socket" } else { "fd" }; 301 | res.field(name, &self.inner.as_inner()).finish() 302 | } 303 | } 304 | -------------------------------------------------------------------------------- /src/sys_common/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod bt; 2 | 3 | /// A trait for viewing representations from std types 4 | #[doc(hidden)] 5 | pub trait AsInner { 6 | fn as_inner(&self) -> &Inner; 7 | } 8 | 9 | /// A trait for viewing representations from std types 10 | #[doc(hidden)] 11 | pub trait AsInnerMut { 12 | fn as_inner_mut(&mut self) -> &mut Inner; 13 | } 14 | 15 | /// A trait for extracting representations from std types 16 | #[doc(hidden)] 17 | pub trait IntoInner { 18 | fn into_inner(self) -> Inner; 19 | } 20 | 21 | /// A trait for creating std types from internal representations 22 | #[doc(hidden)] 23 | pub trait FromInner { 24 | fn from_inner(inner: Inner) -> Self; 25 | } 26 | --------------------------------------------------------------------------------