termscp 1.0.0

termscp is a feature rich terminal file transfer and explorer with support for SCP/SFTP/FTP/Kube/S3/WebDAV
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! ## ConfigClient
//!
//! `config_client` is the module which provides an API between the Config module and the system

// Locals
// Ext
use std::fs::{File, OpenOptions, create_dir, remove_file};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;

use crate::config::params::{DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD, UserConfig};
use crate::config::serialization::{SerializerError, SerializerErrorKind, deserialize, serialize};
use crate::explorer::GroupDirs;
use crate::filetransfer::FileTransferProtocol;

// Types
pub type SshHost = (String, String, PathBuf); // 0: host, 1: username, 2: RSA key path

/// ConfigClient provides a high level API to communicate with the termscp configuration
pub struct ConfigClient {
    config: UserConfig,   // Configuration loaded
    config_path: PathBuf, // Configuration TOML Path
    ssh_key_dir: PathBuf, // SSH Key storage directory
    degraded: bool,       // Indicates the `ConfigClient` is working in degraded mode
}

impl ConfigClient {
    /// Instantiate a new `ConfigClient` with provided path
    pub fn new(config_path: &Path, ssh_key_dir: &Path) -> Result<Self, SerializerError> {
        // Initialize a default configuration
        let default_config: UserConfig = UserConfig::default();
        info!(
            "Setting up config client with config path {} and SSH key directory {}",
            config_path.display(),
            ssh_key_dir.display()
        );
        // Create client
        let mut client: ConfigClient = ConfigClient {
            config: default_config,
            config_path: PathBuf::from(config_path),
            ssh_key_dir: PathBuf::from(ssh_key_dir),
            degraded: false,
        };
        // If ssh key directory doesn't exist, create it
        if !ssh_key_dir.exists() {
            if let Err(err) = create_dir(ssh_key_dir) {
                error!("Failed to create SSH key dir: {}", err);
                return Err(SerializerError::new_ex(
                    SerializerErrorKind::Io,
                    format!(
                        "Could not create SSH key directory \"{}\": {}",
                        ssh_key_dir.display(),
                        err
                    ),
                ));
            }
            debug!("Created SSH key directory");
        }
        // If Config file doesn't exist, create it
        if !config_path.exists() {
            if let Err(err) = client.write_config() {
                error!("Couldn't create configuration file: {}", err);
                return Err(err);
            }
            debug!("Config file didn't exist; created file");
        } else {
            // otherwise Load configuration from file
            if let Err(err) = client.read_config() {
                error!("Couldn't read configuration file: {}", err);
                return Err(err);
            }
            debug!("Read configuration file");
        }
        Ok(client)
    }

    /// Instantiate a ConfigClient in degraded mode.
    /// When in degraded mode, the configuration in use will be the default configuration
    /// and the IO operation on configuration won't be available
    pub fn degraded() -> Self {
        Self {
            config: UserConfig::default(),
            config_path: PathBuf::default(),
            ssh_key_dir: PathBuf::default(),
            degraded: true,
        }
    }

    // Text editor

    /// Get text editor from configuration
    pub fn get_text_editor(&self) -> PathBuf {
        self.config.user_interface.text_editor.clone()
    }

    /// Set text editor path
    pub fn set_text_editor(&mut self, path: PathBuf) {
        self.config.user_interface.text_editor = path;
    }

    // Default protocol

    /// Get default protocol from configuration
    pub fn get_default_protocol(&self) -> FileTransferProtocol {
        match FileTransferProtocol::from_str(self.config.user_interface.default_protocol.as_str()) {
            Ok(p) => p,
            Err(_) => FileTransferProtocol::Sftp,
        }
    }

    /// Set default protocol to configuration
    pub fn set_default_protocol(&mut self, proto: FileTransferProtocol) {
        self.config.user_interface.default_protocol = proto.to_string();
    }

    /// Get value of `show_hidden_files`
    pub fn get_show_hidden_files(&self) -> bool {
        self.config.user_interface.show_hidden_files
    }

    /// Set new value for `show_hidden_files`
    pub fn set_show_hidden_files(&mut self, value: bool) {
        self.config.user_interface.show_hidden_files = value;
    }

    /// Get value of `check_for_updates`
    pub fn get_check_for_updates(&self) -> bool {
        self.config.user_interface.check_for_updates.unwrap_or(true)
    }

    /// Set new value for `check_for_updates`
    pub fn set_check_for_updates(&mut self, value: bool) {
        self.config.user_interface.check_for_updates = Some(value);
    }

