|
| 1 | +use crate::{api, service}; |
| 2 | +use std::{io, process, thread}; |
| 3 | + |
| 4 | +const SERVICE: api::Service = api::Service::Command; |
| 5 | +const SERVICE_KIND: api::ServiceKind = api::ServiceKind::Backend; |
| 6 | + |
| 7 | +pub struct Server {} |
| 8 | + |
| 9 | +impl service::Backend for Server { |
| 10 | + fn accept(rdp_stream: service::RdpStream<'_>) -> Result<(), io::Error> { |
| 11 | + let client_id = rdp_stream.client_id(); |
| 12 | + |
| 13 | + #[cfg(target_os = "windows")] |
| 14 | + let cmd = "cmd.exe"; |
| 15 | + #[cfg(not(target_os = "windows"))] |
| 16 | + let cmd = "sh"; |
| 17 | + |
| 18 | + crate::debug!("starting {cmd:?}"); |
| 19 | + |
| 20 | + thread::scope(|scope| { |
| 21 | + let child = process::Command::new(cmd) |
| 22 | + .stdin(process::Stdio::piped()) |
| 23 | + .stdout(process::Stdio::piped()) |
| 24 | + .stderr(process::Stdio::piped()) |
| 25 | + .spawn()?; |
| 26 | + |
| 27 | + let mut stdin = child |
| 28 | + .stdin |
| 29 | + .ok_or(io::Error::new(io::ErrorKind::InvalidInput, "no stdin"))?; |
| 30 | + let mut stdout = child |
| 31 | + .stdout |
| 32 | + .ok_or(io::Error::new(io::ErrorKind::InvalidInput, "no stdout"))?; |
| 33 | + let mut stderr = child |
| 34 | + .stderr |
| 35 | + .ok_or(io::Error::new(io::ErrorKind::InvalidInput, "no stderr"))?; |
| 36 | + |
| 37 | + let (mut rdp_stream_read, mut rdp_stream_write_out) = rdp_stream.split(); |
| 38 | + let mut rdp_stream_write_err = rdp_stream_write_out.clone(); |
| 39 | + |
| 40 | + thread::Builder::new() |
| 41 | + .name(format!("{SERVICE_KIND} {SERVICE} {client_id:x} stdout")) |
| 42 | + .spawn_scoped(scope, move || { |
| 43 | + if let Err(e) = service::stream_copy(&mut stdout, &mut rdp_stream_write_out) { |
| 44 | + crate::debug!("error: {e}"); |
| 45 | + } else { |
| 46 | + crate::debug!("stopped"); |
| 47 | + } |
| 48 | + }) |
| 49 | + .unwrap(); |
| 50 | + |
| 51 | + thread::Builder::new() |
| 52 | + .name(format!("{SERVICE_KIND} {SERVICE} {client_id:x} stderr")) |
| 53 | + .spawn_scoped(scope, move || { |
| 54 | + if let Err(e) = service::stream_copy(&mut stderr, &mut rdp_stream_write_err) { |
| 55 | + crate::debug!("error: {e}"); |
| 56 | + } else { |
| 57 | + crate::debug!("stopped"); |
| 58 | + } |
| 59 | + }) |
| 60 | + .unwrap(); |
| 61 | + |
| 62 | + if let Err(e) = service::stream_copy(&mut rdp_stream_read, &mut stdin) { |
| 63 | + crate::debug!("error: {e}"); |
| 64 | + } else { |
| 65 | + crate::debug!("stopped"); |
| 66 | + } |
| 67 | + rdp_stream_read.disconnect(); |
| 68 | + |
| 69 | + Ok(()) |
| 70 | + }) |
| 71 | + } |
| 72 | +} |
0 commit comments