FCLauncher/launcher/src/ftp.rs
2024-06-22 16:54:12 -06:00

57 lines
1.8 KiB
Rust

use std::io::Write;
use std::path::PathBuf;
use suppaftp::FtpError;
use suppaftp::NativeTlsFtpStream;
use suppaftp::NativeTlsConnector;
use suppaftp::native_tls::Certificate;
use suppaftp::native_tls::TlsConnector;
fn ftp_connection_anonymous() -> Result<NativeTlsFtpStream, FtpError>{
ftp_connection("anonymous", "anonymous@")
}
fn ftp_connection(username: &str, password: &str) -> Result<NativeTlsFtpStream, FtpError>{
let ftp_stream = NativeTlsFtpStream::connect("gitea.piwalker.net:21").unwrap_or_else(|err|
panic!("{}", err)
);
let cert = include_bytes!("../res/vsftpd.crt");
let cert = Certificate::from_pem(cert).unwrap();
let mut ftp_stream = ftp_stream.into_secure(NativeTlsConnector::from(TlsConnector::builder().add_root_certificate(cert).build().unwrap()), "gitea.piwalker.net").unwrap();
ftp_stream.login("anonymous", "anonymous@").map(|_| Ok(ftp_stream)).unwrap()
}
pub fn ftp_retr(file: PathBuf , mut writer: impl Write, mut callback: impl FnMut(usize)) -> Result<bool, FtpError> {
let mut ftp_stream = ftp_connection_anonymous().unwrap();
let file = file.to_str().unwrap().replace("\\", "/");
let size = ftp_stream.size(&file)?;
let mut total = 0;
ftp_stream.retr(file.as_str(), |stream| {
let mut tx_bytes = [0u8; 1500];
loop {
let bytes_read = stream.read(&mut tx_bytes).unwrap();
writer.write_all(&mut tx_bytes.split_at(bytes_read).0).unwrap();
total += bytes_read;
if total == size || bytes_read == 0 {
break;
}else{
callback(bytes_read);
}
}
Ok(true)
})?;
Ok(true)
}
pub fn ftp_get_size(file: PathBuf) -> Result<usize, FtpError> {
let mut stream = ftp_connection_anonymous()?;
stream.size(file.to_str().unwrap().replace("\\", "/"))
}