Giter Club home page Giter Club logo

Comments (10)

Eugeny avatar Eugeny commented on July 23, 2024

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.

DerDennisOP avatar DerDennisOP commented on July 23, 2024

For tokio::spawn, the channel lifetime is too short. Any way to prevent this?

from russh.

DerDennisOP avatar DerDennisOP commented on July 23, 2024

image

Is that right?

from russh.

Eugeny avatar Eugeny commented on July 23, 2024

You need to move your cin into the closure

tokio::spawn(async move {
   	let cin = cin;
	tokio::io::copy...
}});

from russh.

DerDennisOP avatar DerDennisOP commented on July 23, 2024

image

Hmm, did I do something wrong, same error: channel does not live long enough

from russh.

Eugeny avatar Eugeny commented on July 23, 2024

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.

DerDennisOP avatar DerDennisOP commented on July 23, 2024

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.

DerDennisOP avatar DerDennisOP commented on July 23, 2024

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.

Eugeny avatar Eugeny commented on July 23, 2024

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.

DerDennisOP avatar DerDennisOP commented on July 23, 2024

GREAT! It works, thanks a lot.

from russh.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.