ser2netweb 3.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ser2netweb/__init__.py +20 -0
- ser2netweb/__main__.py +6 -0
- ser2netweb/accounts.py +503 -0
- ser2netweb/cli.py +489 -0
- ser2netweb/clock.py +128 -0
- ser2netweb/config.py +4491 -0
- ser2netweb/console.py +181 -0
- ser2netweb/datalock.py +181 -0
- ser2netweb/engine/__init__.py +0 -0
- ser2netweb/engine/access.py +173 -0
- ser2netweb/engine/bindhint.py +115 -0
- ser2netweb/engine/bridge.py +1928 -0
- ser2netweb/engine/cluster.py +1140 -0
- ser2netweb/engine/modbus.py +530 -0
- ser2netweb/engine/modbus_gateway.py +1465 -0
- ser2netweb/engine/mqtt_pub.py +632 -0
- ser2netweb/engine/netguard.py +805 -0
- ser2netweb/engine/netinfo.py +199 -0
- ser2netweb/engine/portdiag.py +414 -0
- ser2netweb/engine/portlist.py +471 -0
- ser2netweb/engine/protocols/__init__.py +28 -0
- ser2netweb/engine/protocols/base.py +117 -0
- ser2netweb/engine/protocols/raw.py +12 -0
- ser2netweb/engine/protocols/rfc2217.py +586 -0
- ser2netweb/engine/protocols/telnet.py +172 -0
- ser2netweb/engine/serial_compat.py +598 -0
- ser2netweb/engine/serial_io.py +210 -0
- ser2netweb/engine/serial_link.py +414 -0
- ser2netweb/engine/sockopts.py +103 -0
- ser2netweb/engine/sparkplug.py +538 -0
- ser2netweb/engine/sparkplug_node.py +550 -0
- ser2netweb/engine/supervisor.py +533 -0
- ser2netweb/engine/tls.py +232 -0
- ser2netweb/envvars.py +57 -0
- ser2netweb/explain.py +117 -0
- ser2netweb/healthcheck.py +78 -0
- ser2netweb/i18n.py +110 -0
- ser2netweb/importer.py +550 -0
- ser2netweb/layout.py +118 -0
- ser2netweb/licences.py +86 -0
- ser2netweb/locale/tr.json +1569 -0
- ser2netweb/logsetup.py +253 -0
- ser2netweb/logtext.py +23 -0
- ser2netweb/notify.py +761 -0
- ser2netweb/optional.py +76 -0
- ser2netweb/reload.py +295 -0
- ser2netweb/runtime.py +762 -0
- ser2netweb/sdnotify.py +85 -0
- ser2netweb/ser2net_import.py +2001 -0
- ser2netweb/signins.py +98 -0
- ser2netweb/standalone.py +154 -0
- ser2netweb/state.py +1457 -0
- ser2netweb/storage.py +130 -0
- ser2netweb/textfold.py +51 -0
- ser2netweb/tlsreload.py +37 -0
- ser2netweb/watchdog.py +201 -0
- ser2netweb/web/__init__.py +0 -0
- ser2netweb/web/api.py +793 -0
- ser2netweb/web/auth.py +699 -0
- ser2netweb/web/certinfo.py +144 -0
- ser2netweb/web/httpguard.py +413 -0
- ser2netweb/web/ldap_auth.py +556 -0
- ser2netweb/web/oidc_auth.py +330 -0
- ser2netweb/web/proxy.py +398 -0
- ser2netweb/web/routes/__init__.py +78 -0
- ser2netweb/web/routes/cluster.py +669 -0
- ser2netweb/web/routes/common.py +359 -0
- ser2netweb/web/routes/console.py +451 -0
- ser2netweb/web/routes/forms.py +853 -0
- ser2netweb/web/routes/login.py +573 -0
- ser2netweb/web/routes/mappings.py +470 -0
- ser2netweb/web/routes/ops.py +374 -0
- ser2netweb/web/routes/settings.py +2135 -0
- ser2netweb/web/routes/system.py +308 -0
- ser2netweb/web/routes/totp.py +282 -0
- ser2netweb/web/selfsigned.py +129 -0
- ser2netweb/web/server.py +483 -0
- ser2netweb/web/static/app.css +327 -0
- ser2netweb/web/static/app.js +1102 -0
- ser2netweb/web/static/htmx.min.js +1 -0
- ser2netweb/web/static/points.js +218 -0
- ser2netweb/web/static/theme.js +7 -0
- ser2netweb/web/static/xterm-addon-fit.js +2 -0
- ser2netweb/web/static/xterm.css +218 -0
- ser2netweb/web/static/xterm.js +2 -0
- ser2netweb/web/templates/_cluster_body.html +109 -0
- ser2netweb/web/templates/_console.html +21 -0
- ser2netweb/web/templates/_footer.html +13 -0
- ser2netweb/web/templates/_login_notice.html +8 -0
- ser2netweb/web/templates/_macros.html +21 -0
- ser2netweb/web/templates/_mapping_form.html +477 -0
- ser2netweb/web/templates/_mapping_log.html +28 -0
- ser2netweb/web/templates/_mapping_traces.html +44 -0
- ser2netweb/web/templates/_mappings_body.html +149 -0
- ser2netweb/web/templates/_modbus_read.html +18 -0
- ser2netweb/web/templates/_ports_table.html +37 -0
- ser2netweb/web/templates/_serial_port_select.html +48 -0
- ser2netweb/web/templates/_shell.html +41 -0
- ser2netweb/web/templates/audit.html +55 -0
- ser2netweb/web/templates/base.html +77 -0
- ser2netweb/web/templates/dashboard.html +72 -0
- ser2netweb/web/templates/licenses.html +18 -0
- ser2netweb/web/templates/login.html +32 -0
- ser2netweb/web/templates/login_totp.html +23 -0
- ser2netweb/web/templates/settings.html +830 -0
- ser2netweb/web/templates/setup.html +43 -0
- ser2netweb/web/templates/totp.html +41 -0
- ser2netweb/web/totp.py +94 -0
- ser2netweb/winservice.py +1793 -0
- ser2netweb-3.0.0.dist-info/METADATA +120 -0
- ser2netweb-3.0.0.dist-info/RECORD +121 -0
- ser2netweb-3.0.0.dist-info/WHEEL +5 -0
- ser2netweb-3.0.0.dist-info/entry_points.txt +2 -0
- ser2netweb-3.0.0.dist-info/licenses/COMMERCIAL_LICENSE.md +94 -0
- ser2netweb-3.0.0.dist-info/licenses/LICENSE +662 -0
- ser2netweb-3.0.0.dist-info/licenses/NOTICE +20 -0
- ser2netweb-3.0.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +105 -0
- ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/htmx.org.txt +13 -0
- ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm-addon-fit.txt +19 -0
- ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm.txt +21 -0
- ser2netweb-3.0.0.dist-info/top_level.txt +1 -0
ser2netweb/winservice.py
ADDED
|
@@ -0,0 +1,1793 @@
|
|
|
1
|
+
"""Run ser2netweb as a Windows service, with the Windows API itself (ctypes) — neither
|
|
2
|
+
pywin32 nor a wrapper program (NSSM, Shawl) is needed.
|
|
3
|
+
|
|
4
|
+
ser2netweb.exe --install-service [--data-dir DIR] [--service-name NAME] [--reconfigure]
|
|
5
|
+
ser2netweb.exe --uninstall-service [--service-name NAME]
|
|
6
|
+
|
|
7
|
+
``--install-service`` registers ser2netweb to start at boot as LocalSystem, restart 5 s
|
|
8
|
+
after it dies or exits with an error, and starts it. A standalone exe copies itself to
|
|
9
|
+
%ProgramFiles%\\ser2netweb first and runs from there; a new service keeps its data in
|
|
10
|
+
%ProgramData%\\ser2netweb. Both folders are left to SYSTEM and Administrators alone: nobody
|
|
11
|
+
else may change what the service runs. A source checkout (python + ser2netweb.py) can't
|
|
12
|
+
move, so it is refused where another account could change it. Run again on an existing
|
|
13
|
+
service, it upgrades it in place: stops it, keeps its data directory, puts the current
|
|
14
|
+
build in place, starts it — and on a failure puts the previous version back.
|
|
15
|
+
|
|
16
|
+
Up to 2.9.x the product was ser2net: the default service had that name, the exe lived in
|
|
17
|
+
%ProgramFiles%\\ser2net and the data in %ProgramData%\\ser2net (a named service's in a
|
|
18
|
+
folder of its name there). Installing the default service moves such a 2.x service over:
|
|
19
|
+
the ser2net service, recognised as ours by its registered command line, is stopped and,
|
|
20
|
+
once the new ser2netweb service runs, deleted. A data directory in 2.x's default place moves
|
|
21
|
+
to 3.x's when that one doesn't exist yet; any other stays where it is. A named service
|
|
22
|
+
keeps its name and is upgraded in place the same way.
|
|
23
|
+
|
|
24
|
+
The Service Control Manager then runs ``ser2netweb.exe --service --data-dir ...``: ``run()``
|
|
25
|
+
hands the process to the SCM dispatcher, runs the normal server in the service thread and
|
|
26
|
+
stops it cleanly on a stop request or at shutdown. Windows only; everything is imported
|
|
27
|
+
lazily so the module loads (and its pure decision helpers are testable) on any OS.
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import contextlib
|
|
32
|
+
import ctypes
|
|
33
|
+
import functools
|
|
34
|
+
import ntpath
|
|
35
|
+
import os
|
|
36
|
+
import re
|
|
37
|
+
import sys
|
|
38
|
+
import threading
|
|
39
|
+
import time
|
|
40
|
+
from types import SimpleNamespace
|
|
41
|
+
from typing import Any, Callable, Optional
|
|
42
|
+
|
|
43
|
+
from . import clock
|
|
44
|
+
|
|
45
|
+
# ctypes with its Windows-only parts (WinDLL, WINFUNCTYPE, get_last_error, FormatError)
|
|
46
|
+
_win: Any = ctypes
|
|
47
|
+
|
|
48
|
+
DEFAULT_NAME = "ser2netweb"
|
|
49
|
+
_NAME = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
|
|
50
|
+
# where a frozen build installs itself so only administrators can replace the exe a
|
|
51
|
+
# LocalSystem service runs (see install()); the folder name under %ProgramFiles% (and
|
|
52
|
+
# %ProgramData%, for the data of a new service)
|
|
53
|
+
INSTALL_SUBDIR = "ser2netweb"
|
|
54
|
+
# the same up to 2.9.x, when the product was called ser2net: what --install-service of
|
|
55
|
+
# the default service moves over, and --uninstall-service finds
|
|
56
|
+
OLD_DEFAULT_NAME = "ser2net"
|
|
57
|
+
OLD_INSTALL_SUBDIR = "ser2net"
|
|
58
|
+
|
|
59
|
+
# winsvc.h
|
|
60
|
+
SC_MANAGER_CONNECT = 0x0001
|
|
61
|
+
SC_MANAGER_CREATE_SERVICE = 0x0002
|
|
62
|
+
SERVICE_QUERY_CONFIG = 0x0001
|
|
63
|
+
SERVICE_QUERY_STATUS = 0x0004
|
|
64
|
+
SC_STATUS_PROCESS_INFO = 0
|
|
65
|
+
SYNCHRONIZE = 0x00100000
|
|
66
|
+
SERVICE_START = 0x0010
|
|
67
|
+
SERVICE_STOP = 0x0020
|
|
68
|
+
DELETE = 0x00010000
|
|
69
|
+
SERVICE_CHANGE_CONFIG = 0x0002
|
|
70
|
+
SERVICE_WIN32_OWN_PROCESS = 0x00000010
|
|
71
|
+
SERVICE_AUTO_START = 0x00000002
|
|
72
|
+
SERVICE_ERROR_NORMAL = 0x00000001
|
|
73
|
+
SERVICE_NO_CHANGE = 0xFFFFFFFF
|
|
74
|
+
SERVICE_CONFIG_DESCRIPTION = 1
|
|
75
|
+
SERVICE_CONFIG_FAILURE_ACTIONS = 2
|
|
76
|
+
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 4
|
|
77
|
+
SC_ACTION_RESTART = 1
|
|
78
|
+
SERVICE_CONTROL_STOP = 1
|
|
79
|
+
SERVICE_CONTROL_INTERROGATE = 4
|
|
80
|
+
SERVICE_CONTROL_SHUTDOWN = 5
|
|
81
|
+
SERVICE_ACCEPT_STOP = 0x1
|
|
82
|
+
SERVICE_ACCEPT_SHUTDOWN = 0x4
|
|
83
|
+
SERVICE_STOPPED = 1
|
|
84
|
+
SERVICE_START_PENDING = 2
|
|
85
|
+
SERVICE_STOP_PENDING = 3
|
|
86
|
+
SERVICE_RUNNING = 4
|
|
87
|
+
NO_ERROR = 0
|
|
88
|
+
ERROR_ACCESS_DENIED = 5
|
|
89
|
+
ERROR_CALL_NOT_IMPLEMENTED = 120
|
|
90
|
+
ERROR_SERVICE_DOES_NOT_EXIST = 1060
|
|
91
|
+
ERROR_SERVICE_NOT_ACTIVE = 1062
|
|
92
|
+
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063
|
|
93
|
+
ERROR_SERVICE_SPECIFIC_ERROR = 1066
|
|
94
|
+
ERROR_SERVICE_EXISTS = 1073
|
|
95
|
+
ERROR_SERVICE_MARKED_FOR_DELETE = 1072
|
|
96
|
+
|
|
97
|
+
RESTART_DELAY_MS = 5000
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ServiceError(Exception):
|
|
101
|
+
"""A user-facing service installation / control problem."""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# --------------------------------------------------------------------------
|
|
105
|
+
# pure helpers (any OS)
|
|
106
|
+
# --------------------------------------------------------------------------
|
|
107
|
+
def check_name(name: str) -> str:
|
|
108
|
+
if not _NAME.match(name or ""):
|
|
109
|
+
raise ServiceError("Service name: 1-64 letters, digits, '.', '_' or '-'.")
|
|
110
|
+
return name
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _quote(arg: str) -> str:
|
|
114
|
+
"""Quote one command-line argument the way CommandLineToArgvW reads it."""
|
|
115
|
+
if arg and not re.search(r'[\s"]', arg):
|
|
116
|
+
return arg
|
|
117
|
+
out, slashes = ['"'], 0
|
|
118
|
+
for ch in arg:
|
|
119
|
+
if ch == "\\":
|
|
120
|
+
slashes += 1
|
|
121
|
+
continue
|
|
122
|
+
if ch == '"':
|
|
123
|
+
out.append("\\" * (2 * slashes + 1) + '"')
|
|
124
|
+
else:
|
|
125
|
+
out.append("\\" * slashes + ch)
|
|
126
|
+
slashes = 0
|
|
127
|
+
out.append("\\" * (2 * slashes) + '"')
|
|
128
|
+
return "".join(out)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def service_command(name: str, data_dir: str, config: Optional[str] = None,
|
|
132
|
+
frozen: Optional[bool] = None, executable: Optional[str] = None,
|
|
133
|
+
script: Optional[str] = None) -> str:
|
|
134
|
+
"""The command line the SCM starts: this executable (or python + ser2netweb.py) with
|
|
135
|
+
--service and the absolute data directory."""
|
|
136
|
+
frozen = getattr(sys, "frozen", False) if frozen is None else frozen
|
|
137
|
+
executable = executable or sys.executable
|
|
138
|
+
parts = [executable]
|
|
139
|
+
if not frozen:
|
|
140
|
+
parts.append(script or start_script(sys.argv[0]))
|
|
141
|
+
parts += ["--service", "--service-name", check_name(name), "--data-dir", data_dir]
|
|
142
|
+
if config:
|
|
143
|
+
parts += ["--config", config]
|
|
144
|
+
return " ".join(_quote(p) for p in parts)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def start_script(argv0: str) -> str:
|
|
148
|
+
"""The script a source checkout's service runs: the one this process started from
|
|
149
|
+
(ser2netweb.py, or ser2net.py, its 2.9.x name), but ser2netweb.py next to the package for
|
|
150
|
+
`python -m ser2netweb`, whose ser2netweb/__main__.py doesn't run as a script."""
|
|
151
|
+
path = os.path.abspath(argv0)
|
|
152
|
+
if os.path.basename(path) == "__main__.py":
|
|
153
|
+
return os.path.join(os.path.dirname(os.path.dirname(path)), "ser2netweb.py")
|
|
154
|
+
return path
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def display_name(name: str) -> str:
|
|
158
|
+
return "ser2netweb" if name == DEFAULT_NAME else f"ser2netweb ({name})"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def old_display_name(name: str) -> str:
|
|
162
|
+
"""What 2.x called the service in the Services list (and its firewall rule)."""
|
|
163
|
+
return "ser2net" if name == OLD_DEFAULT_NAME else f"ser2net ({name})"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# --------------------------------------------------------------------------
|
|
167
|
+
# Where a frozen build installs itself (admin-only), and the ACL decision table
|
|
168
|
+
# --------------------------------------------------------------------------
|
|
169
|
+
def program_files() -> str:
|
|
170
|
+
return os.environ.get("ProgramFiles") or r"C:\Program Files"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def program_data() -> str:
|
|
174
|
+
return os.environ.get("ProgramData") or r"C:\ProgramData"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def install_dir() -> str:
|
|
178
|
+
"""The admin-only folder a frozen build copies itself into on --install-service."""
|
|
179
|
+
return os.path.join(program_files(), INSTALL_SUBDIR)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def installed_exe_path(name: str) -> str:
|
|
183
|
+
"""Where the service's exe lives after install: ser2netweb.exe for the default service,
|
|
184
|
+
<name>.exe for a named one, so several services share one admin-only folder but each
|
|
185
|
+
upgrades to its own path."""
|
|
186
|
+
return os.path.join(install_dir(), "ser2netweb.exe" if name == DEFAULT_NAME else f"{name}.exe")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def default_service_data_dir(name: str) -> str:
|
|
190
|
+
"""Admin-controlled data directory for a frozen service install (not next to the exe,
|
|
191
|
+
which would otherwise sit under %ProgramFiles% read-only to the service)."""
|
|
192
|
+
base = os.path.join(program_data(), INSTALL_SUBDIR)
|
|
193
|
+
return base if name == DEFAULT_NAME else os.path.join(base, name)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def old_install_dir() -> str:
|
|
197
|
+
"""Where 2.x's --install-service put the exe (%ProgramFiles%\\ser2net)."""
|
|
198
|
+
return os.path.join(program_files(), OLD_INSTALL_SUBDIR)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def old_installed_exe_path(name: str) -> str:
|
|
202
|
+
return os.path.join(old_install_dir(),
|
|
203
|
+
"ser2net.exe" if name == OLD_DEFAULT_NAME else f"{name}.exe")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def old_default_data_dir(name: str) -> str:
|
|
207
|
+
"""The data directory 2.x gave a new service of this name (%ProgramData%\\ser2net, or a
|
|
208
|
+
folder of the name in it)."""
|
|
209
|
+
base = os.path.join(program_data(), OLD_INSTALL_SUBDIR)
|
|
210
|
+
return base if name == OLD_DEFAULT_NAME else os.path.join(base, name)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def is_ours(registered: Optional[dict], name: str) -> bool:
|
|
214
|
+
"""A registered command line (parse_service_command) that --install-service wrote for
|
|
215
|
+
the service `name`, 2.x's included: --service with that --service-name and a
|
|
216
|
+
--data-dir, run by ser2net(web).exe (or a copy named after the service, or the release
|
|
217
|
+
download's ser2net(web)-windows-x64.exe) or by python with ser2net(web).py. What
|
|
218
|
+
--install-service of the default service moves over and deletes must pass this; a
|
|
219
|
+
service of another program called ser2net never does."""
|
|
220
|
+
if not registered or registered.get("service_name") != name or not registered.get("data_dir"):
|
|
221
|
+
return False
|
|
222
|
+
script = registered.get("script")
|
|
223
|
+
if script:
|
|
224
|
+
return ntpath.basename(script).lower() in ("ser2net.py", "ser2netweb.py")
|
|
225
|
+
exe = ntpath.basename(registered.get("executable") or "").lower()
|
|
226
|
+
return exe.endswith(".exe") and ("ser2net" in exe or exe == f"{name.lower()}.exe")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
# What a data directory holds of its own (config.OWN_NAMES' folders): any other folder in a
|
|
230
|
+
# 2.x default data directory may be another service's (named services kept theirs inside
|
|
231
|
+
# %ProgramData%\\ser2net), so such a directory isn't moved.
|
|
232
|
+
_OWN_FOLDERS = frozenset({"backups", "logs", "traces", "tls", "admin-requests", "lost+found"})
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def plan_data_move(registered: Optional[dict], old_name: str, name: str, data_dir: str,
|
|
236
|
+
config: Optional[str], frozen: bool,
|
|
237
|
+
exists: Callable[[str], bool] = os.path.lexists,
|
|
238
|
+
folders: Optional[Callable[[str], list[str]]] = None):
|
|
239
|
+
"""Pure decision (any OS): whether a service's data directory moves from 2.x's default
|
|
240
|
+
place to 3.x's, as (old, new, config at the new place, note), or (None, None, None,
|
|
241
|
+
note) to keep it (note "" when it never was a candidate). It moves when the standalone
|
|
242
|
+
exe installs, the service keeps the data directory it has (no --data-dir), that is
|
|
243
|
+
old_default_data_dir(old_name) with its config.json inside it (a --config elsewhere
|
|
244
|
+
stays as it is), the new default doesn't exist yet, and no other folder is in it."""
|
|
245
|
+
old = old_default_data_dir(old_name)
|
|
246
|
+
new = default_service_data_dir(name)
|
|
247
|
+
keep = (None, None, None)
|
|
248
|
+
if (not frozen or not registered or not registered.get("data_dir")
|
|
249
|
+
or os.path.normcase(os.path.abspath(registered["data_dir"])) != os.path.normcase(old)
|
|
250
|
+
or os.path.normcase(os.path.abspath(data_dir)) != os.path.normcase(old)
|
|
251
|
+
or os.path.normcase(old) == os.path.normcase(new)):
|
|
252
|
+
return (*keep, "")
|
|
253
|
+
if config and not _inside(config, old):
|
|
254
|
+
return (*keep, f"keeping the data directory {old}: its configuration is {config}")
|
|
255
|
+
if exists(new):
|
|
256
|
+
return (*keep, f"keeping the data directory {old}: {new} exists already")
|
|
257
|
+
if folders is None:
|
|
258
|
+
def folders(path: str) -> list[str]:
|
|
259
|
+
return [n for n in os.listdir(path) if os.path.isdir(os.path.join(path, n))]
|
|
260
|
+
try:
|
|
261
|
+
others = sorted(n for n in folders(old) if n.lower() not in _OWN_FOLDERS)
|
|
262
|
+
except OSError:
|
|
263
|
+
others = []
|
|
264
|
+
if others:
|
|
265
|
+
return (*keep, f"keeping the data directory {old}: it also holds {', '.join(others)} "
|
|
266
|
+
f"(other services' data?); move it to {new} by hand once they moved")
|
|
267
|
+
new_config = os.path.join(new, os.path.relpath(config, old)) if config else None
|
|
268
|
+
return old, new, new_config, f"moving the data directory {old} to {new}"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def firewall_command(name: str, exe: Optional[str] = None) -> str:
|
|
272
|
+
"""The netsh rule that lets other hosts reach a LocalSystem service (which never sees
|
|
273
|
+
the interactive Windows Firewall prompt). One program-scoped rule covers the admin UI,
|
|
274
|
+
every mapping's listen port and the cluster's UDP discovery. Printed as a hint, not
|
|
275
|
+
applied — the firewall stays closed by default."""
|
|
276
|
+
if exe is None:
|
|
277
|
+
exe = (installed_exe_path(name) if getattr(sys, "frozen", False)
|
|
278
|
+
else os.path.abspath(sys.executable))
|
|
279
|
+
return (f'netsh advfirewall firewall add rule name="{display_name(name)}" dir=in '
|
|
280
|
+
f'action=allow program="{exe}" enable=yes')
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def split_command_line(cmd: str) -> list[str]:
|
|
284
|
+
"""Split a command line the way CommandLineToArgvW does (the inverse of _quote), so an
|
|
285
|
+
existing service's registered --data-dir / --config can be read back. argv[0] is a
|
|
286
|
+
program path: quotes delimit it, backslashes are literal."""
|
|
287
|
+
args: list[str] = []
|
|
288
|
+
i, n = 0, len(cmd)
|
|
289
|
+
while i < n and cmd[i] in " \t":
|
|
290
|
+
i += 1
|
|
291
|
+
if i >= n:
|
|
292
|
+
return args
|
|
293
|
+
if cmd[i] == '"':
|
|
294
|
+
j = cmd.find('"', i + 1)
|
|
295
|
+
j = n if j < 0 else j
|
|
296
|
+
args.append(cmd[i + 1:j])
|
|
297
|
+
i = j + 1
|
|
298
|
+
else:
|
|
299
|
+
j = i
|
|
300
|
+
while j < n and cmd[j] not in " \t":
|
|
301
|
+
j += 1
|
|
302
|
+
args.append(cmd[i:j])
|
|
303
|
+
i = j
|
|
304
|
+
while True:
|
|
305
|
+
while i < n and cmd[i] in " \t":
|
|
306
|
+
i += 1
|
|
307
|
+
if i >= n:
|
|
308
|
+
return args
|
|
309
|
+
buf: list[str] = []
|
|
310
|
+
quoted = False
|
|
311
|
+
while i < n:
|
|
312
|
+
ch = cmd[i]
|
|
313
|
+
if ch == "\\":
|
|
314
|
+
j = i
|
|
315
|
+
while j < n and cmd[j] == "\\":
|
|
316
|
+
j += 1
|
|
317
|
+
if j < n and cmd[j] == '"': # 2n (+1) backslashes before a quote
|
|
318
|
+
buf.append("\\" * ((j - i) // 2))
|
|
319
|
+
if (j - i) % 2:
|
|
320
|
+
buf.append('"')
|
|
321
|
+
j += 1
|
|
322
|
+
else:
|
|
323
|
+
buf.append("\\" * (j - i))
|
|
324
|
+
i = j
|
|
325
|
+
elif ch == '"':
|
|
326
|
+
quoted = not quoted
|
|
327
|
+
i += 1
|
|
328
|
+
elif ch in " \t" and not quoted:
|
|
329
|
+
break
|
|
330
|
+
else:
|
|
331
|
+
buf.append(ch)
|
|
332
|
+
i += 1
|
|
333
|
+
args.append("".join(buf))
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def parse_service_command(cmd: str) -> Optional[dict]:
|
|
337
|
+
"""What a registered command line says (executable, script, --service-name, --data-dir,
|
|
338
|
+
--config), or None when it isn't one ser2netweb installed (no --service)."""
|
|
339
|
+
argv = split_command_line(cmd or "")
|
|
340
|
+
if "--service" not in argv:
|
|
341
|
+
return None
|
|
342
|
+
|
|
343
|
+
def value(flag: str) -> Optional[str]:
|
|
344
|
+
i = argv.index(flag) if flag in argv else -1
|
|
345
|
+
return argv[i + 1] if 0 <= i < len(argv) - 1 else None
|
|
346
|
+
|
|
347
|
+
script = argv[1] if len(argv) > 1 and argv[1].lower().endswith(".py") else None
|
|
348
|
+
return {"executable": argv[0], "script": script, "service_name": value("--service-name"),
|
|
349
|
+
"data_dir": value("--data-dir"), "config": value("--config")}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def choose_install_paths(data_dir: Optional[str], config: Optional[str],
|
|
353
|
+
registered: Optional[dict], new_default: str,
|
|
354
|
+
exists: Callable[[str], bool] = os.path.exists):
|
|
355
|
+
"""(data_dir, config, notes) for --install-service:
|
|
356
|
+
* what the user passed (--data-dir / --config);
|
|
357
|
+
* else, for an existing service, the ones it already uses — an upgrade never starts
|
|
358
|
+
over in another directory with an empty configuration;
|
|
359
|
+
* else (a new service) new_default.
|
|
360
|
+
Moving an existing service to a --data-dir without a config.json while its current
|
|
361
|
+
one has one is refused: copy the folder there first."""
|
|
362
|
+
notes = []
|
|
363
|
+
old_dir = registered.get("data_dir") if registered else None
|
|
364
|
+
old_cfg = registered.get("config") if registered else None
|
|
365
|
+
if registered is not None and not old_dir:
|
|
366
|
+
raise ServiceError("The existing service's command line names no --data-dir; give "
|
|
367
|
+
"--data-dir to say which data directory it should use.")
|
|
368
|
+
if config:
|
|
369
|
+
config = os.path.abspath(config)
|
|
370
|
+
if data_dir is None:
|
|
371
|
+
if old_dir:
|
|
372
|
+
data_dir, config = old_dir, config or old_cfg
|
|
373
|
+
notes.append(f"keeping the service's data directory {data_dir}")
|
|
374
|
+
else:
|
|
375
|
+
data_dir = new_default
|
|
376
|
+
else:
|
|
377
|
+
data_dir = os.path.abspath(data_dir)
|
|
378
|
+
if old_dir and os.path.normcase(os.path.abspath(old_dir)) != os.path.normcase(data_dir):
|
|
379
|
+
if (not exists(config or os.path.join(data_dir, "config.json"))
|
|
380
|
+
and exists(old_cfg or os.path.join(old_dir, "config.json"))):
|
|
381
|
+
raise ServiceError(
|
|
382
|
+
f"The service keeps its configuration in {old_dir}; {data_dir} has none. "
|
|
383
|
+
f"Copy {old_dir} to {data_dir} first (keep the old folder until the service "
|
|
384
|
+
f"works), or leave out --data-dir to keep using {old_dir}.")
|
|
385
|
+
notes.append(f"moving the service from {old_dir} to {data_dir}")
|
|
386
|
+
return data_dir, config, notes
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
# Access-right bits that let a principal replace or delete a file or add one to a folder
|
|
390
|
+
# (winnt.h). Any of these on the service's exe or its folder is a local-privilege-
|
|
391
|
+
# escalation path when the service runs as LocalSystem.
|
|
392
|
+
FILE_WRITE_DATA = 0x0002
|
|
393
|
+
FILE_APPEND_DATA = 0x0004
|
|
394
|
+
FILE_WRITE_EA = 0x0010
|
|
395
|
+
FILE_DELETE_CHILD = 0x0040
|
|
396
|
+
_DELETE = 0x00010000
|
|
397
|
+
WRITE_DAC = 0x00040000
|
|
398
|
+
WRITE_OWNER = 0x00080000
|
|
399
|
+
GENERIC_WRITE = 0x40000000
|
|
400
|
+
GENERIC_ALL = 0x10000000
|
|
401
|
+
DANGEROUS_RIGHTS = (FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | FILE_DELETE_CHILD
|
|
402
|
+
| _DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_WRITE | GENERIC_ALL)
|
|
403
|
+
# on a folder above the data directory: what lets someone rename it (and so swap the
|
|
404
|
+
# data directory for one of their own)
|
|
405
|
+
RENAME_RIGHTS = _DELETE | FILE_DELETE_CHILD | WRITE_DAC | WRITE_OWNER | GENERIC_ALL
|
|
406
|
+
# ACE flags (winnt.h)
|
|
407
|
+
INHERIT_ONLY_ACE = 0x08
|
|
408
|
+
INHERITED_ACE = 0x10
|
|
409
|
+
|
|
410
|
+
SYSTEM_SID = "S-1-5-18"
|
|
411
|
+
ADMINS_SID = "S-1-5-32-544"
|
|
412
|
+
USERS_SID = "S-1-5-32-545"
|
|
413
|
+
EVERYONE_SID = "S-1-1-0"
|
|
414
|
+
TRUSTED_INSTALLER_SID = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"
|
|
415
|
+
OWNER_RIGHTS_SID = "S-1-3-4"
|
|
416
|
+
# The only accounts that may be able to change what a LocalSystem service runs. Any other
|
|
417
|
+
# account — an administrator's own user account too, whose programs normally run without
|
|
418
|
+
# elevation — counts as one that could.
|
|
419
|
+
SAFE_SIDS = frozenset({SYSTEM_SID, ADMINS_SID, TRUSTED_INSTALLER_SID})
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _is_safe_sid(sid: str) -> bool:
|
|
423
|
+
return sid in SAFE_SIDS
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _is_placeholder_sid(sid: str) -> bool:
|
|
427
|
+
"""CREATOR OWNER / CREATOR GROUP / OWNER RIGHTS (S-1-3-*): stand-ins that are replaced
|
|
428
|
+
by the creating account (an entry of its own) or by the owner (checked as owner)."""
|
|
429
|
+
return sid.startswith("S-1-3-")
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def acl_offenders(aces, owner: Optional[str] = None, rights: int = DANGEROUS_RIGHTS) -> list[str]:
|
|
433
|
+
"""Pure decision table (any OS; the Windows caller reads the ACEs). Given a file/dir's
|
|
434
|
+
access-control entries as (sid, access_mask, allow[, ace_flags]) and its owner, return
|
|
435
|
+
the sorted SIDs of accounts other than SYSTEM / Administrators / TrustedInstaller that
|
|
436
|
+
hold one of `rights` on it, honouring a deny entry for the same SID. Inherit-only
|
|
437
|
+
entries are skipped (they apply only to what is created inside later), and so are the
|
|
438
|
+
CREATOR OWNER-style stand-ins. The owner counts too: it can always rewrite the
|
|
439
|
+
permissions. Empty means only administrators and the system can change it."""
|
|
440
|
+
allow: dict[str, int] = {}
|
|
441
|
+
deny: dict[str, int] = {}
|
|
442
|
+
for ace in aces:
|
|
443
|
+
sid, mask, is_allow = ace[0], int(ace[1]), ace[2]
|
|
444
|
+
flags = ace[3] if len(ace) > 3 else 0
|
|
445
|
+
if flags & INHERIT_ONLY_ACE or _is_placeholder_sid(sid):
|
|
446
|
+
continue
|
|
447
|
+
target = allow if is_allow else deny
|
|
448
|
+
target[sid] = target.get(sid, 0) | mask
|
|
449
|
+
out = {sid for sid, mask in allow.items()
|
|
450
|
+
if not _is_safe_sid(sid) and mask & rights & ~deny.get(sid, 0)}
|
|
451
|
+
if owner and not _is_safe_sid(owner) and not _is_placeholder_sid(owner):
|
|
452
|
+
out.add(owner)
|
|
453
|
+
return sorted(out)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
ANY_ACCESS = 0xFFFFFFFF
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def admin_only(owner: Optional[str], aces) -> bool:
|
|
460
|
+
"""Pure decision (any OS): only SYSTEM / Administrators / TrustedInstaller own the
|
|
461
|
+
file or folder or have any access to it, as a service's data directory once
|
|
462
|
+
--install-service has hardened it."""
|
|
463
|
+
return not acl_offenders(aces, owner, rights=ANY_ACCESS)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def service_folder(owner: Optional[str], aces) -> bool:
|
|
467
|
+
"""Pure decision (any OS): a folder as --install-service leaves a service's data
|
|
468
|
+
directory, or one inheriting from it: admin_only(), and no OWNER RIGHTS entry.
|
|
469
|
+
lock_down_dir() leaves it as it is (its grant for the account running ser2netweb would
|
|
470
|
+
let that account's unelevated programs change what the service runs). A folder made
|
|
471
|
+
private to the account that created it — Python's mkdir(mode=0o700) gives SYSTEM,
|
|
472
|
+
Administrators and OWNER RIGHTS — is that account's own, even when an elevated
|
|
473
|
+
administrator made it and Administrators own it (Windows Server's default for
|
|
474
|
+
them): lock_down_dir() gives it that account's entry, so the folder stays usable
|
|
475
|
+
from its unelevated programs."""
|
|
476
|
+
return admin_only(owner, aces) and not any(
|
|
477
|
+
ace[0] == OWNER_RIGHTS_SID and ace[2] for ace in aces)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def foreign_owner(owner: Optional[str], me: Optional[str]) -> bool:
|
|
481
|
+
"""True for an owner that is neither SYSTEM / Administrators / TrustedInstaller nor the
|
|
482
|
+
installing account: whatever it put in a data directory can't be taken on trust."""
|
|
483
|
+
return bool(owner) and not _is_safe_sid(owner or "") and owner != me
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
# --------------------------------------------------------------------------
|
|
487
|
+
# Windows API (lazy)
|
|
488
|
+
# --------------------------------------------------------------------------
|
|
489
|
+
_api = None
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def require_windows() -> None:
|
|
493
|
+
if os.name != "nt":
|
|
494
|
+
raise ServiceError("Windows services exist only on Windows (on Linux, use systemd: "
|
|
495
|
+
"systemd/ser2netweb.service for a source checkout, "
|
|
496
|
+
"ser2netweb-standalone.service for the binary, which "
|
|
497
|
+
"ser2netweb-install.sh installs, both attached to every release; "
|
|
498
|
+
"README: Run as a service).")
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _advapi():
|
|
502
|
+
global _api
|
|
503
|
+
if _api is not None:
|
|
504
|
+
return _api
|
|
505
|
+
require_windows()
|
|
506
|
+
from ctypes import wintypes as w
|
|
507
|
+
|
|
508
|
+
class SERVICE_STATUS(ctypes.Structure): # Win32 names
|
|
509
|
+
_fields_ = [("dwServiceType", w.DWORD), ("dwCurrentState", w.DWORD),
|
|
510
|
+
("dwControlsAccepted", w.DWORD), ("dwWin32ExitCode", w.DWORD),
|
|
511
|
+
("dwServiceSpecificExitCode", w.DWORD), ("dwCheckPoint", w.DWORD),
|
|
512
|
+
("dwWaitHint", w.DWORD)]
|
|
513
|
+
|
|
514
|
+
class SC_ACTION(ctypes.Structure):
|
|
515
|
+
_fields_ = [("Type", w.DWORD), ("Delay", w.DWORD)]
|
|
516
|
+
|
|
517
|
+
class SERVICE_FAILURE_ACTIONSW(ctypes.Structure):
|
|
518
|
+
_fields_ = [("dwResetPeriod", w.DWORD), ("lpRebootMsg", w.LPWSTR),
|
|
519
|
+
("lpCommand", w.LPWSTR), ("cActions", w.DWORD),
|
|
520
|
+
("lpsaActions", ctypes.POINTER(SC_ACTION))]
|
|
521
|
+
|
|
522
|
+
class SERVICE_FAILURE_ACTIONS_FLAG(ctypes.Structure):
|
|
523
|
+
_fields_ = [("fFailureActionsOnNonCrashFailures", w.BOOL)]
|
|
524
|
+
|
|
525
|
+
class SERVICE_DESCRIPTIONW(ctypes.Structure):
|
|
526
|
+
_fields_ = [("lpDescription", w.LPWSTR)]
|
|
527
|
+
|
|
528
|
+
class QUERY_SERVICE_CONFIGW(ctypes.Structure):
|
|
529
|
+
_fields_ = [("dwServiceType", w.DWORD), ("dwStartType", w.DWORD),
|
|
530
|
+
("dwErrorControl", w.DWORD), ("lpBinaryPathName", w.LPWSTR),
|
|
531
|
+
("lpLoadOrderGroup", w.LPWSTR), ("dwTagId", w.DWORD),
|
|
532
|
+
("lpDependencies", w.LPWSTR), ("lpServiceStartName", w.LPWSTR),
|
|
533
|
+
("lpDisplayName", w.LPWSTR)]
|
|
534
|
+
|
|
535
|
+
class SERVICE_STATUS_PROCESS(ctypes.Structure):
|
|
536
|
+
_fields_ = [("dwServiceType", w.DWORD), ("dwCurrentState", w.DWORD),
|
|
537
|
+
("dwControlsAccepted", w.DWORD), ("dwWin32ExitCode", w.DWORD),
|
|
538
|
+
("dwServiceSpecificExitCode", w.DWORD), ("dwCheckPoint", w.DWORD),
|
|
539
|
+
("dwWaitHint", w.DWORD), ("dwProcessId", w.DWORD),
|
|
540
|
+
("dwServiceFlags", w.DWORD)]
|
|
541
|
+
|
|
542
|
+
main_fn = _win.WINFUNCTYPE(None, w.DWORD, ctypes.POINTER(w.LPWSTR))
|
|
543
|
+
handler_fn = _win.WINFUNCTYPE(w.DWORD, w.DWORD, w.DWORD, w.LPVOID, w.LPVOID)
|
|
544
|
+
|
|
545
|
+
class SERVICE_TABLE_ENTRYW(ctypes.Structure):
|
|
546
|
+
_fields_ = [("lpServiceName", w.LPWSTR), ("lpServiceProc", main_fn)]
|
|
547
|
+
|
|
548
|
+
dll = _win.WinDLL("advapi32", use_last_error=True)
|
|
549
|
+
sig = {
|
|
550
|
+
"OpenSCManagerW": (w.HANDLE, [w.LPCWSTR, w.LPCWSTR, w.DWORD]),
|
|
551
|
+
"CreateServiceW": (w.HANDLE, [w.HANDLE, w.LPCWSTR, w.LPCWSTR, w.DWORD, w.DWORD, w.DWORD,
|
|
552
|
+
w.DWORD, w.LPCWSTR, w.LPCWSTR, w.LPVOID, w.LPCWSTR,
|
|
553
|
+
w.LPCWSTR, w.LPCWSTR]),
|
|
554
|
+
"OpenServiceW": (w.HANDLE, [w.HANDLE, w.LPCWSTR, w.DWORD]),
|
|
555
|
+
"ChangeServiceConfigW": (w.BOOL, [w.HANDLE, w.DWORD, w.DWORD, w.DWORD, w.LPCWSTR,
|
|
556
|
+
w.LPCWSTR, w.LPDWORD, w.LPCWSTR, w.LPCWSTR,
|
|
557
|
+
w.LPCWSTR, w.LPCWSTR]),
|
|
558
|
+
"ChangeServiceConfig2W": (w.BOOL, [w.HANDLE, w.DWORD, w.LPVOID]),
|
|
559
|
+
"StartServiceW": (w.BOOL, [w.HANDLE, w.DWORD, w.LPVOID]),
|
|
560
|
+
"ControlService": (w.BOOL, [w.HANDLE, w.DWORD, ctypes.POINTER(SERVICE_STATUS)]),
|
|
561
|
+
"QueryServiceStatus": (w.BOOL, [w.HANDLE, ctypes.POINTER(SERVICE_STATUS)]),
|
|
562
|
+
"QueryServiceStatusEx": (w.BOOL, [w.HANDLE, ctypes.c_int, ctypes.c_void_p, w.DWORD,
|
|
563
|
+
ctypes.POINTER(w.DWORD)]),
|
|
564
|
+
"QueryServiceConfigW": (w.BOOL, [w.HANDLE, ctypes.c_void_p, w.DWORD,
|
|
565
|
+
ctypes.POINTER(w.DWORD)]),
|
|
566
|
+
"DeleteService": (w.BOOL, [w.HANDLE]),
|
|
567
|
+
"CloseServiceHandle": (w.BOOL, [w.HANDLE]),
|
|
568
|
+
"StartServiceCtrlDispatcherW": (w.BOOL, [ctypes.POINTER(SERVICE_TABLE_ENTRYW)]),
|
|
569
|
+
"RegisterServiceCtrlHandlerExW": (w.HANDLE, [w.LPCWSTR, handler_fn, w.LPVOID]),
|
|
570
|
+
"SetServiceStatus": (w.BOOL, [w.HANDLE, ctypes.POINTER(SERVICE_STATUS)]),
|
|
571
|
+
}
|
|
572
|
+
for fname, (res, args) in sig.items():
|
|
573
|
+
f = getattr(dll, fname)
|
|
574
|
+
f.restype, f.argtypes = res, args
|
|
575
|
+
kernel = _win.WinDLL("kernel32", use_last_error=True)
|
|
576
|
+
for fname, (res, args) in {
|
|
577
|
+
"OpenProcess": (w.HANDLE, [w.DWORD, w.BOOL, w.DWORD]),
|
|
578
|
+
"WaitForSingleObject": (w.DWORD, [w.HANDLE, w.DWORD]),
|
|
579
|
+
"CloseHandle": (w.BOOL, [w.HANDLE]),
|
|
580
|
+
}.items():
|
|
581
|
+
f = getattr(kernel, fname)
|
|
582
|
+
f.restype, f.argtypes = res, args
|
|
583
|
+
|
|
584
|
+
_api = SimpleNamespace(dll=dll, kernel=kernel, SERVICE_STATUS=SERVICE_STATUS,
|
|
585
|
+
SC_ACTION=SC_ACTION,
|
|
586
|
+
SERVICE_FAILURE_ACTIONSW=SERVICE_FAILURE_ACTIONSW,
|
|
587
|
+
SERVICE_FAILURE_ACTIONS_FLAG=SERVICE_FAILURE_ACTIONS_FLAG,
|
|
588
|
+
SERVICE_DESCRIPTIONW=SERVICE_DESCRIPTIONW,
|
|
589
|
+
QUERY_SERVICE_CONFIGW=QUERY_SERVICE_CONFIGW,
|
|
590
|
+
SERVICE_STATUS_PROCESS=SERVICE_STATUS_PROCESS, main_fn=main_fn,
|
|
591
|
+
handler_fn=handler_fn, SERVICE_TABLE_ENTRYW=SERVICE_TABLE_ENTRYW)
|
|
592
|
+
return _api
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
_sec = None
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _secapi():
|
|
599
|
+
"""advapi32 / kernel32 security calls (lazy, Windows only)."""
|
|
600
|
+
global _sec
|
|
601
|
+
if _sec is not None:
|
|
602
|
+
return _sec
|
|
603
|
+
from ctypes import wintypes as w
|
|
604
|
+
|
|
605
|
+
class ACL_SIZE_INFORMATION(ctypes.Structure):
|
|
606
|
+
_fields_ = [("AceCount", w.DWORD), ("AclBytesInUse", w.DWORD),
|
|
607
|
+
("AclBytesFree", w.DWORD)]
|
|
608
|
+
|
|
609
|
+
class ACE_HEADER(ctypes.Structure):
|
|
610
|
+
_fields_ = [("AceType", ctypes.c_ubyte), ("AceFlags", ctypes.c_ubyte),
|
|
611
|
+
("AceSize", w.WORD)]
|
|
612
|
+
|
|
613
|
+
class ALLOWED_ACE(ctypes.Structure): # ACCESS_ALLOWED/DENIED_ACE share a layout
|
|
614
|
+
_fields_ = [("Header", ACE_HEADER), ("Mask", w.DWORD), ("SidStart", w.DWORD)]
|
|
615
|
+
|
|
616
|
+
class SECURITY_ATTRIBUTES(ctypes.Structure):
|
|
617
|
+
_fields_ = [("nLength", w.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p),
|
|
618
|
+
("bInheritHandle", w.BOOL)]
|
|
619
|
+
|
|
620
|
+
vp, pvp = ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)
|
|
621
|
+
advapi = _win.WinDLL("advapi32", use_last_error=True)
|
|
622
|
+
kernel = _win.WinDLL("kernel32", use_last_error=True)
|
|
623
|
+
for dll, sig in ((advapi, {
|
|
624
|
+
"GetNamedSecurityInfoW": (w.DWORD, [w.LPCWSTR, ctypes.c_int, w.DWORD, pvp, pvp, pvp,
|
|
625
|
+
pvp, pvp]),
|
|
626
|
+
"GetAclInformation": (w.BOOL, [vp, vp, w.DWORD, ctypes.c_int]),
|
|
627
|
+
"GetAce": (w.BOOL, [vp, w.DWORD, pvp]),
|
|
628
|
+
"ConvertSidToStringSidW": (w.BOOL, [vp, ctypes.POINTER(w.LPWSTR)]),
|
|
629
|
+
"ConvertStringSidToSidW": (w.BOOL, [w.LPCWSTR, pvp]),
|
|
630
|
+
"LookupAccountSidW": (w.BOOL, [w.LPCWSTR, vp, w.LPWSTR, ctypes.POINTER(w.DWORD),
|
|
631
|
+
w.LPWSTR, ctypes.POINTER(w.DWORD), vp]),
|
|
632
|
+
"OpenProcessToken": (w.BOOL, [w.HANDLE, w.DWORD, ctypes.POINTER(w.HANDLE)]),
|
|
633
|
+
"GetTokenInformation": (w.BOOL, [w.HANDLE, ctypes.c_int, vp, w.DWORD,
|
|
634
|
+
ctypes.POINTER(w.DWORD)]),
|
|
635
|
+
"ConvertStringSecurityDescriptorToSecurityDescriptorW": (w.BOOL, [w.LPCWSTR, w.DWORD,
|
|
636
|
+
pvp, vp]),
|
|
637
|
+
}), (kernel, {
|
|
638
|
+
"LocalFree": (vp, [vp]),
|
|
639
|
+
"GetCurrentProcess": (w.HANDLE, []),
|
|
640
|
+
"CloseHandle": (w.BOOL, [w.HANDLE]),
|
|
641
|
+
"CreateDirectoryW": (w.BOOL, [w.LPCWSTR, vp]),
|
|
642
|
+
})):
|
|
643
|
+
for fname, (res, args) in sig.items():
|
|
644
|
+
f = getattr(dll, fname)
|
|
645
|
+
f.restype, f.argtypes = res, args
|
|
646
|
+
_sec = SimpleNamespace(advapi=advapi, kernel=kernel, ACL_SIZE_INFORMATION=ACL_SIZE_INFORMATION,
|
|
647
|
+
ACE_HEADER=ACE_HEADER, ALLOWED_ACE=ALLOWED_ACE,
|
|
648
|
+
SECURITY_ATTRIBUTES=SECURITY_ATTRIBUTES)
|
|
649
|
+
return _sec
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def _sid_string(s, psid) -> Optional[str]:
|
|
653
|
+
from ctypes import wintypes as w
|
|
654
|
+
|
|
655
|
+
text = w.LPWSTR()
|
|
656
|
+
if not s.advapi.ConvertSidToStringSidW(psid, ctypes.byref(text)):
|
|
657
|
+
return None
|
|
658
|
+
try:
|
|
659
|
+
return text.value or ""
|
|
660
|
+
finally:
|
|
661
|
+
s.kernel.LocalFree(text)
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def read_security(path: str):
|
|
665
|
+
"""(owner SID, [(sid, access_mask, allow, ace_flags), ...]) of a file or folder, read
|
|
666
|
+
through the Windows API; None when it can't be read (or not on Windows)."""
|
|
667
|
+
if sys.platform != "win32" or not os.path.lexists(path):
|
|
668
|
+
return None
|
|
669
|
+
s = _secapi()
|
|
670
|
+
SE_FILE_OBJECT, OWNER_INFO, DACL_INFO = 1, 0x1, 0x4
|
|
671
|
+
powner, pdacl, psd = ctypes.c_void_p(), ctypes.c_void_p(), ctypes.c_void_p()
|
|
672
|
+
if s.advapi.GetNamedSecurityInfoW(path, SE_FILE_OBJECT, OWNER_INFO | DACL_INFO,
|
|
673
|
+
ctypes.byref(powner), None, ctypes.byref(pdacl), None,
|
|
674
|
+
ctypes.byref(psd)) != NO_ERROR:
|
|
675
|
+
return None
|
|
676
|
+
try:
|
|
677
|
+
owner = _sid_string(s, powner) if powner else ""
|
|
678
|
+
if owner is None:
|
|
679
|
+
return None
|
|
680
|
+
if not pdacl: # a NULL DACL grants everyone everything
|
|
681
|
+
return owner, [(EVERYONE_SID, GENERIC_ALL, True, 0)]
|
|
682
|
+
info = s.ACL_SIZE_INFORMATION()
|
|
683
|
+
if not s.advapi.GetAclInformation(pdacl, ctypes.byref(info), ctypes.sizeof(info), 2):
|
|
684
|
+
return None
|
|
685
|
+
aces = []
|
|
686
|
+
for i in range(info.AceCount):
|
|
687
|
+
pace = ctypes.c_void_p()
|
|
688
|
+
if not s.advapi.GetAce(pdacl, i, ctypes.byref(pace)):
|
|
689
|
+
return None
|
|
690
|
+
header = ctypes.cast(pace, ctypes.POINTER(s.ACE_HEADER)).contents
|
|
691
|
+
# 0 allowed, 1 denied, 9 allowed-callback (same layout; counted as allowed)
|
|
692
|
+
if header.AceType not in (0, 1, 9):
|
|
693
|
+
continue
|
|
694
|
+
ace = ctypes.cast(pace, ctypes.POINTER(s.ALLOWED_ACE)).contents
|
|
695
|
+
sid = _sid_string(s, ctypes.c_void_p(pace.value + s.ALLOWED_ACE.SidStart.offset))
|
|
696
|
+
if sid is None:
|
|
697
|
+
return None
|
|
698
|
+
aces.append((sid, ace.Mask, header.AceType != 1, header.AceFlags))
|
|
699
|
+
return owner, aces
|
|
700
|
+
finally:
|
|
701
|
+
s.kernel.LocalFree(psd)
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
_names: dict[str, str] = {}
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def sid_name(sid: str) -> str:
|
|
708
|
+
"""'DOMAIN\\name' for a SID string, else the SID itself."""
|
|
709
|
+
if sid in _names or sys.platform != "win32":
|
|
710
|
+
return _names.get(sid, sid)
|
|
711
|
+
from ctypes import wintypes as w
|
|
712
|
+
|
|
713
|
+
s = _secapi()
|
|
714
|
+
psid = ctypes.c_void_p()
|
|
715
|
+
_names[sid] = sid
|
|
716
|
+
if s.advapi.ConvertStringSidToSidW(sid, ctypes.byref(psid)):
|
|
717
|
+
try:
|
|
718
|
+
name, domain = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(256)
|
|
719
|
+
n, d, use = w.DWORD(256), w.DWORD(256), w.DWORD()
|
|
720
|
+
if s.advapi.LookupAccountSidW(None, psid, name, ctypes.byref(n), domain,
|
|
721
|
+
ctypes.byref(d), ctypes.byref(use)):
|
|
722
|
+
_names[sid] = f"{domain.value}\\{name.value}" if domain.value else name.value
|
|
723
|
+
finally:
|
|
724
|
+
s.kernel.LocalFree(psid)
|
|
725
|
+
return _names[sid]
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def writable_by_non_admins(path: str, rights: int = DANGEROUS_RIGHTS) -> Optional[list[str]]:
|
|
729
|
+
"""Accounts other than SYSTEM / Administrators / TrustedInstaller that can change `path`
|
|
730
|
+
(resolved to names) — [] when none can, None when it can't be determined (an
|
|
731
|
+
unreadable ACL, or not Windows). Decided by acl_offenders(); callers treat None as
|
|
732
|
+
'not checked', never as a failure of the check itself."""
|
|
733
|
+
sec = read_security(path)
|
|
734
|
+
if sec is None:
|
|
735
|
+
return None
|
|
736
|
+
owner, aces = sec
|
|
737
|
+
return [sid_name(sid) for sid in acl_offenders(aces, owner=owner, rights=rights)]
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _unsafe_locations(paths, log: Callable[[str], None]) -> list[str]:
|
|
741
|
+
"""Of `paths`, those another account can change, each as '<path> (<who>)'. A path
|
|
742
|
+
whose ACL can't be read is noted via log and skipped."""
|
|
743
|
+
out = []
|
|
744
|
+
for p in paths:
|
|
745
|
+
if not p or not os.path.lexists(p):
|
|
746
|
+
continue
|
|
747
|
+
who = writable_by_non_admins(p)
|
|
748
|
+
if who is None:
|
|
749
|
+
log(f"note: could not check who can modify {p}")
|
|
750
|
+
elif who:
|
|
751
|
+
out.append(f"{p} ({', '.join(who)})")
|
|
752
|
+
return out
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def _current_user_sid() -> Optional[str]:
|
|
756
|
+
"""The SID of the account running this process (the installing administrator)."""
|
|
757
|
+
from ctypes import wintypes as w
|
|
758
|
+
|
|
759
|
+
s = _secapi()
|
|
760
|
+
token = w.HANDLE()
|
|
761
|
+
if not s.advapi.OpenProcessToken(s.kernel.GetCurrentProcess(), 0x0008, # TOKEN_QUERY
|
|
762
|
+
ctypes.byref(token)):
|
|
763
|
+
return None
|
|
764
|
+
try:
|
|
765
|
+
size = w.DWORD()
|
|
766
|
+
s.advapi.GetTokenInformation(token, 1, None, 0, ctypes.byref(size)) # 1 = TokenUser
|
|
767
|
+
buf = ctypes.create_string_buffer(size.value)
|
|
768
|
+
if not s.advapi.GetTokenInformation(token, 1, buf, size, ctypes.byref(size)):
|
|
769
|
+
return None
|
|
770
|
+
return _sid_string(s, ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p)).contents)
|
|
771
|
+
finally:
|
|
772
|
+
s.kernel.CloseHandle(token)
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def _icacls(*args: str) -> int:
|
|
776
|
+
"""Run icacls by its full System32 path (an unqualified name is searched in the
|
|
777
|
+
program's own folder first)."""
|
|
778
|
+
import subprocess
|
|
779
|
+
|
|
780
|
+
root = os.environ.get("SystemRoot") or os.environ.get("WINDIR") or r"C:\Windows"
|
|
781
|
+
try:
|
|
782
|
+
return subprocess.run([os.path.join(root, "System32", "icacls.exe"), *args],
|
|
783
|
+
capture_output=True, timeout=120).returncode
|
|
784
|
+
except (OSError, subprocess.SubprocessError):
|
|
785
|
+
return -1
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
# SYSTEM and Administrators only, not inherited: what a new service data directory gets
|
|
789
|
+
# from the moment it exists (no window in which ProgramData's "Users may create files"
|
|
790
|
+
# applies to it)
|
|
791
|
+
_ADMIN_ONLY_SDDL = f"D:P(A;OICI;FA;;;{SYSTEM_SID})(A;OICI;FA;;;{ADMINS_SID})"
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def _mkdir_admin_only(path: str) -> None:
|
|
795
|
+
"""Create `path` and any missing parent with an admin-only, non-inherited ACL."""
|
|
796
|
+
missing = []
|
|
797
|
+
p = os.path.abspath(path)
|
|
798
|
+
while not os.path.exists(p):
|
|
799
|
+
missing.append(p)
|
|
800
|
+
parent = os.path.dirname(p)
|
|
801
|
+
if parent == p:
|
|
802
|
+
break
|
|
803
|
+
p = parent
|
|
804
|
+
if not missing:
|
|
805
|
+
return
|
|
806
|
+
s = _secapi()
|
|
807
|
+
psd = ctypes.c_void_p()
|
|
808
|
+
if not s.advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
|
809
|
+
_ADMIN_ONLY_SDDL, 1, ctypes.byref(psd), None):
|
|
810
|
+
raise _fail("Preparing the data directory's permissions")
|
|
811
|
+
try:
|
|
812
|
+
sa = s.SECURITY_ATTRIBUTES(ctypes.sizeof(s.SECURITY_ATTRIBUTES), psd, False)
|
|
813
|
+
for d in reversed(missing):
|
|
814
|
+
if not s.kernel.CreateDirectoryW(d, ctypes.byref(sa)) and not os.path.isdir(d):
|
|
815
|
+
raise _fail(f"Creating {d}")
|
|
816
|
+
finally:
|
|
817
|
+
s.kernel.LocalFree(psd)
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def _harden(path: str, users_read: bool) -> None:
|
|
821
|
+
"""Leave the folder `path` owned by Administrators, with SYSTEM and Administrators as
|
|
822
|
+
the only accounts that may change it or anything in it (plus read for Users when
|
|
823
|
+
users_read) — no entry for the installing account, whose unelevated programs would
|
|
824
|
+
otherwise keep write access. Everything inside only inherits from it."""
|
|
825
|
+
keep = {SYSTEM_SID, ADMINS_SID} | ({USERS_SID} if users_read else set())
|
|
826
|
+
args = [path, "/inheritance:r", "/grant:r", f"*{SYSTEM_SID}:(OI)(CI)F",
|
|
827
|
+
"/grant:r", f"*{ADMINS_SID}:(OI)(CI)F"]
|
|
828
|
+
if users_read:
|
|
829
|
+
args += ["/grant:r", f"*{USERS_SID}:(OI)(CI)RX"]
|
|
830
|
+
_icacls(*args, "/C", "/Q")
|
|
831
|
+
sec = read_security(path)
|
|
832
|
+
for sid in sorted({sid for sid, _mask, _allow, flags in (sec[1] if sec else [])
|
|
833
|
+
if not flags & INHERITED_ACE and sid not in keep}):
|
|
834
|
+
_icacls(path, "/remove", f"*{sid}", "/C", "/Q") # e.g. a per-user grant from earlier
|
|
835
|
+
_icacls(path, "/setowner", f"*{ADMINS_SID}", "/T", "/C", "/Q")
|
|
836
|
+
if os.listdir(path):
|
|
837
|
+
_icacls(os.path.join(path, "*"), "/reset", "/T", "/C", "/Q")
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
def _harden_file(path: str) -> None:
|
|
841
|
+
"""_harden() for a single file (a --config outside the data directory)."""
|
|
842
|
+
_icacls(path, "/inheritance:r", "/grant:r", f"*{SYSTEM_SID}:F", "/grant:r",
|
|
843
|
+
f"*{ADMINS_SID}:F", "/C", "/Q")
|
|
844
|
+
sec = read_security(path)
|
|
845
|
+
for sid in sorted({sid for sid, _mask, _allow, flags in (sec[1] if sec else [])
|
|
846
|
+
if not flags & INHERITED_ACE and sid not in (SYSTEM_SID, ADMINS_SID)}):
|
|
847
|
+
_icacls(path, "/remove", f"*{sid}", "/C", "/Q")
|
|
848
|
+
_icacls(path, "/setowner", f"*{ADMINS_SID}", "/C", "/Q")
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def _inside(path: str, folder: str) -> bool:
|
|
852
|
+
p, f = os.path.normcase(os.path.abspath(path)), os.path.normcase(os.path.abspath(folder))
|
|
853
|
+
return p == f or p.startswith(f.rstrip("\\/") + os.sep)
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _require_protected(paths, what: str) -> None:
|
|
857
|
+
"""Refuse (ServiceError) when another account can still change one of `paths`."""
|
|
858
|
+
problems = []
|
|
859
|
+
for p in paths:
|
|
860
|
+
if not os.path.lexists(p):
|
|
861
|
+
continue
|
|
862
|
+
who = writable_by_non_admins(p)
|
|
863
|
+
if who is None:
|
|
864
|
+
problems.append(f"{p} (its permissions can't be read)")
|
|
865
|
+
elif who:
|
|
866
|
+
problems.append(f"{p} ({', '.join(who)})")
|
|
867
|
+
if problems:
|
|
868
|
+
raise ServiceError(f"{what} could not be restricted to SYSTEM and Administrators: "
|
|
869
|
+
+ "; ".join(problems) + ". Take it over and run --install-service "
|
|
870
|
+
f'again: takeown /f "{paths[0]}" /r /d y, then icacls "{paths[0]}" '
|
|
871
|
+
f"/setowner *{ADMINS_SID} /t /c")
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def _exposed_ancestors(path: str) -> list[str]:
|
|
875
|
+
"""The folders above `path` that another account can rename or re-permission (and so
|
|
876
|
+
swap the directory for one of its own), each as '<folder> (<who>)'."""
|
|
877
|
+
out = []
|
|
878
|
+
p = os.path.dirname(os.path.abspath(path))
|
|
879
|
+
while True:
|
|
880
|
+
who = writable_by_non_admins(p, rights=RENAME_RIGHTS)
|
|
881
|
+
if who:
|
|
882
|
+
out.append(f"{p} ({', '.join(who)})")
|
|
883
|
+
parent = os.path.dirname(p)
|
|
884
|
+
if parent == p:
|
|
885
|
+
return out
|
|
886
|
+
p = parent
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _fail(what: str) -> ServiceError:
|
|
890
|
+
err = _win.get_last_error()
|
|
891
|
+
if err == ERROR_ACCESS_DENIED:
|
|
892
|
+
return ServiceError(f"{what}: access denied — run this from an elevated "
|
|
893
|
+
"(\"Run as administrator\") command prompt.")
|
|
894
|
+
return ServiceError(f"{what} failed: {_win.FormatError(err).strip()} (error {err})")
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def _wait_state(api, svc, want: int, timeout: float = 30.0) -> int:
|
|
898
|
+
st = api.SERVICE_STATUS()
|
|
899
|
+
end = time.monotonic() + timeout
|
|
900
|
+
while True:
|
|
901
|
+
if not api.dll.QueryServiceStatus(svc, ctypes.byref(st)):
|
|
902
|
+
raise _fail("QueryServiceStatus")
|
|
903
|
+
if st.dwCurrentState == want or time.monotonic() > end:
|
|
904
|
+
return st.dwCurrentState
|
|
905
|
+
time.sleep(0.3)
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _retry(action: Callable[[], Any], what: str, timeout: float = 30.0) -> Any:
|
|
909
|
+
"""Run a file operation, retrying while the file is in use (a just-stopped service's
|
|
910
|
+
process, an antivirus scan); then a one-line ServiceError instead of a traceback."""
|
|
911
|
+
end = time.monotonic() + timeout
|
|
912
|
+
while True:
|
|
913
|
+
try:
|
|
914
|
+
return action()
|
|
915
|
+
except OSError as e:
|
|
916
|
+
if time.monotonic() > end or not isinstance(e, PermissionError):
|
|
917
|
+
raise ServiceError(f"{what}: {e.strerror or e}") from e
|
|
918
|
+
time.sleep(0.5)
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
def _place_exe(dest: str, log: Callable[[str], None]) -> Optional[str]:
|
|
922
|
+
"""Copy the running frozen exe to the admin-only install path. The file it replaces
|
|
923
|
+
is kept as <dest>.old (returned) until the upgrade has succeeded, for the rollback."""
|
|
924
|
+
import shutil
|
|
925
|
+
|
|
926
|
+
src = os.path.abspath(sys.executable)
|
|
927
|
+
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
|
928
|
+
new, backup = dest + ".new", None
|
|
929
|
+
_retry(lambda: shutil.copyfile(src, new), f"Copying the program to {new}")
|
|
930
|
+
if os.path.exists(dest):
|
|
931
|
+
backup = dest + ".old"
|
|
932
|
+
if os.path.exists(backup):
|
|
933
|
+
_retry(lambda: os.remove(backup), f"Removing {backup}")
|
|
934
|
+
_retry(lambda: os.replace(dest, backup), f"Moving the previous {dest} aside")
|
|
935
|
+
_retry(lambda: os.replace(new, dest), f"Putting the program in place at {dest}")
|
|
936
|
+
log(f"installed the program to {dest}")
|
|
937
|
+
return backup
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def _service_extras(api, svc, name: str, data_dir: str) -> None:
|
|
941
|
+
"""Description + restart-on-failure actions, shared by a fresh install and an upgrade."""
|
|
942
|
+
desc = api.SERVICE_DESCRIPTIONW(
|
|
943
|
+
f"Serial-to-network bridge with a web UI. Data directory: {data_dir}")
|
|
944
|
+
api.dll.ChangeServiceConfig2W(svc, SERVICE_CONFIG_DESCRIPTION, ctypes.byref(desc))
|
|
945
|
+
actions = (api.SC_ACTION * 3)(*[api.SC_ACTION(SC_ACTION_RESTART, RESTART_DELAY_MS)] * 3)
|
|
946
|
+
fa = api.SERVICE_FAILURE_ACTIONSW(86400, None, None, 3, actions)
|
|
947
|
+
if not api.dll.ChangeServiceConfig2W(svc, SERVICE_CONFIG_FAILURE_ACTIONS, ctypes.byref(fa)):
|
|
948
|
+
raise _fail("Setting the restart-on-failure actions")
|
|
949
|
+
flag = api.SERVICE_FAILURE_ACTIONS_FLAG(True) # also after an exit with an error
|
|
950
|
+
api.dll.ChangeServiceConfig2W(svc, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, ctypes.byref(flag))
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def _program_paths(frozen: bool) -> list[str]:
|
|
954
|
+
"""What the service runs, so what nobody but administrators may change: a frozen
|
|
955
|
+
build's exe and its folder (DLLs are looked up there first); for a source checkout the
|
|
956
|
+
interpreter and its library folders, the checkout, its scripts, ser2netweb/ and lib/."""
|
|
957
|
+
if frozen:
|
|
958
|
+
exe = os.path.abspath(sys.executable)
|
|
959
|
+
return [exe, os.path.dirname(exe)]
|
|
960
|
+
root = os.path.dirname(os.path.abspath(sys.argv[0]))
|
|
961
|
+
base = sys.base_prefix
|
|
962
|
+
candidates = [sys.executable, os.path.dirname(os.path.abspath(sys.executable)), sys.prefix,
|
|
963
|
+
base, os.path.join(base, "Lib"), os.path.join(base, "DLLs"), root,
|
|
964
|
+
os.path.join(root, "ser2netweb.py"), os.path.join(root, "ser2net.py"),
|
|
965
|
+
os.path.join(root, "bootstrap.py"),
|
|
966
|
+
os.path.join(root, "ser2netweb"), os.path.join(root, "lib")]
|
|
967
|
+
seen, out = set(), []
|
|
968
|
+
for p in candidates:
|
|
969
|
+
key = os.path.normcase(os.path.abspath(p))
|
|
970
|
+
if key not in seen and os.path.lexists(p):
|
|
971
|
+
seen.add(key)
|
|
972
|
+
out.append(p)
|
|
973
|
+
return out
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def _guard_location(frozen: bool, allow_unsafe_location: bool,
|
|
977
|
+
log: Callable[[str], None]) -> None:
|
|
978
|
+
"""For a source checkout, refuse to install when an account other than SYSTEM and
|
|
979
|
+
Administrators can change what the service runs (the interpreter, the checkout, ser2netweb/,
|
|
980
|
+
lib/): the LocalSystem service would run that account's code. A frozen build needs no
|
|
981
|
+
check here: install() copies it to an admin-only folder."""
|
|
982
|
+
if frozen:
|
|
983
|
+
return
|
|
984
|
+
unsafe = _unsafe_locations(_program_paths(False), log)
|
|
985
|
+
if unsafe and not allow_unsafe_location:
|
|
986
|
+
raise ServiceError(
|
|
987
|
+
"accounts other than SYSTEM and Administrators can change what this service "
|
|
988
|
+
"would run as LocalSystem (an administrator's own account counts: its programs "
|
|
989
|
+
"usually run unelevated):\n " + "\n ".join(unsafe) + "\nPut the checkout and "
|
|
990
|
+
"Python in an admin-only folder (e.g. under %ProgramFiles%); for a folder you "
|
|
991
|
+
f'have: icacls "<folder>" /setowner *{ADMINS_SID} /t /c, then icacls "<folder>" '
|
|
992
|
+
"/reset /t /c. If this location is trusted, pass --allow-unsafe-location. The "
|
|
993
|
+
"standalone exe installs itself to an admin-only folder and needs neither.")
|
|
994
|
+
if unsafe:
|
|
995
|
+
log("WARNING: installing although accounts other than SYSTEM and Administrators can "
|
|
996
|
+
"change:\n " + "\n ".join(unsafe))
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
def location_warning() -> Optional[str]:
|
|
1000
|
+
"""A WARNING line for the service log when an account other than SYSTEM and
|
|
1001
|
+
Administrators can change the program this (LocalSystem) service runs — else None.
|
|
1002
|
+
Returns None off Windows."""
|
|
1003
|
+
unsafe = _unsafe_locations(_program_paths(getattr(sys, "frozen", False)), lambda *_: None)
|
|
1004
|
+
if not unsafe:
|
|
1005
|
+
return None
|
|
1006
|
+
return ("WARNING: accounts other than SYSTEM and Administrators can change what this "
|
|
1007
|
+
"service runs, so they could run code as LocalSystem: " + "; ".join(unsafe)
|
|
1008
|
+
+ " — reinstall the standalone exe (it installs itself to an admin-only folder) "
|
|
1009
|
+
"or move the checkout under %ProgramFiles%")
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def _check_adoptable(data_dir: str, config_path: str) -> None:
|
|
1013
|
+
"""A new service doesn't take over a data directory (or the shared %ProgramData%\\ser2netweb
|
|
1014
|
+
above a named one, or a --config file elsewhere) that holds anything owned by another
|
|
1015
|
+
account: a standard user can create folders in %ProgramData% and leave a config.json
|
|
1016
|
+
of their own there."""
|
|
1017
|
+
me = _current_user_sid()
|
|
1018
|
+
base = os.path.join(program_data(), INSTALL_SUBDIR)
|
|
1019
|
+
roots = [data_dir]
|
|
1020
|
+
if os.path.normcase(os.path.dirname(os.path.abspath(data_dir))) == os.path.normcase(base):
|
|
1021
|
+
roots.append(base)
|
|
1022
|
+
if not _inside(config_path, data_dir):
|
|
1023
|
+
roots.append(config_path)
|
|
1024
|
+
for root in roots:
|
|
1025
|
+
if not os.path.lexists(root):
|
|
1026
|
+
continue
|
|
1027
|
+
entries = [root] if root != data_dir else [root] + [
|
|
1028
|
+
os.path.join(d, f) for d, dirs, files in os.walk(root) for f in dirs + files]
|
|
1029
|
+
for p in entries:
|
|
1030
|
+
sec = read_security(p)
|
|
1031
|
+
if sec is not None and foreign_owner(sec[0], me):
|
|
1032
|
+
raise ServiceError(
|
|
1033
|
+
f"{p} belongs to {sid_name(sec[0])}, not to an administrator, so ser2netweb "
|
|
1034
|
+
f"won't take over {data_dir}: someone else may have put a configuration "
|
|
1035
|
+
f"there. Check it; if it is yours, take it over (takeown /f \"{root}\" /r "
|
|
1036
|
+
f"/d y, then icacls \"{root}\" /setowner *{ADMINS_SID} /t /c), otherwise "
|
|
1037
|
+
"delete it; then install again.")
|
|
1038
|
+
|
|
1039
|
+
|
|
1040
|
+
def _wait_lock_free(data_dir: str, timeout: float) -> None:
|
|
1041
|
+
"""--install-service only tests the data directory's lock (ser2netweb.datalock): the service
|
|
1042
|
+
it starts must be the one that holds it."""
|
|
1043
|
+
from . import datalock
|
|
1044
|
+
|
|
1045
|
+
end = time.monotonic() + timeout
|
|
1046
|
+
while True:
|
|
1047
|
+
pid = datalock.holder(data_dir)
|
|
1048
|
+
if pid is None:
|
|
1049
|
+
return
|
|
1050
|
+
if time.monotonic() >= end:
|
|
1051
|
+
who = f"process {pid}" if pid else "another process"
|
|
1052
|
+
raise ServiceError(f"{who} is running with the data directory {data_dir}. Stop it "
|
|
1053
|
+
"first, or install with a different --data-dir.")
|
|
1054
|
+
time.sleep(0.5)
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
def _query_registration(api, svc) -> SimpleNamespace:
|
|
1058
|
+
from ctypes import wintypes as w
|
|
1059
|
+
|
|
1060
|
+
needed = w.DWORD()
|
|
1061
|
+
api.dll.QueryServiceConfigW(svc, None, 0, ctypes.byref(needed))
|
|
1062
|
+
buf = ctypes.create_string_buffer(max(needed.value, ctypes.sizeof(api.QUERY_SERVICE_CONFIGW)))
|
|
1063
|
+
if not api.dll.QueryServiceConfigW(svc, buf, len(buf), ctypes.byref(needed)):
|
|
1064
|
+
raise _fail("Reading the service's configuration")
|
|
1065
|
+
q = ctypes.cast(buf, ctypes.POINTER(api.QUERY_SERVICE_CONFIGW)).contents
|
|
1066
|
+
return SimpleNamespace(service_type=q.dwServiceType, start_type=q.dwStartType,
|
|
1067
|
+
error_control=q.dwErrorControl, binary_path=q.lpBinaryPathName or "",
|
|
1068
|
+
display_name=q.lpDisplayName or "")
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def _service_status(api, svc) -> tuple[int, int]:
|
|
1072
|
+
"""(state, process id) of a service."""
|
|
1073
|
+
from ctypes import wintypes as w
|
|
1074
|
+
|
|
1075
|
+
ssp, needed = api.SERVICE_STATUS_PROCESS(), w.DWORD()
|
|
1076
|
+
if not api.dll.QueryServiceStatusEx(svc, SC_STATUS_PROCESS_INFO, ctypes.byref(ssp),
|
|
1077
|
+
ctypes.sizeof(ssp), ctypes.byref(needed)):
|
|
1078
|
+
raise _fail("QueryServiceStatusEx")
|
|
1079
|
+
return ssp.dwCurrentState, ssp.dwProcessId
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
def _stop_and_wait(api, svc, name: str, log: Callable[[str], None]) -> bool:
|
|
1083
|
+
"""Stop a service and wait until its process has exited (only then are its exe and its
|
|
1084
|
+
data directory's lock free: a one-file exe's launcher still cleans up after STOPPED).
|
|
1085
|
+
True when it was running."""
|
|
1086
|
+
state, pid = _service_status(api, svc)
|
|
1087
|
+
if state == SERVICE_STOPPED:
|
|
1088
|
+
return False
|
|
1089
|
+
st = api.SERVICE_STATUS()
|
|
1090
|
+
if not api.dll.ControlService(svc, SERVICE_CONTROL_STOP, ctypes.byref(st)):
|
|
1091
|
+
if _win.get_last_error() == ERROR_SERVICE_NOT_ACTIVE:
|
|
1092
|
+
return False
|
|
1093
|
+
raise _fail("Stopping the service")
|
|
1094
|
+
if _wait_state(api, svc, SERVICE_STOPPED, 60) != SERVICE_STOPPED:
|
|
1095
|
+
raise ServiceError(f"The service '{name}' did not stop within 60 s.")
|
|
1096
|
+
if pid:
|
|
1097
|
+
h = api.kernel.OpenProcess(SYNCHRONIZE, False, pid)
|
|
1098
|
+
if h: # (gone already otherwise)
|
|
1099
|
+
try:
|
|
1100
|
+
api.kernel.WaitForSingleObject(h, 60000)
|
|
1101
|
+
finally:
|
|
1102
|
+
api.kernel.CloseHandle(h)
|
|
1103
|
+
log(f"service '{name}' stopped")
|
|
1104
|
+
return True
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
def state_dir(data_dir: str, config: Optional[str]) -> str:
|
|
1108
|
+
"""Where a service with this --data-dir / --config keeps its state (all.log, backups/,
|
|
1109
|
+
the instance lock): the config file's folder when --config is given."""
|
|
1110
|
+
return os.path.dirname(os.path.abspath(config)) if config else data_dir
|
|
1111
|
+
|
|
1112
|
+
|
|
1113
|
+
def install(name: str, data_dir: Optional[str] = None, config: Optional[str] = None, *,
|
|
1114
|
+
prepare: Callable[[str], Any], default_data_dir: str, start: bool = True,
|
|
1115
|
+
log: Callable[[str], None] = print, frozen: Optional[bool] = None,
|
|
1116
|
+
allow_unsafe_location: bool = False) -> Any:
|
|
1117
|
+
"""Install the service — or, when it exists, upgrade it in place: stop it, keep its
|
|
1118
|
+
data directory (unless --data-dir names another), put the current build in place and
|
|
1119
|
+
start it again; on a failure after the stop the previous version is put back and
|
|
1120
|
+
started. The default service takes over 2.x's (named ser2net) the same way, and deletes
|
|
1121
|
+
it once it runs. `prepare(config_path)` loads (on a first run: creates) the
|
|
1122
|
+
configuration while no instance runs on it, and its result is returned."""
|
|
1123
|
+
api = _advapi()
|
|
1124
|
+
name = check_name(name)
|
|
1125
|
+
frozen = getattr(sys, "frozen", False) if frozen is None else frozen
|
|
1126
|
+
# first, so a prompt that isn't elevated is told so before anything is written
|
|
1127
|
+
scm = api.dll.OpenSCManagerW(None, None, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE)
|
|
1128
|
+
if not scm:
|
|
1129
|
+
raise _fail("Opening the Service Control Manager")
|
|
1130
|
+
svc = old = None
|
|
1131
|
+
try:
|
|
1132
|
+
# (a NULL handle comes back as None or 0: one value for every check below)
|
|
1133
|
+
svc = api.dll.OpenServiceW(scm, name, SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS
|
|
1134
|
+
| SERVICE_START | SERVICE_STOP | SERVICE_CHANGE_CONFIG
|
|
1135
|
+
| DELETE) or None
|
|
1136
|
+
previous = registered = None
|
|
1137
|
+
if svc is not None:
|
|
1138
|
+
previous = _query_registration(api, svc)
|
|
1139
|
+
registered = parse_service_command(previous.binary_path)
|
|
1140
|
+
if registered is None:
|
|
1141
|
+
raise ServiceError(f"A service named '{name}' exists but doesn't run ser2netweb "
|
|
1142
|
+
f"({previous.binary_path}). Pick another --service-name.")
|
|
1143
|
+
elif _win.get_last_error() != ERROR_SERVICE_DOES_NOT_EXIST:
|
|
1144
|
+
raise _fail("Opening the service")
|
|
1145
|
+
elif name == DEFAULT_NAME: # the default service of 2.x, to move over
|
|
1146
|
+
old = _old_service(api, scm, log)
|
|
1147
|
+
if old is not None:
|
|
1148
|
+
previous, registered = old.registration, old.registered
|
|
1149
|
+
new_default = default_service_data_dir(name) if frozen else default_data_dir
|
|
1150
|
+
given = data_dir
|
|
1151
|
+
data_dir, config, notes = choose_install_paths(data_dir, config, registered, new_default)
|
|
1152
|
+
move = None
|
|
1153
|
+
if given is None:
|
|
1154
|
+
src, dest, moved_config, note = plan_data_move(
|
|
1155
|
+
registered, old.name if old else name, name, data_dir, config, frozen)
|
|
1156
|
+
if dest and not _parent_trusted(dest):
|
|
1157
|
+
src, note = None, (f"keeping the data directory {data_dir}: another account "
|
|
1158
|
+
f"owns {os.path.dirname(dest)}")
|
|
1159
|
+
if note:
|
|
1160
|
+
notes.append(note)
|
|
1161
|
+
if src and dest:
|
|
1162
|
+
move = (src, dest)
|
|
1163
|
+
data_dir, config = dest, moved_config
|
|
1164
|
+
for note in notes:
|
|
1165
|
+
log(note)
|
|
1166
|
+
_guard_location(frozen, allow_unsafe_location, log) # before anything is stopped
|
|
1167
|
+
if svc is None and old is None:
|
|
1168
|
+
_check_adoptable(data_dir, config or os.path.join(data_dir, "config.json"))
|
|
1169
|
+
_wait_lock_free(state_dir(data_dir, config), 0)
|
|
1170
|
+
return _install_steps(api, scm, svc, previous, registered, name, data_dir, config,
|
|
1171
|
+
prepare, frozen, start, log, old=old, move=move)
|
|
1172
|
+
finally:
|
|
1173
|
+
if svc:
|
|
1174
|
+
api.dll.CloseServiceHandle(svc)
|
|
1175
|
+
if old is not None:
|
|
1176
|
+
api.dll.CloseServiceHandle(old.handle)
|
|
1177
|
+
api.dll.CloseServiceHandle(scm)
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
def _old_service(api, scm, log: Callable[[str], None]):
|
|
1181
|
+
"""2.x's default service (named ser2net), when it is one --install-service of ours
|
|
1182
|
+
registered (is_ours): its handle, name, registration and parsed command line. A
|
|
1183
|
+
service of that name that runs something else is left alone (None)."""
|
|
1184
|
+
h = api.dll.OpenServiceW(scm, OLD_DEFAULT_NAME, SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS
|
|
1185
|
+
| SERVICE_START | SERVICE_STOP | SERVICE_CHANGE_CONFIG | DELETE) or None
|
|
1186
|
+
if h is None:
|
|
1187
|
+
return None
|
|
1188
|
+
try:
|
|
1189
|
+
registration = _query_registration(api, h)
|
|
1190
|
+
except ServiceError:
|
|
1191
|
+
api.dll.CloseServiceHandle(h)
|
|
1192
|
+
raise
|
|
1193
|
+
registered = parse_service_command(registration.binary_path)
|
|
1194
|
+
if not is_ours(registered, OLD_DEFAULT_NAME):
|
|
1195
|
+
api.dll.CloseServiceHandle(h)
|
|
1196
|
+
log(f"note: the service '{OLD_DEFAULT_NAME}' ({registration.binary_path}) is not one "
|
|
1197
|
+
"ser2net(web) --install-service registered: left as it is")
|
|
1198
|
+
return None
|
|
1199
|
+
log(f"moving the 2.x service '{OLD_DEFAULT_NAME}' over to '{DEFAULT_NAME}' (it is deleted "
|
|
1200
|
+
"once the new one runs)")
|
|
1201
|
+
return SimpleNamespace(handle=h, name=OLD_DEFAULT_NAME, registration=registration,
|
|
1202
|
+
registered=registered)
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
def _parent_trusted(path: str) -> bool:
|
|
1206
|
+
"""The folder a data directory moves into is missing (made admin-only) or not another
|
|
1207
|
+
account's (Windows; True elsewhere)."""
|
|
1208
|
+
parent = os.path.dirname(os.path.abspath(path))
|
|
1209
|
+
if sys.platform != "win32" or not os.path.lexists(parent):
|
|
1210
|
+
return True
|
|
1211
|
+
sec = read_security(parent)
|
|
1212
|
+
return sec is None or not foreign_owner(sec[0], _current_user_sid())
|
|
1213
|
+
|
|
1214
|
+
|
|
1215
|
+
def _move_data(src: str, dest: str, log: Callable[[str], None]) -> None:
|
|
1216
|
+
"""Move a stopped service's data directory (one rename on the same volume, so its
|
|
1217
|
+
permissions go along); the folder it moves into is made admin-only when missing."""
|
|
1218
|
+
parent = os.path.dirname(os.path.abspath(dest))
|
|
1219
|
+
if not os.path.isdir(parent):
|
|
1220
|
+
_mkdir_admin_only(parent)
|
|
1221
|
+
_retry(lambda: os.rename(src, dest), f"Moving the data directory {src} to {dest}")
|
|
1222
|
+
log(f"moved the data directory {src} to {dest}")
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
def _drop_old_copy(exe: Optional[str], keep: Optional[str], log: Callable[[str], None]) -> None:
|
|
1226
|
+
"""After an upgrade or a move to the new names: the exe the service ran before goes
|
|
1227
|
+
when it is a copy 2.x's --install-service made in %ProgramFiles%\\ser2net (with what an
|
|
1228
|
+
interrupted upgrade left next to it); one elsewhere is only named. Best effort."""
|
|
1229
|
+
if not exe or (keep and os.path.normcase(os.path.abspath(exe)) == os.path.normcase(keep)):
|
|
1230
|
+
return
|
|
1231
|
+
if not _inside(exe, old_install_dir()) or not exe.lower().endswith(".exe"):
|
|
1232
|
+
log(f"note: the service no longer runs {exe}; you can delete it")
|
|
1233
|
+
return
|
|
1234
|
+
for path in (exe, exe + ".old", exe + ".new"):
|
|
1235
|
+
if os.path.lexists(path):
|
|
1236
|
+
try:
|
|
1237
|
+
_retry(functools.partial(os.remove, path), f"Removing {path}", timeout=10)
|
|
1238
|
+
log(f"removed {path}")
|
|
1239
|
+
except ServiceError as e:
|
|
1240
|
+
log(f"note: {e}")
|
|
1241
|
+
with contextlib.suppress(OSError):
|
|
1242
|
+
os.rmdir(old_install_dir()) # only when no other service's copy is left in it
|
|
1243
|
+
|
|
1244
|
+
|
|
1245
|
+
def _install_steps(api, scm, svc, previous, registered, name, data_dir, config, prepare,
|
|
1246
|
+
frozen, start, log, old=None, move=None):
|
|
1247
|
+
done = SimpleNamespace(stopped=False, placed=None, backup=None, reconfigured=False,
|
|
1248
|
+
created=None, moved=None)
|
|
1249
|
+
config_path = config or os.path.join(data_dir, "config.json")
|
|
1250
|
+
state = state_dir(data_dir, config) # (the same as data_dir without --config)
|
|
1251
|
+
exe = None
|
|
1252
|
+
try:
|
|
1253
|
+
if svc or old:
|
|
1254
|
+
done.stopped = _stop_and_wait(api, svc or old.handle, old.name if old else name, log)
|
|
1255
|
+
_wait_lock_free(move[0] if move else state, 30)
|
|
1256
|
+
if move:
|
|
1257
|
+
_move_data(move[0], move[1], log)
|
|
1258
|
+
done.moved = move
|
|
1259
|
+
_mkdir_admin_only(data_dir)
|
|
1260
|
+
loaded = prepare(config_path)
|
|
1261
|
+
# after prepare: loading the config may have added a grant for the installing
|
|
1262
|
+
# account (lock_down_dir, on a folder that was not a service folder yet)
|
|
1263
|
+
_harden(data_dir, users_read=False)
|
|
1264
|
+
_require_protected([data_dir, os.path.join(data_dir, "config.json")], "The data directory")
|
|
1265
|
+
if not _inside(config_path, data_dir):
|
|
1266
|
+
_harden_file(config_path)
|
|
1267
|
+
_require_protected([config_path], "The configuration file")
|
|
1268
|
+
if frozen:
|
|
1269
|
+
exe = installed_exe_path(name)
|
|
1270
|
+
if os.path.normcase(os.path.abspath(sys.executable)) != os.path.normcase(exe):
|
|
1271
|
+
done.backup = _place_exe(exe, log)
|
|
1272
|
+
done.placed = exe
|
|
1273
|
+
_harden(install_dir(), users_read=True)
|
|
1274
|
+
_require_protected([install_dir(), exe], "The program folder")
|
|
1275
|
+
cmd = service_command(name, data_dir, config, frozen=frozen, executable=exe)
|
|
1276
|
+
if svc:
|
|
1277
|
+
if not api.dll.ChangeServiceConfigW(svc, SERVICE_WIN32_OWN_PROCESS,
|
|
1278
|
+
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, cmd,
|
|
1279
|
+
None, None, None, None, None, display_name(name)):
|
|
1280
|
+
raise _fail("Updating the service configuration")
|
|
1281
|
+
done.reconfigured = True
|
|
1282
|
+
_service_extras(api, svc, name, state)
|
|
1283
|
+
log(f"service '{name}' upgraded in place\n command: {cmd}")
|
|
1284
|
+
target = svc
|
|
1285
|
+
else:
|
|
1286
|
+
target = api.dll.CreateServiceW(
|
|
1287
|
+
scm, name, display_name(name),
|
|
1288
|
+
SERVICE_QUERY_STATUS | SERVICE_START | SERVICE_STOP | SERVICE_CHANGE_CONFIG | DELETE,
|
|
1289
|
+
SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
|
|
1290
|
+
cmd, None, None, None, None, None) # LocalSystem
|
|
1291
|
+
if not target:
|
|
1292
|
+
raise _fail("Creating the service")
|
|
1293
|
+
done.created = target
|
|
1294
|
+
_service_extras(api, target, name, state)
|
|
1295
|
+
log(f"service '{name}' installed: starts at boot, restarts {RESTART_DELAY_MS // 1000} s "
|
|
1296
|
+
f"after a failure\n command: {cmd}")
|
|
1297
|
+
if start:
|
|
1298
|
+
_start_and_wait(api, target, name, state, log)
|
|
1299
|
+
except BaseException as e:
|
|
1300
|
+
if svc is None and old is None and done.created is not None:
|
|
1301
|
+
# a new service that doesn't start stays registered, as before (see all.log)
|
|
1302
|
+
if isinstance(e, (ServiceError, SystemExit, KeyboardInterrupt)):
|
|
1303
|
+
raise
|
|
1304
|
+
raise ServiceError(f"{type(e).__name__}: {e}") from e
|
|
1305
|
+
note = (_roll_back_move(api, old, done, name) if old is not None
|
|
1306
|
+
else _roll_back(api, svc, previous, done, name))
|
|
1307
|
+
if isinstance(e, (SystemExit, KeyboardInterrupt)):
|
|
1308
|
+
if note:
|
|
1309
|
+
log(note)
|
|
1310
|
+
raise
|
|
1311
|
+
message = str(e) if isinstance(e, ServiceError) else f"{type(e).__name__}: {e}"
|
|
1312
|
+
raise ServiceError(message + (f" ({note})" if note else "")) from e
|
|
1313
|
+
finally:
|
|
1314
|
+
if done.created is not None:
|
|
1315
|
+
api.dll.CloseServiceHandle(done.created)
|
|
1316
|
+
if done.backup:
|
|
1317
|
+
with contextlib.suppress(OSError):
|
|
1318
|
+
os.remove(done.backup)
|
|
1319
|
+
if old is not None: # the new service runs: the 2.x one goes
|
|
1320
|
+
if not api.dll.DeleteService(old.handle) and \
|
|
1321
|
+
_win.get_last_error() != ERROR_SERVICE_MARKED_FOR_DELETE:
|
|
1322
|
+
log(f"note: the 2.x service '{old.name}' could not be deleted ({_fail('Removing it')}); "
|
|
1323
|
+
f"remove it with: sc delete {old.name}")
|
|
1324
|
+
else:
|
|
1325
|
+
log(f"removed the 2.x service '{old.name}'")
|
|
1326
|
+
if registered and exe:
|
|
1327
|
+
_drop_old_copy(registered["executable"], exe, log)
|
|
1328
|
+
if os.path.normcase(registered["executable"]) != os.path.normcase(exe):
|
|
1329
|
+
rule = old_display_name(old.name if old else name)
|
|
1330
|
+
log(f"note: a Windows Firewall rule for the old program (e.g. \"{rule}\") no longer "
|
|
1331
|
+
f"lets other hosts in: add one for {exe} (the command is printed below when the "
|
|
1332
|
+
f'service listens beyond this machine) and delete the old one: netsh advfirewall '
|
|
1333
|
+
f'firewall delete rule name="{rule}"')
|
|
1334
|
+
if done.moved:
|
|
1335
|
+
with contextlib.suppress(OSError): # 2.x's %ProgramData%\ser2net, once it is empty
|
|
1336
|
+
os.rmdir(old_default_data_dir(OLD_DEFAULT_NAME))
|
|
1337
|
+
exposed = _exposed_ancestors(data_dir)
|
|
1338
|
+
if not _inside(config_path, data_dir):
|
|
1339
|
+
exposed += [a for a in _exposed_ancestors(config_path) if a not in exposed]
|
|
1340
|
+
if exposed:
|
|
1341
|
+
log("WARNING: other accounts can rename or re-permission a folder above the data "
|
|
1342
|
+
f"directory, and so swap it for one of their own: {'; '.join(exposed)}. Move the "
|
|
1343
|
+
f"data to {default_service_data_dir(name)} (stop the service, copy the folder, then "
|
|
1344
|
+
"--install-service --data-dir <new folder>; keep the old one until it works).")
|
|
1345
|
+
return loaded
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
def _roll_back_move(api, old, done, name: str) -> str:
|
|
1349
|
+
"""Undo a failed move of a 2.x service to the new name: the new service goes, the data
|
|
1350
|
+
directory and the program copy too, and the 2.x service is started again."""
|
|
1351
|
+
try:
|
|
1352
|
+
if done.created is not None:
|
|
1353
|
+
_stop_and_wait(api, done.created, name, lambda *_: None)
|
|
1354
|
+
api.dll.DeleteService(done.created)
|
|
1355
|
+
if done.placed:
|
|
1356
|
+
if done.backup:
|
|
1357
|
+
_retry(lambda: os.replace(done.backup, done.placed),
|
|
1358
|
+
f"Putting the previous {done.placed} back")
|
|
1359
|
+
else:
|
|
1360
|
+
with contextlib.suppress(OSError):
|
|
1361
|
+
os.remove(done.placed)
|
|
1362
|
+
if done.moved:
|
|
1363
|
+
_retry(lambda: os.rename(done.moved[1], done.moved[0]),
|
|
1364
|
+
f"Moving the data directory back to {done.moved[0]}")
|
|
1365
|
+
if not done.stopped:
|
|
1366
|
+
return f"the 2.x service '{old.name}' was left as it was"
|
|
1367
|
+
if api.dll.StartServiceW(old.handle, 0, None) and \
|
|
1368
|
+
_wait_state(api, old.handle, SERVICE_RUNNING) == SERVICE_RUNNING:
|
|
1369
|
+
return f"the 2.x service '{old.name}' is running again"
|
|
1370
|
+
return f"the 2.x service '{old.name}' was put back but did not start; see its all.log"
|
|
1371
|
+
except Exception as e: # report it; the first failure stays the error
|
|
1372
|
+
return (f"putting the 2.x service back failed too: {e}; check it with sc qc {old.name} "
|
|
1373
|
+
f"and sc qc {name}")
|
|
1374
|
+
|
|
1375
|
+
|
|
1376
|
+
def _roll_back(api, svc, previous, done, name: str) -> str:
|
|
1377
|
+
"""Undo a failed (re)install as far as it got; returns what happened, for the message."""
|
|
1378
|
+
try:
|
|
1379
|
+
if svc is None: # a new service, never created: drop the program copy
|
|
1380
|
+
if done.placed and done.backup is None:
|
|
1381
|
+
with contextlib.suppress(OSError):
|
|
1382
|
+
os.remove(done.placed)
|
|
1383
|
+
return ""
|
|
1384
|
+
if done.reconfigured:
|
|
1385
|
+
api.dll.ChangeServiceConfigW(svc, previous.service_type, previous.start_type,
|
|
1386
|
+
previous.error_control, previous.binary_path, None,
|
|
1387
|
+
None, None, None, None, previous.display_name)
|
|
1388
|
+
if done.placed or done.moved:
|
|
1389
|
+
_stop_and_wait(api, svc, name, lambda *_: None) # the new build may have started
|
|
1390
|
+
if done.placed:
|
|
1391
|
+
if done.backup:
|
|
1392
|
+
_retry(lambda: os.replace(done.backup, done.placed),
|
|
1393
|
+
f"Putting the previous {done.placed} back")
|
|
1394
|
+
else:
|
|
1395
|
+
with contextlib.suppress(OSError):
|
|
1396
|
+
os.remove(done.placed)
|
|
1397
|
+
if done.moved:
|
|
1398
|
+
_retry(lambda: os.rename(done.moved[1], done.moved[0]),
|
|
1399
|
+
f"Moving the data directory back to {done.moved[0]}")
|
|
1400
|
+
if not done.stopped:
|
|
1401
|
+
return "the previous version was left as it was" if done.placed or done.reconfigured else ""
|
|
1402
|
+
if api.dll.StartServiceW(svc, 0, None) and \
|
|
1403
|
+
_wait_state(api, svc, SERVICE_RUNNING) == SERVICE_RUNNING:
|
|
1404
|
+
return "the previous version is running again"
|
|
1405
|
+
return "the previous version was put back but did not start; see its all.log"
|
|
1406
|
+
except Exception as e: # report it; the first failure stays the error
|
|
1407
|
+
return f"putting the previous version back failed too: {e}; check it with sc qc {name}"
|
|
1408
|
+
|
|
1409
|
+
|
|
1410
|
+
START_TIMEOUT_S = 90.0 # how long --install-service waits for the service to be running
|
|
1411
|
+
|
|
1412
|
+
|
|
1413
|
+
def _wait_started(api, svc, timeout: float = START_TIMEOUT_S) -> tuple[int, int]:
|
|
1414
|
+
"""Wait while a service starts: (its state then, its exit code). It is RUNNING once
|
|
1415
|
+
its admin UI listens (run), STOPPED when the start failed, still START_PENDING after
|
|
1416
|
+
``timeout``."""
|
|
1417
|
+
st = api.SERVICE_STATUS()
|
|
1418
|
+
end = time.monotonic() + timeout
|
|
1419
|
+
while True:
|
|
1420
|
+
if not api.dll.QueryServiceStatus(svc, ctypes.byref(st)):
|
|
1421
|
+
raise _fail("QueryServiceStatus")
|
|
1422
|
+
if st.dwCurrentState in (SERVICE_RUNNING, SERVICE_STOPPED) or time.monotonic() > end:
|
|
1423
|
+
code = (st.dwServiceSpecificExitCode
|
|
1424
|
+
if st.dwWin32ExitCode == ERROR_SERVICE_SPECIFIC_ERROR else st.dwWin32ExitCode)
|
|
1425
|
+
return st.dwCurrentState, code
|
|
1426
|
+
time.sleep(0.3)
|
|
1427
|
+
|
|
1428
|
+
|
|
1429
|
+
def _start_and_wait(api, svc, name: str, data_dir: str, log: Callable[[str], None]) -> None:
|
|
1430
|
+
if not api.dll.StartServiceW(svc, 0, None):
|
|
1431
|
+
raise _fail("Starting the service")
|
|
1432
|
+
state, code = _wait_started(api, svc)
|
|
1433
|
+
if state != SERVICE_RUNNING:
|
|
1434
|
+
logs = (f"see {os.path.join(data_dir, 'all.log')} and {SERVICE_LOG} there, or the "
|
|
1435
|
+
"Application event log")
|
|
1436
|
+
if state == SERVICE_STOPPED:
|
|
1437
|
+
raise ServiceError(f"The service did not reach RUNNING: it stopped while starting "
|
|
1438
|
+
f"(exit code {code}); {logs}.")
|
|
1439
|
+
raise ServiceError(f"The service did not reach RUNNING within {START_TIMEOUT_S:g} s "
|
|
1440
|
+
f"(state {state}); {logs}.")
|
|
1441
|
+
log(f"service '{name}' is running")
|
|
1442
|
+
|
|
1443
|
+
|
|
1444
|
+
def kept_data_note(name: str, data_dir: Optional[str]) -> str:
|
|
1445
|
+
"""What --uninstall-service says it leaves: the data directory and what is in it."""
|
|
1446
|
+
where = f" {data_dir}" if data_dir else ""
|
|
1447
|
+
return (f"service '{name}' removed. Its data directory{where} is kept, with config.json "
|
|
1448
|
+
"(the accounts and the stored secrets), backups/, all.log, audit.log, logs/, "
|
|
1449
|
+
"traces/ and tls/: delete that folder to remove them too")
|
|
1450
|
+
START_WAIT_HINT_MS = 30000 # what a START_PENDING report tells the SCM to allow for
|
|
1451
|
+
START_PROGRESS_S = 5.0 # how often a start under way is reported again
|
|
1452
|
+
|
|
1453
|
+
|
|
1454
|
+
class StartProgress:
|
|
1455
|
+
"""While the server starts, ``report`` START_PENDING again every ``every`` seconds
|
|
1456
|
+
(run()'s report() counts the checkpoint up), so the SCM doesn't take a slow start
|
|
1457
|
+
(many serial ports to open) for a hung one. start() when the start begins, finish()
|
|
1458
|
+
once it is over (ready, or failed); finish() is True the first time only."""
|
|
1459
|
+
|
|
1460
|
+
def __init__(self, report: Callable[[], None], every: Optional[float] = None) -> None:
|
|
1461
|
+
self._report = report
|
|
1462
|
+
self._every = START_PROGRESS_S if every is None else every
|
|
1463
|
+
self._done = threading.Event()
|
|
1464
|
+
self._finished = False
|
|
1465
|
+
self._lock = threading.Lock()
|
|
1466
|
+
self._thread: Optional[threading.Thread] = None
|
|
1467
|
+
|
|
1468
|
+
def start(self) -> None:
|
|
1469
|
+
with self._lock:
|
|
1470
|
+
if self._thread is not None or self._finished:
|
|
1471
|
+
return
|
|
1472
|
+
self._thread = threading.Thread(target=self._run, name="service-start-progress",
|
|
1473
|
+
daemon=True)
|
|
1474
|
+
self._thread.start()
|
|
1475
|
+
|
|
1476
|
+
def _run(self) -> None:
|
|
1477
|
+
while not self._done.wait(self._every):
|
|
1478
|
+
self._report()
|
|
1479
|
+
|
|
1480
|
+
def finish(self) -> bool:
|
|
1481
|
+
with self._lock:
|
|
1482
|
+
first, self._finished = not self._finished, True
|
|
1483
|
+
thread = self._thread
|
|
1484
|
+
self._done.set()
|
|
1485
|
+
if thread is not None and thread is not threading.current_thread():
|
|
1486
|
+
thread.join(self._every + 1)
|
|
1487
|
+
return first
|
|
1488
|
+
|
|
1489
|
+
|
|
1490
|
+
def uninstall(name: str, log: Callable[[str], None] = print) -> None:
|
|
1491
|
+
"""Stop and remove the service `name`; for the default name, 2.x's default service
|
|
1492
|
+
(ser2net) when there is no ser2netweb service and that one is ours. Its exe copy in
|
|
1493
|
+
%ProgramFiles%\\ser2netweb (or 2.x's %ProgramFiles%\\ser2net) goes too, its data stays."""
|
|
1494
|
+
api = _advapi()
|
|
1495
|
+
name = check_name(name)
|
|
1496
|
+
scm = api.dll.OpenSCManagerW(None, None, SC_MANAGER_CONNECT)
|
|
1497
|
+
if not scm:
|
|
1498
|
+
raise _fail("Opening the Service Control Manager")
|
|
1499
|
+
access = SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE
|
|
1500
|
+
registered = None
|
|
1501
|
+
try:
|
|
1502
|
+
svc = api.dll.OpenServiceW(scm, name, access)
|
|
1503
|
+
if not svc:
|
|
1504
|
+
if _win.get_last_error() != ERROR_SERVICE_DOES_NOT_EXIST:
|
|
1505
|
+
raise _fail("Opening the service")
|
|
1506
|
+
svc = api.dll.OpenServiceW(scm, OLD_DEFAULT_NAME, access) if name == DEFAULT_NAME else None
|
|
1507
|
+
if svc:
|
|
1508
|
+
try:
|
|
1509
|
+
registered = parse_service_command(_query_registration(api, svc).binary_path)
|
|
1510
|
+
except ServiceError:
|
|
1511
|
+
registered = None
|
|
1512
|
+
if not is_ours(registered, OLD_DEFAULT_NAME):
|
|
1513
|
+
api.dll.CloseServiceHandle(svc)
|
|
1514
|
+
svc = None
|
|
1515
|
+
if not svc:
|
|
1516
|
+
raise ServiceError(f"There is no service named '{name}'.")
|
|
1517
|
+
log(f"there is no service '{name}': removing 2.x's '{OLD_DEFAULT_NAME}'")
|
|
1518
|
+
name = OLD_DEFAULT_NAME
|
|
1519
|
+
elif name == DEFAULT_NAME:
|
|
1520
|
+
other = api.dll.OpenServiceW(scm, OLD_DEFAULT_NAME, SERVICE_QUERY_CONFIG)
|
|
1521
|
+
if other:
|
|
1522
|
+
api.dll.CloseServiceHandle(other)
|
|
1523
|
+
log(f"note: a service '{OLD_DEFAULT_NAME}' (2.x's name) is installed too: "
|
|
1524
|
+
f"remove it with --uninstall-service --service-name {OLD_DEFAULT_NAME}")
|
|
1525
|
+
try:
|
|
1526
|
+
if registered is None:
|
|
1527
|
+
try: # where its data is, for the last message (best effort)
|
|
1528
|
+
registered = parse_service_command(_query_registration(api, svc).binary_path)
|
|
1529
|
+
except ServiceError:
|
|
1530
|
+
registered = None
|
|
1531
|
+
data_dir = registered.get("data_dir") if registered else None
|
|
1532
|
+
_stop_and_wait(api, svc, name, log) # its process gone: the exe is free below
|
|
1533
|
+
if not api.dll.DeleteService(svc):
|
|
1534
|
+
if _win.get_last_error() != ERROR_SERVICE_MARKED_FOR_DELETE:
|
|
1535
|
+
raise _fail("Removing the service")
|
|
1536
|
+
log(kept_data_note(name, data_dir))
|
|
1537
|
+
finally:
|
|
1538
|
+
api.dll.CloseServiceHandle(svc)
|
|
1539
|
+
finally:
|
|
1540
|
+
api.dll.CloseServiceHandle(scm)
|
|
1541
|
+
# drop the copy this service's install put into %ProgramFiles%\ser2netweb (or 2.x's
|
|
1542
|
+
# %ProgramFiles%\ser2net), and what an interrupted upgrade left next to it; best effort
|
|
1543
|
+
copies = [installed_exe_path(name), old_installed_exe_path(name)]
|
|
1544
|
+
exe = registered.get("executable") if registered else None
|
|
1545
|
+
if exe and exe.lower().endswith(".exe") and (_inside(exe, install_dir())
|
|
1546
|
+
or _inside(exe, old_install_dir())):
|
|
1547
|
+
copies.append(exe)
|
|
1548
|
+
seen = set()
|
|
1549
|
+
for dest in copies:
|
|
1550
|
+
if os.path.normcase(dest) in seen:
|
|
1551
|
+
continue
|
|
1552
|
+
seen.add(os.path.normcase(dest))
|
|
1553
|
+
for path in (dest, dest + ".old", dest + ".new"):
|
|
1554
|
+
if os.path.lexists(path):
|
|
1555
|
+
try:
|
|
1556
|
+
_retry(functools.partial(os.remove, path), f"Removing {path}", timeout=10)
|
|
1557
|
+
log(f"removed {path}")
|
|
1558
|
+
except ServiceError as e:
|
|
1559
|
+
log(f"note: {e}")
|
|
1560
|
+
for folder in (install_dir(), old_install_dir()):
|
|
1561
|
+
with contextlib.suppress(OSError):
|
|
1562
|
+
os.rmdir(folder) # only when no other service's copy is left in it
|
|
1563
|
+
|
|
1564
|
+
|
|
1565
|
+
STOP_WAIT_HINT_MS = 30000 # what a STOP_PENDING report tells the SCM to allow for
|
|
1566
|
+
STOP_PROGRESS_S = 5.0 # how often a stop under way is reported again
|
|
1567
|
+
|
|
1568
|
+
|
|
1569
|
+
class StopProgress:
|
|
1570
|
+
"""While a stop is under way, ``report`` it again every ``every`` seconds (STOP_PENDING
|
|
1571
|
+
with the next checkpoint, run()'s report() counts it up): one report with a 30 s
|
|
1572
|
+
hint made the SCM, `sc query` and Services treat a stop that took longer as a hung
|
|
1573
|
+
service. start() after the stop request, finish() once the server has stopped."""
|
|
1574
|
+
|
|
1575
|
+
def __init__(self, report: Callable[[], None], every: float = STOP_PROGRESS_S) -> None:
|
|
1576
|
+
self._report = report
|
|
1577
|
+
self._every = every
|
|
1578
|
+
self._done = threading.Event()
|
|
1579
|
+
self._thread: Optional[threading.Thread] = None
|
|
1580
|
+
self._lock = threading.Lock()
|
|
1581
|
+
|
|
1582
|
+
def start(self) -> None:
|
|
1583
|
+
with self._lock:
|
|
1584
|
+
if self._thread is not None or self._done.is_set():
|
|
1585
|
+
return
|
|
1586
|
+
self._thread = threading.Thread(target=self._run, name="service-stop-progress",
|
|
1587
|
+
daemon=True)
|
|
1588
|
+
self._thread.start()
|
|
1589
|
+
|
|
1590
|
+
def _run(self) -> None:
|
|
1591
|
+
while not self._done.wait(self._every):
|
|
1592
|
+
self._report()
|
|
1593
|
+
|
|
1594
|
+
def finish(self) -> None:
|
|
1595
|
+
self._done.set()
|
|
1596
|
+
with self._lock:
|
|
1597
|
+
thread = self._thread
|
|
1598
|
+
if thread is not None and thread is not threading.current_thread():
|
|
1599
|
+
thread.join(self._every + 1)
|
|
1600
|
+
|
|
1601
|
+
|
|
1602
|
+
def run(name: str, main: Callable[[], int], stop: Callable[[], None],
|
|
1603
|
+
log_path: Optional[str] = None,
|
|
1604
|
+
on_ready: Optional[Callable[[Callable[[], None]], None]] = None) -> int:
|
|
1605
|
+
"""For --service: hand the process to the SCM dispatcher (blocks until the service
|
|
1606
|
+
has stopped). ``main`` runs the server in the service thread; ``stop`` is called
|
|
1607
|
+
(from the SCM's thread) on a stop or shutdown request. ``log_path``: where stderr goes
|
|
1608
|
+
(service_log). ``on_ready(callback)`` (runtime.when_ready) has the server call back
|
|
1609
|
+
once it is ready: the service is START_PENDING until then (StartProgress) and RUNNING
|
|
1610
|
+
from then on, so a start that fails is seen as one; without it, RUNNING is reported
|
|
1611
|
+
before main() runs."""
|
|
1612
|
+
api = _advapi()
|
|
1613
|
+
name = check_name(name)
|
|
1614
|
+
redirect_missing_stdio(log_path)
|
|
1615
|
+
result = {"code": 0}
|
|
1616
|
+
handle = {"h": None}
|
|
1617
|
+
status = api.SERVICE_STATUS(SERVICE_WIN32_OWN_PROCESS, SERVICE_START_PENDING, 0, 0, 0, 0, 0)
|
|
1618
|
+
reporting = threading.Lock() # the SCM's thread, the service's and StopProgress's
|
|
1619
|
+
|
|
1620
|
+
def report(state: int, code: int = 0, wait_hint: int = 0) -> None:
|
|
1621
|
+
with reporting:
|
|
1622
|
+
status.dwCurrentState = state
|
|
1623
|
+
status.dwControlsAccepted = (0 if state == SERVICE_START_PENDING
|
|
1624
|
+
else SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN)
|
|
1625
|
+
status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR if code else NO_ERROR
|
|
1626
|
+
status.dwServiceSpecificExitCode = code
|
|
1627
|
+
status.dwWaitHint = wait_hint
|
|
1628
|
+
status.dwCheckPoint = (0 if state in (SERVICE_RUNNING, SERVICE_STOPPED)
|
|
1629
|
+
else status.dwCheckPoint + 1)
|
|
1630
|
+
if handle["h"]:
|
|
1631
|
+
api.dll.SetServiceStatus(handle["h"], ctypes.byref(status))
|
|
1632
|
+
|
|
1633
|
+
progress = StopProgress(lambda: report(SERVICE_STOP_PENDING, wait_hint=STOP_WAIT_HINT_MS))
|
|
1634
|
+
|
|
1635
|
+
def on_control(control, _event, _data, _ctx):
|
|
1636
|
+
if control in (SERVICE_CONTROL_STOP, SERVICE_CONTROL_SHUTDOWN):
|
|
1637
|
+
report(SERVICE_STOP_PENDING, wait_hint=STOP_WAIT_HINT_MS)
|
|
1638
|
+
progress.start()
|
|
1639
|
+
stop()
|
|
1640
|
+
return NO_ERROR
|
|
1641
|
+
if control == SERVICE_CONTROL_INTERROGATE:
|
|
1642
|
+
return NO_ERROR
|
|
1643
|
+
return ERROR_CALL_NOT_IMPLEMENTED
|
|
1644
|
+
|
|
1645
|
+
handler = api.handler_fn(on_control)
|
|
1646
|
+
|
|
1647
|
+
def service_main(_argc, _argv):
|
|
1648
|
+
handle["h"] = api.dll.RegisterServiceCtrlHandlerExW(name, handler, None)
|
|
1649
|
+
report(SERVICE_START_PENDING, wait_hint=START_WAIT_HINT_MS)
|
|
1650
|
+
starting = StartProgress(lambda: report(SERVICE_START_PENDING,
|
|
1651
|
+
wait_hint=START_WAIT_HINT_MS))
|
|
1652
|
+
|
|
1653
|
+
def running() -> None:
|
|
1654
|
+
if starting.finish():
|
|
1655
|
+
report(SERVICE_RUNNING)
|
|
1656
|
+
if on_ready is None:
|
|
1657
|
+
running()
|
|
1658
|
+
else:
|
|
1659
|
+
on_ready(running)
|
|
1660
|
+
starting.start()
|
|
1661
|
+
code = 1
|
|
1662
|
+
try:
|
|
1663
|
+
code = int(main() or 0)
|
|
1664
|
+
except SystemExit as e:
|
|
1665
|
+
code = e.code if isinstance(e.code, int) else 1
|
|
1666
|
+
except BaseException: # whatever happens, the SCM must still be told STOPPED
|
|
1667
|
+
import traceback
|
|
1668
|
+
traceback.print_exc()
|
|
1669
|
+
starting.finish()
|
|
1670
|
+
result["code"] = code
|
|
1671
|
+
progress.finish()
|
|
1672
|
+
report(SERVICE_STOPPED, code=code)
|
|
1673
|
+
|
|
1674
|
+
entry = api.main_fn(service_main)
|
|
1675
|
+
table = (api.SERVICE_TABLE_ENTRYW * 2)(api.SERVICE_TABLE_ENTRYW(name, entry),
|
|
1676
|
+
api.SERVICE_TABLE_ENTRYW(None, api.main_fn()))
|
|
1677
|
+
if not api.dll.StartServiceCtrlDispatcherW(table):
|
|
1678
|
+
if _win.get_last_error() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
|
|
1679
|
+
raise ServiceError("--service is used by the Windows Service Control Manager. Run "
|
|
1680
|
+
"ser2netweb without it, or install the service with --install-service.")
|
|
1681
|
+
raise _fail("Connecting to the Service Control Manager")
|
|
1682
|
+
return result["code"]
|
|
1683
|
+
|
|
1684
|
+
|
|
1685
|
+
def redirect_missing_stdio(log_path: Optional[str] = None) -> None:
|
|
1686
|
+
"""A service has no console: print() / logging to a missing stdout must not fail.
|
|
1687
|
+
With ``log_path`` a missing stderr goes there (service_log) instead of nowhere."""
|
|
1688
|
+
if log_path is not None and sys.stderr is None:
|
|
1689
|
+
log = service_log(log_path)
|
|
1690
|
+
if log is not None:
|
|
1691
|
+
sys.stderr = log
|
|
1692
|
+
for stream in ("stdout", "stderr"):
|
|
1693
|
+
if getattr(sys, stream) is None:
|
|
1694
|
+
setattr(sys, stream, open(os.devnull, "w", encoding="utf-8"))
|
|
1695
|
+
|
|
1696
|
+
|
|
1697
|
+
EVENTLOG_ERROR_TYPE = 0x0001
|
|
1698
|
+
EVENT_START_FAILED = 1 # the event id of "the service stopped: <why>"
|
|
1699
|
+
|
|
1700
|
+
|
|
1701
|
+
def report_event(source: str, text: str) -> bool:
|
|
1702
|
+
"""An error entry in the Windows Application event log, from ``source`` (the service
|
|
1703
|
+
name), where an administrator looks first. The source is not registered: Event
|
|
1704
|
+
Viewer says it has no description for event 1 and shows ``text`` below that. Best
|
|
1705
|
+
effort, never raises; False when it couldn't be written (or not on Windows)."""
|
|
1706
|
+
if os.name != "nt":
|
|
1707
|
+
return False
|
|
1708
|
+
try:
|
|
1709
|
+
from ctypes import wintypes as w
|
|
1710
|
+
dll = _win.WinDLL("advapi32", use_last_error=True)
|
|
1711
|
+
dll.RegisterEventSourceW.restype = w.HANDLE
|
|
1712
|
+
dll.RegisterEventSourceW.argtypes = [w.LPCWSTR, w.LPCWSTR]
|
|
1713
|
+
dll.ReportEventW.restype = w.BOOL
|
|
1714
|
+
dll.ReportEventW.argtypes = [w.HANDLE, w.WORD, w.WORD, w.DWORD, ctypes.c_void_p,
|
|
1715
|
+
w.WORD, w.DWORD, ctypes.POINTER(w.LPCWSTR),
|
|
1716
|
+
ctypes.c_void_p]
|
|
1717
|
+
dll.DeregisterEventSource.argtypes = [w.HANDLE]
|
|
1718
|
+
handle = dll.RegisterEventSourceW(None, source)
|
|
1719
|
+
if not handle:
|
|
1720
|
+
return False
|
|
1721
|
+
try:
|
|
1722
|
+
strings = (w.LPCWSTR * 1)(text[:31000]) # (an entry holds at most 31839)
|
|
1723
|
+
return bool(dll.ReportEventW(handle, EVENTLOG_ERROR_TYPE, 0, EVENT_START_FAILED,
|
|
1724
|
+
None, 1, 0, strings, None))
|
|
1725
|
+
finally:
|
|
1726
|
+
dll.DeregisterEventSource(handle)
|
|
1727
|
+
except Exception:
|
|
1728
|
+
return False
|
|
1729
|
+
|
|
1730
|
+
|
|
1731
|
+
SERVICE_LOG = "service.log"
|
|
1732
|
+
SERVICE_LOG_MAX = 10 * 1024 * 1024 # what one run writes to it at most
|
|
1733
|
+
|
|
1734
|
+
|
|
1735
|
+
class CappedLog:
|
|
1736
|
+
"""A text stream that takes at most ``limit`` bytes, then one line saying so: what
|
|
1737
|
+
Python itself reports on stderr (tracebacks), which a fault repeated for days must not
|
|
1738
|
+
turn into a full disk."""
|
|
1739
|
+
|
|
1740
|
+
def __init__(self, fh, limit: int = SERVICE_LOG_MAX) -> None:
|
|
1741
|
+
self._fh = fh
|
|
1742
|
+
self._left = limit
|
|
1743
|
+
self._full = False
|
|
1744
|
+
self.encoding = fh.encoding
|
|
1745
|
+
self.errors = fh.errors
|
|
1746
|
+
|
|
1747
|
+
def write(self, text: str) -> int:
|
|
1748
|
+
if self._full:
|
|
1749
|
+
return len(text)
|
|
1750
|
+
data = text.encode(self.encoding, "replace")
|
|
1751
|
+
out = text
|
|
1752
|
+
if len(data) > self._left:
|
|
1753
|
+
self._full = True
|
|
1754
|
+
out = data[:self._left].decode(self.encoding, "ignore") + \
|
|
1755
|
+
"\n... service.log is full for this run: what follows is not kept\n"
|
|
1756
|
+
self._left -= len(data)
|
|
1757
|
+
try:
|
|
1758
|
+
self._fh.write(out)
|
|
1759
|
+
self._fh.flush()
|
|
1760
|
+
except (OSError, ValueError):
|
|
1761
|
+
self._full = True
|
|
1762
|
+
return len(text)
|
|
1763
|
+
|
|
1764
|
+
def flush(self) -> None:
|
|
1765
|
+
with contextlib.suppress(OSError, ValueError):
|
|
1766
|
+
self._fh.flush()
|
|
1767
|
+
|
|
1768
|
+
def fileno(self) -> int:
|
|
1769
|
+
return self._fh.fileno()
|
|
1770
|
+
|
|
1771
|
+
def isatty(self) -> bool:
|
|
1772
|
+
return False
|
|
1773
|
+
|
|
1774
|
+
|
|
1775
|
+
def service_log(path: str) -> Optional[CappedLog]:
|
|
1776
|
+
"""stderr for the Windows service: <data>/service.log, begun anew at each start (the
|
|
1777
|
+
previous one kept as service.log.1). Python's own reports go there: a traceback that
|
|
1778
|
+
no handler took, faulthandler's dump of a crash. The service's log lines are in
|
|
1779
|
+
all.log; this is a separate file because a second handle on all.log would keep
|
|
1780
|
+
Windows from rotating it. None when it can't be opened."""
|
|
1781
|
+
with contextlib.suppress(OSError):
|
|
1782
|
+
if os.path.exists(path):
|
|
1783
|
+
os.replace(path, path + ".1")
|
|
1784
|
+
try:
|
|
1785
|
+
fh = open(path, "w", encoding="utf-8", errors="replace")
|
|
1786
|
+
except OSError:
|
|
1787
|
+
return None
|
|
1788
|
+
log = CappedLog(fh)
|
|
1789
|
+
log.write(f"{clock.stamp()} service start (pid {os.getpid()})\n")
|
|
1790
|
+
with contextlib.suppress(Exception): # a crash in native code: the threads' stacks
|
|
1791
|
+
import faulthandler
|
|
1792
|
+
faulthandler.enable(file=fh, all_threads=True)
|
|
1793
|
+
return log
|