Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use the Channel obtained by channel_direct_tcpip to read and write data separately? #325

Open
tzfun opened this issue Aug 7, 2024 · 0 comments

Comments

@tzfun
Copy link

tzfun commented Aug 7, 2024

Usually when proxying a TCP network, not all requests are responded to. It is possible that two or even multiple requests will result in a response. How can I use the read and write methods in the Channel obtained by channel_direct_tcpip to achieve this effect? ​​Currently, I can only achieve "one request must have one response". I don't know how to do it.

I hope that the read and write methods of this Channel can handle their own things separately, just like the sender and receiver obtained by onshot::channel().

This is my current code. The problem with the code is that read_channel often times out.

pub fn test_ssh_tunnel_with_ssh2() {
    let mut session = Session::new().unwrap();
    let tcp = TcpStream::connect(SSH_ADDR).unwrap();
    session.set_tcp_stream(tcp);
    session.handshake().unwrap();

    session.set_keepalive(false, 5);

    let private_key = Path::new(SSH_KEY);
    session.userauth_pubkey_file("tz", None, private_key, Some(SSH_KEY_PASSPHRASE)).unwrap();

    let session = Arc::new(session);

    let listener = net::TcpListener::bind("127.0.0.1:5000").unwrap();
    for stream in listener.incoming() {
        let mut stream = stream.unwrap();

        let ssh_session = Arc::clone(&session);
        thread::spawn(move || {
            let mut channel = ssh_session.channel_direct_tcpip("127.0.0.1", 2379, None).unwrap();
            loop {
                let (request, size) = read_stream(&mut stream);
                if size <= 0 {
                    break;
                }

                channel.write_all(&request[..size]).unwrap();
                channel.flush().unwrap();
               
                //  This always times out when there is no response to this request
                let (response, size) = read_channel(&mut channel);
                if size <= 0 {
                    break
                }
                stream.write_all(&response[..size]).unwrap();
                stream.flush().unwrap();
            }
            channel.close().unwrap();
        });
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant