├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── accept.rs ├── client.rs ├── lib.rs ├── main.rs ├── main_loop.rs └── telnet.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "autocfg" 7 | version = "1.1.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 10 | 11 | [[package]] 12 | name = "bitflags" 13 | version = "1.3.2" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 16 | 17 | [[package]] 18 | name = "bytes" 19 | version = "1.2.1" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" 22 | 23 | [[package]] 24 | name = "cfg-if" 25 | version = "1.0.0" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 28 | 29 | [[package]] 30 | name = "futures" 31 | version = "0.3.24" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "7f21eda599937fba36daeb58a22e8f5cee2d14c4a17b5b7739c7c8e5e3b8230c" 34 | dependencies = [ 35 | "futures-channel", 36 | "futures-core", 37 | "futures-executor", 38 | "futures-io", 39 | "futures-sink", 40 | "futures-task", 41 | "futures-util", 42 | ] 43 | 44 | [[package]] 45 | name = "futures-channel" 46 | version = "0.3.24" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "30bdd20c28fadd505d0fd6712cdfcb0d4b5648baf45faef7f852afb2399bb050" 49 | dependencies = [ 50 | "futures-core", 51 | "futures-sink", 52 | ] 53 | 54 | [[package]] 55 | name = "futures-core" 56 | version = "0.3.24" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "4e5aa3de05362c3fb88de6531e6296e85cde7739cccad4b9dfeeb7f6ebce56bf" 59 | 60 | [[package]] 61 | name = "futures-executor" 62 | version = "0.3.24" 63 | source = "registry+https://github.com/rust-lang/crates.io-index" 64 | checksum = "9ff63c23854bee61b6e9cd331d523909f238fc7636290b96826e9cfa5faa00ab" 65 | dependencies = [ 66 | "futures-core", 67 | "futures-task", 68 | "futures-util", 69 | ] 70 | 71 | [[package]] 72 | name = "futures-io" 73 | version = "0.3.24" 74 | source = "registry+https://github.com/rust-lang/crates.io-index" 75 | checksum = "bbf4d2a7a308fd4578637c0b17c7e1c7ba127b8f6ba00b29f717e9655d85eb68" 76 | 77 | [[package]] 78 | name = "futures-macro" 79 | version = "0.3.24" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "42cd15d1c7456c04dbdf7e88bcd69760d74f3a798d6444e16974b505b0e62f17" 82 | dependencies = [ 83 | "proc-macro2", 84 | "quote", 85 | "syn", 86 | ] 87 | 88 | [[package]] 89 | name = "futures-sink" 90 | version = "0.3.24" 91 | source = "registry+https://github.com/rust-lang/crates.io-index" 92 | checksum = "21b20ba5a92e727ba30e72834706623d94ac93a725410b6a6b6fbc1b07f7ba56" 93 | 94 | [[package]] 95 | name = "futures-task" 96 | version = "0.3.24" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "a6508c467c73851293f390476d4491cf4d227dbabcd4170f3bb6044959b294f1" 99 | 100 | [[package]] 101 | name = "futures-util" 102 | version = "0.3.24" 103 | source = "registry+https://github.com/rust-lang/crates.io-index" 104 | checksum = "44fb6cb1be61cc1d2e43b262516aafcf63b241cffdb1d3fa115f91d9c7b09c90" 105 | dependencies = [ 106 | "futures-channel", 107 | "futures-core", 108 | "futures-io", 109 | "futures-macro", 110 | "futures-sink", 111 | "futures-task", 112 | "memchr", 113 | "pin-project-lite", 114 | "pin-utils", 115 | "slab", 116 | ] 117 | 118 | [[package]] 119 | name = "hermit-abi" 120 | version = "0.1.19" 121 | source = "registry+https://github.com/rust-lang/crates.io-index" 122 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 123 | dependencies = [ 124 | "libc", 125 | ] 126 | 127 | [[package]] 128 | name = "libc" 129 | version = "0.2.135" 130 | source = "registry+https://github.com/rust-lang/crates.io-index" 131 | checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c" 132 | 133 | [[package]] 134 | name = "lock_api" 135 | version = "0.4.9" 136 | source = "registry+https://github.com/rust-lang/crates.io-index" 137 | checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" 138 | dependencies = [ 139 | "autocfg", 140 | "scopeguard", 141 | ] 142 | 143 | [[package]] 144 | name = "log" 145 | version = "0.4.17" 146 | source = "registry+https://github.com/rust-lang/crates.io-index" 147 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 148 | dependencies = [ 149 | "cfg-if", 150 | ] 151 | 152 | [[package]] 153 | name = "memchr" 154 | version = "2.5.0" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 157 | 158 | [[package]] 159 | name = "mio" 160 | version = "0.8.4" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | checksum = "57ee1c23c7c63b0c9250c339ffdc69255f110b298b901b9f6c82547b7b87caaf" 163 | dependencies = [ 164 | "libc", 165 | "log", 166 | "wasi", 167 | "windows-sys", 168 | ] 169 | 170 | [[package]] 171 | name = "num_cpus" 172 | version = "1.13.1" 173 | source = "registry+https://github.com/rust-lang/crates.io-index" 174 | checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" 175 | dependencies = [ 176 | "hermit-abi", 177 | "libc", 178 | ] 179 | 180 | [[package]] 181 | name = "once_cell" 182 | version = "1.15.0" 183 | source = "registry+https://github.com/rust-lang/crates.io-index" 184 | checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1" 185 | 186 | [[package]] 187 | name = "parking_lot" 188 | version = "0.12.1" 189 | source = "registry+https://github.com/rust-lang/crates.io-index" 190 | checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" 191 | dependencies = [ 192 | "lock_api", 193 | "parking_lot_core", 194 | ] 195 | 196 | [[package]] 197 | name = "parking_lot_core" 198 | version = "0.9.3" 199 | source = "registry+https://github.com/rust-lang/crates.io-index" 200 | checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929" 201 | dependencies = [ 202 | "cfg-if", 203 | "libc", 204 | "redox_syscall", 205 | "smallvec", 206 | "windows-sys", 207 | ] 208 | 209 | [[package]] 210 | name = "pin-project-lite" 211 | version = "0.2.9" 212 | source = "registry+https://github.com/rust-lang/crates.io-index" 213 | checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" 214 | 215 | [[package]] 216 | name = "pin-utils" 217 | version = "0.1.0" 218 | source = "registry+https://github.com/rust-lang/crates.io-index" 219 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 220 | 221 | [[package]] 222 | name = "proc-macro2" 223 | version = "1.0.47" 224 | source = "registry+https://github.com/rust-lang/crates.io-index" 225 | checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" 226 | dependencies = [ 227 | "unicode-ident", 228 | ] 229 | 230 | [[package]] 231 | name = "quote" 232 | version = "1.0.21" 233 | source = "registry+https://github.com/rust-lang/crates.io-index" 234 | checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" 235 | dependencies = [ 236 | "proc-macro2", 237 | ] 238 | 239 | [[package]] 240 | name = "redox_syscall" 241 | version = "0.2.16" 242 | source = "registry+https://github.com/rust-lang/crates.io-index" 243 | checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" 244 | dependencies = [ 245 | "bitflags", 246 | ] 247 | 248 | [[package]] 249 | name = "scopeguard" 250 | version = "1.1.0" 251 | source = "registry+https://github.com/rust-lang/crates.io-index" 252 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 253 | 254 | [[package]] 255 | name = "signal-hook-registry" 256 | version = "1.4.0" 257 | source = "registry+https://github.com/rust-lang/crates.io-index" 258 | checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" 259 | dependencies = [ 260 | "libc", 261 | ] 262 | 263 | [[package]] 264 | name = "slab" 265 | version = "0.4.7" 266 | source = "registry+https://github.com/rust-lang/crates.io-index" 267 | checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" 268 | dependencies = [ 269 | "autocfg", 270 | ] 271 | 272 | [[package]] 273 | name = "smallvec" 274 | version = "1.10.0" 275 | source = "registry+https://github.com/rust-lang/crates.io-index" 276 | checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" 277 | 278 | [[package]] 279 | name = "socket2" 280 | version = "0.4.7" 281 | source = "registry+https://github.com/rust-lang/crates.io-index" 282 | checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd" 283 | dependencies = [ 284 | "libc", 285 | "winapi", 286 | ] 287 | 288 | [[package]] 289 | name = "syn" 290 | version = "1.0.102" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "3fcd952facd492f9be3ef0d0b7032a6e442ee9b361d4acc2b1d0c4aaa5f613a1" 293 | dependencies = [ 294 | "proc-macro2", 295 | "quote", 296 | "unicode-ident", 297 | ] 298 | 299 | [[package]] 300 | name = "telnet-chat" 301 | version = "0.1.0" 302 | dependencies = [ 303 | "bytes", 304 | "futures", 305 | "tokio", 306 | "tokio-util", 307 | ] 308 | 309 | [[package]] 310 | name = "tokio" 311 | version = "1.21.2" 312 | source = "registry+https://github.com/rust-lang/crates.io-index" 313 | checksum = "a9e03c497dc955702ba729190dc4aac6f2a0ce97f913e5b1b5912fc5039d9099" 314 | dependencies = [ 315 | "autocfg", 316 | "bytes", 317 | "libc", 318 | "memchr", 319 | "mio", 320 | "num_cpus", 321 | "parking_lot", 322 | "pin-project-lite", 323 | "signal-hook-registry", 324 | "socket2", 325 | "tokio-macros", 326 | "winapi", 327 | ] 328 | 329 | [[package]] 330 | name = "tokio-macros" 331 | version = "1.8.0" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "9724f9a975fb987ef7a3cd9be0350edcbe130698af5b8f7a631e23d42d052484" 334 | dependencies = [ 335 | "proc-macro2", 336 | "quote", 337 | "syn", 338 | ] 339 | 340 | [[package]] 341 | name = "tokio-util" 342 | version = "0.7.4" 343 | source = "registry+https://github.com/rust-lang/crates.io-index" 344 | checksum = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740" 345 | dependencies = [ 346 | "bytes", 347 | "futures-core", 348 | "futures-sink", 349 | "pin-project-lite", 350 | "tokio", 351 | "tracing", 352 | ] 353 | 354 | [[package]] 355 | name = "tracing" 356 | version = "0.1.37" 357 | source = "registry+https://github.com/rust-lang/crates.io-index" 358 | checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" 359 | dependencies = [ 360 | "cfg-if", 361 | "pin-project-lite", 362 | "tracing-core", 363 | ] 364 | 365 | [[package]] 366 | name = "tracing-core" 367 | version = "0.1.30" 368 | source = "registry+https://github.com/rust-lang/crates.io-index" 369 | checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" 370 | dependencies = [ 371 | "once_cell", 372 | ] 373 | 374 | [[package]] 375 | name = "unicode-ident" 376 | version = "1.0.5" 377 | source = "registry+https://github.com/rust-lang/crates.io-index" 378 | checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" 379 | 380 | [[package]] 381 | name = "wasi" 382 | version = "0.11.0+wasi-snapshot-preview1" 383 | source = "registry+https://github.com/rust-lang/crates.io-index" 384 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 385 | 386 | [[package]] 387 | name = "winapi" 388 | version = "0.3.9" 389 | source = "registry+https://github.com/rust-lang/crates.io-index" 390 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 391 | dependencies = [ 392 | "winapi-i686-pc-windows-gnu", 393 | "winapi-x86_64-pc-windows-gnu", 394 | ] 395 | 396 | [[package]] 397 | name = "winapi-i686-pc-windows-gnu" 398 | version = "0.4.0" 399 | source = "registry+https://github.com/rust-lang/crates.io-index" 400 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 401 | 402 | [[package]] 403 | name = "winapi-x86_64-pc-windows-gnu" 404 | version = "0.4.0" 405 | source = "registry+https://github.com/rust-lang/crates.io-index" 406 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 407 | 408 | [[package]] 409 | name = "windows-sys" 410 | version = "0.36.1" 411 | source = "registry+https://github.com/rust-lang/crates.io-index" 412 | checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" 413 | dependencies = [ 414 | "windows_aarch64_msvc", 415 | "windows_i686_gnu", 416 | "windows_i686_msvc", 417 | "windows_x86_64_gnu", 418 | "windows_x86_64_msvc", 419 | ] 420 | 421 | [[package]] 422 | name = "windows_aarch64_msvc" 423 | version = "0.36.1" 424 | source = "registry+https://github.com/rust-lang/crates.io-index" 425 | checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" 426 | 427 | [[package]] 428 | name = "windows_i686_gnu" 429 | version = "0.36.1" 430 | source = "registry+https://github.com/rust-lang/crates.io-index" 431 | checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" 432 | 433 | [[package]] 434 | name = "windows_i686_msvc" 435 | version = "0.36.1" 436 | source = "registry+https://github.com/rust-lang/crates.io-index" 437 | checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" 438 | 439 | [[package]] 440 | name = "windows_x86_64_gnu" 441 | version = "0.36.1" 442 | source = "registry+https://github.com/rust-lang/crates.io-index" 443 | checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" 444 | 445 | [[package]] 446 | name = "windows_x86_64_msvc" 447 | version = "0.36.1" 448 | source = "registry+https://github.com/rust-lang/crates.io-index" 449 | checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" 450 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "telnet-chat" 3 | version = "0.1.0" 4 | authors = ["Alice Ryhl "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | tokio = { version = "1.1.0", features = ["full"] } 9 | tokio-util = { version = "0.7.4", features = ["codec"] } 10 | futures = "0.3.12" 11 | bytes = "1.0.1" 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2021 Alice Ryhl 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Telnet chat 2 | 3 | This project is an example of how to write a chat server with Tokio using the 4 | technique known as an actor. 5 | 6 | The project is meant to illustrate the techniques outlined in: 7 | -------------------------------------------------------------------------------- /src/accept.rs: -------------------------------------------------------------------------------- 1 | use std::net::SocketAddr; 2 | use std::io; 3 | 4 | use crate::main_loop::{ServerHandle, ToServer}; 5 | use crate::client::{spawn_client, ClientInfo}; 6 | 7 | use tokio::net::TcpListener; 8 | 9 | pub async fn start_accept(bind: SocketAddr, mut handle: ServerHandle) { 10 | let res = accept_loop(bind, handle.clone()).await; 11 | match res { 12 | Ok(()) => {}, 13 | Err(err) => { 14 | handle.send(ToServer::FatalError(err)).await; 15 | }, 16 | } 17 | } 18 | 19 | pub async fn accept_loop( 20 | bind: SocketAddr, 21 | handle: ServerHandle 22 | ) -> Result<(), io::Error> { 23 | 24 | let listen = TcpListener::bind(bind).await?; 25 | 26 | loop { 27 | let (tcp, ip) = listen.accept().await?; 28 | 29 | let id = handle.next_id(); 30 | 31 | let data = ClientInfo { 32 | ip, 33 | id, 34 | tcp, 35 | handle: handle.clone(), 36 | }; 37 | 38 | spawn_client(data); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::net::SocketAddr; 3 | 4 | use futures::stream::StreamExt; 5 | use tokio::io::AsyncWriteExt; 6 | use tokio::net::{TcpStream, tcp::{ReadHalf, WriteHalf}}; 7 | use tokio::sync::mpsc::{unbounded_channel, UnboundedSender, UnboundedReceiver}; 8 | use tokio::sync::mpsc::{channel, Sender, Receiver}; 9 | use tokio::sync::oneshot; 10 | use tokio::{try_join, select}; 11 | use tokio::task::JoinHandle; 12 | use tokio_util::codec::FramedRead; 13 | 14 | use crate::ClientId; 15 | use crate::main_loop::{ServerHandle, ToServer}; 16 | use crate::telnet::{TelnetCodec, Item}; 17 | 18 | /// Messages received from the main loop. 19 | pub enum FromServer { 20 | Message(Vec), 21 | } 22 | 23 | /// A handle to this actor, used by the server. 24 | #[derive(Debug)] 25 | pub struct ClientHandle { 26 | pub id: ClientId, 27 | ip: SocketAddr, 28 | chan: Sender, 29 | kill: JoinHandle<()>, 30 | } 31 | 32 | impl ClientHandle { 33 | /// Send a message to this client actor. Will emit an error if sending does 34 | /// not succeed immediately, as this means that forwarding messages to the 35 | /// tcp connection cannot keep up. 36 | pub fn send(&mut self, msg: FromServer) -> Result<(), io::Error> { 37 | if self.chan.try_send(msg).is_err() { 38 | Err(io::Error::new(io::ErrorKind::BrokenPipe, "Can't keep up or dead")) 39 | } else { 40 | Ok(()) 41 | } 42 | } 43 | 44 | /// Kill the actor. 45 | pub fn kill(self) { 46 | // run the destructor 47 | drop(self); 48 | } 49 | } 50 | 51 | impl Drop for ClientHandle { 52 | fn drop(&mut self) { 53 | self.kill.abort() 54 | } 55 | } 56 | 57 | /// This struct is constructed by the accept loop and used as the argument to 58 | /// `spawn_client`. 59 | pub struct ClientInfo { 60 | pub ip: SocketAddr, 61 | pub id: ClientId, 62 | pub handle: ServerHandle, 63 | pub tcp: TcpStream, 64 | } 65 | 66 | /// This struct stores the information used internally by this client actor. 67 | struct ClientData { 68 | id: ClientId, 69 | handle: ServerHandle, 70 | recv: Receiver, 71 | tcp: TcpStream, 72 | } 73 | 74 | /// Spawn a new client actor. 75 | pub fn spawn_client(info: ClientInfo) { 76 | let (send, recv) = channel(64); 77 | 78 | let data = ClientData { 79 | id: info.id, 80 | handle: info.handle.clone(), 81 | tcp: info.tcp, 82 | recv, 83 | }; 84 | 85 | // This spawns the new task. 86 | let (my_send, my_recv) = oneshot::channel(); 87 | let kill = tokio::spawn(start_client(my_recv, data)); 88 | 89 | // Then we create a ClientHandle to this new task, and use the oneshot 90 | // channel to send it to the task. 91 | let handle = ClientHandle { 92 | id: info.id, 93 | ip: info.ip, 94 | chan: send, 95 | kill, 96 | }; 97 | 98 | // Ignore send errors here. Should only happen if the server is shutting 99 | // down. 100 | let _ = my_send.send(handle); 101 | } 102 | 103 | async fn start_client(my_handle: oneshot::Receiver, mut data: ClientData) { 104 | // Wait for `spawn_client` to send us the `ClientHandle` so we can forward 105 | // it to the main loop. We need the oneshot channel because we cannot 106 | // otherwise get the `JoinHandle` returned by `tokio::spawn`. We forward it 107 | // from here instead of in `spawn_client` because we want the server to see 108 | // the NewClient message before this actor starts sending other messages. 109 | let my_handle = match my_handle.await { 110 | Ok(my_handle) => my_handle, 111 | Err(_) => return, 112 | }; 113 | data.handle.send(ToServer::NewClient(my_handle)).await; 114 | 115 | // We sent the client handle to the main loop. Start talking to the tcp 116 | // connection. 117 | let res = client_loop(data).await; 118 | match res { 119 | Ok(()) => {}, 120 | Err(err) => { 121 | eprintln!("Something went wrong: {}.", err); 122 | }, 123 | } 124 | } 125 | 126 | /// This method performs the actual job of running the client actor. 127 | async fn client_loop(mut data: ClientData) -> Result<(), io::Error> { 128 | let (read, write) = data.tcp.split(); 129 | 130 | // communication between tcp_read and tcp_write 131 | let (send, recv) = unbounded_channel(); 132 | 133 | let ((), ()) = try_join! { 134 | tcp_read(data.id, read, data.handle, send), 135 | tcp_write(write, data.recv, recv), 136 | }?; 137 | 138 | let _ = data.tcp.shutdown().await; 139 | 140 | Ok(()) 141 | } 142 | 143 | #[derive(Debug)] 144 | enum InternalMsg { 145 | GotAreYouThere, 146 | SendDont(u8), 147 | SendWont(u8), 148 | SendDo(u8), 149 | } 150 | 151 | async fn tcp_read( 152 | id: ClientId, 153 | read: ReadHalf<'_>, 154 | mut handle: ServerHandle, 155 | to_tcp_write: UnboundedSender, 156 | ) -> Result<(), io::Error> { 157 | let mut telnet = FramedRead::new(read, TelnetCodec::new()); 158 | 159 | while let Some(item) = telnet.next().await { 160 | match item? { 161 | Item::Line(line) => { 162 | handle.send(ToServer::Message(id, line)).await; 163 | }, 164 | Item::AreYouThere => { 165 | to_tcp_write.send(InternalMsg::GotAreYouThere) 166 | .expect("Should not be closed."); 167 | }, 168 | Item::GoAhead => { /* ignore */ }, 169 | Item::InterruptProcess => return Ok(()), 170 | Item::Will(3) => { // suppress go-ahead 171 | to_tcp_write.send(InternalMsg::SendDo(3)) 172 | .expect("Should not be closed."); 173 | }, 174 | Item::Will(i) => { 175 | to_tcp_write.send(InternalMsg::SendDont(i)) 176 | .expect("Should not be closed."); 177 | }, 178 | Item::Do(i) => { 179 | to_tcp_write.send(InternalMsg::SendWont(i)) 180 | .expect("Should not be closed."); 181 | }, 182 | item => { 183 | return Err(io::Error::new( 184 | io::ErrorKind::Other, 185 | format!("Unable to handle {:?}", item), 186 | )); 187 | }, 188 | } 189 | } 190 | 191 | // disconnected 192 | 193 | Ok(()) 194 | } 195 | 196 | async fn tcp_write( 197 | mut write: WriteHalf<'_>, 198 | mut recv: Receiver, 199 | mut from_tcp_read: UnboundedReceiver, 200 | ) -> Result<(), io::Error> { 201 | loop { 202 | select! { 203 | msg = recv.recv() => match msg { 204 | Some(FromServer::Message(msg)) => { 205 | write.write_all(&msg).await?; 206 | write.write_all(&[13, 10]).await?; 207 | }, 208 | None => { 209 | break; 210 | }, 211 | }, 212 | msg = from_tcp_read.recv() => match msg { 213 | Some(InternalMsg::GotAreYouThere) => { 214 | write.write_all(b"Yes.\r\n").await?; 215 | }, 216 | Some(InternalMsg::SendDont(i)) => { 217 | write.write_all(&[0xff, 254, i]).await?; 218 | }, 219 | Some(InternalMsg::SendWont(i)) => { 220 | write.write_all(&[0xff, 252, i]).await?; 221 | }, 222 | Some(InternalMsg::SendDo(i)) => { 223 | write.write_all(&[0xff, 253, i]).await?; 224 | }, 225 | None => { 226 | break; 227 | }, 228 | }, 229 | }; 230 | } 231 | 232 | Ok(()) 233 | } 234 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod accept; 2 | pub mod client; 3 | pub mod telnet; 4 | pub mod main_loop; 5 | 6 | #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] 7 | pub struct ClientId(usize); 8 | 9 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #[tokio::main] 2 | async fn main() { 3 | let (handle, join) = telnet_chat::main_loop::spawn_main_loop(); 4 | 5 | tokio::spawn(async move { 6 | let bind = ([0, 0, 0, 0], 3456).into(); 7 | telnet_chat::accept::start_accept(bind, handle).await; 8 | }); 9 | 10 | println!("Starting on port 3456"); 11 | 12 | join.await.unwrap(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main_loop.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::collections::HashMap; 3 | use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; 4 | use tokio::sync::mpsc::Sender; 5 | 6 | use tokio::sync::mpsc::{channel, Receiver}; 7 | use tokio::task::JoinHandle; 8 | 9 | use crate::ClientId; 10 | use crate::client::{ClientHandle, FromServer}; 11 | 12 | /// This struct is used by client actors to send messages to the main loop. The 13 | /// message type is `ToServer`. 14 | #[derive(Clone, Debug)] 15 | pub struct ServerHandle { 16 | chan: Sender, 17 | next_id: Arc, 18 | } 19 | impl ServerHandle { 20 | pub async fn send(&mut self, msg: ToServer) { 21 | if self.chan.send(msg).await.is_err() { 22 | panic!("Main loop has shut down."); 23 | } 24 | } 25 | pub fn next_id(&self) -> ClientId { 26 | let id = self.next_id.fetch_add(1, Ordering::Relaxed); 27 | ClientId(id) 28 | } 29 | } 30 | 31 | /// The message type used when a client actor sends messages to the main loop. 32 | pub enum ToServer { 33 | NewClient(ClientHandle), 34 | Message(ClientId, Vec), 35 | FatalError(io::Error), 36 | } 37 | 38 | pub fn spawn_main_loop() -> (ServerHandle, JoinHandle<()>) { 39 | let (send, recv) = channel(64); 40 | 41 | let handle = ServerHandle { 42 | chan: send, 43 | next_id: Default::default(), 44 | }; 45 | 46 | let join = tokio::spawn(async move { 47 | let res = main_loop(recv).await; 48 | match res { 49 | Ok(()) => {}, 50 | Err(err) => { 51 | eprintln!("Oops {}.", err); 52 | }, 53 | } 54 | }); 55 | 56 | (handle, join) 57 | } 58 | 59 | #[derive(Default, Debug)] 60 | struct Data { 61 | clients: HashMap, 62 | } 63 | 64 | async fn main_loop( 65 | mut recv: Receiver, 66 | ) -> Result<(), io::Error> { 67 | let mut data = Data::default(); 68 | 69 | while let Some(msg) = recv.recv().await { 70 | match msg { 71 | ToServer::NewClient(handle) => { 72 | data.clients.insert(handle.id, handle); 73 | }, 74 | ToServer::Message(from_id, msg) => { 75 | // If we fail to send messages to any actor, we need to remove 76 | // it, but we can't do so while iterating. 77 | let mut to_remove = Vec::new(); 78 | 79 | // Iterate through clients so we can send the message. 80 | for (id, handle) in data.clients.iter_mut() { 81 | let id = *id; 82 | 83 | // Don't send it to the client who sent it to us. 84 | if id == from_id { continue; } 85 | 86 | let msg = FromServer::Message(msg.clone()); 87 | 88 | if handle.send(msg).is_err() { 89 | // Remove this client. 90 | to_remove.push(id); 91 | } 92 | } 93 | 94 | // Remove those clients. 95 | for id in to_remove { 96 | // The destructor of ClientHandle will kill the actor when 97 | // we remove it from the HashMap. 98 | data.clients.remove(&id); 99 | } 100 | }, 101 | // This message comes only from the accept loop. 102 | ToServer::FatalError(err) => return Err(err), 103 | } 104 | } 105 | 106 | Ok(()) 107 | } 108 | -------------------------------------------------------------------------------- /src/telnet.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use tokio_util::codec::Decoder; 3 | 4 | use bytes::{Buf, BytesMut}; 5 | 6 | pub struct TelnetCodec { 7 | current_line: Vec, 8 | } 9 | 10 | impl TelnetCodec { 11 | pub fn new() -> Self { 12 | TelnetCodec { 13 | current_line: Vec::with_capacity(1024), 14 | } 15 | } 16 | } 17 | 18 | #[derive(Debug)] 19 | pub enum Item { 20 | Line(Vec), 21 | SE, 22 | DataMark, 23 | Break, 24 | InterruptProcess, 25 | AbortOutput, 26 | AreYouThere, 27 | GoAhead, 28 | SB, 29 | Will(u8), 30 | Wont(u8), 31 | Do(u8), 32 | Dont(u8), 33 | } 34 | 35 | impl Decoder for TelnetCodec { 36 | type Item = Item; 37 | type Error = io::Error; 38 | 39 | fn decode( 40 | &mut self, 41 | src: &mut BytesMut 42 | ) -> Result, Self::Error> { 43 | loop { 44 | if src.is_empty() { 45 | return Ok(None); 46 | } 47 | 48 | if src[0] == 0xff { 49 | let (res, consume) = try_parse_iac(src.chunk()); 50 | src.advance(consume); 51 | 52 | match res { 53 | ParseIacResult::Invalid(err) => { 54 | return Err(io::Error::new( 55 | io::ErrorKind::InvalidData, 56 | err, 57 | )); 58 | }, 59 | ParseIacResult::NeedMore => return Ok(None), 60 | ParseIacResult::Item(item) => return Ok(Some(item)), 61 | ParseIacResult::NOP => { /* go around loop */ }, 62 | ParseIacResult::EraseCharacter => { 63 | self.current_line.pop(); 64 | }, 65 | ParseIacResult::EraseLine => { 66 | self.current_line.clear(); 67 | }, 68 | ParseIacResult::Escaped => { 69 | self.current_line.push(0xff); 70 | }, 71 | } 72 | } else { 73 | let byte = src.get_u8(); 74 | 75 | match byte { 76 | 10 => { 77 | let line = self.current_line.to_vec(); 78 | self.current_line.clear(); 79 | 80 | return Ok(Some(Item::Line(line))); 81 | }, 82 | 0 ..= 31 => { 83 | // ignore 84 | }, 85 | _ => self.current_line.push(byte), 86 | } 87 | } 88 | } 89 | } 90 | } 91 | 92 | enum ParseIacResult { 93 | Invalid(String), 94 | NeedMore, 95 | Item(Item), 96 | NOP, 97 | EraseCharacter, 98 | EraseLine, 99 | Escaped, 100 | } 101 | 102 | /// Returns the parsed result of the first few bytes, as well as how many bytes 103 | /// to consume. 104 | fn try_parse_iac(bytes: &[u8]) -> (ParseIacResult, usize) { 105 | if bytes.len() < 2 { 106 | return (ParseIacResult::NeedMore, 0); 107 | } 108 | if bytes[0] != 0xff { 109 | unreachable!(); 110 | } 111 | if is_three_byte_iac(bytes[1]) && bytes.len() < 3 { 112 | return (ParseIacResult::NeedMore, 0); 113 | } 114 | 115 | match bytes[1] { 116 | 240 => (ParseIacResult::Item(Item::SE), 2), 117 | 241 => (ParseIacResult::NOP, 2), 118 | 242 => (ParseIacResult::Item(Item::DataMark), 2), 119 | 243 => (ParseIacResult::Item(Item::Break), 2), 120 | 244 => (ParseIacResult::Item(Item::InterruptProcess), 2), 121 | 245 => (ParseIacResult::Item(Item::AbortOutput), 2), 122 | 246 => (ParseIacResult::Item(Item::AreYouThere), 2), 123 | 247 => (ParseIacResult::EraseCharacter, 2), 124 | 248 => (ParseIacResult::EraseLine, 2), 125 | 249 => (ParseIacResult::Item(Item::GoAhead), 2), 126 | 250 => (ParseIacResult::Item(Item::SB), 2), 127 | 251 => (ParseIacResult::Item(Item::Will(bytes[2])), 3), 128 | 252 => (ParseIacResult::Item(Item::Wont(bytes[2])), 3), 129 | 253 => (ParseIacResult::Item(Item::Do(bytes[2])), 3), 130 | 254 => (ParseIacResult::Item(Item::Dont(bytes[2])), 3), 131 | 255 => (ParseIacResult::Escaped, 2), 132 | cmd => (ParseIacResult::Invalid(format!("Unknown IAC command {}.", cmd)), 0), 133 | } 134 | } 135 | 136 | fn is_three_byte_iac(byte: u8) -> bool { 137 | match byte { 138 | 251 ..= 254 => true, 139 | _ => false, 140 | } 141 | } 142 | --------------------------------------------------------------------------------