-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPCM.py
More file actions
3426 lines (3012 loc) · 139 KB
/
Copy pathPCM.py
File metadata and controls
3426 lines (3012 loc) · 139 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
#!/usr/bin/env python3
"""
PCM - Python Connection Manager (GTK3 port)
Ispirato a MobaXterm, sviluppato in Python/GTK3.
Licensed under the European Union Public Licence (EUPL) v1.2
© 2025 - All rights reserved
Dipendenze:
python3-gi
gir1.2-gtk-3.0
gir1.2-vte-2.91
gir1.2-gtk-vnc-2.0 (VNC integrato nativo)
python3-paramiko (SFTP)
FreeBSD equivalenti:
py311-gobject3 vte3 gtk-vnc py311-paramiko
"""
import sys
import os
import subprocess
import shutil
import threading
import tempfile
import contextlib
from urllib.parse import urlparse
# ── Controllo dipendenze all'avvio ────────────────────────────────────────────
def _check_deps():
errors = []
hints = []
# Python >= 3.10
if sys.version_info < (3, 10):
errors.append(f"Python 3.10+ richiesto (trovato {sys.version.split()[0]})")
hints.append("Aggiorna Python: https://www.python.org/downloads/")
# gi / PyGObject
try:
import gi as _gi
except ImportError:
errors.append("PyGObject (python3-gi) non installato")
hints.append(" Debian/Ubuntu : sudo apt install python3-gi python3-gi-cairo")
hints.append(" Arch : sudo pacman -S python-gobject")
hints.append(" Fedora : sudo dnf install python3-gobject")
if errors:
_die(errors, hints)
# GTK 3.0
try:
import gi as _gi
_gi.require_version("Gtk", "3.0")
from gi.repository import Gtk as _Gtk # noqa: F401
except (ValueError, ImportError):
errors.append("GTK 3.0 non disponibile (gir1.2-gtk-3.0 / typelib-1_0-Gtk-3_0)")
hints.append(" Debian/Ubuntu : sudo apt install gir1.2-gtk-3.0 libgtk-3-0")
hints.append(" Arch : sudo pacman -S gtk3")
hints.append(" Fedora : sudo dnf install gtk3")
# VTE 2.91
try:
import gi as _gi
_gi.require_version("Vte", "2.91")
from gi.repository import Vte as _Vte # noqa: F401
except (ValueError, ImportError):
errors.append("VTE 2.91 non disponibile (gir1.2-vte-2.91 / typelib-1_0-Vte-2_91)")
hints.append(" Debian/Ubuntu : sudo apt install gir1.2-vte-2.91 libvte-2.91-0")
hints.append(" Arch : sudo pacman -S vte3")
hints.append(" Fedora : sudo dnf install vte291")
if errors:
_die(errors, hints)
def _die(errors, hints):
SEP = "═" * 62
print(f"\n╔{SEP}╗")
print( "║ PCM — dipendenze mancanti ║")
print(f"╠{SEP}╣")
for e in errors:
print(f"║ ✗ {e}")
if hints:
print(f"╠{SEP}╣")
print( "║ Installa le dipendenze mancanti: ║")
for h in hints:
print(f"║ {h}")
print(f"╚{SEP}╝\n")
sys.exit(1)
_check_deps()
# ─────────────────────────────────────────────────────────────────────────────
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Vte", "2.91")
from gi.repository import Gtk, GLib, Gio
from pcm_logging import get_logger
_log = get_logger("pcm")
# ---------------------------------------------------------------------------
# Moduli PCM (tutti GTK3)
# ---------------------------------------------------------------------------
import config_manager
import translations as _tr
from translations import t
from themes import apply_css
from terminal_widget import TerminalWidget
from session_panel import SessionPanel
from session_dialog import SessionDialog
import protocols
from protocols import refresh_from_plugins as _refresh_protocols
from session_command import build_command
from settings_dialog import SettingsDialog
from tunnel_manager import TunnelManagerDialog, get_active_tunnels, stop_tunnel, reattach_tunnels
from vnc_widget import VncWebWidget
from rdp_widget import RdpEmbedWidget
from sftp_browser import SftpBrowserWidget
from winscp_widget import WinScpWidget, FtpWinScpWidget
from log_viewer import LogViewerWidget
from sysmon_widget import SysMonitorWidget
from panel_monitor import InfoPanelWidget
from cron_widget import CronWidget
from sftp_editor import SftpEditorWidget
from snippets_dialog import SnippetsDialog
from welcome_widget import WelcomeWidget
from quick_connect_dialog import QuickConnectDialog
from plugins.plugin_base import (
pcm_has_protocol, pcm_build_command, pcm_create_widget,
pcm_menu_items as _plugin_menu_items,
pcm_context_actions as _plugin_context_actions,
)
from plugins.plugin_manager import load_plugins as _load_plugins
# ---------------------------------------------------------------------------
# Percorso icone
# ---------------------------------------------------------------------------
_HERE = os.path.dirname(os.path.abspath(__file__))
_ICONS_DIR = os.path.join(_HERE, "icons")
def _icon_path(name: str) -> str:
return os.path.join(_ICONS_DIR, name)
def _load_icon(name: str, size: int = 24):
from gi.repository import GdkPixbuf
path = _icon_path(name)
if os.path.isfile(path):
try:
return GdkPixbuf.Pixbuf.new_from_file_at_size(path, size, size)
except Exception as e:
_log.debug("Icona non caricata '%s': %s", name, e)
return None
# ===========================================================================
# Finestra principale
# ===========================================================================
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, app):
super().__init__(application=app, title=t("app.title"))
self.set_default_size(1200, 720)
self.set_position(Gtk.WindowPosition.CENTER)
_tr.init_from_settings()
self._settings = config_manager.load_settings()
config_manager._fix_permissions()
self._profili: dict = {}
# Icona finestra
pb = _load_icon("app.png", 64)
if pb:
self.set_icon(pb)
self._build_ui()
self._connect_signals()
self._setup_accels()
self._pannello.aggiorna()
self._auto_lock_timer = 0
self._avvia_auto_lock()
self.connect("key-press-event", lambda w, e: self._reset_auto_lock())
self.connect("motion-notify-event", lambda w, e: self._reset_auto_lock())
self._pending_cli_uri: str | None = None # URI da aprire dopo unlock crypto
# Avvio a cascata: ogni step richiama il successivo dopo il rendering
# Sblocco credenziali -> notifica tunnel -> ripristino sessioni
GLib.idle_add(self._startup_chain, 0)
# ------------------------------------------------------------------
# Catena di avvio
# ------------------------------------------------------------------
def _startup_chain(self, step: int) -> bool:
"""Esegue la catena di inizializzazione a step:
0: load plugins, 1: unlock crypto, 2: notifica tunnel, 3: restore sessioni, 4: stato live."""
if step == 0:
self._load_pcm_plugins()
GLib.timeout_add(200, self._startup_chain, 1)
elif step == 1:
self._check_crypto_unlock()
GLib.timeout_add(300, self._startup_chain, 2)
elif step == 2:
self._notifica_tunnel_avvio()
GLib.timeout_add(500, self._startup_chain, 3)
elif step == 3:
self._ripristina_sessioni()
GLib.timeout_add(500, self._startup_chain, 4)
elif step == 4:
self._timer_stato_live = GLib.timeout_add(3000, self._aggiorna_stato_live)
return False # one-shot per ogni step
# ------------------------------------------------------------------
# Sblocco credenziali cifrate
# ------------------------------------------------------------------
def _load_pcm_plugins(self):
"""Carica i plugin all'avvio e aggiorna il registro protocolli."""
try:
loaded = _load_plugins()
if loaded:
_refresh_protocols()
self._pannello.aggiorna()
_log.info("%d plugin caricati", len(loaded))
except Exception as e:
_log.warning("Errore caricamento plugin: %s", e)
def _check_crypto_unlock(self):
"""Chiamato 300ms dopo l'avvio per sbloccare le credenziali cifrate.
Gestisce due scenari:
a) crypto.enabled=True + salt in settings → flusso normale
b) ENC: trovati nei profili ma settings incompleto → flusso recovery
(tipico quando si porta connections.json da un'altra installazione)
"""
try:
import crypto_manager
import config_manager as _cm
already_unlocked = crypto_manager.is_unlocked()
if already_unlocked:
return False
# --- Scenario A: impostazioni crypto complete ---
if crypto_manager.is_enabled():
self._esegui_unlock_dialog()
return False
# --- Scenario B: ENC: trovati ma settings incompleto ---
# Controlla se connections.json ha valori cifrati
profili = _cm.load_profiles()
ha_enc = any(
str(v.get("user","")).startswith("ENC:") or
str(v.get("password","")).startswith("ENC:")
for v in profili.values()
)
if not ha_enc:
return False # nessuna cifratura, niente da fare
# Ha valori ENC: ma manca la configurazione crypto in settings.
# Chiedi la password e tenta di recuperare il salt dal vecchio settings.
s = _cm.load_settings()
salt_b64 = s.get("crypto", {}).get("salt", "")
if not salt_b64:
# Manca il salt: non possiamo decifrare senza il pcm_settings.json originale
dlg = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK,
text=t("crypto.unlock.title"),
secondary_text=(
"Il file connections.json contiene credenziali cifrate (ENC:…)\n"
"ma il file pcm_settings.json non contiene il salt di cifratura.\n\n"
"Soluzione: copia il pcm_settings.json originale dalla vecchia installazione\n"
"e assicurati che contenga la sezione \"crypto\" con salt, verify ed enabled:true.\n\n"
"In alternativa, modifica le sessioni manualmente per reinserire le credenziali."
)
)
dlg.run()
dlg.destroy()
return False
# Il salt c'è ma enabled=False: ripristiniamo enabled e proviamo
s["crypto"]["enabled"] = True
_cm.save_settings(s)
self._esegui_unlock_dialog()
except ImportError:
pass
return False
_UNLOCK_MAX_TENTATIVI = 3
def _esegui_unlock_dialog(self):
"""Mostra il dialog password e sblocca le credenziali.
Consente fino a _UNLOCK_MAX_TENTATIVI tentativi senza dover
riavviare l'app: alla password sbagliata il dialog si riapre subito.
Se l'utente annulla, o esaurisce i tentativi, l'app si chiude
(senza sblocco le sessioni cifrate sarebbero comunque inutilizzabili)."""
import crypto_manager
tentativi = 0
while tentativi < self._UNLOCK_MAX_TENTATIVI:
dlg = _CryptoUnlockDialog(parent=self)
resp = dlg.run()
pwd = dlg.get_password()
dlg.destroy()
if resp != Gtk.ResponseType.OK:
self.get_application().quit()
return
if pwd and crypto_manager.unlock(pwd):
self._pannello.aggiorna()
self._aggiorna_welcome_recenti()
falliti = config_manager.decrypt_failures()
if falliti:
self._warn(
"Impossibile decifrare le credenziali di: " + ", ".join(falliti) +
" (token corrotto o chiave non corrispondente)"
)
if self._pending_cli_uri:
uri, self._pending_cli_uri = self._pending_cli_uri, None
GLib.idle_add(self.apri_da_cli, uri)
return
tentativi += 1
rimanenti = self._UNLOCK_MAX_TENTATIVI - tentativi
err = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text=t("crypto.unlock.wrong_master"),
secondary_text=(
f"Tentativi rimasti: {rimanenti}" if rimanenti > 0
else "Troppi tentativi errati: l'applicazione verrà chiusa."
)
)
err.run()
err.destroy()
self.get_application().quit()
# ------------------------------------------------------------------
# Costruzione UI
# ------------------------------------------------------------------
def _avvia_auto_lock(self):
minuti = self._settings.get("general", {}).get("auto_lock_minutes", 15)
if minuti <= 0:
return
if self._auto_lock_timer:
GLib.source_remove(self._auto_lock_timer)
self._auto_lock_timer = GLib.timeout_add_seconds(
minuti * 60, self._lock_now
)
def _reset_auto_lock(self):
if hasattr(self, "_auto_lock_timer") and self._auto_lock_timer:
GLib.source_remove(self._auto_lock_timer)
self._avvia_auto_lock()
def _lock_now(self):
import crypto_manager
if crypto_manager.is_enabled() and crypto_manager.is_unlocked():
crypto_manager.lock()
_log.info("Cifratura bloccata per inattività")
self._auto_lock_timer = 0
return GLib.SOURCE_REMOVE
def _build_ui(self):
# Layout radice: headerbar + contenuto
self._build_headerbar()
# Paned principale: sidebar | area lavoro
self._paned = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)
self._paned.set_position(240)
self.add(self._paned)
# --- Sidebar ---
self._pannello = SessionPanel()
self._paned.pack1(self._pannello, False, False)
# --- Area lavoro destra: paned orizzontale [terminali | pannello info] ---
self._paned_right = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)
self._paned.pack2(self._paned_right, True, True)
right_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self._paned_right.pack1(right_box, True, True)
self._info_panel = InfoPanelWidget()
self._info_panel.set_no_show_all(True)
# shrink=True: l'utente può trascinare il Paned per restringere il pannello
self._paned_right.pack2(self._info_panel, False, True)
# Paned terminali: supporta split verticale/orizzontale
self._paned_term = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)
self._paned_term.set_wide_handle(True)
self._paned_term.set_position(99999) # handle fuori schermo in single mode
right_box.pack_start(self._paned_term, True, True, 0)
# Notebook primario (sempre visibile)
self._notebook = Gtk.Notebook()
self._notebook.set_scrollable(True)
self._notebook.set_show_border(False)
self._notebook.connect("switch-page", self._on_switch_tab)
self._notebook.connect("button-press-event", self._on_nb_button_press)
self._paned_term.pack1(self._notebook, True, True)
# Notebook secondario (split — inizialmente nascosto)
self._notebook2 = Gtk.Notebook()
self._notebook2.set_scrollable(True)
self._notebook2.set_show_border(False)
self._notebook2.set_no_show_all(True)
self._notebook2.connect("button-press-event", self._on_nb2_button_press)
self._notebook2.connect("switch-page", self._on_switch_tab)
self._paned_term.pack2(self._notebook2, True, True)
# Quale notebook è attivo (aggiornato da switch-page di entrambi)
self._notebook_attivo = self._notebook
# page_widget → Gtk.Label dentro la box del tab (per leggere/scrivere il nome)
self._tab_labels: dict = {}
# page_widget → Gtk.Notebook (lookup O(1) per _trova_in_notebook)
self._widget_nb_map: dict = {}
# Barra inferiore: toast notifications + statusbar
bottom_bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
bottom_bar.get_style_context().add_class("bottom-bar")
self._toast_revealer = Gtk.Revealer()
self._toast_revealer.set_transition_type(Gtk.RevealerTransitionType.SLIDE_UP)
self._toast_revealer.set_transition_duration(250)
self._toast_label = Gtk.Label()
self._toast_label.set_xalign(0.0)
self._toast_label.set_margin_start(12)
self._toast_label.set_margin_end(12)
self._toast_label.set_margin_top(4)
self._toast_label.set_margin_bottom(4)
self._toast_close_btn = Gtk.Button()
self._toast_close_btn.set_relief(Gtk.ReliefStyle.NONE)
self._toast_close_btn.add(Gtk.Image.new_from_icon_name("window-close-symbolic", Gtk.IconSize.MENU))
self._toast_close_btn.connect("clicked", lambda b: self._nascondi_toast())
self._toast_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4)
self._toast_box.pack_start(self._toast_label, True, True, 0)
self._toast_box.pack_start(self._toast_close_btn, False, False, 0)
self._toast_revealer.add(self._toast_box)
self._toast_timer = 0
self._statusbar = Gtk.Statusbar()
self._statusbar_ctx = self._statusbar.get_context_id("main")
self._statusbar.set_hexpand(True)
bottom_bar.pack_start(self._statusbar, True, True, 0)
right_box.pack_start(bottom_bar, False, False, 0)
bottom_bar.pack_start(self._toast_revealer, True, True, 0)
# Schermata benvenuto (prima tab)
self._mostra_benvenuto()
def _build_headerbar(self):
hb = Gtk.HeaderBar()
hb.set_show_close_button(True)
hb.set_title(t("app.title"))
self.set_titlebar(hb)
# Pulsante nuova sessione
btn_new = Gtk.Button()
btn_new.set_tooltip_text(t("toolbar.session.tooltip"))
btn_new.add(Gtk.Image.new_from_icon_name("list-add-symbolic", Gtk.IconSize.BUTTON))
btn_new.connect("clicked", lambda b: self._on_nuova_sessione())
hb.pack_start(btn_new)
# Pulsante terminale locale
btn_term = Gtk.Button()
btn_term.set_tooltip_text(t("toolbar.local.tooltip"))
btn_term.add(Gtk.Image.new_from_icon_name("utilities-terminal-symbolic", Gtk.IconSize.BUTTON))
btn_term.connect("clicked", lambda b: self._on_terminale_locale())
hb.pack_start(btn_term)
# Pulsante quick connect
btn_qc = Gtk.Button()
btn_qc.set_tooltip_text(t("toolbar.quickconn.tooltip"))
btn_qc.add(Gtk.Image.new_from_icon_name("go-jump-symbolic", Gtk.IconSize.BUTTON))
btn_qc.connect("clicked", lambda b: self._on_quick_connect())
hb.pack_start(btn_qc)
# Pulsante cluster
btn_cl = Gtk.Button()
btn_cl.set_tooltip_text(t("toolbar.cluster.tooltip"))
btn_cl.add(Gtk.Image.new_from_icon_name("network-workgroup-symbolic", Gtk.IconSize.BUTTON))
btn_cl.connect("clicked", lambda b: self._on_cluster_from_toolbar())
hb.pack_start(btn_cl)
# Bottone tunnel unificato: indicatore stato + accesso al gestore
self._btn_tun_ind = Gtk.MenuButton()
_tun_box = Gtk.Box(spacing=2)
self._img_tun = Gtk.Image.new_from_icon_name("network-vpn-symbolic", Gtk.IconSize.BUTTON)
_tun_box.pack_start(self._img_tun, False, False, 0)
self._lbl_tun_count = Gtk.Label(label="")
_tun_box.pack_start(self._lbl_tun_count, False, False, 0)
self._btn_tun_ind.add(_tun_box)
self._btn_tun_ind.set_tooltip_text(t("tunnel.indicator_tooltip"))
self._tun_pop = Gtk.Popover()
self._tun_pop_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self._tun_pop_box.set_margin_start(8)
self._tun_pop_box.set_margin_end(8)
self._tun_pop_box.set_margin_top(8)
self._tun_pop_box.set_margin_bottom(8)
self._tun_pop.add(self._tun_pop_box)
self._tun_pop.connect("show", self._on_tun_pop_show)
self._btn_tun_ind.set_popover(self._tun_pop)
hb.pack_start(self._btn_tun_ind)
self._timer_tun_ind = GLib.timeout_add(3000, self._aggiorna_tun_indicator)
self._aggiorna_tun_indicator()
# Pulsante split
btn_split = Gtk.MenuButton()
btn_split.set_tooltip_text(t("toolbar.split.tooltip"))
self._split_img = Gtk.Image.new_from_icon_name("view-dual-symbolic", Gtk.IconSize.BUTTON)
btn_split.add(self._split_img)
split_menu = Gtk.Menu()
self._split_menu_items = []
for label, cb, mode in [
(f"□ {t('toolbar.split.single')}", self._split_singolo, "single"),
(f"◫ {t('toolbar.split.vertical')}", self._split_verticale, "vertical"),
(f"⬒ {t('toolbar.split.horizontal')}", self._split_orizzontale, "horizontal"),
]:
mi = Gtk.CheckMenuItem(label=label)
mi.connect("activate", lambda _, c=cb, m=mode: (c(), self._aggiorna_split_indicator(mode)))
split_menu.append(mi)
self._split_menu_items.append((mi, mode))
split_menu.show_all()
btn_split.set_popup(split_menu)
hb.pack_start(btn_split)
# Menu applicazione (⋮ tre puntini verticali)
self._menu_btn = Gtk.MenuButton()
self._menu_btn.set_direction(Gtk.ArrowType.DOWN)
self._menu_btn.set_tooltip_text(t("toolbar.menu.tooltip"))
self._menu_btn.add(Gtk.Image.new_from_icon_name("view-more-symbolic", Gtk.IconSize.BUTTON))
self._menu_btn.set_popup(self._build_menu())
hb.pack_end(self._menu_btn)
# Impostazioni (rotella ⚙)
btn_set = Gtk.Button()
btn_set.set_tooltip_text(t("toolbar.settings.tooltip"))
btn_set.add(Gtk.Image.new_from_icon_name("preferences-system-symbolic", Gtk.IconSize.BUTTON))
btn_set.connect("clicked", lambda b: self._on_impostazioni())
hb.pack_end(btn_set)
def _build_menu(self) -> Gtk.Menu:
menu = Gtk.Menu()
def _item(label, callback):
mi = Gtk.MenuItem(label=label)
mi.connect("activate", lambda _: callback())
menu.append(mi)
_item(t("menu.tools.tunnels"), self._on_tunnel_manager)
_item(t("menu.tools.broadcast"), self._on_broadcast)
_item(t("menu.tools.variables"), self._on_variabili_globali)
_item(t("menu.tools.ftp_server"), self._on_ftp_server)
_item(t("menu.tools.snippets"), self._apri_snippet_dialog)
_item(t("menu.tools.import_from"), self._on_importa_sessioni)
_item(t("menu.tools.audit"), self._on_audit_log)
_item(t("menu.tools.keepass"), self._on_keepass_settings)
menu.append(Gtk.SeparatorMenuItem())
for p_label, p_icon, p_callback in _plugin_menu_items():
_item(p_label, p_callback)
if _plugin_menu_items():
menu.append(Gtk.SeparatorMenuItem())
_item(t("menu.tools.crypto"), self._on_gestione_crypto)
_item(t("menu.tools.check_deps"), self._on_check_deps)
menu.append(Gtk.SeparatorMenuItem())
_item(t("menu.help.guide"), self._on_guida)
_item(t("menu.help.about"), self._on_about)
menu.append(Gtk.SeparatorMenuItem())
_item(t("menu.file.quit"), self._on_esci)
menu.show_all()
return menu
# ------------------------------------------------------------------
# Segnali
# ------------------------------------------------------------------
def _connect_signals(self):
self._pannello.connect("connetti", self._on_connetti)
self._pannello.connect("nuova", lambda p: self._on_nuova_sessione())
self._pannello.connect("modifica", self._on_modifica_sessione)
self._pannello.connect("elimina", self._on_elimina_sessione)
self._pannello.connect("duplica", self._on_duplica_sessione)
self._pannello.connect("apri-ft", lambda _p, n, d: self._apri_ft_da_sessione(d))
self._pannello.connect("ping", self._on_ping_sessione)
self._pannello.connect("apri-log", lambda _p, n, d: self._apri_log_viewer(n, d))
self._pannello.connect("apri-monitor", lambda _p, n, d: self._apri_sysmon(n, d))
self._pannello.connect("apri-cron", lambda _p, n, d: self._apri_cron(n, d))
self._pannello.connect("apri-cluster", lambda _p, n, d: self._apri_cluster(n, d))
self.connect("delete-event", self._on_close)
def _accel_to_gtk(self, shortcut):
parti = shortcut.rsplit("+", 1)
if len(parti) != 2:
return None
mods_str, tasto = parti
parti_mods = mods_str.split("+")
gtk_mods = []
for m in parti_mods:
m = m.strip()
if m in ("Ctrl", "Control"):
gtk_mods.append("<Primary>")
elif m == "Shift":
gtk_mods.append("<Shift>")
elif m == "Alt":
gtk_mods.append("<Alt>")
elif m in ("Super", "Meta"):
gtk_mods.append("<Super>")
else:
return None
acceleratore = "".join(gtk_mods) + tasto.strip()
key, mod = Gtk.accelerator_parse(acceleratore)
if key == 0 and mod == 0:
return None
return acceleratore, key, mod
def _toggle_sidebar(self):
visibile = self._pannello.get_visible()
self._pannello.set_visible(not visibile)
s = config_manager.load_settings()
s.setdefault("display", {})["sidebar_visible"] = not visibile
config_manager.save_settings(s)
return True
def _toggle_fullscreen(self):
if hasattr(self, "_fullscreen_active") and self._fullscreen_active:
self.unfullscreen()
self._fullscreen_active = False
else:
self.fullscreen()
self._fullscreen_active = True
return True
def _setup_accels(self):
if hasattr(self, "_accel_group") and self._accel_group:
self.remove_accel_group(self._accel_group)
ag = Gtk.AccelGroup()
self.add_accel_group(ag)
self._accel_group = ag
mappa_azioni = {
"new_terminal": self._on_terminale_locale,
"new_session": self._on_nuova_sessione,
"close_tab": self._chiudi_tab_corrente,
"next_tab": lambda: self._notebook_attivo.next_page() or True,
"prev_tab": lambda: self._notebook_attivo.prev_page() or True,
"find": self._attiva_ricerca_terminale,
"toggle_sidebar": self._toggle_sidebar,
"fullscreen": self._toggle_fullscreen,
}
shortcuts = config_manager.load_settings().get("shortcuts", {})
for nome, combinazione in shortcuts.items():
azione = mappa_azioni.get(nome)
if not azione:
continue
risultato = self._accel_to_gtk(combinazione)
if risultato is None:
continue
_, key, mod = risultato
ag.connect(key, mod, Gtk.AccelFlags.VISIBLE, lambda *a, cb=azione: cb())
key_fissa, mod_fissa = Gtk.accelerator_parse("<Primary><Shift>G")
if key_fissa:
ag.connect(key_fissa, mod_fissa, Gtk.AccelFlags.VISIBLE,
lambda *_: self._on_variabili_globali() or True)
def _attiva_ricerca_terminale(self):
idx = self._notebook_attivo.get_current_page()
if idx < 0:
return True
page = self._notebook_attivo.get_nth_page(idx)
if hasattr(page, "mostra_cerca"):
page.mostra_cerca()
return True
def _aggiorna_welcome_recenti(self):
"""Aggiorna la lista recenti nella schermata home dopo lo sblocco crypto."""
idx = self._notebook.page_num(self._notebook.get_nth_page(0))
welcome = self._notebook.get_nth_page(0)
if hasattr(welcome, "aggiorna"):
welcome.aggiorna()
def _mostra_benvenuto(self):
welcome = WelcomeWidget()
welcome.connect("nuova-sessione", lambda w: self._on_nuova_sessione())
welcome.connect("terminale-locale", lambda w: self._on_terminale_locale())
welcome.connect("apri-sessione", lambda w, n, d: self._on_connetti(None, n, d))
welcome.show_all()
lbl = Gtk.Label(label=t("app.home_tab"))
self._notebook.append_page(welcome, lbl)
# ------------------------------------------------------------------
# Apertura sessioni
# ------------------------------------------------------------------
def _on_connetti(self, panel, nome: str, dati: dict):
proto = dati.get("protocol", "ssh")
pre_cmd = dati.get("pre_cmd", "").strip()
wol_mac = dati.get("wol_mac", "") if dati.get("wol_enabled") else ""
if (dati.get("jump_host", "").strip() and
proto not in ("ssh", "mosh") and
not self._supports_ssh_gateway(dati)):
self._warn(
"SSH gateway supportato solo per SFTP, Telnet, RDP, VNC e SPICE; "
"FTP/FTPS e i protocolli locali non possono usare un singolo port forwarding."
)
return
config_manager.add_recent(nome, dati)
self._pannello.aggiorna()
self._aggiorna_welcome_recenti()
use_gateway = self._needs_ssh_gateway(dati)
if pre_cmd or wol_mac or use_gateway:
def _bg():
try:
dati_loc = dict(dati)
if pre_cmd:
timeout = dati_loc.get("pre_cmd_timeout", 15)
try:
import shlex as _shlex_pre
subprocess.run(_shlex_pre.split(pre_cmd), shell=False, timeout=timeout)
except Exception as e:
GLib.idle_add(self._warn, f"Pre-cmd fallito: {e}")
return
if wol_mac:
err = self._invia_wol(wol_mac, dati_loc.get("wol_wait", 20))
if err:
GLib.idle_add(self._warn, f"WoL fallito: {err}")
return
if use_gateway:
local_port, gw_proc = self._start_ssh_gateway(dati_loc)
if local_port is None:
GLib.idle_add(self._warn, "SSH gateway fallito: tunnel non stabilito")
return
dati_loc["_gateway_tunnel"] = gw_proc
dati_loc["_gateway_local_port"] = str(local_port)
dati_loc["_gateway_target_host"] = dati_loc.get("host", "")
GLib.idle_add(self._apri_protocollo, proto, nome, dati_loc)
except Exception as exc:
_log.error("Errore nel thread di connessione (_bg): %s", exc, exc_info=True)
GLib.idle_add(self._warn, f"Errore di connessione: {exc}")
threading.Thread(target=_bg, daemon=True).start()
return
self._apri_protocollo(proto, nome, dati)
def _needs_ssh_gateway(self, dati: dict) -> bool:
"""Check if this connection needs an SSH gateway tunnel."""
return bool(dati.get("jump_host", "").strip() and
self._supports_ssh_gateway(dati))
@staticmethod
def _supports_ssh_gateway(dati: dict) -> bool:
"""Return whether one local TCP forward can carry this protocol."""
proto = dati.get("protocol", "")
return (proto in ("sftp", "telnet", "rdp", "vnc", "spice") or
(proto == "file_transfer" and
dati.get("ft_protocol", "SFTP").upper() == "SFTP"))
@staticmethod
def _apply_ssh_gateway(dati: dict) -> dict:
"""Route a gateway-backed connection through its local TCP forward."""
local_port = dati.get("_gateway_local_port")
if not local_port:
return dati
forwarded = dict(dati)
forwarded["host"] = "127.0.0.1"
forwarded["port"] = str(local_port)
return forwarded
def _start_ssh_gateway(self, dati: dict) -> tuple:
"""Start an SSH tunnel to the jump host for gateway access.
Returns (local_port, process) or (None, None) on failure.
"""
import socket as _sock
import time
jump_host = dati.get("jump_host", "").strip()
jump_user = dati.get("jump_user", "").strip()
jump_port = dati.get("jump_port", "22").strip()
target_host = dati.get("host", "").strip()
target_port = dati.get("port", "").strip()
pkey = dati.get("private_key", "").strip()
pwd = dati.get("password", "")
local_port = self._find_free_port()
if local_port is None:
return None, None
ssh_exe = shutil.which("ssh") or "ssh"
strict_default = config_manager.load_settings().get("ssh", {}).get("strict_host_check", True)
strict = "yes" if dati.get("strict_host", strict_default) else "accept-new"
cmd = [
ssh_exe, "-N", "-T",
"-o", f"StrictHostKeyChecking={strict}",
"-o", "ConnectTimeout=10",
"-o", "ServerAliveInterval=15",
"-o", "ExitOnForwardFailure=yes",
"-p", jump_port,
]
if pkey and os.path.exists(pkey):
cmd.extend(["-i", pkey])
target = f"{jump_user}@{jump_host}" if jump_user else jump_host
cmd.extend(["-L", f"{local_port}:{target_host}:{target_port}", target])
env = os.environ.copy()
askpass = None
if pwd and not pkey:
askpass_dir = os.path.join(os.path.expanduser("~"), ".cache", "pcm")
os.makedirs(askpass_dir, mode=0o700, exist_ok=True)
if os.stat(askpass_dir).st_uid != os.getuid():
_log.error("SSH gateway: directory SSH_ASKPASS non di proprieta dell'utente")
return None, None
fd, askpass = tempfile.mkstemp(prefix=".pcm_ask_", suffix=".sh", dir=askpass_dir, text=True)
import shlex as _shlex
with os.fdopen(fd, "w") as f:
f.write(f"#!/bin/sh\nprintf '%s' {_shlex.quote(pwd)}\n")
os.chmod(askpass, 0o700)
env["SSH_ASKPASS"] = askpass
env["SSH_ASKPASS_REQUIRE"] = "force"
try:
proc = subprocess.Popen(
cmd, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
env=env,
)
if askpass:
def _cleanup_askpass():
proc.wait()
with contextlib.suppress(OSError):
os.unlink(askpass)
threading.Thread(target=_cleanup_askpass, daemon=True).start()
for _ in range(60):
time.sleep(0.1)
try:
s = _sock.create_connection(("127.0.0.1", local_port), timeout=0.5)
s.close()
return local_port, proc
except OSError:
if proc.poll() is not None:
return None, None
proc.terminate()
try:
proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
return None, None
except Exception:
if askpass:
with contextlib.suppress(OSError):
os.unlink(askpass)
return None, None
def apri_da_cli(self, uri: str):
"""Apre una connessione da URI passato via riga di comando.
Formati supportati:
ssh://nome_sessione — cerca sessione salvata per nome o hostname
ssh://user@host:port — connessione ad-hoc
rdp://host?mode=external — forza client esterno
sftp://host / ftp://host — file transfer
vnc://host / telnet://host — altri protocolli
Query string opzionali (solo connessioni ad-hoc):
?mode=external — apre in terminale/client esterno
?terminal=xterm — emulatore esterno specifico
"""
_PROTO_MAP = {
"ssh": "ssh", "telnet": "telnet", "mosh": "mosh", "serial": "serial",
"rdp": "rdp", "vnc": "vnc",
"sftp": "file_transfer", "ftp": "file_transfer", "ftps": "file_transfer",
}
_DEFAULT_PORTS = {
"ssh": "22", "telnet": "23", "mosh": "60001", "rdp": "3389",
"vnc": "5900", "file_transfer": "22", "ftp": "21", "ftps": "21",
}
_FT_PROTO = {"sftp": "SFTP", "ftp": "FTP", "ftps": "FTPS"}
# Se crypto è abilitato ma non ancora sbloccato, rimanda dopo l'unlock
try:
import crypto_manager
if crypto_manager.is_enabled() and not crypto_manager.is_unlocked():
self._pending_cli_uri = uri
return
except ImportError:
_log.warning("cryptography non installato — apertura URI sospesa")
GLib.idle_add(self._warn, "cryptography non installato; impossibile aprire URI con credenziali cifrate.")
parsed = urlparse(uri)
scheme = (parsed.scheme or "ssh").lower()
proto = _PROTO_MAP.get(scheme)
if not proto:
self._warn(f"Protocollo non supportato nella URI: {scheme}")
return
host = parsed.hostname or ""
port = str(parsed.port) if parsed.port else ""
user = parsed.username or ""
password = parsed.password or ""
# Opzioni da query string (solo per connessioni ad-hoc)
from urllib.parse import parse_qs
qs = parse_qs(parsed.query)
mode_ext = qs.get("mode", [""])[0].lower() == "external"
terminal_ext = qs.get("terminal", [""])[0]
# --- Cerca sessione salvata ---
profili = config_manager.load_profiles()
nome_match = None
dati_match = None
# 1. Nome sessione == host nella URI (case-insensitive)
for nome_s, dati_s in profili.items():
if nome_s.lower() == host.lower():
nome_match, dati_match = nome_s, dati_s
break
# 2. Hostname + stesso protocollo
if not dati_match:
for nome_s, dati_s in profili.items():
if (dati_s.get("host", "").lower() == host.lower()
and dati_s.get("protocol") == proto):
nome_match, dati_match = nome_s, dati_s
break
# 3. Hostname qualsiasi protocollo
if not dati_match:
for nome_s, dati_s in profili.items():
if dati_s.get("host", "").lower() == host.lower():
nome_match, dati_match = nome_s, dati_s
break
if dati_match:
dati = dict(dati_match)
if user:
dati["user"] = user
if port:
dati["port"] = port
self._on_connetti(None, nome_match, dati)
return
# --- Connessione ad-hoc ---
dati = {
"protocol": proto,
"host": host,
"port": port or _DEFAULT_PORTS.get(proto, ""),
"user": user,
"password": password,
}
if scheme in _FT_PROTO:
dati["ft_protocol"] = _FT_PROTO[scheme]
dati["ftp_tls"] = scheme == "ftps"
# Modalità apertura per protocollo
mode = qs.get("mode", [""])[0].lower() # "external" | "internal" | ""
if proto in ("ssh", "telnet", "mosh", "serial"):
if mode in ("external", "internal"):
dati["ssh_open_mode"] = mode
if terminal_ext:
dati["terminal_type"] = terminal_ext
elif proto == "rdp":
# default RDP è già "external"; accetta esplicito "internal"
if mode in ("external", "internal"):
dati["rdp_open_mode"] = mode
elif proto == "vnc":
# vnc_internal=True → viewer embedded, False → client esterno
if mode == "internal":
dati["vnc_internal"] = True