-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
1514 lines (1302 loc) · 65.8 KB
/
main.py
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
import base64
import configparser
import io
import locale
import msvcrt
import os
import random
import re
import signal
import socket
import subprocess
import sys
import time
import traceback
import urllib.parse
from ctypes import byref, cast, sizeof, create_unicode_buffer
from ctypes.wintypes import LPWSTR, HKEY, POINT
from winapp.const import *
from winapp.wintypes_extended import *
from winapp.dlls import advapi32, kernel32, user32
from winapp.mainwin import MainWin, LPMINMAXINFO
from winapp.dialog import Dialog
from winapp.trayicon import TrayIcon
from winapp.controls.button import Button
from winapp.controls.listbox import ListBox
from const import *
LANG = locale.windows_locale[kernel32.GetUserDefaultUILanguage()]
if not os.path.isdir(os.path.join(APP_DIR, 'resources', 'locale', LANG)):
LANG = 'en_US'
LANG_DIR = os.path.join(APP_DIR, 'resources', 'locale', LANG)
with open(os.path.join(LANG_DIR, 'strings.pson'), 'rb') as f:
__ = eval(f.read())
def _(s):
return __[s] if s in __ else s
IS_FROZEN = getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS')
IS_CONSOLE = kernel32.GetStdHandle(STD_OUTPUT_HANDLE) != 0
class App(MainWin):
def __init__(self, args=[]):
self._con_counter = CON_ID_START
self._current_connections = {}
self._reconnects = {}
self._hmenu_popup = None
self._debug = ''
########################################
# create main window
########################################
if IS_FROZEN:
hicon = user32.LoadIconW(kernel32.GetModuleHandleW(None), MAKEINTRESOURCEW(IDI_APPICON))
else:
hicon = user32.LoadImageW(0, os.path.join(APP_DIR, 'app.ico'), IMAGE_ICON, 16, 16, LR_LOADFROMFILE)
# load menu resource
with open(os.path.join(APP_DIR, 'resources', 'locale', LANG, 'menu_app.pson'), 'rb') as f:
menu_data = eval(f.read())
self.COMMAND_MESSAGE_MAP = {
IDM_SETTINGS: self.show_centered,
IDM_QUIT: self.quit,
IDM_EXPORT: self.export_connections,
IDM_IMPORT: self.import_connections,
IDM_IMPORT_FILEZILLA: self.import_connections_filezilla,
IDM_IMPORT_WINSCP: self.import_connections_winscp,
IDM_IMPORT_PUTTY: self.import_connections_putty,
IDM_IMPORT_KITTY: lambda: self.import_connections_putty(True),
IDM_IMPORT_CYBERDUCK: self.import_connections_cyberduck,
IDM_IMPORT_OPENSSH: self.import_connections_openssh,
IDM_ABOUT: lambda: self.show_message_box(
_('ABOUT_TEXT').format(APP_NAME, APP_VERSION),
_('ABOUT_CAPTION').format(APP_NAME))
}
super().__init__(
_('Edit Connections'),
window_class=APP_CLASS,
width=480, height=480,
hicon=hicon,
menu_data=menu_data,
hbrush = COLOR_3DFACE + 1
)
hkey = HKEY()
has_putty = advapi32.RegOpenKeyW(HKEY_CURRENT_USER, 'Software\\SimonTatham\\PuTTY\\Sessions', byref(hkey)) == ERROR_SUCCESS
if has_putty:
advapi32.RegCloseKey(hkey)
if not has_putty:
user32.EnableMenuItem(self.hmenu, IDM_IMPORT_PUTTY, MF_BYCOMMAND | MF_DISABLED)
has_kitty = advapi32.RegOpenKeyW(HKEY_CURRENT_USER, 'Software\\9bis.com\\KiTTY\\Sessions', byref(hkey)) == ERROR_SUCCESS
if has_kitty:
advapi32.RegCloseKey(hkey)
if not has_kitty:
user32.EnableMenuItem(self.hmenu, IDM_IMPORT_KITTY, MF_BYCOMMAND | MF_DISABLED)
has_cyberduck = os.path.isdir(os.path.join(os.environ['APPDATA'], 'Cyberduck', 'Bookmarks'))
if not has_cyberduck:
user32.EnableMenuItem(self.hmenu, IDM_IMPORT_CYBERDUCK, MF_BYCOMMAND | MF_DISABLED)
has_openssh = os.path.isfile(os.path.join(os.environ['USERPROFILE'], '.ssh', 'config'))
if not has_openssh:
user32.EnableMenuItem(self.hmenu, IDM_IMPORT_OPENSSH, MF_BYCOMMAND | MF_DISABLED)
self.trayicon = TrayIcon(self, self.hicon, APP_NAME, MSG_TRAYICON, show=False)
connection_list, use_dark, has_autorun = self.load_connections()
self.connection_dict = {}
for row in connection_list:
con_id = self._new_con_id()
self.connection_dict[con_id] = row
self.create_ui()
self.create_popup_menu()
self.create_dialogs()
if not IS_CONSOLE:
self.create_console()
########################################
#
########################################
def _on_WM_SIZE(hwnd, wparam, lparam):
width, height = lparam & 0xFFFF, (lparam >> 16) & 0xFFFF
self.listbox.set_window_pos(
width=width - BUTTON_WIDTH - 3 * MARGIN,
height=height - 2 * MARGIN,
flags=SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER
)
button_x = width - BUTTON_WIDTH - MARGIN
self.button_add.set_window_pos(
x=button_x,
y=20,
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
self.button_edit.set_window_pos(
x=button_x,
y=52,
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
self.button_delete.set_window_pos(
x=button_x,
y=84,
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
self.button_delete_all.set_window_pos(
x=button_x,
y=116,
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
self.button_connect.set_window_pos(
x=button_x,
y=116 + 2 * 32,
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
self.button_dark.set_window_pos(
x=button_x,
y=height - 2 * MARGIN - 12,
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
if not IS_CONSOLE:
self.button_console.set_window_pos(
x=button_x,
y=height - 2 * MARGIN - (60 if IS_FROZEN else 36),
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
if IS_FROZEN:
self.button_autorun.set_window_pos(
x=button_x,
y=height - 2 * MARGIN - 36,
flags=SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER
)
self.register_message_callback(WM_SIZE, _on_WM_SIZE)
########################################
#
########################################
def _on_WM_GETMINMAXINFO(hwnd, wparam, lparam):
mmi = cast(lparam, LPMINMAXINFO).contents
mmi.ptMinTrackSize.x = mmi.ptMinTrackSize.y = MIN_WINDOW_SIZE
return 0
self.register_message_callback(WM_GETMINMAXINFO, _on_WM_GETMINMAXINFO)
########################################
#
########################################
def _on_WM_CLOSE(hwnd, wparam, lparam):
self.show(SW_HIDE)
return TRUE
self.register_message_callback(WM_CLOSE, _on_WM_CLOSE, True)
########################################
#
########################################
def _on_MSG_TRAYICON(hwnd, wparam, lparam):
if lparam == WM_LBUTTONDBLCLK: # WM_LBUTTONUP
self.show_centered()
self.set_foreground_window()
elif lparam == WM_RBUTTONUP:
pt = POINT()
user32.GetCursorPos(byref(pt))
self.set_foreground_window()
item_id = user32.TrackPopupMenuEx(self._hmenu_popup, TPM_LEFTBUTTON | TPM_RETURNCMD, pt.x, pt.y, self.hwnd, 0)
user32.PostMessageW(self.hwnd, WM_NULL, 0, 0)
if item_id in self.COMMAND_MESSAGE_MAP:
self.COMMAND_MESSAGE_MAP[item_id]()
elif item_id >= CON_ID_START:
if item_id in self._current_connections:
self.disconnect(item_id)
else:
self.connect(item_id)
self.register_message_callback(MSG_TRAYICON, _on_MSG_TRAYICON)
########################################
#
########################################
def _on_WM_COMMAND(hwnd, wparam, lparam):
command = HIWORD(wparam)
if lparam == 0:
command_id = LOWORD(wparam)
if command_id in self.COMMAND_MESSAGE_MAP:
self.COMMAND_MESSAGE_MAP[command_id]()
elif lparam == self.listbox.hwnd:
if command == LBN_SELCHANGE:
idx = user32.SendMessageW(self.listbox.hwnd, LB_GETCURSEL, 0, 0)
self.button_edit.enable_window(int(idx != LB_ERR))
self.button_delete.enable_window(int(idx != LB_ERR))
self.button_connect.enable_window(int(idx != LB_ERR))
elif command == LBN_DBLCLK:
self.edit_connection()
elif lparam == self.button_add.hwnd:
if command == BN_CLICKED:
self.add_connection()
elif lparam == self.button_edit.hwnd:
if command == BN_CLICKED:
self.edit_connection()
elif lparam == self.button_delete.hwnd:
if command == BN_CLICKED:
self.delete_connection()
elif lparam == self.button_delete_all.hwnd:
if command == BN_CLICKED:
self.delete_all_connections()
elif lparam == self.button_connect.hwnd:
if command == BN_CLICKED:
idx = user32.SendMessageW(self.listbox.hwnd, LB_GETCURSEL, 0, 0)
con_id = user32.SendMessageW(self.listbox.hwnd, LB_GETITEMDATA, idx, 0)
if con_id not in self._current_connections:
self.connect(con_id)
elif lparam == self.button_dark.hwnd:
if command == BN_CLICKED:
self.apply_theme(not self.is_dark)
hkey = HKEY()
if advapi32.RegOpenKeyW(HKEY_CURRENT_USER, f'Software\\{APP_NAME}' , byref(hkey)) == ERROR_SUCCESS:
dwsize = sizeof(DWORD)
advapi32.RegSetValueExW(hkey, 'dark', 0, REG_DWORD, byref(DWORD(int(self.is_dark))), sizeof(DWORD))
advapi32.RegCloseKey(hkey)
elif IS_FROZEN and lparam == self.button_autorun.hwnd:
if command == BN_CLICKED:
is_checked = user32.SendMessageW(self.button_autorun.hwnd, BM_GETCHECK, 0, 0) == BST_CHECKED
hkey = HKEY()
if advapi32.RegOpenKeyW(HKEY_CURRENT_USER, f'Software\\Microsoft\\Windows\\CurrentVersion\\Run', byref(hkey)) == ERROR_SUCCESS:
if is_checked:
exe_path = os.path.realpath(os.path.join(APP_DIR, '..', APP_NAME + '.exe'))
buf = create_unicode_buffer(f'"{exe_path}" -autorun')
advapi32.RegSetValueExW(hkey, APP_NAME, 0, REG_SZ, buf, sizeof(buf))
else:
advapi32.RegDeleteValueW(hkey, APP_NAME)
advapi32.RegCloseKey(hkey)
elif not IS_CONSOLE and lparam == self.button_console.hwnd:
if command == BN_CLICKED:
is_checked = user32.SendMessageW(self.button_console.hwnd, BM_GETCHECK, 0, 0) == BST_CHECKED
user32.ShowWindow(self.hwnd_console, SW_SHOW if is_checked else SW_HIDE)
self._debug = '-odebug -ologlevel=debug1' if is_checked else ''
return FALSE
self.register_message_callback(WM_COMMAND, _on_WM_COMMAND)
########################################
#
########################################
def _on_WM_COPYDATA(hwnd, wparam, lparam):
ds = cast(lparam, POINTER(COPYDATASTRUCT))
args = eval(cast(ds.contents.lpData, LPWSTR).value)
if type(args) == list:
if len(args) >= 2:
if args[0] == '-eject':
self.disconnect_by_letter(args[1][:1])
elif args[0] == '-mount':
self.connect_by_name(args[1])
self.register_message_callback(WM_COPYDATA, _on_WM_COPYDATA)
########################################
#
########################################
def _on_poll():
for con_id in list(self._current_connections.keys()):
proc = self._current_connections[con_id]['proc']
exit_code = proc.poll()
if exit_code is not None:
#print('Process ended', exit_code)
user32.CheckMenuItem(self._hmenu_popup, con_id, MF_BYCOMMAND | MF_UNCHECKED)
del self._current_connections[con_id]
con = self.connection_dict[con_id]
if con["reconnect"] and self._reconnects[con_id] < MAX_RECONNECTS:
#print('Reconnecting...', self._reconnects[con_id])
self.connect(con_id, True)
else:
self.set_foreground_window()
self.show_message_box(_("Connection '{}' was disconnected.").format(con["name"]),
_('Connection lost'), MB_ICONWARNING | MB_OK)
self.timer_id_poll = self.create_timer(_on_poll, POLL_PERIOD_MS)
if has_autorun:
user32.SendMessageW(self.button_autorun.hwnd, BM_SETCHECK, BST_CHECKED, 0)
if use_dark:
self.apply_theme(True)
user32.SendMessageW(self.button_dark.hwnd, BM_SETCHECK, BST_CHECKED, 0)
self.trayicon.show()
if len(connection_list) == 0:
if not '-autorun' in args:
self.show_centered()
else:
for con_id, con in self.connection_dict.items():
if con["auto"]:
self.connect(con_id)
########################################
#
########################################
def load_connections(self):
connections, use_dark, has_autorun = [], True, False
data_int = (BYTE * sizeof(DWORD))()
cbData = DWORD(sizeof(data_int))
hkey = HKEY()
if IS_FROZEN and advapi32.RegOpenKeyW(HKEY_CURRENT_USER, f'Software\\Microsoft\\Windows\\CurrentVersion\\Run', byref(hkey)) == ERROR_SUCCESS:
has_autorun = advapi32.RegQueryValueExW(hkey, APP_NAME, None, None, None, byref(cbData)) == ERROR_SUCCESS
advapi32.RegCloseKey(hkey)
if advapi32.RegOpenKeyW(HKEY_CURRENT_USER, f'Software\\{APP_NAME}', byref(hkey)) != ERROR_SUCCESS:
advapi32.RegCreateKeyW(HKEY_CURRENT_USER, f'Software\\{APP_NAME}', byref(hkey))
advapi32.RegCloseKey(hkey)
return connections, use_dark, has_autorun
if advapi32.RegQueryValueExW(hkey, 'connections', None, None, None,
byref(cbData)) == ERROR_SUCCESS:
data_str = (BYTE * cbData.value)()
if advapi32.RegQueryValueExW(hkey, 'connections', None, None, data_str,
byref(DWORD(sizeof(data_str)))) == ERROR_SUCCESS:
connections = eval(cast(data_str, LPWSTR).value)
if advapi32.RegQueryValueExW(hkey, 'dark', None, None, byref(data_int), byref(DWORD(sizeof(data_int)))) == ERROR_SUCCESS:
use_dark = cast(data_int, POINTER(DWORD)).contents.value == 1
advapi32.RegCloseKey(hkey)
return connections, use_dark, has_autorun
########################################
#
########################################
def save_connections(self, connection_list):
hkey = HKEY()
if advapi32.RegOpenKeyW(HKEY_CURRENT_USER, f'Software\\{APP_NAME}', byref(hkey)) != ERROR_SUCCESS:
advapi32.RegCreateKeyW(HKEY_CURRENT_USER, f'Software\\{APP_NAME}', byref(hkey))
buf = create_unicode_buffer(str(connection_list))
advapi32.RegSetValueExW(hkey, 'connections', 0, REG_SZ, buf, sizeof(buf))
advapi32.RegCloseKey(hkey)
return True
########################################
#
########################################
def show_centered(self):
sw, sh = user32.GetSystemMetrics(SM_CXSCREEN), user32.GetSystemMetrics(SM_CYSCREEN)
rc = self.get_window_rect()
w, h = rc.right - rc.left, rc.bottom - rc.top
self.move_window((sw - w) // 2, (sh - h) // 2, w, h, FALSE)
self.show()
########################################
#
########################################
def create_ui(self):
self.listbox = ListBox(
self,
style=WS_TABSTOP | WS_CHILD | WS_VISIBLE | LBS_STANDARD | LBS_NOINTEGRALHEIGHT,
left=MARGIN, top=MARGIN,
)
self.listbox.set_font()
for con_id, con in self.connection_dict.items():
pos = self.listbox.add_string(con["name"])
self.listbox.set_item_data(pos, con_id)
self.button_add = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
width=BUTTON_WIDTH, height=BUTTON_HEIGHT,
window_title=_("Add Connection"))
self.button_add.set_font()
self.button_edit = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
width=BUTTON_WIDTH, height=BUTTON_HEIGHT,
window_title=_("Edit Connection"))
self.button_edit.set_font()
self.button_edit.enable_window(0)
self.button_delete = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
width=BUTTON_WIDTH, height=BUTTON_HEIGHT,
window_title=_("Delete Connection"))
self.button_delete.set_font()
self.button_delete.enable_window(0)
self.button_delete_all = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
width=BUTTON_WIDTH, height=BUTTON_HEIGHT,
window_title=_("Delete All"))
self.button_delete_all.set_font()
self.button_connect = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
width=BUTTON_WIDTH, height=BUTTON_HEIGHT,
window_title=_("Connect"))
self.button_connect.set_font()
self.button_connect.enable_window(0)
self.button_dark = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX,
width=BUTTON_WIDTH, height=22,
window_title=_("Use Dark Mode"))
self.button_dark.set_font()
if not IS_CONSOLE:
self.button_console = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX,
width=BUTTON_WIDTH, height=22,
window_title=_("Debug Console"))
self.button_console.set_font()
if IS_FROZEN:
self.button_autorun = Button(
self,
style=WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX,
width=BUTTON_WIDTH, height=22,
window_title=_("Autorun (Current User)"))
self.button_autorun.set_font()
self.hide_focus_rects()
########################################
#
########################################
def create_popup_menu(self):
if self._hmenu_popup:
user32.DestroyMenu(self._hmenu_popup)
menu_data = {"items": []}
for con_id, row in sorted(self.connection_dict.items(), key=lambda x: x[1]['name']):
menu_data["items"].append({
"caption": row["name"],
"id": con_id,
"flags": "CHECKED" if con_id in self._current_connections else "",
})
menu_data["items"].append({
"caption": "-"
})
menu_data["items"].append({
"caption": _("Edit Connections") + "...",
"id": IDM_SETTINGS
})
menu_data["items"].append({
"caption": "-"
})
menu_data["items"].append({
"caption": _("Exit"),
"id": IDM_QUIT
})
self._hmenu_popup = self.make_popup_menu(menu_data)
self.button_delete_all.enable_window(int(len(self.connection_dict.keys()) > 0))
########################################
#
########################################
def create_dialogs(self):
class ctx():
con_id = None
with open(os.path.join(LANG_DIR, 'dialog_connection.pson'), 'r') as f:
dialog_dict = eval(f.read())
def _dialog_proc_connection(hwnd, msg, wparam, lparam):
def _get_control_text(control_id):
hwnd_edit = user32.GetDlgItem(hwnd, control_id)
text_len = user32.GetWindowTextLengthW(hwnd_edit)
buf = create_unicode_buffer(text_len + 1)
user32.GetWindowTextW(hwnd_edit, buf, text_len + 1)
return buf.value
if msg == WM_INITDIALOG:
hwnd_combo_letter = user32.GetDlgItem(hwnd, IDC_COMBO_LETTER)
user32.SendMessageW(hwnd_combo_letter, CB_ADDSTRING, 0, create_unicode_buffer('Auto'))
for i in range(67, 91): # 67 - 90
user32.SendMessageW(hwnd_combo_letter, CB_ADDSTRING, 0, create_unicode_buffer(chr(i)))
hwnd_combo_auth = user32.GetDlgItem(hwnd, IDC_COMBO_AUTH)
user32.SendMessageW(hwnd_combo_auth, CB_ADDSTRING, 0, create_unicode_buffer(_('Private Key File')))
user32.SendMessageW(hwnd_combo_auth, CB_ADDSTRING, 0, create_unicode_buffer(_('Password (saved)')))
user32.SendMessageW(hwnd_combo_auth, CB_ADDSTRING, 0, create_unicode_buffer(_('Password (ask on connect)')))
ctx.con_id = lparam
if ctx.con_id == 0: # new connection
user32.SendMessageW(hwnd_combo_letter, CB_SETCURSEL, 0, 0)
user32.SendMessageW(hwnd_combo_auth, CB_SETCURSEL, 0, 0)
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_PORT), create_unicode_buffer('22'))
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_PATH), create_unicode_buffer('/'))
user_ssh_dir = os.path.join(os.environ['USERPROFILE'], '.ssh')
if os.path.isdir(user_ssh_dir):
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_KEY),
create_unicode_buffer(os.path.join(user_ssh_dir, 'id_rsa')))
return FALSE
con = self.connection_dict[lparam]
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_NAME), create_unicode_buffer(con["name"]))
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_HOST), create_unicode_buffer(con["host"]))
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_PORT), create_unicode_buffer(str(con["port"])))
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_USER), create_unicode_buffer(con["user"]))
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_PATH), create_unicode_buffer(con["path"]))
hwnd_static_password = user32.GetDlgItem(hwnd, IDC_STATIC_PASSWORD)
hwnd_edit_password = user32.GetDlgItem(hwnd, IDC_EDIT_PASSWORD)
if con["auth"] == "password":
pw = self._dec(con['password'])
user32.SetWindowTextW(hwnd_edit_password, create_unicode_buffer(pw))
user32.ShowWindow(hwnd_static_password, int(con["auth"] == "password"))
user32.ShowWindow(hwnd_edit_password, int(con["auth"] == "password"))
hwnd_edit_key = user32.GetDlgItem(hwnd, IDC_EDIT_KEY)
if con["auth"] == "key":
user32.SendMessageW(hwnd_edit_key, WM_SETTEXT, 0, create_unicode_buffer(con["key_file"].replace('/', '\\')))
user32.ShowWindow(user32.GetDlgItem(hwnd, IDC_STATIC_KEY), int(con["auth"] == "key"))
user32.ShowWindow(hwnd_edit_key, int(con["auth"] == "key"))
user32.ShowWindow(user32.GetDlgItem(hwnd, IDC_SELECT_KEY), int(con["auth"] == "key"))
user32.SendMessageW(hwnd_combo_letter, CB_SETCURSEL, 0 if con["letter"] is None else ord(con["letter"]) - 66, 0)
user32.SendMessageW(hwnd_combo_auth, CB_SETCURSEL, ["key", "password", "ask_password"].index(con["auth"]), 0)
user32.SendMessageW(user32.GetDlgItem(hwnd, IDC_CHECK_AUTOCONNECT), BM_SETCHECK, BST_CHECKED if con["auto"] else BST_UNCHECKED, 0)
user32.SendMessageW(user32.GetDlgItem(hwnd, IDC_CHECK_RECONNECT), BM_SETCHECK, BST_CHECKED if con["reconnect"] else BST_UNCHECKED, 0)
elif msg == WM_COMMAND:
control_id = LOWORD(wparam)
command = HIWORD(wparam)
if command == CBN_SELCHANGE:
if control_id == IDC_COMBO_AUTH:
hwnd_combo_auth = user32.GetDlgItem(hwnd, IDC_COMBO_AUTH)
idx = user32.SendMessageW(hwnd_combo_auth, CB_GETCURSEL, 0, 0)
# "key", "password", "ask_password"
user32.ShowWindow(user32.GetDlgItem(hwnd, IDC_STATIC_PASSWORD), int(idx == 1))
user32.ShowWindow(user32.GetDlgItem(hwnd, IDC_EDIT_PASSWORD), int(idx == 1))
user32.ShowWindow(user32.GetDlgItem(hwnd, IDC_STATIC_KEY), int(idx == 0))
user32.ShowWindow(user32.GetDlgItem(hwnd, IDC_EDIT_KEY), int(idx == 0))
user32.ShowWindow(user32.GetDlgItem(hwnd, IDC_SELECT_KEY), int(idx == 0))
if idx == 0 and _get_control_text(IDC_EDIT_KEY) == '':
user_ssh_dir = os.path.join(os.environ['USERPROFILE'], '.ssh')
if os.path.isdir(user_ssh_dir):
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_KEY),
create_unicode_buffer(os.path.join(user_ssh_dir, 'id_rsa')))
elif command == BN_CLICKED:
if control_id == IDC_SELECT_KEY:
fn = self.get_open_filename(_('Select Private Key'),
initial_dir=os.path.join(os.environ['USERPROFILE'], '.ssh'))
if fn:
user32.SetWindowTextW(user32.GetDlgItem(hwnd, IDC_EDIT_KEY), create_unicode_buffer(fn))
elif control_id == IDC_OK:
con = {}
con["name"] = _get_control_text(IDC_EDIT_NAME)
con["host"] = _get_control_text(IDC_EDIT_HOST)
con["port"] = _get_control_text(IDC_EDIT_PORT)
con["user"] = _get_control_text(IDC_EDIT_USER)
con["path"] = _get_control_text(IDC_EDIT_PATH)
for v in con.values():
if v == '':
self.show_message_box(
_('Please fill out all fields.'),
_('Settings incomplete'),
MB_ICONERROR | MB_OK)
return FALSE
# if a new connection, make sure that name is unique
if ctx.con_id is None and con["name"] in [con["name"] for con in self.connection_dict.values()]:
self.show_message_box(
_('Please select a unique connection name.'),
_('Name already used'),
MB_ICONERROR | MB_OK)
return FALSE
hwnd_combo_letter = user32.GetDlgItem(hwnd, IDC_COMBO_LETTER)
idx = user32.SendMessageW(hwnd_combo_letter, CB_GETCURSEL, 0, 0)
con["letter"] = None if idx == 0 else chr(66 + idx)
hwnd_combo_auth = user32.GetDlgItem(hwnd, IDC_COMBO_AUTH)
idx = user32.SendMessageW(hwnd_combo_auth, CB_GETCURSEL, 0, 0)
con["auth"] = ["key", "password", "ask_password"][idx]
if con["auth"] == 'key':
fn = _get_control_text(IDC_EDIT_KEY)
if fn == '':
self.show_message_box(
_('Please select a private key file.'),
_('Key missing'),
MB_ICONERROR | MB_OK)
return FALSE
elif not os.path.isfile(fn):
self.show_message_box(
_('Please select an existing private key file.'),
_('Key doesn\'t exist'),
MB_ICONERROR | MB_OK)
return FALSE
con["key_file"] = fn
elif con["auth"] == 'password':
pw = _get_control_text(IDC_EDIT_PASSWORD)
if pw == '':
self.show_message_box(
_('Please enter a password.'),
_('Password missing'),
MB_ICONERROR | MB_OK)
return FALSE
con["password"] = self._enc(pw)
con["auto"] = user32.SendMessageW(user32.GetDlgItem(hwnd, IDC_CHECK_AUTOCONNECT), BM_GETCHECK, 0, 0) == BST_CHECKED
con["reconnect"] = user32.SendMessageW(user32.GetDlgItem(hwnd, IDC_CHECK_RECONNECT), BM_GETCHECK, 0, 0) == BST_CHECKED
if ctx.con_id:
con_id = ctx.con_id
idx = user32.SendMessageW(self.listbox.hwnd, LB_GETCURSEL, 0, 0)
user32.SendMessageW(self.listbox.hwnd, LB_DELETESTRING, idx, 0)
else:
con_id = self._new_con_id()
self.connection_dict[con_id] = con
idx = self.listbox.add_string(con["name"])
self.listbox.set_item_data(idx, con_id)
user32.SendMessageW(self.listbox.hwnd, LB_SETCURSEL, idx, 0)
self.save_connections(list(self.connection_dict.values()))
self.create_popup_menu()
user32.EndDialog(hwnd, 1)
elif control_id == IDC_CANCEL:
user32.EndDialog(hwnd, 0)
return FALSE
self.dialog_connection = Dialog(self, dialog_dict, _dialog_proc_connection)
########################################
#
########################################
def create_console(self):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
proc = subprocess.Popen(
os.path.join(BIN_DIR, 'bash.exe'),
env = {'PATH': BIN_DIR},
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
startupinfo=startupinfo
)
for i in range(50):
time.sleep(.05)
if kernel32.AttachConsole(proc.pid):
break
kernel32.SetConsoleTitleW(_("Debug Console"))
self.hwnd_console = kernel32.GetConsoleWindow()
user32.SendMessageW(self.hwnd_console, WM_SETICON, 0, self.hicon)
# deactivate console's close button
hmenu = user32.GetSystemMenu(self.hwnd_console, FALSE)
if hmenu:
user32.DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND)
# redirect unbuffered STDOUT to the console
lStdOutHandle = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
hConHandle = msvcrt.open_osfhandle(lStdOutHandle, os.O_TEXT)
sys.stdout = io.TextIOWrapper(os.fdopen(hConHandle, 'wb', 0), write_through=True)
# redirect unbuffered STDERR to the console
lStdErrHandle = kernel32.GetStdHandle(STD_ERROR_HANDLE)
hConHandle = msvcrt.open_osfhandle(lStdErrHandle, os.O_TEXT)
sys.stderr = io.TextIOWrapper(os.fdopen(hConHandle, 'wb', 0), write_through=True)
# redirect unbuffered STDIN to the console
lStdInHandle = kernel32.GetStdHandle(STD_INPUT_HANDLE)
hConHandle = msvcrt.open_osfhandle(lStdInHandle, os.O_TEXT)
sys.stdin = io.TextIOWrapper(os.fdopen(hConHandle, 'rb', 0), write_through=True)
########################################
#
########################################
def _check_is_open(self, host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((host, int(port)))
s.shutdown(2)
return True
except:
return False
########################################
#
########################################
def connect(self, con_id, is_reconnect=False):
con = self.connection_dict[con_id]
# first check if host and ip are accessible at all
if not is_reconnect and not self._check_is_open(con['host'], con['port']):
self.show_message_box(_("{}:{} can\'t be reached.").format(con["host"], con["port"]),
_('No connection possible'), MB_ICONERROR | MB_OK)
return
bash = os.path.join(BIN_DIR, 'bash.exe')
if con["letter"]:
if self._drive_letter_in_use(con["letter"]):
res = self.show_message_box(
_('Drive letter {} is already in use.\n\n'
'Do you want to use the first free letter instead?')
.format(con["letter"]),
_('Drive letter in use'),
MB_ICONQUESTION | MB_YESNO)
if res != IDYES:
if is_reconnect:
del self._current_connections[con_id]
return
letter = self._find_free_drive_letter()
else:
letter = con["letter"]
else:
letter = self._find_free_drive_letter()
env = {'PATH': BIN_DIR}
volname = re.sub(r'[<>:"/\\|?*]', '_', con['name'][:32])
command = ("sshfs {user}@{host}:{path} {use_letter}: -p{port} -ovolname='{volname}' -f {debug} "
"-oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oServerAliveInterval=30 -oidmap=user -ouid=-1 "
"-ogid=-1 -oumask=000 -ocreate_umask=000 -omax_readahead=1GB "
"-oallow_other -olarge_read -okernel_cache -ofollow_symlinks -oConnectTimeout={connect_timeout}"
.format(**{'volname': volname, 'use_letter': letter, 'connect_timeout': SSH_CONNECT_TIMEOUT_SEC,
'debug': self._debug}, **con))
if con["auth"] == "key":
if not os.path.isfile(con['key_file']):
self.show_message_box(
_('The assigned private key file does not exist:\n\n{}').format(con['key_file']),
_('Key doesn\'t exist'),
MB_ICONERROR | MB_OK, dialog_width=240)
return
command += " -oPreferredAuthentications=publickey -oIdentityFile='{}'".format(con['key_file'].replace('\\', '/'))
# check if ke is protected by passphrase
with open(con['key_file'], 'r') as f:
is_protected = 'Proc-Type: 4,ENCRYPTED' in f.read()
if is_protected:
pw = self.show_prompt(text=_('Passphrase for key "{}":').format(os.path.basename(con['key_file'])),
caption=_('Enter Passphrase'), is_password=True, dialog_width=200)
if not pw:
return
env["SSHPASS"] = pw
command += f" -ossh_command='sshpass -e -P assphrase ssh'"
proc = subprocess.Popen(
f'"{bash}" -c "{command}"',
env = env,
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP,
)
self._current_connections[con_id] = {'proc': proc, 'letter' : letter}
else:
if con["auth"] == "ask_password":
pw = self.show_prompt(text=_('Password for {}:').format(con['name']),
caption=_('Enter Password'), is_password=True, dialog_width=200)
if not pw:
return
else:
pw = self._dec(con['password'])
env["SSHPASS"] = pw
command += f" -ossh_command='sshpass -e ssh'"
proc = subprocess.Popen(
f'"{bash}" -c "{command}"',
env = env,
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP,
)
self._current_connections[con_id] = {'proc': proc, 'letter' : letter}
self._reconnects[con_id] = self._reconnects[con_id] + 1 if is_reconnect else 0
user32.CheckMenuItem(self._hmenu_popup, con_id, MF_BYCOMMAND | MF_CHECKED)
self._update_explorer_menu()
if not is_reconnect:
for i in range(10):
time.sleep(.5)
if os.path.isdir(f'{letter}:/'):
os.system(f'C:\\Windows\\explorer.exe {letter}:\\')
break
########################################
#
########################################
def connect_by_name(self, con_name):
for con_id, row in self._current_connections.items():
if row['name'] == con_name:
self.connect(con_id)
break
########################################
#
########################################
def disconnect(self, con_id):
if con_id in self._current_connections:
proc = self._current_connections[con_id]['proc']
del self._current_connections[con_id]
proc.send_signal(signal.CTRL_BREAK_EVENT)
self._update_explorer_menu()
user32.CheckMenuItem(self._hmenu_popup, con_id, MF_BYCOMMAND | MF_UNCHECKED)
########################################
#
########################################
def disconnect_by_letter(self, letter):
for con_id, row in self._current_connections.items():
if row['letter'] == letter:
self.disconnect(con_id)
break
########################################
#
########################################
def _update_explorer_menu(self, deactivate=False):
if not IS_FROZEN:
return
key_path = 'Software\\Classes\\Drive\\shell\\ejectsshfs'
hkey = HKEY()
if advapi32.RegOpenKeyW(HKEY_CURRENT_USER, key_path, byref(hkey)) != ERROR_SUCCESS:
if advapi32.RegCreateKeyW(HKEY_CURRENT_USER, key_path, byref(hkey)) != ERROR_SUCCESS:
return
exe_path = os.path.realpath(os.path.join(APP_DIR, '..', APP_NAME + '.exe'))
buf = create_unicode_buffer(_('Eject SSHFS Drive'))
advapi32.RegSetValueExW(hkey, '', 0, REG_SZ, buf, sizeof(buf))
buf = create_unicode_buffer(f'"{exe_path}"')
advapi32.RegSetValueExW(hkey, 'Icon', 0, REG_SZ, buf, sizeof(buf))
hkey_sub = HKEY()
if advapi32.RegCreateKeyW(HKEY_CURRENT_USER, key_path + '\\command', byref(hkey_sub)) == ERROR_SUCCESS:
buf = create_unicode_buffer(f'"{exe_path}" -eject %V')
advapi32.RegSetValueExW(hkey_sub, '', 0, REG_SZ, buf, sizeof(buf))
advapi32.RegCloseKey(hkey_sub)
if deactivate:
buf = create_unicode_buffer(':::')
else:
letters = [row['letter'] + ':' for row in self._current_connections.values()]
buf = create_unicode_buffer(' OR '.join(letters) if len(letters) else ':::')
advapi32.RegSetValueExW(hkey, 'AppliesTo', 0, REG_SZ, buf, sizeof(buf))
advapi32.RegCloseKey(hkey)
########################################
#
########################################
def add_connection(self):
self.dialog_show_sync(self.dialog_connection, 0)
########################################
#
########################################
def edit_connection(self):
idx = user32.SendMessageW(self.listbox.hwnd, LB_GETCURSEL, 0, 0)
con_id = user32.SendMessageW(self.listbox.hwnd, LB_GETITEMDATA, idx, 0)
self.dialog_show_sync(self.dialog_connection, con_id)
########################################
# TODO: check if this connection is currently active, ask if it should e disconnected
########################################
def delete_connection(self):
idx = user32.SendMessageW(self.listbox.hwnd, LB_GETCURSEL, 0, 0)
con_id = user32.SendMessageW(self.listbox.hwnd, LB_GETITEMDATA, idx, 0)
user32.SendMessageW(self.listbox.hwnd, LB_DELETESTRING, idx, 0)
self.button_edit.enable_window(0)
self.button_delete.enable_window(0)
self.button_connect.enable_window(0)
del self.connection_dict[con_id]
self.save_connections(list(self.connection_dict.values()))
self.create_popup_menu()
########################################
# TODO: check if thee are active connections, ask if they should be disconnected
########################################
def delete_all_connections(self):
if not self.connection_dict:
return
res = self.show_message_box(
_('Do you really want to delete all connections?'),
_('Delete all connections'),
MB_ICONQUESTION | MB_YESNO)
if res != IDYES:
return
user32.SendMessageW(self.listbox.hwnd, LB_RESETCONTENT, 0, 0)
self.button_edit.enable_window(0)
self.button_delete.enable_window(0)
self.button_connect.enable_window(0)
self.connection_dict = {}
self.save_connections([])
self.create_popup_menu()
########################################
#
########################################
def export_connections(self):
fn = self.get_save_filename(_('Export connections'), default_extension='.pson',
filter_string='All Files (*.*)\0*.*\0\0', initial_path='connections.pson')
if not fn:
return
try:
with open(fn, 'w') as f:
f.write(str(list(self.connection_dict.values())))
except Exception as e:
print(e)
########################################
#
########################################
def import_connections(self):
fn = self.get_open_filename(_('Import connections'), default_extension='.pson',
filter_string='Win-SSHFS-Mounter Connections File (*.pson)\0*.pson\0\0',
#initial_path='connections.pson'
)
if not fn:
return
try:
with open(fn, 'r') as f:
imported = eval(f.read())