Comments (10)
You need to tokio::spawn
both copy tasks instead of joining them, otherwise channel_open_session
never completes.
Ideally you also want to hold on to the Channel
first and wait until you see a Handler::shell_request
for it as the client might not be ready to receive output until then.
from russh.
For tokio::spawn, the channel lifetime is too short. Any way to prevent this?
from russh.
Is that right?
from russh.
You need to move your cin
into the closure
tokio::spawn(async move {
let cin = cin;
tokio::io::copy...
}});
from russh.
Hmm, did I do something wrong, same error: channel
does not live long enough
from russh.
Sorry, I can't help with generic Rust issues. You can post your entire code instead of a screenshot and maybe I or somebody else could check it out later.
from russh.
here is my code:
use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
use russh::server::{Msg, Server as _, Session};
use russh::*;
use russh_keys::*;
use tokio::sync::Mutex;
use std::fs::File;
use std::io::Read;
use tokio::net::TcpListener;
use tokio::process::Command;
use std::process::Stdio;
#[tokio::main]
async fn main() {
env_logger::builder()
.filter_level(log::LevelFilter::Debug)
.init();
// let skey = russh_keys::key::KeyPair::generate_ed25519().unwrap();
// let mut buffer = File::create("id_ed25519").unwrap();
// encode_pkcs8_pem(&skey, buffer).unwrap();
let mut buffer = File::open("id_ed25519").unwrap();
let mut file_content = String::new();
buffer.read_to_string(&mut file_content).unwrap();
let skey = decode_secret_key(file_content.as_mut_str(), None).unwrap();
let config = russh::server::Config {
inactivity_timeout: Some(std::time::Duration::from_secs(3600)),
auth_rejection_time: std::time::Duration::from_secs(3),
auth_rejection_time_initial: Some(std::time::Duration::from_secs(0)),
keys: vec![skey],
..Default::default()
};
let config = Arc::new(config);
let mut sh = Server {
clients: Arc::new(Mutex::new(HashMap::new())),
id: 0,
};
// sh.run_on_address(config, ("127.0.0.1", 2222)).await.unwrap();
let socket = TcpListener::bind(("127.0.0.1", 2222)).await.unwrap();
sh.run_on_socket(config, &socket).await.unwrap()
}
#[derive(Clone)]
struct Server {
clients: Arc<Mutex<HashMap<(usize, ChannelId), russh::server::Handle>>>,
id: usize,
}
impl Server {
async fn post(&mut self, data: CryptoVec) {
let mut clients = self.clients.lock().await;
for ((id, channel), ref mut s) in clients.iter_mut() {
if *id != self.id {
let _ = s.data(*channel, data.clone()).await;
}
}
}
}
impl server::Server for Server {
type Handler = Self;
fn new_client(&mut self, _: Option<std::net::SocketAddr>) -> Self {
let s = self.clone();
self.id += 1;
s
}
}
#[async_trait]
impl server::Handler for Server {
type Error = anyhow::Error;
async fn channel_open_session(
&mut self,
mut channel: Channel<Msg>,
session: &mut Session,
) -> Result<bool, Self::Error> {
self.shell_request(channel.id(), session).await.unwrap();
let cin = channel.make_writer();
let cout = channel.make_reader();
let cmd = Command::new("/bin/sh").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap();
tokio::spawn(async {
let mut cin = cin;
let mut stdout = cmd.stdout.unwrap();
tokio::io::copy(&mut stdout, &mut cin).await.unwrap();
});
tokio::spawn(async {
let mut cout = cout;
let mut stdin = cmd.stdin.unwrap();
tokio::io::copy(&mut cout, &mut stdin).await.unwrap();
});
Ok(true)
}
async fn auth_publickey(
&mut self,
_: &str,
_: &key::PublicKey,
) -> Result<server::Auth, Self::Error> {
Ok(server::Auth::Accept)
}
async fn data(
&mut self,
channel: ChannelId,
data: &[u8],
session: &mut Session,
) -> Result<(), Self::Error> {
let data = CryptoVec::from(format!("Got data: {}\r\n", String::from_utf8_lossy(data)));
self.post(data.clone()).await;
session.data(channel, data);
Ok(())
}
async fn tcpip_forward(
&mut self,
address: &str,
port: &mut u32,
session: &mut Session,
) -> Result<bool, Self::Error> {
let handle = session.handle();
let address = address.to_string();
let port = *port;
tokio::spawn(async move {
let channel = handle
.channel_open_forwarded_tcpip(address, port, "1.2.3.4", 1234)
.await
.unwrap();
let _ = channel.data(&b"Hello from a forwarded port"[..]).await;
let _ = channel.eof().await;
});
Ok(true)
}
}
from russh.
Sorry, I can't help with generic Rust issues. You can post your entire code instead of a screenshot and maybe I or somebody else could check it out later.
is there somewhere and example where it is working, is there documentation on how some would do that?
from russh.
It is indeed tricky to get the lifetimes to work right in your case - in particular because the return value of make_reader
implicitly references Channel
.
This works though because the lifetime of the Reader is scoped to the lifetime of the Channel here:
async fn channel_open_session(
&mut self,
channel: Channel<Msg>,
session: &mut Session,
) -> Result<bool, Self::Error> {
self.shell_request(channel.id(), session).await.unwrap();
let cmd = Command::new("/bin/sh")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = cmd.stdin.unwrap();
let mut stdout = cmd.stdout.unwrap();
let mut channel = channel;
let mut cin = channel.make_writer();
tokio::spawn(async move {
tokio::io::copy(&mut stdout, &mut cin).await.unwrap();
});
tokio::spawn(async move {
let mut cout = channel.make_reader();
tokio::io::copy(&mut cout, &mut stdin).await.unwrap();
});
Ok(true)
}
from russh.
GREAT! It works, thanks a lot.
from russh.
Related Issues (20)
- 100% cpu usage when send data with channel.data HOT 6
- `decode_pkcs5` does not remove padding HOT 2
- `write_key_v1` writes `ed25519` key incorrectly HOT 1
- Missing ciphers HOT 2
- Blocking API
- russh-config: Opinion: deprecate parse_home() and add crate documentation that it parses an OpenSSH-like format HOT 1
- Incorrect sha2 hash function for ecdh-sha2-nistp{384,521}
- The new `Handler` definition makes it harder to build state machines HOT 2
- Support for SCP protocol
- FEATURE REQUEST: add a Geller Field when ssh
- TryFrom<PrivateKey> for KeyPair: RSA assumes SHA512 HOT 3
- `russh::server::Server::handle_session_error` seems to reference the new client instance rather than the one with the failed session HOT 5
- ERROR - Unsupported key type ssh-rsa HOT 2
- Host key checking is lazy
- Error with CryptoVec
- streamlocal-forward support HOT 3
- Why is String being used for Paths? HOT 1
- Unclear interaction between inactivity timer and server keepalive
- Shutdown ssh server HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from russh.