    /// Get value of `prompt_on_file_replace`
    pub fn get_prompt_on_file_replace(&self) -> bool {
        self.config
            .user_interface
            .prompt_on_file_replace
            .unwrap_or(true)
    }

    /// Set new value for `prompt_on_file_replace`
    pub fn set_prompt_on_file_replace(&mut self, value: bool) {
        self.config.user_interface.prompt_on_file_replace = Some(value);
    }

    /// Get GroupDirs value from configuration (will be converted from string)
    pub fn get_group_dirs(&self) -> Option<GroupDirs> {
        // Convert string to `GroupDirs`
        match &self.config.user_interface.group_dirs {
            None => None,
            Some(val) => GroupDirs::from_str(val.as_str()).ok(),
        }
    }

    /// Set value for group_dir in configuration.
    /// Provided value, if `Some` will be converted to `GroupDirs`
    pub fn set_group_dirs(&mut self, val: Option<GroupDirs>) {
        self.config.user_interface.group_dirs = val.map(|val| val.to_string());
    }

    /// Get current file fmt for local host
    pub fn get_local_file_fmt(&self) -> Option<String> {
        self.config.user_interface.file_fmt.clone()
    }

    /// Set file fmt parameter for local host
    pub fn set_local_file_fmt(&mut self, s: String) {
        self.config.user_interface.file_fmt = match s.is_empty() {
            true => None,
            false => Some(s),
        };
    }

    /// Get current file fmt for remote host
    pub fn get_remote_file_fmt(&self) -> Option<String> {
        self.config.user_interface.remote_file_fmt.clone()
    }

    /// Set file fmt parameter for remote host
    pub fn set_remote_file_fmt(&mut self, s: String) {
        self.config.user_interface.remote_file_fmt = match s.is_empty() {
            true => None,
            false => Some(s),
        };
    }

    /// Get value of `notifications`
    pub fn get_notifications(&self) -> bool {
        self.config.user_interface.notifications.unwrap_or(true)
    }

    /// Set new value for `notifications`
    pub fn set_notifications(&mut self, value: bool) {
        self.config.user_interface.notifications = Some(value);
    }

    /// Get value of `notification_threshold`
    pub fn get_notification_threshold(&self) -> u64 {
        self.config
            .user_interface
            .notification_threshold
            .unwrap_or(DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD)
    }

    /// Set new value for `notification_threshold`
    pub fn set_notification_threshold(&mut self, value: u64) {
        self.config.user_interface.notification_threshold = Some(value);
    }

    // Remote params

    /// Get ssh config path
    pub fn get_ssh_config(&self) -> Option<&str> {
        self.config.remote.ssh_config.as_deref()
    }

    /// Set ssh config path
    pub fn set_ssh_config(&mut self, p: Option<String>) {
        self.config.remote.ssh_config = p;
    }

    // SSH Keys

    /// Save a SSH key into configuration.
    /// This operation also creates the key file in `ssh_key_dir`
    /// and also commits changes to configuration, to prevent incoerent data
    pub fn add_ssh_key(
        &mut self,
        host: &str,
        username: &str,
        ssh_key: &str,
    ) -> Result<(), SerializerError> {
        if self.degraded {
            return Err(SerializerError::new_ex(
                SerializerErrorKind::Generic,
                String::from("Configuration won't be saved, since in degraded mode"),
            ));
        }
        let host_name: String = Self::make_ssh_host_key(host, username);
        // Get key path
        let ssh_key_path: PathBuf = {
            let mut p: PathBuf = self.ssh_key_dir.clone();
            p.push(format!("{host_name}.key"));
            p
        };
        info!(
            "Writing SSH file to {} for host {}",
            ssh_key_path.display(),
            host_name
        );
        // Write key to file
        let mut f: File = match File::create(ssh_key_path.as_path()) {
            Ok(f) => f,
            Err(err) => return Self::make_io_err(err),
        };
        if let Err(err) = f.write_all(ssh_key.as_bytes()) {
            error!("Failed to write SSH key to file: {}", err);
            return Self::make_io_err(err);
        }
        // Add host to keys
        self.config.remote.ssh_keys.insert(host_name, ssh_key_path);
        // Write config
        self.write_config()
    }

