I want to pass a ssh2::Sftp
struct between functions. This structure depends on the ssh2::Session
, which in turn depends on the std::net::TcpStream
.
extern crate ssh2;
use std::path::Path;
use std::net::TcpStream;
fn new_sftp<'a>() -> ssh2::Sftp<'a> {
let tcp = TcpStream::connect("localhost").unwrap();
let mut session = ssh2::Session::new().unwrap();
session.handshake(&tcp).unwrap();
session.userauth_pubkey_file("user", None, Path::new("/home/user/.ssh/id_rsa"), None)
.unwrap();
session.sftp().unwrap()
}
fn main() {
let sftp = new_sftp();
}
error:
error: `session` does not live long enough
session.sftp().unwrap()
^~~~~~~
I tried to do in this way, but I don't understand which option lifetime pass for the ssh2::Sftp
:
extern crate ssh2;
use std::path::Path;
use std::net::TcpStream;
struct Sftp {
tcp: TcpStream,
session: ssh2::Session,
sftp: ssh2::Sftp,
}
fn main() {
let tcp = TcpStream::connect("localhost").unwrap();
let mut session = ssh2::Session::new().unwrap();
session.handshake(&tcp).unwrap();
session.userauth_pubkey_file("user", None, Path::new("/home/user/.ssh/id_rsa"), None)
.unwrap();
let sftp = session.sftp().unwrap();
let sftp = Sftp {
tcp: tcp,
session: session,
sftp: sftp,
};
}
Update
I have several functions which work with files. I want to create a new type, which would have a function "open", which returns a file descriptor, regardless of where the file (on the local computer or on the remote). Now I'm trying to figure out how do I keep ssh::Sftp
within this new type. I think it is not the best to create a new structure every time I call function "open", because the creation of something new always requires resources. Perhaps the compiler understands what I want and optimize this place, but I'm not sure.