-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbrowser.py
More file actions
1837 lines (1663 loc) · 63.9 KB
/
Copy pathbrowser.py
File metadata and controls
1837 lines (1663 loc) · 63.9 KB
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Curses-based SMB share browser and file viewer."""
from __future__ import annotations
import curses
import fnmatch
import ntpath
import re
import textwrap
from pathlib import Path
from cursor_position import CursorPosition
from keyboard import KeyboardInputMixin
from protocol import RemoteEntry, SmbClient, SmbError, TreeFile, UploadCancelled
DISPLAY_CONFIRM_THRESHOLD = 1024 * 1024
SESSION_ERROR_MARKER = "SMB SessionError"
SESSION_ERROR_COLOR_PAIR = 1
SENSITIVE_FILE_COLOR_PAIR = 2
MODE_LIVE_COLOR_PAIR = 3
MODE_OPSEC_COLOR_PAIR = 4
GREP_MATCH_COLOR_PAIR = 5
GREP_SELECTED_MATCH_COLOR_PAIR = 6
MODES = ("LIVE", "OPSEC")
SENSITIVE_FILENAME_MARKERS = (
"_history",
".cert",
".dmp",
".kdbx",
".ova",
".pem",
".ppk",
".vmdk",
"password",
"passwd",
"id_rsa",
"web.config",
)
HELP_CONTENT = """Keyboard shortcuts
[UP]/[k] Move up
[DOWN]/[j] Move down
[PAGE UP] Move up one screen
[PAGE DOWN] Move down one screen
[HOME]/[g] Jump to the beginning
[END]/[G] Jump to the end
[ENTER] Open the selected item
[BACKSPACE] Return to the parent or previous view
[d] Download the selected file
[SUPPR] Delete the selected or open file
[/] Open the command prompt
[h] Display this help
[r] Refresh the browser listing
[m] Toggle between LIVE and OPSEC modes
[n] Jump to the next /grep match in a file preview
[ESC]/[q] Close the viewer; [q] quits from the browser
Commands
/get [<filename>] Download the selected/open file or a named file
/download, /dl Aliases for /get
/put <local-path> Upload a local file to the current directory
/upload <local-path>
Alias for /put
/filter <pattern> Filter the current listing by regex or glob
/filter Clear the active filter
/refresh Refetch the current directory and update the cache
/mode <mode> Switch to LIVE or OPSEC mode
/grep <regex> Highlight regex matches in the open file preview
/grep Clear preview match highlighting
/tree Open an interactive recursive file listing
/tree_download Recursively download the current directory
/rm [<filename>] Delete the selected/open file or a named file
/delete [<filename>]
Alias for /rm
/mkdir <directory> Create a directory in the current directory
/rmdir [<directory>]
Remove a selected/named empty directory
/help Display this help
/exit, /quit Exit SMBLoot
Preview option
--auto-loot-preview Automatically download each successfully previewed file
--highlight-sensitive-files Display potentially sensitive files in orange
"""
class SmbBrowser(KeyboardInputMixin):
def __init__(
self,
screen: curses.window,
client: SmbClient,
start_share: str | None = None,
start_path: str = "",
loot_dir: str = "loot",
*,
auto_loot_preview: bool = False,
highlight_sensitive_files: bool = True,
mode: str = "LIVE",
tree_workers: int = 4,
) -> None:
self.screen = screen
self.client = client
self.loot_dir = Path(loot_dir).expanduser().resolve()
self.auto_loot_preview = auto_loot_preview
self.highlight_sensitive_files = highlight_sensitive_files
self.mode = mode.upper()
if self.mode not in MODES:
raise ValueError(f"mode must be one of: {', '.join(MODES)}")
if not 1 <= tree_workers <= 16:
raise ValueError("tree_workers must be between 1 and 16")
self.tree_workers = tree_workers
self.share = start_share or None
self.path = self._normalise_path(start_path) if self.share else ""
self.all_entries: list[RemoteEntry] = []
self.entries: list[RemoteEntry] = []
self.selected = 0
self.top = 0
self.cursor_positions: dict[tuple[str | None, str], CursorPosition] = {}
self.filter_pattern = ""
self.filter_regex: re.Pattern[str] | None = None
self.filter_kind = ""
self.grep_pattern = ""
self.grep_regex: re.Pattern[str] | None = None
self.grep_match_index = -1
self.entry_cache: dict[
tuple[str | None, str],
list[RemoteEntry],
] = {}
self.status = "Loading..."
self.view_path: str | None = None
self.view_content = ""
self.view_size = 0
self.view_top = 0
self.view_kind = "File"
self.view_share: str | None = None
self.view_remote_path: str | None = None
self.view_status = ""
self.tree_files: list[TreeFile] = []
self.tree_errors: list[str] = []
self.tree_selected = 0
self.exit_requested = False
self.help_return_view: (
tuple[
str,
str,
int,
int,
str,
str | None,
str | None,
str,
list[TreeFile],
list[str],
int,
]
| None
) = None
self.session_error_attr = curses.A_BOLD
self.sensitive_file_attr = curses.A_BOLD
self.live_mode_attr = curses.A_BOLD
self.opsec_mode_attr = curses.A_BOLD
self.grep_match_attr = curses.A_REVERSE | curses.A_BOLD
self.grep_selected_match_attr = (
curses.A_REVERSE | curses.A_BOLD | curses.A_UNDERLINE
)
@staticmethod
def _normalise_path(path: str) -> str:
path = ntpath.normpath((path or "").replace("/", "\\"))
return "" if path == "." else path.strip("\\")
@property
def location(self) -> str:
return self.client.unc_path(self.share, self.path)
@property
def _location_key(self) -> tuple[str | None, str]:
return self.share, self.path
def _remember_cursor(self) -> None:
selected_name = None
if 0 <= self.selected < len(self.entries):
selected_name = self.entries[self.selected].name
self.cursor_positions[self._location_key] = CursorPosition(
selected_name=selected_name,
selected_index=self.selected,
row_offset=max(0, self.selected - self.top),
)
def _restore_cursor(self) -> None:
position = self.cursor_positions.get(self._location_key)
if position is None or not self.entries:
return
selected = min(position.selected_index, len(self.entries) - 1)
if position.selected_name is not None:
selected_name = position.selected_name.casefold()
selected = next(
(
index
for index, entry in enumerate(self.entries)
if entry.name.casefold() == selected_name
),
selected,
)
body_height = max(1, self.screen.getmaxyx()[0] - 3)
row_offset = min(position.row_offset, body_height - 1)
max_top = max(0, len(self.entries) - body_height)
self.selected = selected
self.top = max(0, min(selected - row_offset, max_top))
def _safe_addstr(
self, row: int, col: int, text: str, attr: int = curses.A_NORMAL
) -> None:
height, width = self.screen.getmaxyx()
if row < 0 or row >= height or col >= width or width <= 0:
return
try:
self.screen.addnstr(row, col, text, max(0, width - col - 1), attr)
except curses.error:
pass
def _draw_bar(self, row: int, text: str, attr: int) -> None:
_, width = self.screen.getmaxyx()
self._safe_addstr(row, 0, text.ljust(max(0, width - 1)), attr)
@staticmethod
def _is_session_error(message: str) -> bool:
return SESSION_ERROR_MARKER.casefold() in message.casefold()
def _message_attr(self, message: str, default: int) -> int:
if self._is_session_error(message):
return self.session_error_attr
return default
def _initialise_colors(self) -> None:
try:
curses.start_color()
try:
curses.use_default_colors()
background = -1
except curses.error:
background = curses.COLOR_BLACK
curses.init_pair(
SESSION_ERROR_COLOR_PAIR,
curses.COLOR_RED,
background,
)
self.session_error_attr = (
curses.color_pair(SESSION_ERROR_COLOR_PAIR) | curses.A_BOLD
)
orange = 208 if getattr(curses, "COLORS", 0) >= 256 else curses.COLOR_YELLOW
curses.init_pair(
SENSITIVE_FILE_COLOR_PAIR,
orange,
background,
)
self.sensitive_file_attr = curses.color_pair(SENSITIVE_FILE_COLOR_PAIR)
curses.init_pair(
MODE_LIVE_COLOR_PAIR,
curses.COLOR_RED,
background,
)
self.live_mode_attr = (
curses.color_pair(MODE_LIVE_COLOR_PAIR) | curses.A_BOLD
)
curses.init_pair(
MODE_OPSEC_COLOR_PAIR,
curses.COLOR_GREEN,
background,
)
self.opsec_mode_attr = (
curses.color_pair(MODE_OPSEC_COLOR_PAIR) | curses.A_BOLD
)
curses.init_pair(
GREP_MATCH_COLOR_PAIR,
curses.COLOR_BLACK,
curses.COLOR_YELLOW,
)
self.grep_match_attr = (
curses.color_pair(GREP_MATCH_COLOR_PAIR) | curses.A_BOLD
)
curses.init_pair(
GREP_SELECTED_MATCH_COLOR_PAIR,
curses.COLOR_BLACK,
curses.COLOR_CYAN,
)
self.grep_selected_match_attr = (
curses.color_pair(GREP_SELECTED_MATCH_COLOR_PAIR) | curses.A_BOLD
)
except curses.error:
pass
def _mode_badge(self) -> tuple[str, int]:
if self.mode == "LIVE":
return "[LIVE]", self.live_mode_attr
return "[OPSEC]", self.opsec_mode_attr
def _draw_mode_badge(self) -> None:
_, width = self.screen.getmaxyx()
badge, attr = self._mode_badge()
self._safe_addstr(0, max(0, width - len(badge) - 1), badge, attr)
def _draw_header(self, text: str) -> None:
self._draw_bar(0, text, curses.A_REVERSE)
self._draw_mode_badge()
def _set_mode(self, mode: str) -> None:
normalised_mode = mode.upper()
if normalised_mode not in MODES:
raise ValueError(f"mode must be one of: {', '.join(MODES)}")
self.mode = normalised_mode
if self._entry_cache_key not in self.entry_cache:
self.entry_cache[self._entry_cache_key] = list(self.all_entries)
message = f"Mode changed to {self.mode}"
if self.view_path is None:
self.status = message
else:
self.view_status = message
def _toggle_mode(self) -> None:
self._set_mode("OPSEC" if self.mode == "LIVE" else "LIVE")
@staticmethod
def _is_sensitive_filename(filename: str) -> bool:
folded_name = filename.casefold()
return any(marker in folded_name for marker in SENSITIVE_FILENAME_MARKERS)
def _file_attr(self, filename: str, *, selected: bool) -> int:
attr = curses.A_REVERSE if selected else curses.A_NORMAL
if self.highlight_sensitive_files and self._is_sensitive_filename(filename):
attr |= self.sensitive_file_attr
return attr
@staticmethod
def _compile_filter(pattern: str) -> tuple[re.Pattern[str], str]:
try:
return re.compile(pattern, re.IGNORECASE), "regex"
except re.error:
if not any(character in pattern for character in "*?["):
raise
return re.compile(fnmatch.translate(pattern), re.IGNORECASE), "glob"
def _filter_entries(self) -> list[RemoteEntry]:
if self.filter_regex is None:
return list(self.all_entries)
return [
entry
for entry in self.all_entries
if entry.is_parent or self.filter_regex.search(entry.name)
]
def _listing_counts(self) -> tuple[int, int, str]:
parent_count = sum(entry.is_parent for entry in self.all_entries)
visible_parent_count = sum(entry.is_parent for entry in self.entries)
total = len(self.all_entries) - parent_count
visible = len(self.entries) - visible_parent_count
return visible, total, "shares" if self.share is None else "entries"
@staticmethod
def _folder_file_counts(entries: list[RemoteEntry]) -> tuple[int, int]:
folders = sum(
entry.is_directory and not entry.is_parent and not entry.is_share
for entry in entries
)
files = sum(
not entry.is_directory and not entry.is_parent and not entry.is_share
for entry in entries
)
return folders, files
@staticmethod
def _format_item_counts(
file_count: int,
*,
folder_count: int | None = None,
total_file_count: int | None = None,
total_folder_count: int | None = None,
) -> str:
def count_text(count: int, total: int | None, noun: str) -> str:
amount = str(count) if total is None else f"{count}/{total}"
suffix = "" if count == 1 and total is None else "s"
return f"{amount} {noun}{suffix}"
parts: list[str] = []
if folder_count is not None:
parts.append(count_text(folder_count, total_folder_count, "folder"))
parts.append(count_text(file_count, total_file_count, "file"))
return ", ".join(parts)
def _listing_status(self) -> str:
visible, total, noun = self._listing_counts()
if self.share is not None:
visible_folders, visible_files = self._folder_file_counts(self.entries)
total_folders, total_files = self._folder_file_counts(self.all_entries)
if self.filter_regex is None:
return self._format_item_counts(
visible_files,
folder_count=visible_folders,
)
counts = self._format_item_counts(
visible_files,
folder_count=visible_folders,
total_file_count=total_files,
total_folder_count=total_folders,
)
return f"{counts} ({self.filter_kind} filter: {self.filter_pattern})"
if self.filter_regex is None:
return f"{total} {noun}"
return (
f"{visible}/{total} {noun} "
f"({self.filter_kind} filter: {self.filter_pattern})"
)
def _set_filter(self, pattern: str) -> None:
selected_name = None
if 0 <= self.selected < len(self.entries):
selected_name = self.entries[self.selected].name
if pattern:
try:
compiled, kind = self._compile_filter(pattern)
except re.error as exc:
self.status = f"Invalid filter regex: {exc}"
return
self.filter_pattern = pattern
self.filter_regex = compiled
self.filter_kind = kind
else:
self.filter_pattern = ""
self.filter_regex = None
self.filter_kind = ""
self.entries = self._filter_entries()
self.selected = 0
self.top = 0
if selected_name is not None:
selected_folded = selected_name.casefold()
self.selected = next(
(
index
for index, entry in enumerate(self.entries)
if entry.name.casefold() == selected_folded
),
0,
)
self.status = self._listing_status()
def _draw_browser(self) -> None:
height, _ = self.screen.getmaxyx()
self._draw_header(f" SMB browser {self.location}")
body_height = max(1, height - 3)
self.top = min(self.top, self.selected)
if self.selected >= self.top + body_height:
self.top = self.selected - body_height + 1
for row, index in enumerate(
range(self.top, min(len(self.entries), self.top + body_height)), 1
):
entry = self.entries[index]
prefix = (
" s " if entry.is_share else " d " if entry.is_directory else " f "
)
if entry.is_directory:
attr = (
curses.A_REVERSE
if index == self.selected
else curses.A_NORMAL | curses.A_BOLD
)
else:
attr = self._file_attr(entry.name, selected=index == self.selected)
self._safe_addstr(row, 0, prefix + entry.label, attr)
if not self.entries:
self._safe_addstr(2, 2, "(no entries)")
self._draw_bar(
height - 2,
" [UP]/[DOWN] move [ENTER] open [d] download "
"[SUPPR] delete [/] commands [m] mode [h] help [q] quit",
curses.A_REVERSE,
)
self._draw_bar(
height - 1,
f" {self.status}",
self._message_attr(self.status, curses.A_DIM),
)
def _wrapped_content(self, width: int) -> list[str]:
wrap_width = max(1, width - 1)
result: list[str] = []
for line in self.view_content.expandtabs(4).split("\n"):
result.extend(
textwrap.wrap(
line,
width=wrap_width,
replace_whitespace=False,
drop_whitespace=False,
break_long_words=True,
break_on_hyphens=False,
)
or [""]
)
return result
def _draw_preview_line(
self,
row: int,
line: str,
matches: list[tuple[int, int, int]] | None = None,
) -> None:
if self.grep_regex is None:
self._safe_addstr(row, 0, line, curses.A_NORMAL)
return
if matches is None:
matches = [
(index, match.start(), match.end())
for index, match in enumerate(self.grep_regex.finditer(line))
if match.end() > match.start()
]
column = 0
for match_index, start, end in matches:
if start > column:
self._safe_addstr(
row,
column,
line[column:start],
curses.A_NORMAL,
)
self._safe_addstr(
row,
start,
line[start:end],
(
self.grep_selected_match_attr
if match_index == self.grep_match_index
else self.grep_match_attr
),
)
column = end
if column < len(line):
self._safe_addstr(row, column, line[column:], curses.A_NORMAL)
def _set_grep(self, pattern: str) -> None:
if self.view_kind != "File":
self.view_status = "/grep is only available in a file preview"
return
if not pattern:
self.grep_pattern = ""
self.grep_regex = None
self.view_status = "Grep highlighting cleared"
return
try:
compiled = re.compile(pattern, re.IGNORECASE)
except re.error as exc:
self.view_status = f"Invalid grep regex: {exc}"
return
self.grep_pattern = pattern
self.grep_regex = compiled
match_lines = self._grep_match_lines()
if match_lines:
self.grep_match_index = 0
self._jump_to_grep_match(match_lines)
else:
self.grep_match_index = -1
self.view_status = f"Grep: 0 matches for {pattern!r}"
def _grep_matches(
self,
lines: list[str] | None = None,
) -> list[tuple[int, int, int]]:
if self.grep_regex is None:
return []
if lines is None:
_, width = self.screen.getmaxyx()
lines = self._wrapped_content(width)
matches: list[tuple[int, int, int]] = []
for line_index, line in enumerate(lines):
matches.extend(
(line_index, match.start(), match.end())
for match in self.grep_regex.finditer(line)
if match.end() > match.start()
)
return matches
def _grep_match_lines(self) -> list[int]:
return [line_index for line_index, _, _ in self._grep_matches()]
def _jump_to_grep_match(self, match_lines: list[int]) -> None:
height, _ = self.screen.getmaxyx()
body_height = max(1, height - 3)
match_line = match_lines[self.grep_match_index]
self.view_top = max(0, match_line - body_height // 2)
self.view_status = (
f"Grep: match {self.grep_match_index + 1}/{len(match_lines)} "
f"for {self.grep_pattern!r}"
)
def _next_grep_match(self) -> None:
if self.grep_regex is None:
self.view_status = "No active grep; use /grep <regex>"
return
match_lines = self._grep_match_lines()
if not match_lines:
self.grep_match_index = -1
self.view_status = f"Grep: 0 matches for {self.grep_pattern!r}"
return
self.grep_match_index = (self.grep_match_index + 1) % len(match_lines)
self._jump_to_grep_match(match_lines)
def _clear_grep(self) -> None:
self.grep_pattern = ""
self.grep_regex = None
self.grep_match_index = -1
def _draw_viewer(self) -> None:
if self.view_kind == "Tree":
self._draw_tree_viewer()
return
height, width = self.screen.getmaxyx()
assert self.view_path is not None
lines = self._wrapped_content(width)
body_height = max(1, height - 3)
max_top = max(0, len(lines) - body_height)
self.view_top = max(0, min(self.view_top, max_top))
self._draw_header(f" {self.view_kind} {self.view_path}")
grep_matches_by_line: dict[int, list[tuple[int, int, int]]] = {}
if self.view_kind == "File":
for match_index, (line_index, start, end) in enumerate(
self._grep_matches(lines)
):
grep_matches_by_line.setdefault(line_index, []).append(
(match_index, start, end)
)
visible_lines = lines[self.view_top : self.view_top + body_height]
for offset, line in enumerate(visible_lines):
row = offset + 1
line_index = self.view_top + offset
if self.view_kind == "File":
self._draw_preview_line(
row,
line,
grep_matches_by_line.get(line_index, []),
)
else:
attr = self._message_attr(line, curses.A_NORMAL)
self._safe_addstr(row, 0, line, attr)
percent = 100 if not max_top else int(100 * self.view_top / max_top)
if self.view_kind == "Help":
self._draw_bar(
height - 2,
f" [UP]/[DOWN] scroll [ESC]/[q] back {percent:3d}%",
curses.A_REVERSE,
)
self._draw_bar(height - 1, f" {self.view_status}", curses.A_DIM)
else:
self._draw_bar(
height - 2,
f" [UP]/[DOWN] scroll [n] next match [SUPPR] delete "
f"/get /put [TAB] "
f"[ESC]/[q] back {percent:3d}%",
curses.A_REVERSE,
)
status = f" {self.view_status}" if self.view_status else ""
self._draw_bar(
height - 1,
f" {self.view_size} bytes{status}",
self._message_attr(self.view_status, curses.A_DIM),
)
def _tree_display_lines(self) -> list[tuple[str, int | None]]:
lines: list[tuple[str, int | None]] = [
(
(
f"{self._format_item_counts(len(self.tree_files))}, "
f"{SmbClient._format_size(self.view_size)} total"
),
None,
),
("", None),
]
lines.extend(
(
(
f"{SmbClient._format_size(item.size):>10} "
f"{item.date} "
f"{self._relative_tree_path(item.path)}"
),
index,
)
for index, item in enumerate(self.tree_files)
)
if not self.tree_files:
lines.append(("(no files)", None))
if self.tree_errors:
lines.extend(
[
("", None),
(f"Errors ({len(self.tree_errors)}):", None),
*((error, None) for error in self.tree_errors),
]
)
return lines
def _draw_tree_viewer(self) -> None:
height, _ = self.screen.getmaxyx()
assert self.view_path is not None
lines = self._tree_display_lines()
body_height = max(1, height - 3)
selected_line = 2 + self.tree_selected if self.tree_files else 0
if selected_line < self.view_top:
self.view_top = selected_line
elif selected_line >= self.view_top + body_height:
self.view_top = selected_line - body_height + 1
max_top = max(0, len(lines) - body_height)
self.view_top = max(0, min(self.view_top, max_top))
self._draw_header(f" Tree {self.view_path}")
visible = lines[self.view_top : self.view_top + body_height]
for row, (line, file_index) in enumerate(visible, 1):
attr = self._message_attr(line, curses.A_NORMAL)
if file_index is not None and self.highlight_sensitive_files:
filename = ntpath.basename(self.tree_files[file_index].path)
if self._is_sensitive_filename(filename):
attr |= self.sensitive_file_attr
if file_index == self.tree_selected:
attr |= curses.A_REVERSE
self._safe_addstr(row, 0, line, attr)
self._draw_bar(
height - 2,
" [UP]/[DOWN] select [ENTER] open [d] download "
"[SUPPR] delete [h] help [ESC]/[q] back",
curses.A_REVERSE,
)
self._draw_bar(
height - 1,
f" {self.view_status}",
self._message_attr(self.view_status, curses.A_DIM),
)
def draw(self) -> None:
self.screen.erase()
if self.view_path is None:
self._draw_browser()
else:
self._draw_viewer()
self.screen.refresh()
def _show_help(self) -> None:
if self.view_kind == "Help":
self.view_top = 0
return
if self.view_path is not None:
self.help_return_view = (
self.view_path,
self.view_content,
self.view_size,
self.view_top,
self.view_kind,
self.view_share,
self.view_remote_path,
self.view_status,
list(self.tree_files),
list(self.tree_errors),
self.tree_selected,
)
else:
self.help_return_view = None
self.view_path = "Commands and keyboard shortcuts"
self.view_content = HELP_CONTENT
self.view_size = 0
self.view_top = 0
self.view_kind = "Help"
self.view_share = None
self.view_remote_path = None
self.view_status = "Press [ESC], [BACKSPACE], or [q] to return"
self.tree_files = []
self.tree_errors = []
self.tree_selected = 0
def _close_viewer(self) -> None:
if self.view_kind == "Help" and self.help_return_view is not None:
(
self.view_path,
self.view_content,
self.view_size,
self.view_top,
self.view_kind,
self.view_share,
self.view_remote_path,
self.view_status,
self.tree_files,
self.tree_errors,
self.tree_selected,
) = self.help_return_view
self.help_return_view = None
return
self.view_path = None
self.view_content = ""
self.view_size = 0
self.view_top = 0
self.view_kind = "File"
self.view_share = None
self.view_remote_path = None
self.view_status = ""
self._clear_grep()
self.tree_files = []
self.tree_errors = []
self.tree_selected = 0
self.help_return_view = None
@property
def _entry_cache_key(self) -> tuple[str | None, str]:
return self._make_entry_cache_key(self.share, self.path)
@staticmethod
def _make_entry_cache_key(
share: str | None,
path: str,
) -> tuple[str | None, str]:
share = share.casefold() if share is not None else None
path = ntpath.normcase(ntpath.normpath(path or "."))
return share, path
def _show_cached_entries_if_current(
self,
cache_key: tuple[str | None, str],
) -> None:
if cache_key != self._entry_cache_key:
return
self.all_entries = list(self.entry_cache[cache_key])
self.entries = self._filter_entries()
self.selected = min(self.selected, max(0, len(self.entries) - 1))
def _upsert_cached_entry(
self,
share: str,
directory: str,
entry: RemoteEntry,
) -> None:
cache_key = self._make_entry_cache_key(share, directory)
cached_entries = list(self.entry_cache.get(cache_key, self.all_entries))
folded_name = entry.name.casefold()
cached_entries = [
cached
for cached in cached_entries
if cached.is_parent or cached.name.casefold() != folded_name
]
cached_entries.append(entry)
cached_entries.sort(
key=lambda cached: (
not cached.is_parent,
not cached.is_directory,
cached.name.casefold(),
)
)
self.entry_cache[cache_key] = cached_entries
self._show_cached_entries_if_current(cache_key)
def _remove_cached_entry(self, share: str, remote_path: str) -> None:
directory = ntpath.dirname(remote_path)
filename = ntpath.basename(remote_path).casefold()
cache_key = self._make_entry_cache_key(share, directory)
cached_entries = self.entry_cache.get(cache_key)
if cached_entries is None:
return
self.entry_cache[cache_key] = [
entry
for entry in cached_entries
if entry.is_parent or entry.name.casefold() != filename
]
self._show_cached_entries_if_current(cache_key)
def _discard_cached_subtree(self, share: str, path: str) -> None:
subtree_key = self._make_entry_cache_key(share, path)
subtree_share, subtree_path = subtree_key
prefix = subtree_path + "\\"
for cache_key in list(self.entry_cache):
cached_share, cached_path = cache_key
if cached_share == subtree_share and (
cached_path == subtree_path or cached_path.startswith(prefix)
):
del self.entry_cache[cache_key]
def refresh(self, *, force: bool = False) -> None:
self.status = f"Reading {self.location}..."
self.draw()
try:
cache_key = self._entry_cache_key
cached_entries = self.entry_cache.get(cache_key)
if self.mode == "OPSEC" and not force and cached_entries is not None:
self.all_entries = list(cached_entries)
else:
if self.share is None:
self.all_entries = self.client.list_shares()
else:
self.all_entries = [
RemoteEntry("..", True, is_parent=True),
*self.client.list_directory(self.share, self.path),
]
self.entry_cache[cache_key] = list(self.all_entries)
self.entries = self._filter_entries()
self.selected = min(self.selected, max(0, len(self.entries) - 1))
self.status = self._listing_status()
except SmbError as exc:
self.all_entries = []
self.entries = []
self.selected = 0
self.status = f"Error: {exc}"
def _parent(self) -> None:
if self.share is None:
return
self._remember_cursor()
if self.path:
self.path = ntpath.dirname(self.path)
else:
self.share = None
self.selected = self.top = 0
self.refresh()
self._restore_cursor()
def _open_selected(self) -> None:
if not self.entries:
return
entry = self.entries[self.selected]
if entry.is_parent:
self._parent()
return
if entry.is_share:
old_share = self.share
old_path = self.path
old_all_entries = self.all_entries
old_entries = self.entries
old_selected = self.selected
old_top = self.top
self._remember_cursor()
self.share = entry.name
self.path = ""
self.selected = self.top = 0
self.refresh()
if not self.entries and self.status.startswith("Error:"):
self.share = old_share
self.path = old_path
self.all_entries = old_all_entries
self.entries = old_entries
self.selected = old_selected
self.top = old_top
else:
self._restore_cursor()
return
assert self.share is not None
destination = ntpath.join(self.path, entry.name) if self.path else entry.name
if entry.is_directory:
old_path = self.path
old_all_entries = self.all_entries
old_entries = self.entries
old_selected = self.selected
old_top = self.top
self._remember_cursor()
self.path = destination
self.selected = self.top = 0
self.refresh()
if not self.entries and self.status.startswith("Error:"):
self.path = old_path
self.all_entries = old_all_entries
self.entries = old_entries
self.selected = old_selected
self.top = old_top
else:
self._restore_cursor()
return
view_path = self.client.unc_path(self.share, destination)
if (
entry.size is not None
and entry.size > DISPLAY_CONFIRM_THRESHOLD
and not self._confirm_large_display(view_path, entry.size)
):
self.status = "Display cancelled; file was not read"
return
self.status = f"Reading {view_path}..."