kronbot 0.2.1__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.
kronbot/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Автозапись на физкультуру ИТМО."""
kronbot/__main__.py ADDED
@@ -0,0 +1,11 @@
1
+ """Точка входа приложения."""
2
+
3
+
4
+ def main() -> int:
5
+ from .cli import main as cli_main
6
+
7
+ return cli_main()
8
+
9
+
10
+ if __name__ == "__main__":
11
+ raise SystemExit(main())
@@ -0,0 +1,302 @@
1
+ """Per-user launchd and systemd service integration.
2
+
3
+ The service definition contains only paths, never the current environment or credentials.
4
+ """
5
+
6
+ import os
7
+ from pathlib import Path
8
+ import plistlib
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ from xml.parsers.expat import ExpatError
13
+ import tempfile
14
+
15
+ _LABEL = "ru.kronbot.agent"
16
+ _UNIT = "kronbot.service"
17
+ _TIMEOUT = 15
18
+ _HEADER = "# Managed by kronbot user service; do not edit.\n"
19
+
20
+
21
+ def _platform() -> str:
22
+ if sys.platform == "darwin":
23
+ return "launchd"
24
+ if sys.platform.startswith("linux"):
25
+ return "systemd"
26
+ raise RuntimeError("Пользовательская служба не поддерживается на этой платформе.")
27
+
28
+
29
+ def _path(kind: str) -> Path:
30
+ home = Path.home()
31
+ if kind == "launchd":
32
+ return home / "Library" / "LaunchAgents" / f"{_LABEL}.plist"
33
+ xdg = os.environ.get("XDG_CONFIG_HOME", "")
34
+ base = Path(xdg) if xdg and Path(xdg).is_absolute() else home / ".config"
35
+ return base / "systemd" / "user" / _UNIT
36
+
37
+
38
+ def _quote(value: str) -> str:
39
+ # systemd expands specifiers and environment variables inside quotes too.
40
+ escaped = []
41
+ for char in value:
42
+ if char in ('\\', '"'):
43
+ escaped.append("\\" + char)
44
+ elif char in ("%", "$"):
45
+ escaped.append(char * 2)
46
+ elif ord(char) < 32 or ord(char) == 127:
47
+ escaped.append(f"\\x{ord(char):02x}")
48
+ else:
49
+ escaped.append(char)
50
+ return '"' + "".join(escaped) + '"'
51
+
52
+
53
+ def _definition(kind: str, executable: str, state_dir: Path) -> bytes:
54
+ args = [executable, "service", "run", "--state-dir", str(state_dir)]
55
+ if kind == "launchd":
56
+ return plistlib.dumps({"Label": _LABEL, "ProgramArguments": args,
57
+ "RunAtLoad": True, "KeepAlive": False}, sort_keys=True)
58
+ return (_HEADER + "[Unit]\nDescription=kronbot user service\n\n"
59
+ "[Service]\nType=simple\nExecStart=" + " ".join(map(_quote, args)) +
60
+ "\nRestart=no\n\n"
61
+ "[Install]\nWantedBy=default.target\n").encode("utf-8")
62
+
63
+
64
+ def _owned(kind: str, data: bytes) -> bool:
65
+ if kind == "launchd":
66
+ try:
67
+ value = plistlib.loads(data)
68
+ if not isinstance(value, dict) or set(value) != {"Label", "ProgramArguments", "RunAtLoad", "KeepAlive"}:
69
+ return False
70
+ args = value["ProgramArguments"]
71
+ return (value["Label"] == _LABEL and value["RunAtLoad"] is True
72
+ and value["KeepAlive"] is False and isinstance(args, list)
73
+ and len(args) == 5 and all(isinstance(a, str) for a in args)
74
+ and args[1:4] == ["service", "run", "--state-dir"]
75
+ and Path(args[0]).is_absolute() and Path(args[4]).is_absolute())
76
+ except (ValueError, TypeError, OverflowError, ExpatError):
77
+ return False
78
+ try:
79
+ text = data.decode("utf-8")
80
+ except UnicodeError:
81
+ return False
82
+ # Match the complete definition, not merely a comment another file might contain.
83
+ token = r'"(?:[^"\\\n\r]|\\(?:[\\"]|x[0-9a-f]{2}))*"'
84
+ pattern = (re.escape(_HEADER + "[Unit]\nDescription=kronbot user service\n\n"
85
+ "[Service]\nType=simple\nExecStart=") + token +
86
+ re.escape(' "service" "run" "--state-dir" ') + token +
87
+ re.escape("\nRestart=no\n\n"
88
+ "[Install]\nWantedBy=default.target\n"))
89
+ return re.fullmatch(pattern, text) is not None
90
+
91
+
92
+ def _require_owned(kind: str, path: Path) -> None:
93
+ try:
94
+ if path.is_symlink() or not path.is_file() or not _owned(kind, path.read_bytes()):
95
+ raise RuntimeError("Конфигурация службы отсутствует или принадлежит другой программе.")
96
+ except OSError:
97
+ raise RuntimeError("Не удалось прочитать конфигурацию службы.") from None
98
+
99
+
100
+ def _unquote(token: str) -> str:
101
+ """Reverse exactly the escaping produced by _quote, in a single pass."""
102
+ result = []
103
+ index = 1
104
+ while index < len(token) - 1:
105
+ char = token[index]
106
+ if char == "\\":
107
+ index += 1
108
+ char = token[index]
109
+ if char == "x":
110
+ char = chr(int(token[index + 1 : index + 3], 16))
111
+ index += 2
112
+ elif char in ("%", "$"):
113
+ if token[index : index + 2] != char * 2:
114
+ raise ValueError
115
+ index += 1
116
+ result.append(char)
117
+ index += 1
118
+ value = "".join(result)
119
+ if _quote(value) != token:
120
+ raise ValueError
121
+ return value
122
+
123
+
124
+ def configured_state_dir() -> Path | None:
125
+ """Read the state directory from this application's installed definition."""
126
+ kind = _platform()
127
+ path = _path(kind)
128
+ try:
129
+ try:
130
+ path.lstat()
131
+ except FileNotFoundError:
132
+ return None
133
+ if path.is_symlink() or not path.is_file():
134
+ raise ValueError
135
+ data = path.read_bytes()
136
+ if not _owned(kind, data):
137
+ raise ValueError
138
+ if kind == "launchd":
139
+ args = plistlib.loads(data)["ProgramArguments"]
140
+ executable, directory = args[0], args[4]
141
+ else:
142
+ text = data.decode("utf-8")
143
+ line = next(
144
+ line for line in text.split("\n") if line.startswith("ExecStart=")
145
+ )
146
+ token = r'"(?:[^"\\\n\r]|\\(?:[\\"]|x[0-9a-f]{2}))*"'
147
+ match = re.fullmatch(
148
+ r"ExecStart=("
149
+ + token
150
+ + r') "service" "run" "--state-dir" ('
151
+ + token
152
+ + r")",
153
+ line,
154
+ )
155
+ if match is None:
156
+ raise ValueError
157
+ executable, directory = (_unquote(value) for value in match.groups())
158
+ if (
159
+ "\x00" in executable
160
+ or "\x00" in directory
161
+ or not Path(executable).is_absolute()
162
+ or not Path(directory).is_absolute()
163
+ ):
164
+ raise ValueError
165
+ return Path(directory)
166
+ except (
167
+ OSError,
168
+ ValueError,
169
+ TypeError,
170
+ UnicodeError,
171
+ OverflowError,
172
+ ExpatError,
173
+ StopIteration,
174
+ KeyError,
175
+ IndexError,
176
+ ):
177
+ raise RuntimeError(
178
+ "Не удалось прочитать принадлежащую kronbot конфигурацию службы."
179
+ ) from None
180
+
181
+
182
+ def _command(
183
+ args: list[str], *, allowed: tuple[int, ...] = (0,)
184
+ ) -> subprocess.CompletedProcess:
185
+ try:
186
+ result = subprocess.run(args, shell=False, capture_output=True, text=True,
187
+ timeout=_TIMEOUT, check=False)
188
+ except (OSError, subprocess.SubprocessError, UnicodeError):
189
+ raise RuntimeError("Не удалось обратиться к диспетчеру пользовательских служб.") from None
190
+ if result.returncode not in allowed:
191
+ raise RuntimeError("Диспетчер пользовательских служб отклонил операцию.")
192
+ return result
193
+
194
+
195
+ def _domain() -> str:
196
+ return f"gui/{os.getuid()}"
197
+
198
+
199
+ def _launch_loaded() -> bool:
200
+ result = _command(["launchctl", "print", f"{_domain()}/{_LABEL}"], allowed=(0, 113))
201
+ return result.returncode == 0
202
+
203
+
204
+ def _install_file(path: Path, data: bytes) -> None:
205
+ temporary = None
206
+ try:
207
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
208
+ fd, name = tempfile.mkstemp(prefix=".kronbot-", dir=path.parent)
209
+ temporary = Path(name)
210
+ with os.fdopen(fd, "wb") as stream:
211
+ stream.write(data)
212
+ stream.flush()
213
+ os.fsync(stream.fileno())
214
+ # A hard link publishes the complete file atomically without replacing a
215
+ # pre-existing file, even if one appears after the initial check.
216
+ os.link(temporary, path)
217
+ except FileExistsError:
218
+ raise RuntimeError("Конфигурация службы уже существует; она не изменена.") from None
219
+ except OSError:
220
+ raise RuntimeError("Не удалось создать конфигурацию службы.") from None
221
+ finally:
222
+ if temporary is not None:
223
+ try:
224
+ temporary.unlink(missing_ok=True)
225
+ except OSError:
226
+ pass
227
+
228
+
229
+ def install(executable: str, state_dir: Path) -> None:
230
+ kind = _platform()
231
+ try:
232
+ exe = os.fspath(executable)
233
+ directory = os.fspath(state_dir)
234
+ if (not isinstance(exe, str) or not isinstance(directory, str)
235
+ or not Path(exe).is_absolute() or not Path(directory).is_absolute()
236
+ or "\x00" in exe or "\x00" in directory):
237
+ raise ValueError
238
+ data = _definition(kind, exe, Path(directory))
239
+ except (TypeError, ValueError, UnicodeError, OverflowError):
240
+ raise RuntimeError("Для службы нужны корректные абсолютные пути.") from None
241
+ path = _path(kind)
242
+ _install_file(path, data)
243
+ if kind == "launchd":
244
+ _command(["launchctl", "bootstrap", _domain(), str(path)])
245
+ else:
246
+ _command(["systemctl", "--user", "daemon-reload"])
247
+ _command(["systemctl", "--user", "enable", "--now", _UNIT])
248
+
249
+
250
+ def uninstall() -> None:
251
+ kind = _platform()
252
+ path = _path(kind)
253
+ _require_owned(kind, path)
254
+ if kind == "launchd":
255
+ if _launch_loaded():
256
+ _command(["launchctl", "bootout", _domain(), str(path)])
257
+ else:
258
+ _command(["systemctl", "--user", "disable", "--now", _UNIT])
259
+ try:
260
+ path.unlink()
261
+ except OSError:
262
+ raise RuntimeError("Не удалось удалить конфигурацию службы.") from None
263
+ if kind == "systemd":
264
+ _command(["systemctl", "--user", "daemon-reload"])
265
+
266
+
267
+ def start() -> None:
268
+ kind = _platform()
269
+ path = _path(kind)
270
+ _require_owned(kind, path)
271
+ if kind == "launchd":
272
+ # A stopped LaunchAgent is unloaded; bootstrap both registers and starts it.
273
+ if not _launch_loaded():
274
+ _command(["launchctl", "bootstrap", _domain(), str(path)])
275
+ else:
276
+ _command(["systemctl", "--user", "start", _UNIT])
277
+
278
+
279
+ def stop() -> None:
280
+ kind = _platform()
281
+ path = _path(kind)
282
+ _require_owned(kind, path)
283
+ if kind == "launchd":
284
+ if _launch_loaded():
285
+ _command(["launchctl", "bootout", _domain(), str(path)])
286
+ else:
287
+ _command(["systemctl", "--user", "stop", _UNIT])
288
+
289
+
290
+ def status() -> str:
291
+ kind = _platform()
292
+ path = _path(kind)
293
+ if not path.exists() and not path.is_symlink():
294
+ return "not installed"
295
+ _require_owned(kind, path)
296
+ if kind == "launchd":
297
+ result = _command(["launchctl", "print", f"{_domain()}/{_LABEL}"], allowed=(0, 113))
298
+ if result.returncode == 113:
299
+ return "stopped"
300
+ return "running" if re.search(r"^\s*state\s*=\s*running\s*$", result.stdout, re.MULTILINE) else "stopped"
301
+ result = _command(["systemctl", "--user", "is-active", "--quiet", _UNIT], allowed=(0, 3, 4))
302
+ return "running" if result.returncode == 0 else "stopped"
@@ -0,0 +1,223 @@
1
+ """Per-user Task Scheduler integration; no credentials are stored in the task."""
2
+
3
+ from contextlib import contextmanager
4
+ from pathlib import Path
5
+ import os
6
+ import subprocess
7
+
8
+
9
+ _TASK_NAME = "kronbot-user-background-service"
10
+ _MARKER = "kronbot user background service v1"
11
+ _NOT_FOUND = 0x80070002
12
+
13
+
14
+ class _ServiceError(Exception):
15
+ """A deliberately safe message intended for the caller."""
16
+
17
+
18
+ @contextmanager
19
+ def _scheduler():
20
+ # Imports stay lazy so the module can also be inspected on other platforms.
21
+ import pythoncom
22
+ import win32api
23
+ import win32con
24
+ import win32security
25
+ import win32com.client
26
+
27
+ pythoncom.CoInitialize()
28
+ try:
29
+ token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
30
+ try:
31
+ sid = win32security.ConvertSidToStringSid(
32
+ win32security.GetTokenInformation(token, win32security.TokenUser)[0]
33
+ )
34
+ finally:
35
+ token.Close()
36
+ service = win32com.client.Dispatch("Schedule.Service")
37
+ service.Connect()
38
+ yield service, service.GetFolder("\\"), sid
39
+ finally:
40
+ pythoncom.CoUninitialize()
41
+
42
+
43
+ def _missing(error: Exception) -> bool:
44
+ code = getattr(error, "hresult", None)
45
+ return isinstance(code, int) and code & 0xFFFFFFFF == _NOT_FOUND
46
+
47
+
48
+ def _get_task(folder):
49
+ try:
50
+ return folder.GetTask(_TASK_NAME)
51
+ except Exception as error:
52
+ if _missing(error):
53
+ return None
54
+ raise
55
+
56
+
57
+ def _owned(task, sid: str) -> bool:
58
+ definition = task.Definition
59
+ actions = definition.Actions
60
+ return (
61
+ definition.RegistrationInfo.Description == _MARKER
62
+ and definition.Principal.UserId == sid
63
+ and definition.Principal.LogonType == 3 # interactive token, no password
64
+ and actions.Count == 1
65
+ and actions.Item(1).Type == 0 # executable action
66
+ )
67
+
68
+
69
+ def _require_owned(folder, sid: str):
70
+ task = _get_task(folder)
71
+ if task is None:
72
+ raise _ServiceError("Служба kronbot не установлена.")
73
+ if not _owned(task, sid):
74
+ raise _ServiceError("Имя службы занято другой задачей.")
75
+ return task
76
+
77
+
78
+ def _split_arguments(arguments: str) -> list[str]:
79
+ """Decode Task Scheduler arguments using the Windows command-line rules."""
80
+ import ctypes
81
+ from ctypes import wintypes
82
+
83
+ shell32 = ctypes.WinDLL("shell32", use_last_error=True)
84
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
85
+ shell32.CommandLineToArgvW.argtypes = [
86
+ wintypes.LPCWSTR,
87
+ ctypes.POINTER(ctypes.c_int),
88
+ ]
89
+ shell32.CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)
90
+ kernel32.LocalFree.argtypes = [wintypes.HLOCAL]
91
+ kernel32.LocalFree.restype = wintypes.HLOCAL
92
+ count = ctypes.c_int()
93
+ # A dummy executable ensures the first real argument is parsed as an argument,
94
+ # rather than under the special rules for argv[0].
95
+ argv = shell32.CommandLineToArgvW("kronbot.exe " + arguments, ctypes.byref(count))
96
+ if not argv:
97
+ raise OSError("CommandLineToArgvW failed")
98
+ try:
99
+ return [argv[index] for index in range(1, count.value)]
100
+ finally:
101
+ kernel32.LocalFree(ctypes.cast(argv, wintypes.HLOCAL))
102
+
103
+
104
+ def configured_state_dir() -> Path | None:
105
+ try:
106
+ with _scheduler() as (_, folder, sid):
107
+ task = _get_task(folder)
108
+ if task is None:
109
+ return None
110
+ if not _owned(task, sid):
111
+ raise _ServiceError("Имя службы занято другой задачей.")
112
+ arguments = task.Definition.Actions.Item(1).Arguments
113
+ if not isinstance(arguments, str) or "\0" in arguments:
114
+ raise ValueError
115
+ parts = _split_arguments(arguments)
116
+ if len(parts) != 4 or parts[:3] != ["service", "run", "--state-dir"]:
117
+ raise ValueError
118
+ state_dir = Path(parts[3])
119
+ if not state_dir.is_absolute():
120
+ raise ValueError
121
+ return state_dir
122
+ except _ServiceError as error:
123
+ raise RuntimeError(str(error)) from None
124
+ except Exception:
125
+ raise RuntimeError(
126
+ "Не удалось определить каталог состояния службы kronbot."
127
+ ) from None
128
+
129
+
130
+ def install(executable: str, state_dir: Path) -> None:
131
+ if not isinstance(executable, str) or not os.path.isabs(executable) or not state_dir.is_absolute():
132
+ raise RuntimeError("Для службы нужны абсолютные пути.")
133
+ try:
134
+ with _scheduler() as (service, folder, sid):
135
+ if _get_task(folder) is not None:
136
+ raise _ServiceError("Имя службы занято существующей задачей.")
137
+ definition = service.NewTask(0)
138
+ definition.RegistrationInfo.Description = _MARKER
139
+ definition.Principal.UserId = sid
140
+ definition.Principal.LogonType = 3 # TASK_LOGON_INTERACTIVE_TOKEN
141
+ definition.Principal.RunLevel = 0 # TASK_RUNLEVEL_LUA
142
+ trigger = definition.Triggers.Create(9) # TASK_TRIGGER_LOGON
143
+ trigger.UserId = sid
144
+ settings = definition.Settings
145
+ settings.Enabled = True
146
+ settings.StartWhenAvailable = True
147
+ settings.DisallowStartIfOnBatteries = False
148
+ settings.StopIfGoingOnBatteries = False
149
+ settings.ExecutionTimeLimit = "PT0S"
150
+ settings.MultipleInstances = 2 # TASK_INSTANCES_IGNORE_NEW
151
+ action = definition.Actions.Create(0) # TASK_ACTION_EXEC
152
+ action.Path = executable
153
+ action.Arguments = subprocess.list2cmdline(
154
+ ["service", "run", "--state-dir", str(state_dir)]
155
+ )
156
+ # TASK_CREATE fails atomically if a task appeared after the check.
157
+ task = folder.RegisterTaskDefinition(_TASK_NAME, definition, 2, sid, None, 3, None)
158
+ try:
159
+ task.Run("")
160
+ except Exception:
161
+ raise _ServiceError("Служба установлена, но не запущена.") from None
162
+ except _ServiceError as error:
163
+ raise RuntimeError(str(error)) from None
164
+ except Exception:
165
+ raise RuntimeError("Не удалось установить службу kronbot.") from None
166
+
167
+
168
+ def uninstall() -> None:
169
+ try:
170
+ with _scheduler() as (_, folder, sid):
171
+ task = _get_task(folder)
172
+ if task is None:
173
+ return
174
+ if not _owned(task, sid):
175
+ raise _ServiceError("Имя службы занято другой задачей.")
176
+ if task.State in (2, 4):
177
+ task.Stop(0)
178
+ folder.DeleteTask(_TASK_NAME, 0)
179
+ except _ServiceError as error:
180
+ raise RuntimeError(str(error)) from None
181
+ except Exception:
182
+ raise RuntimeError("Не удалось удалить службу kronbot.") from None
183
+
184
+
185
+ def start() -> None:
186
+ try:
187
+ with _scheduler() as (_, folder, sid):
188
+ _require_owned(folder, sid).Run("")
189
+ except _ServiceError as error:
190
+ raise RuntimeError(str(error)) from None
191
+ except Exception:
192
+ raise RuntimeError("Не удалось запустить службу kronbot.") from None
193
+
194
+
195
+ def stop() -> None:
196
+ try:
197
+ with _scheduler() as (_, folder, sid):
198
+ task = _require_owned(folder, sid)
199
+ if task.State in (2, 4):
200
+ task.Stop(0)
201
+ except _ServiceError as error:
202
+ raise RuntimeError(str(error)) from None
203
+ except Exception:
204
+ raise RuntimeError("Не удалось остановить службу kronbot.") from None
205
+
206
+
207
+ def status() -> str:
208
+ try:
209
+ with _scheduler() as (_, folder, sid):
210
+ task = _get_task(folder)
211
+ if task is None:
212
+ return "not installed"
213
+ if not _owned(task, sid):
214
+ raise _ServiceError("Имя службы занято другой задачей.")
215
+ if task.State == 4:
216
+ return "running"
217
+ if task.State in (1, 2, 3):
218
+ return "stopped"
219
+ raise _ServiceError("Не удалось определить состояние службы kronbot.")
220
+ except _ServiceError as error:
221
+ raise RuntimeError(str(error)) from None
222
+ except Exception:
223
+ raise RuntimeError("Не удалось определить состояние службы kronbot.") from None
kronbot/_win_state.py ADDED
@@ -0,0 +1,27 @@
1
+ """Проверки владельца и DACL пользовательского хранилища Windows."""
2
+
3
+ import win32api
4
+ import win32con
5
+ import win32security
6
+
7
+
8
+ def validate(path):
9
+ info = win32security.GetNamedSecurityInfo(
10
+ str(path), win32security.SE_FILE_OBJECT,
11
+ win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION,
12
+ )
13
+ token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
14
+ user = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
15
+ if info.GetSecurityDescriptorOwner() != user:
16
+ raise ValueError("неверный владелец")
17
+ acl = info.GetSecurityDescriptorDacl()
18
+ if acl is None or acl.GetAceCount() == 0:
19
+ raise ValueError("пустой DACL")
20
+ allowed = {win32security.ConvertSidToStringSid(user), "S-1-5-18", "S-1-5-32-544"}
21
+ for index in range(acl.GetAceCount()):
22
+ ace = acl.GetAce(index)
23
+ kind = ace[0][0]
24
+ if kind not in (win32security.ACCESS_ALLOWED_ACE_TYPE, win32security.ACCESS_DENIED_ACE_TYPE):
25
+ raise ValueError("неподдерживаемый ACE")
26
+ if kind == win32security.ACCESS_ALLOWED_ACE_TYPE and win32security.ConvertSidToStringSid(ace[2]) not in allowed:
27
+ raise ValueError("небезопасный DACL")