    /// Delete a ssh key from configuration, using host as key.
    /// This operation also unlinks the key file in `ssh_key_dir`
    /// and also commits changes to configuration, to prevent incoerent data
    pub fn del_ssh_key(&mut self, host: &str, username: &str) -> Result<(), SerializerError> {
        if self.degraded {
            return Err(SerializerError::new_ex(
                SerializerErrorKind::Generic,
                String::from("Configuration won't be saved, since in degraded mode"),
            ));
        }
        // Remove key from configuration and get key path
        info!("Removing key for {}@{}", host, username);
        let key_path: PathBuf = match self
            .config
            .remote
            .ssh_keys
            .remove(&Self::make_ssh_host_key(host, username))
        {
            Some(p) => p,
            None => return Ok(()), // Return ok if host doesn't exist
        };
        // Remove file
        if let Err(err) = remove_file(key_path.as_path()) {
            error!("Failed to remove key file {}: {}", key_path.display(), err);
            return Self::make_io_err(err);
        }
        // Commit changes to configuration
        self.write_config()
    }

    /// Get ssh key from host.
    /// None is returned if key doesn't exist
    pub fn get_ssh_key(&self, mkey: &str) -> Option<SshHost> {
        if self.degraded {
            return None;
        }
        // Check if Key exists
        match self.config.remote.ssh_keys.get(mkey) {
            None => None,
            Some(key_path) => {
                // Get host and username
                let (host, username) = Self::get_ssh_tokens(mkey)?;
                // Return key
                Some((host, username, PathBuf::from(key_path)))
            }
        }
    }

    /// Get an iterator through hosts in the ssh key storage
    pub fn iter_ssh_keys(&self) -> impl Iterator<Item = &String> + '_ {
        Box::new(self.config.remote.ssh_keys.keys())
    }

    // I/O

    /// Write configuration to file
    pub fn write_config(&self) -> Result<(), SerializerError> {
        if self.degraded {
            return Err(SerializerError::new_ex(
                SerializerErrorKind::Generic,
                String::from("Configuration won't be saved, since in degraded mode"),
            ));
        }
        // Open file
        match OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(self.config_path.as_path())
        {
            Ok(writer) => serialize(&self.config, Box::new(writer)),
            Err(err) => {
                error!("Failed to write configuration file: {}", err);
                Err(SerializerError::new_ex(
                    SerializerErrorKind::Io,
                    err.to_string(),
                ))
            }
        }
    }

    /// Read configuration from file (or reload it if already read)
    pub fn read_config(&mut self) -> Result<(), SerializerError> {
        if self.degraded {
            return Err(SerializerError::new_ex(
                SerializerErrorKind::Generic,
                String::from("Configuration won't be loaded, since in degraded mode"),
            ));
        }
        // Open bookmarks file for read
        match OpenOptions::new()
            .read(true)
            .open(self.config_path.as_path())
        {
            Ok(reader) => {
                // Deserialize
                match deserialize(Box::new(reader)) {
                    Ok(config) => {
                        self.config = config;
                        Ok(())
                    }
                    Err(err) => Err(err),
                }
            }
            Err(err) => {
                error!("Failed to read configuration: {}", err);
                Err(SerializerError::new_ex(
                    SerializerErrorKind::Io,
                    err.to_string(),
                ))
            }
        }
    }

    /// Hosts are saved as `username@host` into configuration.
    /// This method creates the key name, starting from host and username
    fn make_ssh_host_key(host: &str, username: &str) -> String {
        format!("{username}@{host}")
    }

    /// Get ssh tokens starting from ssh host key
    /// Returns: (host, username) or None if key has invalid syntax
    fn get_ssh_tokens(host_key: &str) -> Option<(String, String)> {
        let tokens: Vec<&str> = host_key.split('@').collect();
        if tokens.len() >= 2 {
            Some((String::from(tokens[1]), String::from(tokens[0])))
        } else {
            error!(
                "Invalid SSH host key format: '{}' (expected 'username@host')",
                host_key
            );
            None
        }
    }

    /// Make serializer error from `std::io::Error`
    fn make_io_err(err: std::io::Error) -> Result<(), SerializerError> {
        Err(SerializerError::new_ex(
            SerializerErrorKind::Io,
            err.to_string(),
        ))
    }
}

#[cfg(test)]
mod tests {

    use std::io::Read;

    use pretty_assertions::assert_eq;
    use tempfile::TempDir;

    use super::*;
    use crate::config::params::UserConfig;
    use crate::utils::random::random_alphanumeric_with_len;

