Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 91 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["crates/core", "crates/disks", "crates/vfs", "crates/theme", "crates/ui", "crates/index", "crates/config", "crates/net", "crates/phone", "crates/connect"]
members = ["crates/core", "crates/disks", "crates/vfs", "crates/theme", "crates/ui", "crates/index", "crates/config", "crates/net", "crates/phone", "crates/phonefs", "crates/connect"]

[workspace.package]
version = "0.1.0"
Expand All @@ -17,6 +17,7 @@ ef-index = { path = "crates/index", package = "echofiles-index" }
ef-config = { path = "crates/config", package = "echofiles-config" }
ef-net = { path = "crates/net", package = "echofiles-net" }
ef-phone = { path = "crates/phone", package = "echofiles-phone" }
ef-phonefs = { path = "crates/phonefs", package = "echofiles-phonefs" }
rustix = { version = "1.1", features = ["fs"] }
rayon = "1.12"
zbus = { version = "5.19", default-features = false, features = ["blocking-api", "async-io"] }
Expand Down
14 changes: 12 additions & 2 deletions android/app/src/main/java/app/echoconnect/files/Files.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ object Files : Plugin {

override fun onPacket(ctx: Context, laptop: String, type: String, body: JSONObject) {
if (!Prefs.on(ctx, "files") || !allowed()) {
Connect.send(type, JSONObject().put("requestId", body.optString("requestId")).put("error", "Enable Files and All files access on your phone"), laptop)
fail(laptop, type, body, "Turn on Files in EchoConnect and allow All files access on the phone.")
return
}
Work.run {
Expand All @@ -52,10 +52,20 @@ object Files : Plugin {
}
"echofiles.files.read" -> Connect.sendFile(resolve(body.getString("path")), "echofiles.files.read", body)
} } catch (error: Exception) {
Connect.send(type, JSONObject().put("requestId", body.optString("requestId")).put("error", error.message ?: "Could not read shared storage"), laptop)
fail(laptop, type, body, error.message ?: "Could not read shared storage")
}
}
}

/** Say why a request failed, in the reply EchoFiles waits for: the file server's answer
* (`kdeconnect.sftp` with `errorMessage`), or the request's own type with `error`. */
private fun fail(laptop: String, type: String, body: JSONObject, message: String) {
if (type == "kdeconnect.sftp.request") {
Connect.send("kdeconnect.sftp", JSONObject().put("errorMessage", message), laptop)
} else {
Connect.send(type, JSONObject().put("requestId", body.optString("requestId")).put("error", message), laptop)
}
}
override fun onIncoming(ctx: Context, laptop: String, transfer: Long, name: String, size: Long, type: String, body: JSONObject): Boolean {
if (type != "echofiles.files.write") return false
if (!Prefs.on(ctx, "files") || !allowed()) Connect.rejectFile(transfer)
Expand Down
13 changes: 13 additions & 0 deletions crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,19 @@ pub fn state_dir() -> PathBuf {
xdg("XDG_STATE_HOME", ".local/state").join("echofiles")
}

/// `$XDG_RUNTIME_DIR/echofiles` — per-login, private: the phone's folder is mounted here.
/// Without a runtime dir, a private folder in the config dir stands in.
pub fn runtime_dir() -> PathBuf {
use std::os::unix::fs::DirBuilderExt;
let dir = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.map(|p| p.join("echofiles"))
.unwrap_or_else(|| config_dir().join("runtime"));
let _ = std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir);
dir
}

/// `$XDG_RUNTIME_DIR/echofiles.sock` — the running app listens here. A Unix socket path
/// holds at most 107 bytes; when the runtime folder's path is too long for the longest
/// socket name (`echofiles-ef.sock`), the private folder in the config dir is used, so
Expand Down
3 changes: 2 additions & 1 deletion crates/connect/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "echoconnect-core"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "EchoConnect's Rust core for Android: the KDE Connect protocol (phone role) exposed to Kotlin through UniFFI"
description = "EchoConnect's Rust core for Android: the EchoFiles link (phone role) exposed to Kotlin through UniFFI"

[lib]
name = "echoconnect"
Expand All @@ -16,6 +16,7 @@ path = "src/bindgen.rs"
[dependencies]
ef-phone.workspace = true
getrandom = "0.3"
rustix.workspace = true
russh = "0.63.3"
russh-sftp = "3.0.1"
serde_json = "1"
Expand Down
7 changes: 4 additions & 3 deletions crates/connect/examples/sftp_serve.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Serve a folder over EchoConnect's SFTP server: `cargo run -p echoconnect-core --example sftp_serve -- <dir>`.
//! Prints the port, user, password and host-key fingerprint EchoFiles needs to mount it.
fn main() {
let dir = std::env::args().nth(1).expect("dir");
let s = echoconnect::sftp::Server::start(vec![dir]).expect("start");
println!("{} {} {}", s.port(), s.user(), s.password());
std::thread::sleep(std::time::Duration::from_secs(60));
let s = echoconnect::sftp::Server::start(vec![dir], [7; 32]).expect("start");
println!("{} {} {} {}", s.port(), s.user(), s.password(), s.fingerprint());
std::thread::sleep(std::time::Duration::from_secs(600));
}
25 changes: 23 additions & 2 deletions crates/connect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,26 @@ fn event_json(e: &Event, progress: &Mutex<HashMap<u64, (u64, Arc<AtomicU64>)>>)
}
}

/// The file server's host key seed, made once and kept with the pairings: the server's
/// key then stays the same however often Android restarts it.
fn host_key_seed(dir: &std::path::Path) -> Result<[u8; 32], String> {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let path = dir.join("sftp-host-key");
if let Ok(b) = std::fs::read(&path)
&& let Ok(seed) = <[u8; 32]>::try_from(b.as_slice())
{
return Ok(seed);
}
let mut seed = [0u8; 32];
getrandom::fill(&mut seed).map_err(|e| e.to_string())?;
let tmp = dir.join("sftp-host-key.tmp");
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp).map_err(|e| e.to_string())?;
f.write_all(&seed).and_then(|_| f.sync_all()).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
Ok(seed)
}

fn parse(body: &str) -> Value {
serde_json::from_str(body).unwrap_or_else(|_| json!({}))
}
Expand Down Expand Up @@ -231,13 +251,14 @@ impl Core {
.to_string()
}

/// Serve `roots` (name → folder) over SFTP for the laptop and tell it how to connect.
/// Serve `roots` (name → folder) over SFTP for the laptop and tell it how to connect,
/// including the host key's fingerprint, which EchoFiles pins.
/// Returns the port, or an error.
pub fn start_sftp(&self, laptop: String, roots: Vec<String>, names: Vec<String>) -> Result<u16, CoreError> {
let mut slot = self.sftp.lock().unwrap();
let server = match slot.take() {
Some(s) => s,
None => sftp::Server::start(roots.clone()).map_err(CoreError::Failed)?,
None => sftp::Server::start(roots.clone(), host_key_seed(&self.dir).map_err(CoreError::Failed)?).map_err(CoreError::Failed)?,
};
let port = server.port();
let body = json!({
Expand Down
Loading
Loading