smb2-cli 0.7.3

Command-line SMB2/3 client: list, stat, move, and delete files on a share without mounting it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! `smb2`: a command-line SMB2/3 client that talks to a share directly,
//! without mounting it.

mod auth;
mod batch;
mod commands;
mod output;
mod pool;
mod remote;
mod target;

use std::path::PathBuf;

use anyhow::Result;
use clap::{Parser, Subcommand};

use crate::auth::AuthArgs;
use crate::target::Target;

#[derive(Parser)]
#[command(
    name = "smb2",
    version,
    about = "List, move, and delete files on an SMB share without mounting it",
    after_help = "Targets look like //host/share/path. Passwords come from --password-command, \
                  SMB2_PASS, or a prompt. -j goes after the subcommand, on the commands that \
                  spread work over connections: stat, mkdir, rm, rmdir, mv, xattr."
)]
struct Cli {
    #[command(flatten)]
    auth: AuthArgs,

    /// Print machine-readable JSON instead of text.
    #[arg(long, global = true)]
    json: bool,

    /// Show what would happen without changing anything.
    #[arg(long, global = true)]
    dry_run: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// List a directory, printing entries in the server's order as they arrive.
    Ls {
        /// Target like //host/share/path.
        target: String,
        /// Show size and modification time.
        #[arg(short = 'l', long)]
        long: bool,
        /// Descend into subdirectories.
        #[arg(short = 'R', long)]
        recursive: bool,
        /// Sort by path. Waits for the whole listing before printing anything.
        /// `--json` is always sorted.
        #[arg(long)]
        sort: bool,
        /// Show each entry's index number (the file system's file ID, like an
        /// inode number), or `-` when the server has none.
        #[arg(short = 'i', long = "inode")]
        index: bool,
    },
    /// Show metadata for one or more paths.
    Stat {
        /// Targets like //host/share/path.
        targets: Vec<String>,
        #[command(flatten)]
        input: batch::BatchInput,
        #[command(flatten)]
        concurrency: pool::Concurrency,
    },
    /// Create directories.
    Mkdir {
        targets: Vec<String>,
        #[command(flatten)]
        input: batch::BatchInput,
        #[command(flatten)]
        concurrency: pool::Concurrency,
        /// Create missing parent directories too.
        #[arg(short = 'p', long)]
        parents: bool,
    },
    /// Delete files.
    Rm {
        targets: Vec<String>,
        #[command(flatten)]
        input: batch::BatchInput,
        #[command(flatten)]
        concurrency: pool::Concurrency,
    },
    /// Remove empty directories.
    Rmdir {
        targets: Vec<String>,
        #[command(flatten)]
        input: batch::BatchInput,
        #[command(flatten)]
        concurrency: pool::Concurrency,
    },
    /// Move or rename within one share.
    Mv {
        /// Source and destination, or one base target with --from-file.
        targets: Vec<String>,
        /// Read `from<TAB>to` pairs from this file, or `-` for stdin.
        #[arg(long, value_name = "FILE")]
        from_file: Option<String>,
        /// Replace a file already at the destination, in one step on the
        /// server. Without it, a taken name is an error.
        #[arg(long)]
        replace: bool,
        #[command(flatten)]
        concurrency: pool::Concurrency,
    },
    /// Read and change extended attributes, stored the way macOS stores them on
    /// SMB, so Finder sees them. With no flag, lists each path's attribute names.
    Xattr {
        targets: Vec<String>,
        #[command(flatten)]
        input: batch::BatchInput,
        #[command(flatten)]
        concurrency: pool::Concurrency,
        /// List attributes with their values.
        #[arg(short = 'l', conflicts_with_all = ["print", "write", "delete"])]
        list: bool,
        /// Print one attribute's value.
        #[arg(short = 'p', value_name = "NAME", conflicts_with_all = ["write", "delete"])]
        print: Option<String>,
        /// Write one attribute.
        #[arg(short = 'w', num_args = 2, value_names = ["NAME", "VALUE"], conflicts_with = "delete")]
        write: Option<Vec<String>>,
        /// Delete one attribute. Deleting one that isn't there succeeds.
        #[arg(short = 'd', value_name = "NAME")]
        delete: Option<String>,
        /// Print values as hex, and read `-w`'s VALUE as hex.
        #[arg(short = 'x')]
        hex: bool,
    },
    /// List a path's named streams.
    Streams { target: String },
    /// Print a file to stdout.
    Cat { target: String },
    /// Download a file.
    Get {
        target: String,
        /// Local destination; defaults to the file's name here.
        destination: Option<String>,
    },
    /// Upload a file.
    Put {
        source: PathBuf,
        /// Target like //host/share/path.
        target: String,
    },
    /// Print the path the server stores a file under (its casing, and long
    /// names for 8.3 aliases).
    Realpath { target: String },
    /// Show free space on a share.
    Df { target: String },
    /// List the shares a server offers.
    Shares {
        /// Host, or a target like //host.
        host: String,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    env_logger::init();
    let cli = Cli::parse();
    let credentials = cli.auth.resolve()?;

    match &cli.command {
        Commands::Ls {
            target,
            long,
            recursive,
            sort,
            index,
        } => {
            let target = Target::parse(target)?;
            let format = commands::meta::LsFormat {
                long: *long,
                recursive: *recursive,
                sort: *sort,
                index: *index,
            };
            commands::meta::ls(&target, &credentials, format, cli.json).await
        }
        Commands::Stat {
            targets,
            input,
            concurrency,
        } => {
            let (base, paths) = input.collect(targets)?;
            commands::meta::stat(&base, &credentials, paths, concurrency.workers(), cli.json).await
        }
        Commands::Mkdir {
            targets,
            input,
            concurrency,
            parents,
        } => {
            commands::mutate::mkdir(
                targets,
                input,
                &credentials,
                concurrency.workers(),
                *parents,
                cli.dry_run,
            )
            .await
        }
        Commands::Rm {
            targets,
            input,
            concurrency,
        } => {
            commands::mutate::rm(
                targets,
                input,
                &credentials,
                concurrency.workers(),
                cli.dry_run,
            )
            .await
        }
        Commands::Rmdir {
            targets,
            input,
            concurrency,
        } => {
            commands::mutate::rmdir(
                targets,
                input,
                &credentials,
                concurrency.workers(),
                cli.dry_run,
            )
            .await
        }
        Commands::Mv {
            targets,
            from_file,
            replace,
            concurrency,
        } => {
            commands::mutate::mv(
                targets,
                from_file.as_deref(),
                *replace,
                &credentials,
                concurrency.workers(),
                cli.dry_run,
            )
            .await
        }
        Commands::Xattr {
            targets,
            input,
            concurrency,
            list,
            print,
            write,
            delete,
            hex,
        } => {
            let action = commands::xattr::Action::from_flags(
                *list,
                print.as_ref(),
                write.as_ref(),
                delete.as_ref(),
                *hex,
            )?;
            commands::xattr::xattr(
                targets,
                input,
                &credentials,
                action,
                commands::xattr::Options {
                    concurrency: concurrency.workers(),
                    hex: *hex,
                    as_json: cli.json,
                    dry_run: cli.dry_run,
                },
            )
            .await
        }
        Commands::Streams { target } => {
            commands::xattr::streams(&Target::parse(target)?, &credentials, cli.json).await
        }
        Commands::Cat { target } => {
            commands::transfer::cat(&Target::parse(target)?, &credentials).await
        }
        Commands::Get {
            target,
            destination,
        } => {
            commands::transfer::get(
                &Target::parse(target)?,
                &credentials,
                destination.as_deref(),
                cli.dry_run,
            )
            .await
        }
        Commands::Put { source, target } => {
            commands::transfer::put(source, &Target::parse(target)?, &credentials, cli.dry_run)
                .await
        }
        Commands::Realpath { target } => {
            commands::meta::realpath(&Target::parse(target)?, &credentials, cli.json).await
        }
        Commands::Df { target } => {
            commands::meta::df(&Target::parse(target)?, &credentials, cli.json).await
        }
        Commands::Shares { host } => {
            let (host, port) = parse_host(host);
            commands::meta::shares(&host, port, &credentials, cli.json).await
        }
    }
}

/// Accepts a bare host, `host:port`, or a `//host` target.
fn parse_host(input: &str) -> (String, u16) {
    let trimmed = input
        .trim_start_matches("smb://")
        .trim_start_matches("//")
        .trim_end_matches('/');
    match trimmed.rsplit_once(':') {
        Some((host, port)) => (host.to_string(), port.parse().unwrap_or(445)),
        None => (trimmed.to_string(), 445),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn verifies_the_cli_definition() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }

    /// `-j` opens connections, so it belongs to the commands that open more
    /// than one. The flag-before-the-subcommand spelling has to stop parsing.
    #[test]
    fn takes_concurrency_after_the_subcommand_but_not_before_it() {
        assert!(Cli::try_parse_from(["smb2", "rm", "//host/share/a", "-j", "16"]).is_ok());
        assert!(Cli::try_parse_from(["smb2", "-j", "16", "rm", "//host/share/a"]).is_err());
    }

    #[test]
    fn offers_concurrency_on_every_command_that_spreads_work_over_connections() {
        for command in commands_that_pool() {
            let mut args = command.clone();
            args.extend(["-j", "4"]);
            assert!(
                Cli::try_parse_from(&args).is_ok(),
                "{} feeds pool::run, so it has to take -j",
                command[1]
            );
        }
    }

    #[test]
    fn keeps_concurrency_off_commands_that_open_one_connection() {
        for command in commands_that_open_one_connection() {
            let mut args = command.clone();
            args.extend(["-j", "4"]);
            assert!(
                Cli::try_parse_from(&args).is_err(),
                "{} opens one connection, so advertising -j on it is a lie",
                command[1]
            );
        }
    }

    /// The commands whose work goes through `pool::run`.
    fn commands_that_pool() -> Vec<Vec<&'static str>> {
        vec![
            vec!["smb2", "stat", "//host/share/a"],
            vec!["smb2", "mkdir", "//host/share/a"],
            vec!["smb2", "rm", "//host/share/a"],
            vec!["smb2", "rmdir", "//host/share/a"],
            vec!["smb2", "mv", "//host/share/a", "//host/share/b"],
            vec!["smb2", "xattr", "//host/share/a"],
        ]
    }

    /// The commands that call `pool::connect_all` with a count of one.
    fn commands_that_open_one_connection() -> Vec<Vec<&'static str>> {
        vec![
            vec!["smb2", "ls", "//host/share/a"],
            vec!["smb2", "streams", "//host/share/a"],
            vec!["smb2", "cat", "//host/share/a"],
            vec!["smb2", "get", "//host/share/a"],
            vec!["smb2", "put", "./a", "//host/share/a"],
            vec!["smb2", "realpath", "//host/share/a"],
            vec!["smb2", "df", "//host/share"],
            vec!["smb2", "shares", "host"],
        ]
    }

    #[test]
    fn parses_host_forms() {
        assert_eq!(parse_host("raspi"), ("raspi".to_string(), 445));
        assert_eq!(parse_host("//raspi/"), ("raspi".to_string(), 445));
        assert_eq!(parse_host("raspi:4450"), ("raspi".to_string(), 4450));
    }
}