├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── factorio.rs ├── minecraft.rs └── source-engine.rs └── src ├── lib.rs ├── packet.rs ├── rt_async_std.rs └── rt_tokio.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Build 18 | run: cargo build --verbose 19 | build_tokio: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Build 24 | run: cargo build --verbose --features rt-tokio 25 | build_async_std: 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - name: Build 30 | run: cargo build --verbose --all-targets --features rt-async-std 31 | build_tokio_async_std: 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v2 35 | - name: Build 36 | run: cargo build --verbose --all-targets --features rt-tokio,rt-async-std 37 | test: 38 | runs-on: ubuntu-latest 39 | steps: 40 | - uses: actions/checkout@v2 41 | - name: Run tests 42 | run: cargo test --all-features --verbose 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | sudo: false 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ### Added 11 | - example for Source engine games (tested against Counter Strike: Global Offensive). [@jenrik](https://github.com/jenrik) 12 | 13 | ## [0.5.0] - 2021-07-10 14 | 15 | ### Added 16 | - support for running on an `async-std` executer. It should now be possible to use `rcon` with both, `tokio` and `async-std`. [@jenrik](https://github.com/jenrik) 17 | 18 | ## [0.4.0] - 2020-12-26 19 | 20 | ### Breaking 21 | - upgraded to tokio 1.0 22 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rcon" 3 | version = "0.5.2" 4 | authors = ["panicbit "] 5 | description = "An rcon protocol implementation" 6 | license = "MIT OR Apache-2.0" 7 | keywords = ["source", "rcon", "protocol", "minecraft"] 8 | repository = "https://github.com/panicbit/rust-rcon" 9 | edition = "2018" 10 | resolver = "2" 11 | 12 | [dependencies] 13 | err-derive = "0.3.0" 14 | tokio = { version = "1.10.1", features = ["io-util"] } 15 | 16 | async-std = { version = "1.9.0", optional = true } 17 | 18 | [features] 19 | default = [] 20 | rt-async-std = ["async-std"] 21 | rt-tokio = ["tokio/net", "tokio/time"] 22 | 23 | [package.metadata.docs.rs] 24 | all-features = true 25 | rustdoc-args = ["--cfg", "doc_cfg"] 26 | 27 | [dev-dependencies] 28 | async-std = { version = "1.9.0", features = ["attributes"] } 29 | futures-timer = "3.0.2" 30 | -------------------------------------------------------------------------------- /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 | Copyright (c) 2015 rust-rcon developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | rust-rcon [![Build Status](https://travis-ci.org/panicbit/rust-rcon.svg?branch=master)](https://travis-ci.org/panicbit/rust-rcon) 2 | ========= 3 | 4 | An RCON implementation in the Rust programming language. 5 | 6 | This project aims to at least work with the Minecraft implementation of RCON. 7 | 8 | ## Status 9 | - basic rcon sessions work 10 | - multi-packet responses 11 | - works with minecraft 12 | - not working with factorio 13 | 14 | ## How to install 15 | 16 | Add this your Cargo.toml: 17 | ```toml 18 | [dependencies] 19 | rcon = "0" 20 | ``` 21 | 22 | 23 | ## How to use 24 | ```rust 25 | extern crate rcon; 26 | ``` 27 | 28 | 29 | ## Examples 30 | 31 | See the examples in [the examples folder](https://github.com/panicbit/rust-rcon/tree/master/examples) 32 | 33 | ## License 34 | 35 | Licensed under either of 36 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 37 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 38 | at your option. 39 | 40 | ### Contribution 41 | 42 | Unless you explicitly state otherwise, any contribution intentionally submitted 43 | for inclusion in the work by you shall be dual licensed as above, without any 44 | additional terms or conditions. 45 | 46 | -------------------------------------------------------------------------------- /examples/factorio.rs: -------------------------------------------------------------------------------- 1 | use rcon::{AsyncStdStream, Connection, Error}; 2 | 3 | #[async_std::main] 4 | async fn main() -> Result<(), Error> { 5 | let address = "localhost:1234"; 6 | let mut conn = >::builder() 7 | .enable_factorio_quirks(true) 8 | .connect(address, "test") 9 | .await?; 10 | 11 | demo(&mut conn, "/c print('hello')").await?; 12 | demo(&mut conn, "/c print('world')").await?; 13 | println!("commands finished"); 14 | 15 | Ok(()) 16 | } 17 | 18 | async fn demo(conn: &mut Connection, cmd: &str) -> Result<(), Error> { 19 | println!("request: {}", cmd); 20 | let resp = conn.cmd(cmd).await?; 21 | println!("response: {}", resp); 22 | Ok(()) 23 | } 24 | -------------------------------------------------------------------------------- /examples/minecraft.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 [rust-rcon developers] 2 | // Licensed under the Apache License, Version 2.0 3 | // or the MIT 5 | // license , 6 | // at your option. All files in the project carrying such 7 | // notice may not be copied, modified, or distributed except 8 | // according to those terms. 9 | 10 | use rcon::{AsyncStdStream, Connection, Error}; 11 | 12 | /* 13 | This example expects a Minecraft with rcon enabled on port 25575 14 | and the rcon password "test" 15 | */ 16 | 17 | #[async_std::main] 18 | async fn main() -> Result<(), Error> { 19 | let address = "localhost:25575"; 20 | let mut conn = >::builder() 21 | .enable_minecraft_quirks(true) 22 | .connect(address, "test") 23 | .await?; 24 | 25 | demo(&mut conn, "list").await?; 26 | demo(&mut conn, "say Rust lang rocks! ;P").await?; 27 | demo(&mut conn, "save-all").await?; 28 | //demo(&mut conn, "stop"); 29 | Ok(()) 30 | } 31 | 32 | async fn demo(conn: &mut Connection, cmd: &str) -> Result<(), Error> { 33 | let resp = conn.cmd(cmd).await?; 34 | println!("{}", resp); 35 | Ok(()) 36 | } 37 | -------------------------------------------------------------------------------- /examples/source-engine.rs: -------------------------------------------------------------------------------- 1 | use rcon::{AsyncStdStream, Connection, Error}; 2 | 3 | #[async_std::main] 4 | async fn main() -> Result<(), Error> { 5 | let address = "localhost:27015"; 6 | let mut conn = >::builder() 7 | .connect(address, "test") 8 | .await?; 9 | 10 | demo(&mut conn, "status").await?; 11 | demo(&mut conn, "users").await?; 12 | demo(&mut conn, "echo \"Rust lang rocks! ;P\"").await?; 13 | println!("commands finished"); 14 | 15 | Ok(()) 16 | } 17 | 18 | async fn demo(conn: &mut Connection, cmd: &str) -> Result<(), Error> { 19 | println!("request: {}", cmd); 20 | let resp = conn.cmd(cmd).await?; 21 | println!("response: {}", resp); 22 | Ok(()) 23 | } 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 [rust-rcon developers] 2 | // Licensed under the Apache License, Version 2.0 3 | // or the MIT 5 | // license , 6 | // at your option. All files in the project carrying such 7 | // notice may not be copied, modified, or distributed except 8 | // according to those terms. 9 | //! Asynchronous API for the RCON protocol used by games such as Minecraft and Factorio. 10 | //! 11 | //! # Feature flags 12 | //! 13 | //! - `rt-tokio`: Enable integration with the [Tokio](tokio) asynchronous runtime. 14 | //! - `rt-async-std`: Enable integration with the [async-std](async_std) asynchronous runtime. 15 | #![cfg_attr(doc_cfg, feature(doc_cfg))] 16 | 17 | use err_derive::Error; 18 | use packet::{Packet, PacketType}; 19 | use std::fmt::{self, Debug, Formatter}; 20 | use std::future::Future; 21 | use std::io; 22 | use std::marker::PhantomData; 23 | use std::pin::Pin; 24 | use std::sync::Arc; 25 | use std::time::Duration; 26 | use tokio::io::{AsyncRead, AsyncWrite}; 27 | 28 | #[cfg(feature = "rt-async-std")] 29 | mod rt_async_std; 30 | #[cfg(feature = "rt-async-std")] 31 | pub use rt_async_std::AsyncStdStream; 32 | 33 | #[cfg(feature = "rt-tokio")] 34 | mod rt_tokio; 35 | 36 | mod packet; 37 | 38 | const INITIAL_PACKET_ID: i32 = 1; 39 | const DELAY_TIME_MILLIS: u64 = 3; 40 | const MINECRAFT_MAX_PAYLOAD_SIZE: usize = 1413; 41 | 42 | #[derive(Debug, Error)] 43 | pub enum Error { 44 | #[error(display = "authentication failed")] 45 | Auth, 46 | #[error(display = "command exceeds the maximum length")] 47 | CommandTooLong, 48 | #[error(display = "{}", _0)] 49 | Io(#[error(source)] io::Error), 50 | } 51 | 52 | pub type Result = std::result::Result; 53 | 54 | pub struct Connection { 55 | io: T, 56 | next_packet_id: i32, 57 | minecraft_quirks_enabled: bool, 58 | factorio_quirks_enabled: bool, 59 | sleep_fn: SleepFn, 60 | } 61 | 62 | impl Connection { 63 | /// Create a connectiion builder. 64 | /// Allows configuring the rcon connection. 65 | pub fn builder() -> Builder { 66 | Builder::new() 67 | } 68 | 69 | /// Perform a handshake on an existing connection to an rcon server. 70 | /// 71 | /// This is a lower-level method mostly useful when integrating this crate with another 72 | /// runtime, or running rcon over a transport other than TCP. You generally will want to use 73 | /// one of the higher-level `connect` methods. 74 | /// 75 | /// By default this enables Minecraft quirks. 76 | /// If you need to customize this behaviour, use a [`Builder`]. 77 | /// 78 | /// This method requires one of the runtime features to be activated so that Minecraft quirks 79 | /// mode is able to asynchronously sleep. If you want to provide a custom sleep function, see 80 | /// [`Builder::sleep_fn`]. 81 | #[cfg(any(feature = "rt-tokio", feature = "rt-async-std"))] 82 | #[cfg_attr(doc_cfg, doc(cfg(any(feature = "rt-tokio", feature = "rt-async-std"))))] 83 | pub async fn handshake(io: T, password: &str) -> Result { 84 | Self::builder() 85 | .enable_minecraft_quirks(true) 86 | .handshake(io, password) 87 | .await 88 | } 89 | 90 | pub async fn cmd(&mut self, cmd: &str) -> Result { 91 | if self.minecraft_quirks_enabled && cmd.len() > MINECRAFT_MAX_PAYLOAD_SIZE { 92 | return Err(Error::CommandTooLong); 93 | } 94 | 95 | self.send(PacketType::ExecCommand, cmd).await?; 96 | 97 | if self.minecraft_quirks_enabled { 98 | self.sleep_fn 99 | .call(Duration::from_millis(DELAY_TIME_MILLIS)) 100 | .await; 101 | } 102 | 103 | let response = self.receive_response().await?; 104 | 105 | Ok(response) 106 | } 107 | 108 | async fn receive_response(&mut self) -> Result { 109 | if self.factorio_quirks_enabled { 110 | self.receive_single_packet_response().await 111 | } else { 112 | self.receive_multi_packet_response().await 113 | } 114 | } 115 | 116 | async fn receive_single_packet_response(&mut self) -> Result { 117 | let received_packet = self.receive_packet().await?; 118 | 119 | Ok(received_packet.get_body().into()) 120 | } 121 | 122 | async fn receive_multi_packet_response(&mut self) -> Result { 123 | // the server processes packets in order, so send an empty packet and 124 | // remember its id to detect the end of a multi-packet response 125 | let end_id = self.send(PacketType::ExecCommand, "").await?; 126 | 127 | let mut result = String::new(); 128 | 129 | loop { 130 | let received_packet = self.receive_packet().await?; 131 | 132 | if received_packet.get_id() == end_id { 133 | // This is the response to the end-marker packet 134 | return Ok(result); 135 | } 136 | 137 | result += received_packet.get_body(); 138 | } 139 | } 140 | 141 | async fn auth(&mut self, password: &str) -> Result<()> { 142 | self.send(PacketType::Auth, password).await?; 143 | let received_packet = loop { 144 | let received_packet = self.receive_packet().await?; 145 | if received_packet.get_type() == PacketType::AuthResponse { 146 | break received_packet; 147 | } 148 | }; 149 | 150 | if received_packet.is_error() { 151 | Err(Error::Auth) 152 | } else { 153 | Ok(()) 154 | } 155 | } 156 | 157 | async fn send(&mut self, ptype: PacketType, body: &str) -> io::Result { 158 | let id = self.generate_packet_id(); 159 | 160 | let packet = Packet::new(id, ptype, body.into()); 161 | 162 | packet.serialize(&mut self.io).await?; 163 | 164 | Ok(id) 165 | } 166 | 167 | async fn receive_packet(&mut self) -> io::Result { 168 | Packet::deserialize(&mut self.io).await 169 | } 170 | 171 | fn generate_packet_id(&mut self) -> i32 { 172 | let id = self.next_packet_id; 173 | 174 | // only use positive ids as the server uses negative ids to signal 175 | // a failed authentication request 176 | self.next_packet_id = self 177 | .next_packet_id 178 | .checked_add(1) 179 | .unwrap_or(INITIAL_PACKET_ID); 180 | 181 | id 182 | } 183 | } 184 | 185 | #[derive(Clone)] 186 | enum SleepFn { 187 | #[cfg(feature = "rt-tokio")] 188 | Tokio, 189 | #[cfg(feature = "rt-async-std")] 190 | AsyncStd, 191 | #[cfg(not(any(feature = "rt-tokio", feature = "rt-async-std")))] 192 | None, 193 | Custom(CustomSleepFn), 194 | } 195 | 196 | impl Debug for SleepFn { 197 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 198 | match self { 199 | #[cfg(feature = "rt-tokio")] 200 | Self::Tokio => f.write_str("tokio::time::sleep"), 201 | #[cfg(feature = "rt-async-std")] 202 | Self::AsyncStd => f.write_str("async_std::task::sleep"), 203 | #[cfg(not(any(feature = "rt-tokio", feature = "rt-async-std")))] 204 | Self::None => f.write_str("None"), 205 | Self::Custom(_) => f.write_str("custom sleep function"), 206 | } 207 | } 208 | } 209 | 210 | type CustomSleepFn = 211 | Arc Pin + Send>> + Send + Sync>; 212 | 213 | impl SleepFn { 214 | async fn call(&mut self, duration: Duration) { 215 | match self { 216 | #[cfg(feature = "rt-tokio")] 217 | Self::Tokio => tokio::time::sleep(duration).await, 218 | #[cfg(feature = "rt-async-std")] 219 | Self::AsyncStd => async_std::task::sleep(duration).await, 220 | #[cfg(not(any(feature = "rt-tokio", feature = "rt-async-std")))] 221 | Self::None => unreachable!(), 222 | Self::Custom(f) => f(duration).await, 223 | } 224 | } 225 | } 226 | 227 | #[derive(Debug)] 228 | pub struct Builder { 229 | minecraft_quirks_enabled: bool, 230 | factorio_quirks_enabled: bool, 231 | sleep_fn: SleepFn, 232 | _io: PhantomData T>, 233 | } 234 | 235 | impl Default for Builder { 236 | fn default() -> Self { 237 | #[cfg(feature = "rt-tokio")] 238 | let sleep_fn = SleepFn::Tokio; 239 | #[cfg(all(feature = "rt-async-std", not(feature = "rt-tokio")))] 240 | let sleep_fn = SleepFn::AsyncStd; 241 | #[cfg(not(any(feature = "rt-async-std", feature = "rt-tokio")))] 242 | let sleep_fn = SleepFn::None; 243 | 244 | Self { 245 | minecraft_quirks_enabled: false, 246 | factorio_quirks_enabled: false, 247 | sleep_fn, 248 | _io: PhantomData, 249 | } 250 | } 251 | } 252 | 253 | impl Clone for Builder { 254 | fn clone(&self) -> Self { 255 | Self { 256 | minecraft_quirks_enabled: self.minecraft_quirks_enabled, 257 | factorio_quirks_enabled: self.factorio_quirks_enabled, 258 | sleep_fn: self.sleep_fn.clone(), 259 | _io: PhantomData, 260 | } 261 | } 262 | } 263 | 264 | impl Builder { 265 | pub fn new() -> Self { 266 | Self::default() 267 | } 268 | 269 | /// This enables the following quirks for Minecraft: 270 | /// 271 | /// Commands are delayed by 3ms to reduce the chance of crashing the server. 272 | /// See . 273 | /// 274 | /// The command length is limited to 1413 bytes. 275 | /// Tests have shown the server to not work reliably 276 | /// with greater command lengths. 277 | pub fn enable_minecraft_quirks(mut self, value: bool) -> Self { 278 | self.minecraft_quirks_enabled = value; 279 | self 280 | } 281 | 282 | /// This enables the following quirks for Factorio: 283 | /// 284 | /// Only single-packet responses are enabled. 285 | /// Multi-packets appear to work differently than in other server implementations 286 | /// (an empty packet gives no response). 287 | pub fn enable_factorio_quirks(mut self, value: bool) -> Self { 288 | self.factorio_quirks_enabled = value; 289 | self 290 | } 291 | 292 | /// Set a custom function to use for sleeping between requests when [Minecraft quirks mode is 293 | /// enabled](Self::enable_minecraft_quirks). 294 | /// 295 | /// When either of the `rt-tokio` or `rt-async-std` feature flags is enabled, this library will 296 | /// default to using the runtime's native sleeping function. This can be used to override it, 297 | /// or set the sleeping function to use when no runtime feature is active. 298 | /// 299 | /// # Example 300 | /// 301 | /// Using [futures-timer](https://docs.rs/futures-timer) instead of Tokio's native timer: 302 | /// 303 | /// ``` 304 | /// # use tokio::net::TcpStream; 305 | /// # async { 306 | /// let connection = >::builder() 307 | /// .enable_minecraft_quirks(true) 308 | /// .sleep_fn(futures_timer::Delay::new) 309 | /// .connect("localhost:25575", "hunter2") 310 | /// .await?; 311 | /// # drop(connection); 312 | /// # rcon::Result::Ok(()) 313 | /// # }; 314 | /// ``` 315 | pub fn sleep_fn(mut self, f: F) -> Self 316 | where 317 | F: Fn(Duration) -> Fut + Send + Sync + 'static, 318 | Fut: Future + Send + 'static, 319 | { 320 | self.sleep_fn = SleepFn::Custom(Arc::new(move |duration| Box::pin(f(duration)))); 321 | self 322 | } 323 | 324 | /// Perform a handshake on an existing connection to an rcon server. 325 | /// 326 | /// This is a lower-level method mostly useful when integrating this crate with another 327 | /// runtime, or running rcon over a transport other than TCP. You generally will want to use 328 | /// one of the higher-level `connect` methods. 329 | /// 330 | /// # Panics 331 | /// 332 | /// If neither of the `rt-tokio` or `rt-async-std` feature flags are activated, no [custom sleep 333 | /// function](Self::sleep_fn) has been set and [Minecraft quirks](Self::enable_minecraft_quirks) 334 | /// have been enabled, this function will panic as Minecraft quirks need some way to 335 | /// asynchronously sleep. 336 | pub async fn handshake(self, io: T, password: &str) -> Result> 337 | where 338 | T: AsyncRead + AsyncWrite + Unpin, 339 | { 340 | #[cfg(not(any(feature = "rt-tokio", feature = "rt-async-std")))] 341 | if self.minecraft_quirks_enabled && matches!(self.sleep_fn, SleepFn::None) { 342 | panic!( 343 | "\ 344 | Minecraft quirks mode is enabled, but no runtime or custom sleep function has been \ 345 | set. Enable one of the `rt-tokio` or `rt-async-std` feature flags, or set a custom \ 346 | sleep function with `rcon::Builder::sleep_fn`.\ 347 | " 348 | ); 349 | } 350 | 351 | let mut conn = Connection { 352 | io, 353 | next_packet_id: INITIAL_PACKET_ID, 354 | minecraft_quirks_enabled: self.minecraft_quirks_enabled, 355 | factorio_quirks_enabled: self.factorio_quirks_enabled, 356 | sleep_fn: self.sleep_fn, 357 | }; 358 | 359 | conn.auth(password).await?; 360 | 361 | Ok(conn) 362 | } 363 | } 364 | -------------------------------------------------------------------------------- /src/packet.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 [rust-rcon developers] 2 | // Licensed under the Apache License, Version 2.0 3 | // or the MIT 5 | // license , 6 | // at your option. All files in the project carrying such 7 | // notice may not be copied, modified, or distributed except 8 | // according to those terms. 9 | 10 | use std::io; 11 | use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; 12 | 13 | #[derive(Debug, Clone, Copy, PartialEq)] 14 | pub enum PacketType { 15 | Auth, 16 | AuthResponse, 17 | ExecCommand, 18 | ResponseValue, 19 | Unknown(i32), 20 | } 21 | 22 | impl PacketType { 23 | fn to_i32(self) -> i32 { 24 | match self { 25 | PacketType::Auth => 3, 26 | PacketType::AuthResponse => 2, 27 | PacketType::ExecCommand => 2, 28 | PacketType::ResponseValue => 0, 29 | PacketType::Unknown(n) => n, 30 | } 31 | } 32 | 33 | pub fn from_i32(n: i32, is_response: bool) -> PacketType { 34 | match n { 35 | 3 => PacketType::Auth, 36 | 2 if is_response => PacketType::AuthResponse, 37 | 2 => PacketType::ExecCommand, 38 | 0 => PacketType::ResponseValue, 39 | n => PacketType::Unknown(n), 40 | } 41 | } 42 | } 43 | 44 | #[derive(Debug)] 45 | pub struct Packet { 46 | length: i32, 47 | id: i32, 48 | ptype: PacketType, 49 | body: String, 50 | } 51 | 52 | impl Packet { 53 | pub fn new(id: i32, ptype: PacketType, body: String) -> Packet { 54 | Packet { 55 | length: 10 + body.len() as i32, 56 | id, 57 | ptype, 58 | body, 59 | } 60 | } 61 | 62 | pub fn is_error(&self) -> bool { 63 | self.id < 0 64 | } 65 | 66 | pub async fn serialize(&self, w: &mut T) -> io::Result<()> { 67 | // Write bytes to a buffer first so only one tcp packet is sent 68 | // This is done in order to not overwhelm a Minecraft server 69 | let mut buf = Vec::with_capacity(self.length as usize); 70 | 71 | buf.extend_from_slice(&self.length.to_le_bytes()); 72 | buf.extend_from_slice(&self.id.to_le_bytes()); 73 | buf.extend_from_slice(&self.ptype.to_i32().to_le_bytes()); 74 | buf.extend_from_slice(self.body.as_bytes()); 75 | buf.extend_from_slice(&[0x00, 0x00]); 76 | 77 | w.write_all(&buf).await?; 78 | 79 | Ok(()) 80 | } 81 | 82 | pub async fn deserialize(r: &mut T) -> io::Result { 83 | let mut buf = [0u8; 4]; 84 | 85 | r.read_exact(&mut buf).await?; 86 | let length = i32::from_le_bytes(buf); 87 | r.read_exact(&mut buf).await?; 88 | let id = i32::from_le_bytes(buf); 89 | r.read_exact(&mut buf).await?; 90 | let ptype = i32::from_le_bytes(buf); 91 | let body_length = length - 10; 92 | let mut body_buffer = Vec::with_capacity(body_length as usize); 93 | 94 | r.take(body_length as u64) 95 | .read_to_end(&mut body_buffer) 96 | .await?; 97 | 98 | let body = String::from_utf8(body_buffer) 99 | .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; 100 | 101 | // terminating nulls 102 | let mut buf = [0u8; 2]; 103 | r.read_exact(&mut buf).await?; 104 | 105 | let packet = Packet { 106 | length, 107 | id, 108 | ptype: PacketType::from_i32(ptype, true), 109 | body, 110 | }; 111 | 112 | Ok(packet) 113 | } 114 | 115 | pub fn get_body(&self) -> &str { 116 | &self.body 117 | } 118 | 119 | pub fn get_type(&self) -> PacketType { 120 | self.ptype 121 | } 122 | 123 | pub fn get_id(&self) -> i32 { 124 | self.id 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/rt_async_std.rs: -------------------------------------------------------------------------------- 1 | use async_std::io::{Read, Write}; 2 | use async_std::net::{TcpStream, ToSocketAddrs}; 3 | use async_std::task::ready; 4 | use std::io::{self, IoSlice}; 5 | use std::pin::Pin; 6 | use std::task::{Context, Poll}; 7 | use tokio::io::{AsyncRead as TokioRead, AsyncWrite as TokioWrite, ReadBuf}; 8 | 9 | use crate::{Builder, Connection, Result}; 10 | 11 | impl Connection { 12 | /// Connect to an rcon server using the [async-std](async_std) runtime. 13 | /// 14 | /// By default this enables Minecraft quirks. 15 | /// If you need to customize this behaviour, use a [`Builder`]. 16 | #[cfg_attr(doc_cfg, doc(cfg(feature = "rt-async-std")))] 17 | pub async fn connect(address: A, password: &str) -> Result { 18 | Self::builder() 19 | .enable_minecraft_quirks(true) 20 | .connect(address, password) 21 | .await 22 | } 23 | } 24 | 25 | impl Builder { 26 | /// Connect to an rcon server using the [async-std](async_std) runtime. 27 | #[cfg_attr(doc_cfg, doc(cfg(feature = "rt-async-std")))] 28 | #[cfg_attr(not(feature = "tokio"), allow(unused_mut))] 29 | pub async fn connect( 30 | mut self, 31 | address: A, 32 | password: &str, 33 | ) -> Result> { 34 | // If the `rt-tokio` feature flag is also enabled the sleep_fn will use it by default, so 35 | // we have to change it to use async-std instead. 36 | #[cfg(feature = "rt-tokio")] 37 | if let crate::SleepFn::Tokio = self.sleep_fn { 38 | self.sleep_fn = crate::SleepFn::AsyncStd; 39 | } 40 | self.handshake(AsyncStdStream(TcpStream::connect(address).await?), password) 41 | .await 42 | } 43 | } 44 | 45 | /// The inner transport of an [async-std](async_std) rcon connection. 46 | /// 47 | /// This is a simple wrapper around a [`TcpStream`] that implements Tokio's I/O traits so it can be 48 | /// used inside [`Connection`]. 49 | #[derive(Debug)] 50 | #[cfg_attr(doc_cfg, doc(cfg(feature = "rt-async-std")))] 51 | pub struct AsyncStdStream(pub TcpStream); 52 | 53 | impl TokioRead for AsyncStdStream { 54 | fn poll_read( 55 | mut self: Pin<&mut Self>, 56 | cx: &mut Context<'_>, 57 | buf: &mut ReadBuf<'_>, 58 | ) -> Poll> { 59 | let bytes = ready!(Pin::new(&mut self.0).poll_read(cx, buf.initialize_unfilled()))?; 60 | buf.advance(bytes); 61 | Poll::Ready(Ok(())) 62 | } 63 | } 64 | 65 | impl TokioWrite for AsyncStdStream { 66 | fn poll_write( 67 | mut self: Pin<&mut Self>, 68 | cx: &mut Context<'_>, 69 | buf: &[u8], 70 | ) -> Poll> { 71 | Pin::new(&mut self.0).poll_write(cx, buf) 72 | } 73 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 74 | Pin::new(&mut self.0).poll_flush(cx) 75 | } 76 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 77 | Pin::new(&mut self.0).poll_close(cx) 78 | } 79 | fn poll_write_vectored( 80 | mut self: Pin<&mut Self>, 81 | cx: &mut Context<'_>, 82 | bufs: &[IoSlice<'_>], 83 | ) -> Poll> { 84 | Pin::new(&mut self.0).poll_write_vectored(cx, bufs) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/rt_tokio.rs: -------------------------------------------------------------------------------- 1 | use tokio::net::{TcpStream, ToSocketAddrs}; 2 | 3 | use crate::{Builder, Connection, Result}; 4 | 5 | impl Connection { 6 | /// Connect to an rcon server using the [Tokio](tokio) runtime. 7 | /// 8 | /// By default this enables Minecraft quirks. 9 | /// If you need to customize this behaviour, use a [`Builder`]. 10 | #[cfg_attr(doc_cfg, doc(cfg(feature = "rt-tokio")))] 11 | pub async fn connect(address: A, password: &str) -> Result { 12 | Self::builder() 13 | .enable_minecraft_quirks(true) 14 | .connect(address, password) 15 | .await 16 | } 17 | } 18 | 19 | impl Builder { 20 | /// Connect to an rcon server using the [Tokio](tokio) runtime. 21 | #[cfg_attr(doc_cfg, doc(cfg(feature = "rt-tokio")))] 22 | pub async fn connect( 23 | self, 24 | address: A, 25 | password: &str, 26 | ) -> Result> { 27 | self.handshake(TcpStream::connect(address).await?, password) 28 | .await 29 | } 30 | } 31 | --------------------------------------------------------------------------------