344 lines
10 KiB
Rust
344 lines
10 KiB
Rust
#![forbid(unsafe_code)]
|
|
|
|
use anyhow::{Context, Result, anyhow};
|
|
use clap::{Args, Parser, Subcommand};
|
|
use drosync_core::Mapping;
|
|
use drosync_daemon::{IpcRequest, request};
|
|
use drosync_protocol::{DeviceAuthorization, PROTOCOL_VERSION};
|
|
use serde_json::{Value, json};
|
|
use std::path::PathBuf;
|
|
use std::process::ExitCode;
|
|
use std::time::Duration;
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Debug, Parser)]
|
|
#[command(
|
|
name = "drosync",
|
|
version,
|
|
about = "Secure one-way local-to-BOS synchronization"
|
|
)]
|
|
struct App {
|
|
#[arg(long, global = true)]
|
|
json: bool,
|
|
#[arg(long, global = true)]
|
|
non_interactive: bool,
|
|
#[command(subcommand)]
|
|
command: Command,
|
|
}
|
|
|
|
#[derive(Debug, Subcommand)]
|
|
enum Command {
|
|
Configure(Configure),
|
|
Auth(Auth),
|
|
Mapping(MappingCommand),
|
|
Plan(MappingRun),
|
|
Sync(MappingRun),
|
|
Status,
|
|
Conflicts,
|
|
Retry(IdArgument),
|
|
Abort(IdArgument),
|
|
Doctor,
|
|
Daemon(DaemonCommand),
|
|
Update(UpdateCommand),
|
|
Version,
|
|
}
|
|
|
|
#[derive(Debug, Args)]
|
|
struct Configure {
|
|
#[arg(long)]
|
|
server: String,
|
|
}
|
|
|
|
#[derive(Debug, Args)]
|
|
struct Auth {
|
|
#[arg(long)]
|
|
server: String,
|
|
#[arg(long, default_value = "default")]
|
|
profile: String,
|
|
#[arg(long, default_value_t = default_device_name())]
|
|
device_name: String,
|
|
}
|
|
|
|
#[derive(Debug, Args)]
|
|
struct MappingCommand {
|
|
#[command(subcommand)]
|
|
command: MappingSubcommand,
|
|
}
|
|
|
|
#[derive(Debug, Subcommand)]
|
|
enum MappingSubcommand {
|
|
List,
|
|
Add {
|
|
local_root: PathBuf,
|
|
#[arg(long)]
|
|
space: String,
|
|
#[arg(long)]
|
|
remote_prefix: Option<String>,
|
|
#[arg(long)]
|
|
include_hidden: bool,
|
|
#[arg(long)]
|
|
require_done: bool,
|
|
},
|
|
Remove {
|
|
id: String,
|
|
},
|
|
}
|
|
|
|
#[derive(Debug, Args)]
|
|
struct MappingRun {
|
|
mapping_id: String,
|
|
#[arg(long)]
|
|
dry_run: bool,
|
|
}
|
|
|
|
#[derive(Debug, Args)]
|
|
struct IdArgument {
|
|
id: String,
|
|
}
|
|
|
|
#[derive(Debug, Args)]
|
|
struct DaemonCommand {
|
|
#[arg(long)]
|
|
foreground: bool,
|
|
}
|
|
|
|
#[derive(Debug, Args)]
|
|
struct UpdateCommand {
|
|
#[arg(long)]
|
|
check: bool,
|
|
#[arg(long)]
|
|
pin: Option<String>,
|
|
#[arg(long)]
|
|
pause: bool,
|
|
#[arg(long)]
|
|
rollback: bool,
|
|
}
|
|
|
|
fn default_device_name() -> String {
|
|
std::env::var("COMPUTERNAME")
|
|
.or_else(|_| std::env::var("HOSTNAME"))
|
|
.unwrap_or_else(|_| "drosync-device".to_owned())
|
|
}
|
|
|
|
async fn ipc(command: &str, arguments: Value) -> Result<Value> {
|
|
let paths = drosync_platform::paths()?;
|
|
let response = request(
|
|
&paths.ipc_endpoint,
|
|
&IpcRequest {
|
|
command: command.to_owned(),
|
|
arguments,
|
|
},
|
|
)
|
|
.await?;
|
|
if response.ok {
|
|
Ok(response.result)
|
|
} else {
|
|
Err(anyhow!(response.error))
|
|
}
|
|
}
|
|
|
|
fn print_value(value: &Value, as_json: bool) {
|
|
if as_json {
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string(value).expect("serializable output")
|
|
);
|
|
} else {
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string_pretty(value).expect("serializable output")
|
|
);
|
|
}
|
|
}
|
|
|
|
fn exit_code_for(error: &anyhow::Error) -> u8 {
|
|
if let Some(drosync_transfer::TransferError::Api { status, error }) =
|
|
error.downcast_ref::<drosync_transfer::TransferError>()
|
|
{
|
|
if status.as_u16() == 401
|
|
|| error.code.contains("credential")
|
|
|| error.code.contains("authorization")
|
|
{
|
|
return 10;
|
|
}
|
|
if status.as_u16() == 403
|
|
|| error.code.contains("scope")
|
|
|| error.code.contains("capability")
|
|
|| error.code.contains("space_not_ready")
|
|
{
|
|
return 20;
|
|
}
|
|
if status.as_u16() == 409 || error.code.contains("lease") || error.code.contains("conflict")
|
|
{
|
|
return 30;
|
|
}
|
|
}
|
|
let message = error.to_string().to_ascii_lowercase();
|
|
if message.contains("credential") || message.contains("authorization") {
|
|
10
|
|
} else if message.contains("scope")
|
|
|| message.contains("capability")
|
|
|| message.contains("space is")
|
|
{
|
|
20
|
|
} else if message.contains("lease") || message.contains("conflict") {
|
|
30
|
|
} else if message.contains("sqlite")
|
|
|| message.contains("mapping root")
|
|
|| message.contains("local path")
|
|
|| message.contains("file changed")
|
|
{
|
|
40
|
|
} else {
|
|
50
|
|
}
|
|
}
|
|
|
|
#[allow(clippy::too_many_lines)]
|
|
async fn execute(app: &App) -> Result<Value> {
|
|
match &app.command {
|
|
Command::Configure(input) => ipc("configure", json!({"serverUrl": input.server})).await,
|
|
Command::Auth(input) => {
|
|
let client = drosync_transfer::Client::new(&input.server, None)?;
|
|
let authorization = client
|
|
.create_device_authorization(&DeviceAuthorization {
|
|
device_id: Uuid::new_v4().to_string(),
|
|
device_name: input.device_name.clone(),
|
|
platform: drosync_platform::platform_name().to_owned(),
|
|
architecture: drosync_platform::architecture().to_owned(),
|
|
client_version: env!("CARGO_PKG_VERSION").to_owned(),
|
|
})
|
|
.await?;
|
|
if app.non_interactive {
|
|
return Ok(serde_json::to_value(authorization)?);
|
|
}
|
|
eprintln!(
|
|
"Approve device code {} at {}",
|
|
authorization.user_code, authorization.verification_uri
|
|
);
|
|
let deadline =
|
|
tokio::time::Instant::now() + Duration::from_secs(authorization.expires_in);
|
|
loop {
|
|
tokio::time::sleep(Duration::from_secs(authorization.interval.max(1))).await;
|
|
match client
|
|
.poll_device_authorization(&authorization.device_code)
|
|
.await
|
|
{
|
|
Ok(value) => {
|
|
let token = value
|
|
.get("credential")
|
|
.and_then(Value::as_str)
|
|
.ok_or_else(|| anyhow!("authorization response omitted credential"))?;
|
|
drosync_platform::save_credential(&input.profile, token)?;
|
|
let _ = ipc(
|
|
"configure",
|
|
json!({
|
|
"serverUrl": input.server,
|
|
"credentialProfile": input.profile,
|
|
}),
|
|
)
|
|
.await;
|
|
return Ok(json!({"authorized": true, "profile": input.profile}));
|
|
}
|
|
Err(drosync_transfer::TransferError::Api { error, .. })
|
|
if error.code == "authorization_pending"
|
|
&& tokio::time::Instant::now() < deadline => {}
|
|
Err(error) => return Err(error.into()),
|
|
}
|
|
}
|
|
}
|
|
Command::Mapping(input) => match &input.command {
|
|
MappingSubcommand::List => ipc("mapping.list", json!({})).await,
|
|
MappingSubcommand::Add {
|
|
local_root,
|
|
space,
|
|
remote_prefix,
|
|
include_hidden,
|
|
require_done,
|
|
} => {
|
|
let canonical = local_root
|
|
.canonicalize()
|
|
.with_context(|| format!("invalid mapping root {}", local_root.display()))?;
|
|
let mut mapping = Mapping::new(canonical, space.clone());
|
|
mapping.remote_prefix = remote_prefix.clone().unwrap_or_default();
|
|
mapping.include_hidden = *include_hidden;
|
|
mapping.require_done_marker = *require_done;
|
|
ipc("mapping.add", serde_json::to_value(mapping)?).await
|
|
}
|
|
MappingSubcommand::Remove { id } => ipc("mapping.remove", json!({"id": id})).await,
|
|
},
|
|
Command::Plan(input) => {
|
|
ipc(
|
|
"plan",
|
|
json!({"mappingId": input.mapping_id, "dryRun": true}),
|
|
)
|
|
.await
|
|
}
|
|
Command::Sync(input) => {
|
|
ipc(
|
|
"sync",
|
|
json!({"mappingId": input.mapping_id, "dryRun": input.dry_run}),
|
|
)
|
|
.await
|
|
}
|
|
Command::Status => ipc("status", json!({})).await,
|
|
Command::Conflicts => ipc("conflicts", json!({})).await,
|
|
Command::Retry(input) => ipc("retry", json!({"id": input.id})).await,
|
|
Command::Abort(input) => ipc("abort", json!({"id": input.id})).await,
|
|
Command::Doctor => ipc("doctor", json!({})).await,
|
|
Command::Daemon(input) => {
|
|
if input.foreground {
|
|
let paths = drosync_platform::paths()?;
|
|
drosync_daemon::run(&paths).await?;
|
|
Ok(json!({"stopped": true}))
|
|
} else {
|
|
Err(anyhow!(
|
|
"use `drosync daemon --foreground` or the installed service"
|
|
))
|
|
}
|
|
}
|
|
Command::Update(input) => {
|
|
ipc(
|
|
"update",
|
|
json!({
|
|
"check": input.check,
|
|
"pin": input.pin,
|
|
"pause": input.pause,
|
|
"rollback": input.rollback,
|
|
}),
|
|
)
|
|
.await
|
|
}
|
|
Command::Version => Ok(json!({
|
|
"name": "drosync",
|
|
"version": env!("CARGO_PKG_VERSION"),
|
|
"protocolVersion": PROTOCOL_VERSION,
|
|
"platform": drosync_platform::platform_name(),
|
|
"architecture": drosync_platform::architecture(),
|
|
})),
|
|
}
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() -> ExitCode {
|
|
let app = App::parse();
|
|
match execute(&app).await {
|
|
Ok(value) => {
|
|
print_value(&value, app.json);
|
|
ExitCode::SUCCESS
|
|
}
|
|
Err(error) => {
|
|
let exit_code = exit_code_for(&error);
|
|
if app.json {
|
|
println!(
|
|
"{}",
|
|
json!({"error": error.to_string(), "retryable": false, "exitCode": exit_code})
|
|
);
|
|
} else {
|
|
eprintln!("drosync: {error:#}");
|
|
}
|
|
ExitCode::from(exit_code)
|
|
}
|
|
}
|
|
}
|