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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
use std::collections::{HashMap, VecDeque};
use std::io;
use std::path::PathBuf;
use std::sync::{Arc, Weak};
use std::time::Duration;
use async_compat::CompatExt;
use async_once_cell::OnceCell;
use async_trait::async_trait;
use distant_core::protocol::semver;
use distant_core::protocol::{
DirEntry, Environment, FileType, Metadata, Permissions, ProcessId, PtySize,
SetPermissionsOptions, SystemInfo, UnixMetadata, Version, PROTOCOL_VERSION,
};
use distant_core::{DistantApi, DistantCtx};
use log::*;
use tokio::sync::{mpsc, RwLock};
use wezterm_ssh::{
FilePermissions, OpenFileType, OpenOptions, Session as WezSession, Utf8PathBuf, WriteMode,
};
use crate::process::{spawn_pty, spawn_simple, SpawnResult};
use crate::utils::{self, to_other_error};
/// Time after copy completes to wait for stdout/stderr to close
const COPY_COMPLETE_TIMEOUT: Duration = Duration::from_secs(1);
struct Process {
stdin_tx: mpsc::Sender<Vec<u8>>,
kill_tx: mpsc::Sender<()>,
resize_tx: mpsc::Sender<PtySize>,
}
/// Represents implementation of [`DistantApi`] for SSH
pub struct SshDistantApi {
/// Internal ssh session
session: WezSession,
/// Global tracking of running processes by id
processes: Arc<RwLock<HashMap<ProcessId, Process>>>,
}
impl SshDistantApi {
pub fn new(session: WezSession) -> Self {
Self {
session,
processes: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Checks if the remote server is a Windows machine
async fn is_windows(&self) -> io::Result<bool> {
// We cache the request as it should not change for the lifetime of the ssh connection
static IS_WINDOWS: OnceCell<bool> = OnceCell::new();
// Look up whether the remote system is windows
Ok(*IS_WINDOWS
.get_or_try_init(utils::is_windows(&self.session))
.await?)
}
}
#[async_trait]
impl DistantApi for SshDistantApi {
async fn read_file(&self, ctx: DistantCtx, path: PathBuf) -> io::Result<Vec<u8>> {
debug!(
"[Conn {}] Reading bytes from file {:?}",
ctx.connection_id, path
);
use smol::io::AsyncReadExt;
let mut file = self
.session
.sftp()
.open(path)
.compat()
.await
.map_err(to_other_error)?;
let mut contents = String::new();
file.read_to_string(&mut contents).compat().await?;
Ok(contents.into_bytes())
}
async fn read_file_text(&self, ctx: DistantCtx, path: PathBuf) -> io::Result<String> {
debug!(
"[Conn {}] Reading text from file {:?}",
ctx.connection_id, path
);
use smol::io::AsyncReadExt;
let mut file = self
.session
.sftp()
.open(path)
.compat()
.await
.map_err(to_other_error)?;
let mut contents = String::new();
file.read_to_string(&mut contents).compat().await?;
Ok(contents)
}
async fn write_file(&self, ctx: DistantCtx, path: PathBuf, data: Vec<u8>) -> io::Result<()> {
debug!(
"[Conn {}] Writing bytes to file {:?}",
ctx.connection_id, path
);
use smol::io::AsyncWriteExt;
let mut file = self
.session
.sftp()
.create(path)
.compat()
.await
.map_err(to_other_error)?;
file.write_all(data.as_ref()).compat().await?;
Ok(())
}
async fn write_file_text(
&self,
ctx: DistantCtx,
path: PathBuf,
data: String,
) -> io::Result<()> {
debug!(
"[Conn {}] Writing text to file {:?}",
ctx.connection_id, path
);
use smol::io::AsyncWriteExt;
let mut file = self
.session
.sftp()
.create(path)
.compat()
.await
.map_err(to_other_error)?;
file.write_all(data.as_ref()).compat().await?;
Ok(())
}
async fn append_file(&self, ctx: DistantCtx, path: PathBuf, data: Vec<u8>) -> io::Result<()> {
debug!(
"[Conn {}] Appending bytes to file {:?}",
ctx.connection_id, path
);
use smol::io::AsyncWriteExt;
let mut file = self
.session
.sftp()
.open_with_mode(
path,
OpenOptions {
read: false,
write: Some(WriteMode::Append),
// Using 644 as this mirrors "ssh <host> touch ..."
// 644: rw-r--r--
mode: 0o644,
ty: OpenFileType::File,
},
)
.compat()
.await
.map_err(to_other_error)?;
file.write_all(data.as_ref()).compat().await?;
Ok(())
}
async fn append_file_text(
&self,
ctx: DistantCtx,
path: PathBuf,
data: String,
) -> io::Result<()> {
debug!(
"[Conn {}] Appending text to file {:?}",
ctx.connection_id, path
);
use smol::io::AsyncWriteExt;
let mut file = self
.session
.sftp()
.open_with_mode(
path,
OpenOptions {
read: false,
write: Some(WriteMode::Append),
// Using 644 as this mirrors "ssh <host> touch ..."
// 644: rw-r--r--
mode: 0o644,
ty: OpenFileType::File,
},
)
.compat()
.await
.map_err(to_other_error)?;
file.write_all(data.as_ref()).compat().await?;
Ok(())
}
async fn read_dir(
&self,
ctx: DistantCtx,
path: PathBuf,
depth: usize,
absolute: bool,
canonicalize: bool,
include_root: bool,
) -> io::Result<(Vec<DirEntry>, Vec<io::Error>)> {
debug!(
"[Conn {}] Reading directory {:?} {{depth: {}, absolute: {}, canonicalize: {}, include_root: {}}}",
ctx.connection_id, path, depth, absolute, canonicalize, include_root
);
let sftp = self.session.sftp();
// Canonicalize our provided path to ensure that it is exists, not a loop, and absolute
let root_path = utils::canonicalize(&sftp, path).await?;
// Build up our entry list
let mut entries = Vec::new();
let mut errors: Vec<io::Error> = Vec::new();
let mut to_traverse = vec![DirEntry {
path: root_path.to_path_buf(),
file_type: FileType::Dir,
depth: 0,
}];
while let Some(entry) = to_traverse.pop() {
let is_root = entry.depth == 0;
let next_depth = entry.depth + 1;
let ft = entry.file_type;
let path = if entry.path.is_relative() {
root_path.join(&entry.path)
} else {
entry.path.to_path_buf()
};
// Always include any non-root in our traverse list, but only include the
// root directory if flagged to do so
if !is_root || include_root {
entries.push(entry);
}
let is_dir = match ft {
FileType::Dir => true,
FileType::File => false,
FileType::Symlink => match sftp.metadata(path.to_path_buf()).await {
Ok(metadata) => metadata.is_dir(),
Err(x) => {
errors.push(to_other_error(x));
continue;
}
},
};
// Determine if we continue traversing or stop
if is_dir && (depth == 0 || next_depth <= depth) {
match sftp
.read_dir(path.to_path_buf())
.compat()
.await
.map_err(to_other_error)
{
Ok(entries) => {
for (path, metadata) in entries {
// Canonicalize the path if specified, otherwise just return
// the path as is
let mut path = if canonicalize {
match utils::canonicalize(&sftp, path.as_std_path()).await {
Ok(path) => path,
Err(x) => {
errors.push(to_other_error(x));
continue;
}
}
} else {
path.into_std_path_buf()
};
// Strip the path of its prefix based if not flagged as absolute
if !absolute {
// NOTE: In the situation where we canonicalized the path earlier,
// there is no guarantee that our root path is still the parent of
// the symlink's destination; so, in that case we MUST just return
// the path if the strip_prefix fails
path = path
.strip_prefix(root_path.as_path())
.map(|p| p.to_path_buf())
.unwrap_or(path);
};
// If we canonicalized the path, we also want to refresh our metadata
// on windows since it doesn't reflect the real file type from read_dir
let metadata = if canonicalize {
sftp.metadata(path.to_path_buf())
.compat()
.await
.unwrap_or(metadata)
} else {
metadata
};
let ft = metadata.ty;
to_traverse.push(DirEntry {
path,
file_type: if ft.is_dir() {
FileType::Dir
} else if ft.is_file() {
FileType::File
} else {
FileType::Symlink
},
depth: next_depth,
});
}
}
Err(x) if is_root => return Err(io::Error::new(io::ErrorKind::Other, x)),
Err(x) => errors.push(x),
}
}
}
// Sort entries by filename
entries.sort_unstable_by_key(|e| e.path.to_path_buf());
Ok((entries, errors))
}
async fn create_dir(&self, ctx: DistantCtx, path: PathBuf, all: bool) -> io::Result<()> {
debug!(
"[Conn {}] Creating directory {:?} {{all: {}}}",
ctx.connection_id, path, all
);
let sftp = self.session.sftp();
// Makes the immediate directory, failing if given a path with missing components
async fn mkdir(sftp: &wezterm_ssh::Sftp, path: PathBuf) -> io::Result<()> {
// Using 755 as this mirrors "ssh <host> mkdir ..."
// 755: rwxr-xr-x
sftp.create_dir(path, 0o755)
.compat()
.await
.map_err(to_other_error)
}
if all {
// Keep trying to create a directory, moving up to parent each time a failure happens
let mut failed_paths = Vec::new();
let mut cur_path = path.as_path();
let mut first_err = None;
loop {
match mkdir(&sftp, cur_path.to_path_buf()).await {
Ok(_) => break,
Err(x) => {
failed_paths.push(cur_path);
if let Some(path) = cur_path.parent() {
cur_path = path;
if first_err.is_none() {
first_err = Some(x);
}
} else {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
first_err.unwrap_or(x),
));
}
}
}
}
// Now that we've successfully created a parent component (or the directory), proceed
// to attempt to create each failed directory
while let Some(path) = failed_paths.pop() {
mkdir(&sftp, path.to_path_buf()).await?;
}
} else {
mkdir(&sftp, path).await?;
}
Ok(())
}
async fn remove(&self, ctx: DistantCtx, path: PathBuf, force: bool) -> io::Result<()> {
debug!(
"[Conn {}] Removing {:?} {{force: {}}}",
ctx.connection_id, path, force
);
let sftp = self.session.sftp();
// Determine if we are dealing with a file or directory
let stat = sftp
.metadata(path.to_path_buf())
.compat()
.await
.map_err(to_other_error)?;
// If a file or symlink, we just unlink (easy)
if stat.is_file() || stat.is_symlink() {
sftp.remove_file(path)
.compat()
.await
.map_err(|x| io::Error::new(io::ErrorKind::PermissionDenied, x))?;
// If directory and not forcing, we just rmdir (easy)
} else if !force {
sftp.remove_dir(path)
.compat()
.await
.map_err(|x| io::Error::new(io::ErrorKind::PermissionDenied, x))?;
// Otherwise, we need to find all files and directories, keep track of their depth, and
// then attempt to remove them all
} else {
let mut entries = Vec::new();
let mut to_traverse = vec![DirEntry {
path,
file_type: FileType::Dir,
depth: 0,
}];
// Collect all entries within directory
while let Some(entry) = to_traverse.pop() {
if entry.file_type == FileType::Dir {
let path = entry.path.to_path_buf();
let depth = entry.depth;
entries.push(entry);
for (path, stat) in sftp.read_dir(path).await.map_err(to_other_error)? {
to_traverse.push(DirEntry {
path: path.into_std_path_buf(),
file_type: if stat.is_dir() {
FileType::Dir
} else if stat.is_file() {
FileType::File
} else {
FileType::Symlink
},
depth: depth + 1,
});
}
} else {
entries.push(entry);
}
}
// Sort by depth such that deepest are last as we will be popping
// off entries from end to remove first
entries.sort_unstable_by_key(|e| e.depth);
while let Some(entry) = entries.pop() {
if entry.file_type == FileType::Dir {
sftp.remove_dir(entry.path)
.compat()
.await
.map_err(|x| io::Error::new(io::ErrorKind::PermissionDenied, x))?;
} else {
sftp.remove_file(entry.path)
.compat()
.await
.map_err(|x| io::Error::new(io::ErrorKind::PermissionDenied, x))?;
}
}
}
Ok(())
}
async fn copy(&self, ctx: DistantCtx, src: PathBuf, dst: PathBuf) -> io::Result<()> {
debug!(
"[Conn {}] Copying {:?} to {:?}",
ctx.connection_id, src, dst
);
// NOTE: SFTP does not provide a remote-to-remote copy method, so we instead execute
// a program based on the platform and hope that it applies
let is_windows = self.is_windows().await?;
let output = if is_windows {
utils::powershell_output(
&self.session,
&format!("Copy-Item -Path {src:?} -Destination {dst:?} -Recurse"),
COPY_COMPLETE_TIMEOUT,
)
.await?
} else {
utils::execute_output(
&self.session,
&format!("cp -R {src:?} {dst:?}"),
COPY_COMPLETE_TIMEOUT,
)
.await?
};
// NOTE: For some reason, powershell.exe is not returning an error upon failure, so we
// have to check if we got some stderr as output and consider that a failure
let success = output.success && (!is_windows || output.stderr.is_empty());
if success {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Copy command failed: {}",
String::from_utf8_lossy(&output.stderr)
),
))
}
}
async fn rename(&self, ctx: DistantCtx, src: PathBuf, dst: PathBuf) -> io::Result<()> {
debug!(
"[Conn {}] Renaming {:?} to {:?}",
ctx.connection_id, src, dst
);
self.session
.sftp()
.rename(src, dst, Default::default())
.compat()
.await
.map_err(to_other_error)?;
Ok(())
}
async fn exists(&self, ctx: DistantCtx, path: PathBuf) -> io::Result<bool> {
debug!("[Conn {}] Checking if {:?} exists", ctx.connection_id, path);
// NOTE: SFTP does not provide a means to check if a path exists that can be performed
// separately from getting permission errors; so, we just assume any error means that the path
// does not exist
let exists = self
.session
.sftp()
.symlink_metadata(path)
.compat()
.await
.is_ok();
Ok(exists)
}
async fn metadata(
&self,
ctx: DistantCtx,
path: PathBuf,
canonicalize: bool,
resolve_file_type: bool,
) -> io::Result<Metadata> {
debug!(
"[Conn {}] Reading metadata for {:?} {{canonicalize: {}, resolve_file_type: {}}}",
ctx.connection_id, path, canonicalize, resolve_file_type
);
let sftp = self.session.sftp();
let canonicalized_path = if canonicalize {
Some(utils::canonicalize(&sftp, path.as_path()).await?)
} else {
None
};
let metadata = if resolve_file_type {
sftp.metadata(path).compat().await.map_err(to_other_error)?
} else {
sftp.symlink_metadata(path)
.compat()
.await
.map_err(to_other_error)?
};
let file_type = if metadata.is_dir() {
FileType::Dir
} else if metadata.is_file() {
FileType::File
} else {
FileType::Symlink
};
Ok(Metadata {
canonicalized_path,
file_type,
len: metadata.size.unwrap_or(0),
// Check that owner, group, or other has write permission (if not, then readonly)
readonly: metadata
.permissions
.map(|x| !x.owner_write && !x.group_write && !x.other_write)
.unwrap_or(true),
accessed: metadata.accessed,
modified: metadata.modified,
created: None,
unix: metadata.permissions.as_ref().map(|p| UnixMetadata {
owner_read: p.owner_read,
owner_write: p.owner_write,
owner_exec: p.owner_exec,
group_read: p.group_read,
group_write: p.group_write,
group_exec: p.group_exec,
other_read: p.other_read,
other_write: p.other_write,
other_exec: p.other_exec,
}),
windows: None,
})
}
#[allow(unreachable_code)]
async fn set_permissions(
&self,
ctx: DistantCtx,
path: PathBuf,
permissions: Permissions,
options: SetPermissionsOptions,
) -> io::Result<()> {
debug!(
"[Conn {}] Setting permissions for {:?} {{permissions: {:?}, options: {:?}}}",
ctx.connection_id, path, permissions, options
);
// Unsupported until issue resolved: https://github.com/wez/wezterm/issues/3784
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"Unsupported until issue resolved: https://github.com/wez/wezterm/issues/3784",
));
let sftp = self.session.sftp();
macro_rules! set_permissions {
($path:ident, $metadata:ident) => {{
let mut current = Permissions::from_unix_mode(
$metadata
.permissions
.ok_or_else(|| to_other_error("Unable to read file permissions"))?
.to_unix_mode(),
);
current.apply_from(&permissions);
$metadata.permissions =
Some(FilePermissions::from_unix_mode(current.to_unix_mode()));
println!("set_metadata for {:?}", $path.as_path());
sftp.set_metadata($path.as_path(), $metadata)
.compat()
.await
.map_err(to_other_error)?;
if $metadata.is_dir() {
Some($path)
} else {
None
}
}};
($path:ident) => {{
let mut path = Utf8PathBuf::try_from($path).map_err(to_other_error)?;
// Query metadata to determine if we are working with a symlink
println!("symlink_metadata for {:?}", path);
let mut metadata = sftp
.symlink_metadata(&path)
.compat()
.await
.map_err(to_other_error)?;
// If we are excluding symlinks and this is a symlink, then we're done
if options.exclude_symlinks && metadata.is_symlink() {
None
} else {
// If we are following symlinks and this is a symlink, then get the real path
// and destination metadata
if options.follow_symlinks && metadata.is_symlink() {
println!("read_link for {:?}", path);
path = sftp
.read_link(path)
.compat()
.await
.map_err(to_other_error)?;
println!("metadata for {:?}", path);
metadata = sftp
.metadata(&path)
.compat()
.await
.map_err(to_other_error)?;
}
set_permissions!(path, metadata)
}
}};
}
let mut paths = VecDeque::new();
// Queue up our path if it is a directory
if let Some(path) = set_permissions!(path) {
paths.push_back(path);
}
if options.recursive {
while let Some(path) = paths.pop_front() {
println!("read_dir for {:?}", path);
let paths_and_metadata =
sftp.read_dir(path).compat().await.map_err(to_other_error)?;
for (mut path, mut metadata) in paths_and_metadata {
if options.exclude_symlinks && metadata.is_symlink() {
println!("skipping symlink for {:?}", path);
continue;
}
// If we are following symlinks, then adjust our path and metadata
if options.follow_symlinks && metadata.is_symlink() {
println!("read_link for {:?}", path);
path = sftp
.read_link(path)
.compat()
.await
.map_err(to_other_error)?;
println!("metadata for {:?}", path);
metadata = sftp
.metadata(&path)
.compat()
.await
.map_err(to_other_error)?;
}
if let Some(path) = set_permissions!(path, metadata) {
paths.push_back(path);
}
}
}
}
Ok(())
}
async fn proc_spawn(
&self,
ctx: DistantCtx,
cmd: String,
environment: Environment,
current_dir: Option<PathBuf>,
pty: Option<PtySize>,
) -> io::Result<ProcessId> {
debug!(
"[Conn {}] Spawning {} {{environment: {:?}, current_dir: {:?}, pty: {:?}}}",
ctx.connection_id, cmd, environment, current_dir, pty
);
let global_processes = Arc::downgrade(&self.processes);
let cleanup = |id: ProcessId| async move {
if let Some(processes) = Weak::upgrade(&global_processes) {
processes.write().await.remove(&id);
}
};
let SpawnResult {
id,
stdin,
killer,
resizer,
} = match pty {
None => {
spawn_simple(
&self.session,
&cmd,
environment,
current_dir,
ctx.reply.clone_reply(),
cleanup,
)
.await?
}
Some(size) => {
spawn_pty(
&self.session,
&cmd,
environment,
current_dir,
size,
ctx.reply.clone_reply(),
cleanup,
)
.await?
}
};
self.processes.write().await.insert(
id,
Process {
stdin_tx: stdin,
kill_tx: killer,
resize_tx: resizer,
},
);
debug!(
"[Conn {}] Spawned process {} successfully!",
ctx.connection_id, id
);
Ok(id)
}
async fn proc_kill(&self, ctx: DistantCtx, id: ProcessId) -> io::Result<()> {
debug!("[Conn {}] Killing process {}", ctx.connection_id, id);
if let Some(process) = self.processes.read().await.get(&id) {
if process.kill_tx.send(()).await.is_ok() {
return Ok(());
}
}
Err(io::Error::new(
io::ErrorKind::BrokenPipe,
format!(
"[Conn {}] Unable to send kill signal to process {}",
ctx.connection_id, id
),
))
}
async fn proc_stdin(&self, ctx: DistantCtx, id: ProcessId, data: Vec<u8>) -> io::Result<()> {
debug!(
"[Conn {}] Sending stdin to process {}",
ctx.connection_id, id
);
if let Some(process) = self.processes.read().await.get(&id) {
if process.stdin_tx.send(data).await.is_ok() {
return Ok(());
}
}
Err(io::Error::new(
io::ErrorKind::BrokenPipe,
format!(
"[Conn {}] Unable to send stdin to process {}",
ctx.connection_id, id
),
))
}
async fn proc_resize_pty(
&self,
ctx: DistantCtx,
id: ProcessId,
size: PtySize,
) -> io::Result<()> {
debug!(
"[Conn {}] Resizing pty of process {} to {}",
ctx.connection_id, id, size
);
if let Some(process) = self.processes.read().await.get(&id) {
if process.resize_tx.send(size).await.is_ok() {
return Ok(());
}
}
Err(io::Error::new(
io::ErrorKind::BrokenPipe,
format!(
"[Conn {}] Unable to resize process {}",
ctx.connection_id, id
),
))
}
async fn system_info(&self, ctx: DistantCtx) -> io::Result<SystemInfo> {
// We cache each of these requested values since they should not change for the
// lifetime of the ssh connection
static CURRENT_DIR: OnceCell<PathBuf> = OnceCell::new();
static USERNAME: OnceCell<String> = OnceCell::new();
static SHELL: OnceCell<String> = OnceCell::new();
debug!("[Conn {}] Reading system information", ctx.connection_id);
// Look up whether the remote system is windows
let is_windows = self.is_windows().await?;
// Look up the current directory
let current_dir = CURRENT_DIR
.get_or_try_init(async move {
let current_dir: PathBuf = utils::canonicalize(&self.session.sftp(), ".").await?;
// If windows, we need to see if we got a weird directory from ssh in the form of
// /C:/... or /C/... as examples. Easiest way is to convert into a WindowsPath,
// check if the first component is a root dir, and then make a new windows path to
// see if it now starts with a prefix.
let current_dir: PathBuf = current_dir
.to_str()
.and_then(utils::convert_to_windows_path_string)
.map(PathBuf::from)
.unwrap_or(current_dir);
Result::<_, io::Error>::Ok(current_dir)
})
.await?
.clone();
// Look up username and shell
let username = USERNAME
.get_or_try_init(utils::query_username(&self.session, is_windows))
.await?
.clone();
let shell = SHELL
.get_or_try_init(utils::query_shell(&self.session, is_windows))
.await?
.clone();
Ok(SystemInfo {
family: if is_windows { "windows" } else { "unix" }.to_string(),
os: if is_windows { "windows" } else { "" }.to_string(),
arch: "".to_string(),
current_dir,
main_separator: if is_windows { '\\' } else { '/' },
username,
shell,
})
}
async fn version(&self, ctx: DistantCtx) -> io::Result<Version> {
debug!("[Conn {}] Querying capabilities", ctx.connection_id);
let capabilities = vec![
Version::CAP_EXEC.to_string(),
Version::CAP_FS_IO.to_string(),
Version::CAP_SYS_INFO.to_string(),
];
// Parse our server's version
let mut server_version: semver::Version = env!("CARGO_PKG_VERSION")
.parse()
.map_err(|x| io::Error::new(io::ErrorKind::Other, x))?;
// Add the package name to the version information
if server_version.build.is_empty() {
server_version.build = semver::BuildMetadata::new(env!("CARGO_PKG_NAME"))
.map_err(|x| io::Error::new(io::ErrorKind::Other, x))?;
} else {
let raw_build_str = format!(
"{}.{}",
server_version.build.as_str(),
env!("CARGO_PKG_NAME")
);
server_version.build = semver::BuildMetadata::new(&raw_build_str)
.map_err(|x| io::Error::new(io::ErrorKind::Other, x))?;
}
Ok(Version {
server_version,
protocol_version: PROTOCOL_VERSION,
capabilities,
})
}
}