Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
537 lines (467 loc) · 22.2 KB
/
Copy pathmain.py
File metadata and controls
537 lines (467 loc) · 22.2 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
"""
main.py - Entry point for NEO SSH-Win Manager.
"""
import sys
import os
import threading
import traceback
from pathlib import Path
# ── 0. SSH askpass helper (MUST BE FIRST, before anything else) ───────────
# OpenSSH SSH_ASKPASS helper for non-interactive password input.
# Reads SSH_ASKPASS_TOKEN env var and fetches password via Secure IPC.
# Used by system_info_panel.py for password-based SSH connections.
if len(sys.argv) > 1 and sys.argv[1] == "--pass-helper":
# Hardened SSH_ASKPASS helper: Fetch password from main instance via Secure IPC.
token = os.environ.get("SSH_ASKPASS_TOKEN", "")
if not token:
sys.exit(1)
import json
import ctypes
import ctypes.wintypes
pipe_name = r"\\.\pipe\SSHWinManager_IPC_v1"
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
OPEN_EXISTING = 3
handle = ctypes.windll.kernel32.CreateFileW(
pipe_name, GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None
)
if handle != -1:
req = json.dumps({"action": "get_askpass", "token": token}).encode('utf-8')
written = ctypes.wintypes.DWORD()
ctypes.windll.kernel32.WriteFile(handle, req, len(req), ctypes.byref(written), None)
buf = ctypes.create_string_buffer(4096)
read = ctypes.wintypes.DWORD()
if ctypes.windll.kernel32.ReadFile(handle, buf, 4096, ctypes.byref(read), None):
try:
resp = json.loads(buf.value[:read.value].decode('utf-8'))
if resp.get("success"):
print(resp.get("password", ""), end="")
except Exception:
pass
ctypes.windll.kernel32.CloseHandle(handle)
sys.exit(0)
# ── 0.2 Elevated Rechte-Reparatur-Helfer (via UAC-Relaunch, siehe
# src/permission_repair.py) ─────────────────────────────────────────────────
# Headless: repairs owner and permissions only, then exits — no GUI, no
# single-instance check, no second tray entry.
# Usage: --repair-permissions "<path>[;<path>...]" ["<target-sid>"]
# The target SID names the user the folder should belong to. It is required
# because the UAC prompt can be answered with the credentials of a *different*
# administrator — without it, the repair would hand the data folder to that
# administrator instead of the actual user.
if len(sys.argv) > 2 and sys.argv[1] == "--repair-permissions":
sys.path.insert(0, os.path.dirname(__file__))
from src.permission_repair import repair_owner
_paths = [Path(p) for p in sys.argv[2].split(";") if p]
_target_sid = sys.argv[3] if len(sys.argv) > 3 else None
sys.exit(0 if repair_owner(_paths, _target_sid) else 1)
# ── 0.5 CLI-Modus ist nicht Sache der GUI-EXE ───────────────────────────────
# Eine --windowed EXE hat keine nutzbare stdin/stdout im Parent-Terminal.
# Für CLI-Zugriff existiert NeoSSHWinManager-cli.exe (console-subsystem).
if any(arg in sys.argv for arg in ("--connect-cli", "-connectssh")):
import ctypes
sys.path.insert(0, os.path.dirname(__file__))
from src.config import read_install_prefs
from src.i18n import set_language, tr as _tr
# No user is signed in yet: use the language chosen in the installer.
set_language(read_install_prefs().get("language", "en"))
ctypes.windll.user32.MessageBoxW(
None,
_tr("cli.wrong_entry.body"),
_tr("cli.wrong_entry.title"),
0x30, # MB_ICONWARNING
)
sys.exit(2)
# ── 1. Single-instance check (before QApplication and all others) ─────────────
from src.single_instance import ensure_single_instance
ensure_single_instance()
# ── 2. Now import everything else ────────────────────────────────
import ctypes
import json
# Ensure src/ is importable from project root
sys.path.insert(0, os.path.dirname(__file__))
def _is_admin() -> bool:
"""Check if the process is running with administrator rights."""
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except Exception:
return False
def _request_elevation() -> bool:
"""
Restart the app with admin rights (UAC dialog).
Returns True if the app was restarted (caller should exit).
"""
if _is_admin():
return False
if "--no-elevate" in sys.argv:
return False
try:
from src.config import get_config_path, AppSettings
config_file = get_config_path()
if config_file.exists():
with open(config_file, 'r', encoding='utf-8') as f:
data = json.load(f)
settings = AppSettings.from_dict(data.get('settings', {}))
if not settings.require_admin:
return False
except Exception:
pass
try:
params = " ".join(f'"{a}"' if " " in a else a for a in sys.argv[1:] if a != "--no-elevate")
ret = ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, params, None, 1 # SW_SHOWNORMAL
)
if ret > 32:
return True
except Exception:
pass
return False
from PyQt6.QtWidgets import QApplication
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QIcon
from src.ui.theme import STYLESHEET, get_stylesheet
from src.database import init_db
from src.i18n import tr
from src.channel import display_name
def _install_global_exception_handlers():
"""
Install process-wide exception handlers for UI and worker threads.
Goal: log/notify on unexpected errors and avoid silent hard-crashes.
"""
_in_handler = {"active": False}
def _handle(exc_type, exc_value, exc_tb):
# Keep standard behavior for Ctrl+C.
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_tb)
return
if _in_handler["active"]:
# Avoid recursive exception handling loops.
return
_in_handler["active"] = True
try:
err_text = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
# Persist for diagnostics.
try:
appdata = os.environ.get("APPDATA", str(Path.home()))
report_path = Path(appdata) / "SSHWinManager" / "crash_report.txt"
with open(report_path, "a", encoding="utf-8") as f:
f.write("\n" + "=" * 80 + "\n")
f.write(err_text)
# SECURITY FIX: Restrict crash_report.txt to owner only
# to prevent other local users from reading stack traces that may
# contain connection metadata (host, user, etc.)
try:
from src.database import _set_secure_permissions
_set_secure_permissions(report_path)
except Exception:
pass
except Exception:
pass
# App logger (if already initialized).
try:
from src.app_logger import logger as _logger
_logger.error("UNHANDLED EXCEPTION\n%s", err_text)
except Exception:
pass
# User-visible error without aborting process.
try:
from PyQt6.QtWidgets import QMessageBox, QPushButton
from src.ui.icons import icon as svg_icon
box = QMessageBox(None)
box.setIcon(QMessageBox.Icon.Critical)
box.setWindowTitle(tr("app.unexpected_error.title"))
box.setText(tr("app.unexpected_error.body"))
copy_btn = box.addButton(tr("app.unexpected_error.copy"), QMessageBox.ButtonRole.ActionRole)
copy_btn.setIcon(svg_icon("copy", "#ffffff", 14))
copy_btn.clicked.connect(lambda: QApplication.clipboard().setText(err_text))
box.addButton(QMessageBox.StandardButton.Ok)
box.exec()
except Exception:
# Last-resort stderr output.
try:
print(err_text, file=sys.stderr)
except Exception:
pass
finally:
_in_handler["active"] = False
def _threading_hook(args: threading.ExceptHookArgs):
_handle(args.exc_type, args.exc_value, args.exc_traceback)
sys.excepthook = _handle
threading.excepthook = _threading_hook
def main():
# Admin elevation only if permanently enabled in settings
if os.name == "nt":
try:
from src.config import get_config_path, AppSettings
config_file = get_config_path()
if config_file.exists():
with open(config_file, 'r', encoding='utf-8') as f:
data = json.load(f)
settings = AppSettings.from_dict(data.get('settings', {}))
if settings.require_admin and _request_elevation():
sys.exit(0)
except Exception:
pass
# Enable HiDPI scaling
QApplication.setHighDpiScaleFactorRoundingPolicy(
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
)
try:
with open(os.path.join(os.path.dirname(__file__), "src", "version.txt"), "r", encoding="utf-8") as f:
APP_VERSION = f.read().strip()
except Exception:
APP_VERSION = "?"
# ── Pending update ────────────────────────────────────────────────────
# If an update installer was downloaded and armed, hand over to it before
# anything else touches the database or the UI: a helper script waits for
# this process to exit, runs the installer and starts the app again — also
# when the installer is cancelled.
try:
from src.updater import maybe_install_pending_update
if maybe_install_pending_update(APP_VERSION):
sys.exit(0)
except Exception:
pass # never block startup because of the updater
# Windows taskbar icon fix (AppUserModelID)
try:
myappid = f'neo.sshwinmanager.{APP_VERSION}'
if os.name == 'nt':
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except Exception:
pass
# QtWebEngineWidgets MUST be imported before QApplication is created.
try:
from PyQt6.QtWebEngineWidgets import QWebEngineView as _QWebEngineView # noqa: F401
from PyQt6.QtWebEngineCore import QWebEnginePage as _QWebEnginePage # noqa: F401
from PyQt6.QtWebChannel import QWebChannel as _QWebChannel # noqa: F401
except ImportError:
pass # xterm terminal feature unavailable; app still runs without it
app = QApplication(sys.argv)
app_name = display_name()
app.setApplicationName(app_name)
app.setApplicationDisplayName(app_name)
app.setApplicationVersion(APP_VERSION)
app.setOrganizationName("NeoSSHWinManager")
_install_global_exception_handlers()
def get_resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.dirname(__file__), relative_path)
for icon_file in ("app_icon.ico", "app_icon.png"):
icon_path = get_resource_path(os.path.join("assets", icon_file))
if os.path.exists(icon_path):
app.setWindowIcon(QIcon(icon_path))
break
# Init logger AFTER QApplication (QObject requires QApplication to exist)
from src.app_logger import init_logger, logger
init_logger()
logger.info("Application started (Standard Mode)")
# Default font – set BEFORE stylesheet so Qt can correctly convert px→pt
font = QFont("Segoe UI", 10)
app.setFont(font)
# Apply global stylesheet
from src.ui.theme import THEME_COLORS
app.setStyleSheet(get_stylesheet("dark"))
# Setze Palette für native Popups
from PyQt6.QtGui import QPalette, QColor
palette = app.palette()
palette.setColor(QPalette.ColorRole.Window, QColor(THEME_COLORS["dark"]["surface"]))
palette.setColor(QPalette.ColorRole.WindowText, QColor(THEME_COLORS["dark"]["text"]))
app.setPalette(palette)
# ── 3. Database Initialization ────────────────────────────────
# Repair check first: makes the data folder usable again if an older
# version locked us out of it or an install/update left it owned by
# another account (see src/permission_repair.py), before init_db() runs.
from src.database import data_dir
from src.permission_repair import is_accessible, run_startup_check
_data_dir = data_dir()
run_startup_check(_data_dir)
# If the folder is still unusable, say so in plain words instead of dying
# in init_db() with "unable to open database file" and a stack trace the
# user cannot act on (GitHub issue #22).
if not is_accessible(_data_dir):
from src.ui.dialogs.styled_message_box import StyledMessageBox
StyledMessageBox.critical(
None,
tr("permrepair.blocked.title"),
tr("permrepair.blocked.body", folder=str(_data_dir)),
)
sys.exit(1)
init_db()
# ── 3.5 Windows Auto-Login (wenn aktiviert) ────────────────────
windows_user = os.environ.get("USERNAME", "").strip()
if windows_user:
from src.auth_manager import AuthManager, Session
user_data = AuthManager.get_user_by_username(windows_user)
if user_data:
# Prüfe ob Auto-Login aktiviert ist für diesen Benutzer
from src.database import get_connection
with get_connection() as conn:
row = conn.execute(
"SELECT auto_login FROM app_settings WHERE user_id = ?",
(user_data["id"],)
).fetchone()
auto_login_enabled = row and bool(row["auto_login"])
if auto_login_enabled:
logger.info(f"Windows Auto-Login: Benutzer '{windows_user}' gefunden.")
# Für Auto-Login ohne Passwort können wir den Encryption Key nicht laden
# Wir zeigen trotzdem den Login-Dialog, aber mit vorausgefülltem Benutzernamen
# Der Benutzer muss nur das Passwort eingeben
else:
logger.debug(f"Auto-Login deaktiviert für '{windows_user}'")
# ── 4. Login / Registration ──────────────────────────────────
# AuthManager loads the persisted login attempts on import, so it is
# imported only now, after the permission repair and init_db().
from src.auth_manager import AuthManager, Session
from src.ui.dialogs.login_dialog import LoginDialog
# Single-user mode keeps the app password in Windows Credential Manager
# and therefore needs no interactive login. It is also how the app starts
# the very first time, so nobody has to create an account up front.
single_user = AuthManager.sign_in_automatically()
if single_user:
Session.login(single_user)
else:
# The login screen looks like the app did for whoever signed in last:
# same theme, accent colour and language.
look = AuthManager.login_screen_appearance()
from src.i18n import set_language, is_rtl
from src.ui.theme import set_current_accent
set_language(look["language"])
app.setLayoutDirection(
Qt.LayoutDirection.RightToLeft if is_rtl() else Qt.LayoutDirection.LeftToRight
)
set_current_accent(look["accent"], look["accent_text"])
from src.ui.node_network import set_background_enabled
set_background_enabled(look["background_network"])
app.setStyleSheet(get_stylesheet(look["theme"]))
login_dlg = LoginDialog(theme=look["theme"])
if login_dlg.exec() != LoginDialog.DialogCode.Accepted:
sys.exit(0)
if not Session.is_logged_in():
sys.exit(0)
AuthManager.record_login(Session.current().id)
# Apply user's preferred language
user_settings = None
try:
from src.auth_manager import UserConnectionManager
from src.i18n import set_language, is_rtl
ucm = UserConnectionManager(Session.current())
user_settings = ucm.get_settings()
set_language(user_settings.language)
# Mirror the whole UI for right-to-left languages (Arabic).
app.setLayoutDirection(
Qt.LayoutDirection.RightToLeft if is_rtl() else Qt.LayoutDirection.LeftToRight
)
from src.ui.theme import set_current_accent
set_current_accent(getattr(user_settings, "accent_color", ""),
getattr(user_settings, "accent_text_color", ""))
app.setStyleSheet(get_stylesheet(user_settings.theme))
# Telemetry Opt-In / Send
if not getattr(user_settings, 'telemetry_prompt_shown', False):
from src.ui.dialogs.telemetry_prompt_dialog import TelemetryPromptDialog
from PyQt6.QtWidgets import QDialog
prompt = TelemetryPromptDialog()
if prompt.exec() == QDialog.DialogCode.Accepted:
user_settings.telemetry_enabled = True
else:
user_settings.telemetry_enabled = False
user_settings.telemetry_prompt_shown = True
ucm.update_settings(user_settings)
from src.telemetry import send_telemetry_async
send_telemetry_async('install', user_settings)
from src.telemetry import send_telemetry_async
send_telemetry_async('login', user_settings)
# Wurde ein zuvor angestoßenes Update tatsächlich durchgeführt? Das
# sieht man erst jetzt: läuft die Zielversion, hat der Installer
# gegriffen, sonst wurde er abgebrochen oder ist gescheitert.
from src.updater import take_update_attempt
_attempt = take_update_attempt()
if _attempt:
send_telemetry_async(
'update_result',
user_settings,
result='installed' if APP_VERSION == _attempt.get("to_version") else 'not_installed',
target=_attempt.get("to_version"),
)
except Exception as e:
logger.warning(f"Language/theme/telemetry init failed: {e}")
# ── Prerequisite check: WinFSP + SSHFS-Win required ─────────────────
from src.sshfs_controller import SSHFSController
import webbrowser as _webbrowser
_prereq = SSHFSController.get_install_status()
if not _prereq["winfsp"] or not _prereq["sshfs_win"]:
from PyQt6.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton
from PyQt6.QtCore import Qt as _Qt
_dlg = QDialog()
_dlg.setWindowTitle(tr("prereq.dialog.title"))
_dlg.setMinimumWidth(440)
_dlg.setWindowFlag(_Qt.WindowType.WindowCloseButtonHint, False)
_vl = QVBoxLayout(_dlg)
_vl.setSpacing(16)
_vl.setContentsMargins(24, 24, 24, 24)
if not _prereq["winfsp"] and not _prereq["sshfs_win"]:
_msg = tr("prereq.dialog.text_both")
elif not _prereq["winfsp"]:
_msg = tr("prereq.dialog.text_winfsp")
else:
_msg = tr("prereq.dialog.text_sshfs")
_lbl = QLabel(_msg)
_lbl.setWordWrap(True)
_vl.addWidget(_lbl)
_btn_row = QHBoxLayout()
_btn_row.setSpacing(8)
if not _prereq["winfsp"]:
_b1 = QPushButton(tr("prereq.dialog.download_winfsp"))
_b1.clicked.connect(lambda: _webbrowser.open("https://winfsp.dev/rel/"))
_btn_row.addWidget(_b1)
if not _prereq["sshfs_win"]:
_b2 = QPushButton(tr("prereq.dialog.download_sshfs"))
_b2.clicked.connect(lambda: _webbrowser.open("https://github.com/winfsp/sshfs-win/releases/latest"))
_btn_row.addWidget(_b2)
_vl.addLayout(_btn_row)
_exit_btn = QPushButton(tr("prereq.dialog.exit"))
_exit_btn.clicked.connect(_dlg.accept)
_vl.addWidget(_exit_btn)
_dlg.exec()
sys.exit(0)
# Don't quit when the last window is hidden (tray support)
app.setQuitOnLastWindowClosed(False)
try:
# Create and show main window (maximiert mit Titelleiste)
# The large UI module is imported only after the login, so the
# login dialog appears sooner.
from src.ui.main_window import MainWindow
window = MainWindow()
window.showMaximized()
# Start Update Check
from src.updater import UpdaterManager
from src.ui.dialogs.update_dialog import run_update_dialog, run_pending_update_dialog
updater = UpdaterManager(app.applicationVersion())
def _on_update_available(version: str, changelog: str, download_url: str, obj_type: str):
run_update_dialog(window, updater, version, changelog, download_url, obj_type)
def _on_no_update():
# A leftover installer for a *newer* version can only exist if the
# user declined it earlier — offer it again instead of hiding it.
run_pending_update_dialog(window, updater)
updater.update_available.connect(_on_update_available)
updater.check_failed.connect(lambda _msg: _on_no_update())
updater.no_update_available.connect(_on_no_update)
# Prüfung beim Programmstart von der manuellen aus den Einstellungen
# unterscheidbar machen (siehe src/telemetry.py).
from src.telemetry import attach_update_telemetry
attach_update_telemetry(updater, 'startup', user_settings)
updater.check_for_updates_async()
sys.exit(app.exec())
except Exception as e:
err_msg = f"FATAL CRASH during startup/main loop: {e}\n{traceback.format_exc()}"
print(err_msg, file=sys.stderr)
with open("crash_report.txt", "w", encoding="utf-8") as f:
f.write(err_msg)
try:
from src.app_logger import logger
logger.error(err_msg)
except Exception:
pass
sys.exit(1)
if __name__ == "__main__":
main()