    #[test]
    fn test_system_config_new() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, ssh_keys_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let client: ConfigClient = ConfigClient::new(cfg_path.as_path(), ssh_keys_path.as_path())
            .ok()
            .unwrap();
        // Verify parameters
        let default_config: UserConfig = UserConfig::default();
        assert_eq!(client.degraded, false);
        assert_eq!(client.config.remote.ssh_keys.len(), 0);
        assert_eq!(
            client.config.user_interface.default_protocol,
            default_config.user_interface.default_protocol
        );
        assert_eq!(
            client.config.user_interface.text_editor,
            default_config.user_interface.text_editor
        );
        assert_eq!(client.config_path, cfg_path);
        assert_eq!(client.ssh_key_dir, ssh_keys_path);
    }

    #[test]
    fn test_system_config_degraded() {
        let mut client: ConfigClient = ConfigClient::degraded();
        assert_eq!(client.degraded, true);
        assert_eq!(client.config_path, PathBuf::default());
        assert_eq!(client.ssh_key_dir, PathBuf::default());
        // I/O
        assert!(client.add_ssh_key("Omar", "omar", "omar").is_err());
        assert!(client.del_ssh_key("omar", "omar").is_err());
        assert!(client.get_ssh_key("omar").is_none());
        assert!(client.write_config().is_err());
        assert!(client.read_config().is_err());
    }

    #[test]
    fn test_system_config_new_err() {
        assert!(
            ConfigClient::new(Path::new("/tmp/oifoif/omar"), Path::new("/tmp/efnnu/omar"),)
                .is_err()
        );
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, _): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        assert!(ConfigClient::new(cfg_path.as_path(), Path::new("/tmp/efnnu/omar")).is_err());
    }

    #[test]
    fn test_system_config_from_existing() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        // Change some stuff
        client.set_text_editor(PathBuf::from("/usr/bin/vim"));
        client.set_default_protocol(FileTransferProtocol::Scp);
        assert!(
            client
                .add_ssh_key("192.168.1.31", "pi", "piroporopero")
                .is_ok()
        );
        assert!(client.write_config().is_ok());
        // Istantiate a new client
        let client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        // Verify client has updated parameters
        assert_eq!(client.get_default_protocol(), FileTransferProtocol::Scp);
        assert_eq!(client.get_text_editor(), PathBuf::from("/usr/bin/vim"));
        let mut expected_key_path: PathBuf = key_path;
        expected_key_path.push("pi@192.168.1.31.key");
        assert_eq!(
            client.get_ssh_key("pi@192.168.1.31").unwrap(),
            (
                String::from("192.168.1.31"),
                String::from("pi"),
                expected_key_path,
            )
        );
    }

    #[test]
    fn test_system_config_text_editor() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        client.set_text_editor(PathBuf::from("mcedit"));
        assert_eq!(client.get_text_editor(), PathBuf::from("mcedit"));
    }

    #[test]
    fn test_system_config_default_protocol() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        client.set_default_protocol(FileTransferProtocol::Ftp(true));
        assert_eq!(
            client.get_default_protocol(),
            FileTransferProtocol::Ftp(true)
        );
    }

    #[test]
    fn test_system_config_show_hidden_files() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        client.set_show_hidden_files(true);
        assert_eq!(client.get_show_hidden_files(), true);
    }

    #[test]
    fn test_system_config_check_for_updates() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        assert_eq!(client.get_check_for_updates(), true); // Null ?
        client.set_check_for_updates(true);
        assert_eq!(client.get_check_for_updates(), true);
        client.set_check_for_updates(false);
        assert_eq!(client.get_check_for_updates(), false);
    }

    #[test]
    fn test_system_config_prompt_on_file_replace() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        assert_eq!(client.get_prompt_on_file_replace(), true); // Null ?
        client.set_prompt_on_file_replace(true);
        assert_eq!(client.get_prompt_on_file_replace(), true);
        client.set_prompt_on_file_replace(false);
        assert_eq!(client.get_prompt_on_file_replace(), false);
    }

    #[test]
    fn test_system_config_group_dirs() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        client.set_group_dirs(Some(GroupDirs::First));
        assert_eq!(client.get_group_dirs(), Some(GroupDirs::First),);
        client.set_group_dirs(None);
        assert_eq!(client.get_group_dirs(), None,);
    }

    #[test]
    fn test_system_config_local_file_fmt() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        assert_eq!(client.get_local_file_fmt(), None);
        client.set_local_file_fmt(String::from("{NAME}"));
        assert_eq!(client.get_local_file_fmt().unwrap(), String::from("{NAME}"));
        // Delete
        client.set_local_file_fmt(String::from(""));
        assert_eq!(client.get_local_file_fmt(), None);
    }

    #[test]
    fn test_system_config_remote_file_fmt() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        assert_eq!(client.get_remote_file_fmt(), None);
        client.set_remote_file_fmt(String::from("{NAME}"));
        assert_eq!(
            client.get_remote_file_fmt().unwrap(),
            String::from("{NAME}")
        );
        // Delete
        client.set_remote_file_fmt(String::from(""));
        assert_eq!(client.get_remote_file_fmt(), None);
    }

    #[test]
    fn test_system_config_notifications() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        assert_eq!(client.get_notifications(), true); // Null ?
        client.set_notifications(true);
        assert_eq!(client.get_notifications(), true);
        client.set_notifications(false);
        assert_eq!(client.get_notifications(), false);
    }

    #[test]
    fn test_system_config_remote_notification_threshold() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        assert_eq!(
            client.get_notification_threshold(),
            DEFAULT_NOTIFICATION_TRANSFER_THRESHOLD
        ); // Null ?
        client.set_notification_threshold(1024);
        assert_eq!(client.get_notification_threshold(), 1024);
        client.set_notification_threshold(64);
        assert_eq!(client.get_notification_threshold(), 64);
    }

    #[test]
    fn should_get_and_set_ssh_config_dir() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();

        let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/root"));
        let mut ssh_config_path = "~/.ssh/config".to_string();
        ssh_config_path = ssh_config_path.replacen('~', &home_dir.to_string_lossy(), 1);

        let ssh_config_path = if PathBuf::from(&ssh_config_path).exists() {
            Some(ssh_config_path)
        } else {
            None
        };

        assert_eq!(client.get_ssh_config(), ssh_config_path.as_deref()); // Null ?
        client.set_ssh_config(Some(String::from("/tmp/ssh_config")));
        assert_eq!(client.get_ssh_config(), Some("/tmp/ssh_config"));
        client.set_ssh_config(None);
        assert_eq!(client.get_ssh_config(), None);
    }

    #[test]
    fn test_system_config_ssh_keys() {
        let tmp_dir: TempDir = TempDir::new().ok().unwrap();
        let (cfg_path, key_path): (PathBuf, PathBuf) = get_paths(tmp_dir.path());
        let mut client: ConfigClient = ConfigClient::new(cfg_path.as_path(), key_path.as_path())
            .ok()
            .unwrap();
        // Add a new key
        let rsa_key: String = get_sample_rsa_key();
        assert!(
            client
                .add_ssh_key("192.168.1.31", "pi", rsa_key.as_str())
                .is_ok()
        );
        // Iterate keys
        for key in client.iter_ssh_keys() {
            let host: SshHost = client.get_ssh_key(key).unwrap();
            assert_eq!(host.0, String::from("192.168.1.31"));
            assert_eq!(host.1, String::from("pi"));
            let mut expected_key_path: PathBuf = key_path.clone();
            expected_key_path.push("pi@192.168.1.31.key");
            assert_eq!(host.2, expected_key_path);
            // Read rsa key
            let mut key_file: File = File::open(expected_key_path.as_path()).ok().unwrap();
            // Read
            let mut key: String = String::new();
            assert!(key_file.read_to_string(&mut key).is_ok());
            // Verify rsa key
            assert_eq!(key, rsa_key);
        }
        // Unexisting key
        assert!(client.get_ssh_key("test").is_none());
        // Delete key
        assert!(client.del_ssh_key("192.168.1.31", "pi").is_ok());
    }

    #[test]
    fn test_system_config_make_key() {
        assert_eq!(
            ConfigClient::make_ssh_host_key("192.168.1.31", "pi"),
            String::from("pi@192.168.1.31")
        );
        assert_eq!(
            ConfigClient::get_ssh_tokens("pi@192.168.1.31"),
            Some((String::from("192.168.1.31"), String::from("pi")))
        );
    }

    #[test]
    fn test_system_config_get_ssh_tokens_invalid() {
        assert!(ConfigClient::get_ssh_tokens("invalid").is_none());
        assert!(ConfigClient::get_ssh_tokens("").is_none());
    }

    #[test]
    fn test_system_config_make_io_err() {
        let err: SerializerError =
            ConfigClient::make_io_err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
                .err()
                .unwrap();
        assert_eq!(err.to_string(), "IO error (permission denied)");
    }

    /// Get paths for configuration and keys directory
    fn get_paths(dir: &Path) -> (PathBuf, PathBuf) {
        let mut k: PathBuf = PathBuf::from(dir);
        let mut c: PathBuf = k.clone();
        k.push("ssh-keys/");
        c.push("config.toml");
        (c, k)
    }

    fn get_sample_rsa_key() -> String {
        format!(
            "-----BEGIN OPENSSH PRIVATE KEY-----\n{}\n-----END OPENSSH PRIVATE KEY-----",
            random_alphanumeric_with_len(2536)
        )
    }
}