instar 1.3.1669 → 1.3.1671
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.
- package/dist/commands/init.d.ts +6 -3
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +9 -6
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/server.d.ts.map +1 -1
- package/dist/commands/server.js +41 -17
- package/dist/commands/server.js.map +1 -1
- package/dist/core/BackupManager.d.ts.map +1 -1
- package/dist/core/BackupManager.js +6 -0
- package/dist/core/BackupManager.js.map +1 -1
- package/dist/core/ClassReviewReplicatedStore.d.ts +13 -1
- package/dist/core/ClassReviewReplicatedStore.d.ts.map +1 -1
- package/dist/core/ClassReviewReplicatedStore.js +16 -0
- package/dist/core/ClassReviewReplicatedStore.js.map +1 -1
- package/dist/core/CodexLifecycleProductionComposition.d.ts +1 -1
- package/dist/core/CodexLifecycleProductionComposition.d.ts.map +1 -1
- package/dist/core/FileClassifier.d.ts.map +1 -1
- package/dist/core/FileClassifier.js +4 -0
- package/dist/core/FileClassifier.js.map +1 -1
- package/dist/core/PostUpdateMigrator.d.ts +29 -7
- package/dist/core/PostUpdateMigrator.d.ts.map +1 -1
- package/dist/core/PostUpdateMigrator.js +127 -24
- package/dist/core/PostUpdateMigrator.js.map +1 -1
- package/dist/core/ReplicatedPeerStreamReader.d.ts +3 -0
- package/dist/core/ReplicatedPeerStreamReader.d.ts.map +1 -1
- package/dist/core/ReplicatedPeerStreamReader.js +35 -2
- package/dist/core/ReplicatedPeerStreamReader.js.map +1 -1
- package/dist/core/SlackReplyRelayInstaller.d.ts.map +1 -1
- package/dist/core/SlackReplyRelayInstaller.js +5 -0
- package/dist/core/SlackReplyRelayInstaller.js.map +1 -1
- package/dist/core/WriteDomainRegistry.d.ts.map +1 -1
- package/dist/core/WriteDomainRegistry.js +7 -0
- package/dist/core/WriteDomainRegistry.js.map +1 -1
- package/dist/core/linuxBrowserProvision.d.ts +93 -0
- package/dist/core/linuxBrowserProvision.d.ts.map +1 -0
- package/dist/core/linuxBrowserProvision.js +254 -0
- package/dist/core/linuxBrowserProvision.js.map +1 -0
- package/dist/core/rebalanceProof.d.ts.map +1 -1
- package/dist/core/rebalanceProof.js +3 -1
- package/dist/core/rebalanceProof.js.map +1 -1
- package/dist/data/builtinSkillContent.d.ts +7 -2
- package/dist/data/builtinSkillContent.d.ts.map +1 -1
- package/dist/data/builtinSkillContent.js +34 -12
- package/dist/data/builtinSkillContent.js.map +1 -1
- package/dist/data/standards-guard-index.json +1 -1
- package/dist/data/standards-guard-index.meta.json +2 -2
- package/dist/data/standards-registry.meta.json +1 -1
- package/dist/messaging/slack/SlackAdapter.d.ts +1 -0
- package/dist/messaging/slack/SlackAdapter.d.ts.map +1 -1
- package/dist/messaging/slack/SlackAdapter.js +2 -0
- package/dist/messaging/slack/SlackAdapter.js.map +1 -1
- package/dist/messaging/slack/SlackMrkdwnFormatter.d.ts +1 -1
- package/dist/messaging/slack/SlackMrkdwnFormatter.d.ts.map +1 -1
- package/dist/messaging/slack/SlackMrkdwnFormatter.js +36 -5
- package/dist/messaging/slack/SlackMrkdwnFormatter.js.map +1 -1
- package/dist/messaging/slack/threadHistoryLabel.d.ts +1 -1
- package/dist/messaging/slack/threadHistoryLabel.d.ts.map +1 -1
- package/dist/messaging/slack/threadHistoryLabel.js +3 -1
- package/dist/messaging/slack/threadHistoryLabel.js.map +1 -1
- package/dist/messaging/telegram-origin/OriginCodexModelCanary.d.ts.map +1 -1
- package/dist/messaging/telegram-origin/OriginCodexModelCanary.js +5 -1
- package/dist/messaging/telegram-origin/OriginCodexModelCanary.js.map +1 -1
- package/dist/native/InstarWedgeCanary.app/Contents/MacOS/InstarWedgeCanary +0 -0
- package/dist/native/instar-desktop-host +0 -0
- package/dist/recommended/offerPrerequisites.d.ts.map +1 -1
- package/dist/recommended/offerPrerequisites.js +3 -0
- package/dist/recommended/offerPrerequisites.js.map +1 -1
- package/dist/scaffold/templates.d.ts.map +1 -1
- package/dist/scaffold/templates.js +4 -0
- package/dist/scaffold/templates.js.map +1 -1
- package/dist/server/CapabilityIndex.d.ts.map +1 -1
- package/dist/server/CapabilityIndex.js +24 -1
- package/dist/server/CapabilityIndex.js.map +1 -1
- package/dist/server/SecretDrop.d.ts +19 -0
- package/dist/server/SecretDrop.d.ts.map +1 -1
- package/dist/server/SecretDrop.js +4 -0
- package/dist/server/SecretDrop.js.map +1 -1
- package/dist/server/fileRoutes.d.ts.map +1 -1
- package/dist/server/fileRoutes.js +6 -0
- package/dist/server/fileRoutes.js.map +1 -1
- package/dist/server/mobileConsolePagesRoutes.d.ts +60 -0
- package/dist/server/mobileConsolePagesRoutes.d.ts.map +1 -0
- package/dist/server/mobileConsolePagesRoutes.js +473 -0
- package/dist/server/mobileConsolePagesRoutes.js.map +1 -0
- package/dist/server/mobilePairingRoutes.d.ts.map +1 -1
- package/dist/server/mobilePairingRoutes.js +8 -0
- package/dist/server/mobilePairingRoutes.js.map +1 -1
- package/dist/server/routes.d.ts +1 -0
- package/dist/server/routes.d.ts.map +1 -1
- package/dist/server/routes.js +90 -14
- package/dist/server/routes.js.map +1 -1
- package/dist/testing/selfActionRegistry.d.ts.map +1 -1
- package/dist/testing/selfActionRegistry.js +31 -0
- package/dist/testing/selfActionRegistry.js.map +1 -1
- package/package.json +1 -1
- package/scripts/blocking-decision-surfaces-baseline.json +29 -9
- package/scripts/lint-blocking-decisions-declared.mjs +1 -1
- package/src/data/builtin-manifest.json +66 -66
- package/src/data/builtinSkillContent.ts +35 -12
- package/src/data/standards-guard-index.json +1 -1
- package/src/data/standards-guard-index.meta.json +2 -2
- package/src/data/standards-registry.meta.json +1 -1
- package/src/data/state-coherence-registry.json +18 -0
- package/src/scaffold/templates.ts +4 -0
- package/src/templates/scripts/browser/chrome-close.sh +1 -1
- package/src/templates/scripts/browser/chrome-js.sh +1 -1
- package/src/templates/scripts/browser/chrome-launch.sh +1 -1
- package/src/templates/scripts/browser/chrome-mainworld.sh +1 -1
- package/src/templates/scripts/browser/chrome-renew.sh +1 -1
- package/src/templates/scripts/browser/chrome-unsaved.sh +1 -1
- package/src/templates/scripts/browser/ndrive.sh +1 -1
- package/src/templates/scripts/browser/x-drive.py +1594 -0
- package/src/templates/scripts/browser/xdrive-provision.sh +87 -0
- package/src/templates/scripts/browser/xdrive.sh +120 -0
- package/src/templates/scripts/secret-drop-retrieve.mjs +60 -7
- package/src/templates/scripts/slack-reply.sh +17 -1
- package/upgrades/1.3.1670.md +27 -0
- package/upgrades/1.3.1671.md +42 -0
- package/upgrades/proof-accepts-queued.eli16.md +20 -0
- package/upgrades/side-effects/codex-canary-0166.md +14 -0
- package/upgrades/side-effects/mobile-native-console-pages.md +24 -0
- package/upgrades/side-effects/normal-chrome-linux.md +84 -0
- package/upgrades/side-effects/peer-stream-read-cache.md +14 -0
- package/upgrades/side-effects/proof-accepts-queued.md +11 -0
- package/upgrades/side-effects/slack-native-reference-repair.md +74 -0
|
@@ -0,0 +1,1594 @@
|
|
|
1
|
+
#!/usr/bin/python3
|
|
2
|
+
# x-drive.py: the Linux normal-Chrome driver (ACT-138). Run it through xdrive.sh, never directly.
|
|
3
|
+
# Installed by instar into .instar/scripts/browser/, overwritten on every update.
|
|
4
|
+
#
|
|
5
|
+
# It reads pages through the accessibility tree (AT-SPI) and acts through real X input (XTEST) on a
|
|
6
|
+
# private virtual display this agent owns, so a click carries user activation and no person shares the
|
|
7
|
+
# keyboard or pointer. There is no page-world JavaScript, no CDP and no WebDriver.
|
|
8
|
+
#
|
|
9
|
+
# These rules are guardrails against an honest agent's mistakes (wrong window, wrong page, a stale
|
|
10
|
+
# coordinate, text on argv). They are not a boundary against other code running as the same Linux user.
|
|
11
|
+
# Standards: docs/specs/normal-chrome-linux.md, docs/specs/normal-chrome-cross-platform.md.
|
|
12
|
+
#
|
|
13
|
+
# Layout: the rule functions come first and import nothing beyond the standard library, so they run and
|
|
14
|
+
# are tested on any OS. Everything that needs X or AT-SPI sits below and loads only on Linux.
|
|
15
|
+
import ctypes
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import resource
|
|
21
|
+
import signal
|
|
22
|
+
import socket
|
|
23
|
+
import stat
|
|
24
|
+
import struct
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
import tempfile
|
|
28
|
+
import time
|
|
29
|
+
import unicodedata
|
|
30
|
+
from urllib.parse import unquote, urlsplit
|
|
31
|
+
|
|
32
|
+
EXIT_OK, EXIT_ERROR, EXIT_REFUSED, EXIT_CHECK, EXIT_ARG = 0, 1, 2, 3, 64
|
|
33
|
+
|
|
34
|
+
CREDENTIAL_PARAMS = frozenset((
|
|
35
|
+
'code', 'token', 'access_token', 'id_token', 'refresh_token', 'oobcode', 'api_key', 'apikey', 'key',
|
|
36
|
+
'secret', 'password', 'otp', 'auth', 'sig', 'signature', 'ticket', 'assertion', 'session',
|
|
37
|
+
))
|
|
38
|
+
NAMED_KEYS = frozenset((
|
|
39
|
+
'Return', 'Tab', 'Escape', 'BackSpace', 'Delete', 'Left', 'Right', 'Up', 'Down', 'Home', 'End',
|
|
40
|
+
'Page_Up', 'Page_Down',
|
|
41
|
+
))
|
|
42
|
+
ALLOWED_EXTRA_FLAGS = re.compile(r'^(--disable-extensions|--window-size=\d{1,5},\d{1,5}|--lang=[a-z]{2}(-[A-Z]{2})?)$')
|
|
43
|
+
PROFILE_ID = re.compile(r'^[a-z0-9-]{1,64}$')
|
|
44
|
+
DISPLAY_FIRST, DISPLAY_LAST = 100, 119
|
|
45
|
+
SOCKET_PATH_LIMIT = 100
|
|
46
|
+
SCREEN_W, SCREEN_H = 1600, 1000
|
|
47
|
+
FIND_CANDIDATE_CAP = 200
|
|
48
|
+
TEXT_NODE_CAP, TEXT_BYTE_CAP = 200000, 20 * 1024 * 1024
|
|
49
|
+
OUT_MAX_AGE_S, OUT_MAX_BYTES, OUT_MIN_AGE_S = 86400, 200 * 1024 * 1024, 600
|
|
50
|
+
PER_KEY_SECONDS = 0.02
|
|
51
|
+
SECRET_MAX_BYTES = 4096
|
|
52
|
+
|
|
53
|
+
# The US keymap: every printable ASCII character as (keysym name, shift). Anything else has no keycode here.
|
|
54
|
+
_UNSHIFTED = {
|
|
55
|
+
' ': 'space', '-': 'minus', '=': 'equal', '[': 'bracketleft', ']': 'bracketright', '\\': 'backslash',
|
|
56
|
+
';': 'semicolon', "'": 'apostrophe', '`': 'grave', ',': 'comma', '.': 'period', '/': 'slash',
|
|
57
|
+
}
|
|
58
|
+
_SHIFTED = {
|
|
59
|
+
'!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0',
|
|
60
|
+
'_': 'minus', '+': 'equal', '{': 'bracketleft', '}': 'bracketright', '|': 'backslash', ':': 'semicolon',
|
|
61
|
+
'"': 'apostrophe', '~': 'grave', '<': 'comma', '>': 'period', '?': 'slash',
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
INPUT_SENT = [False] # set by the backend on the first real event, so a later refusal keeps the latch
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Refuse(Exception):
|
|
69
|
+
"""A deterministic refusal: the message is safe to print and the exit code is part of the contract."""
|
|
70
|
+
|
|
71
|
+
def __init__(self, code, message):
|
|
72
|
+
super().__init__(message)
|
|
73
|
+
self.code = code
|
|
74
|
+
self.message = message
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def us_key(ch):
|
|
78
|
+
"""(keysym name, shift) for one character, or None when the US keymap cannot type it."""
|
|
79
|
+
if len(ch) != 1:
|
|
80
|
+
return None
|
|
81
|
+
if 'a' <= ch <= 'z' or '0' <= ch <= '9':
|
|
82
|
+
return (ch, False)
|
|
83
|
+
if 'A' <= ch <= 'Z':
|
|
84
|
+
return (ch.lower(), True)
|
|
85
|
+
if ch in _UNSHIFTED:
|
|
86
|
+
return (_UNSHIFTED[ch], False)
|
|
87
|
+
if ch in _SHIFTED:
|
|
88
|
+
return (_SHIFTED[ch], True)
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def require_typable(text):
|
|
93
|
+
"""Refuse before any key goes down. The character is never named: this also guards secrets."""
|
|
94
|
+
for ch in text:
|
|
95
|
+
if us_key(ch) is None:
|
|
96
|
+
raise Refuse(EXIT_REFUSED, 'ERR untypable-character: the text holds a character the private display\'s US layout cannot type; nothing was typed')
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def require_fits_deadline(length, deadline_s):
|
|
100
|
+
if length * PER_KEY_SECONDS > max(deadline_s - 5, 0):
|
|
101
|
+
raise Refuse(EXIT_REFUSED, 'ERR text-exceeds-deadline: this text would outlast the command time limit; nothing was typed')
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def escape_page(value):
|
|
105
|
+
"""Page text can never forge a driver line: controls, format and separator characters are escaped."""
|
|
106
|
+
out = []
|
|
107
|
+
for ch in value or '':
|
|
108
|
+
if unicodedata.category(ch) in ('Cc', 'Cf', 'Zl', 'Zp'):
|
|
109
|
+
out.append('\\u%04x' % ord(ch))
|
|
110
|
+
else:
|
|
111
|
+
out.append(ch)
|
|
112
|
+
return ''.join(out)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _param_name(part):
|
|
116
|
+
return unquote(part.split('=', 1)[0]).strip().lower()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def has_credential_param(url):
|
|
120
|
+
for chunk in re.split(r'[?&#;]', url)[1:]:
|
|
121
|
+
if '=' in chunk and _param_name(chunk) in CREDENTIAL_PARAMS:
|
|
122
|
+
return True
|
|
123
|
+
return False
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def redact_uri(uri):
|
|
127
|
+
"""Replace the value of every credential-shaped query or fragment parameter."""
|
|
128
|
+
if not uri:
|
|
129
|
+
return ''
|
|
130
|
+
|
|
131
|
+
def fix(match):
|
|
132
|
+
lead, name = match.group(1), match.group(2)
|
|
133
|
+
if unquote(name).strip().lower() in CREDENTIAL_PARAMS:
|
|
134
|
+
return lead + name + '=[redacted]'
|
|
135
|
+
return match.group(0)
|
|
136
|
+
|
|
137
|
+
return re.sub(r'([?&#;])([^=?&#;]+)=([^&#;]*)', fix, uri)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def check_url(url):
|
|
141
|
+
"""The url rule for launch and nav. The url is never echoed in a refusal."""
|
|
142
|
+
if not url or re.search(r'[\s"\'`\x00-\x1f\x7f]', url):
|
|
143
|
+
raise Refuse(EXIT_ARG, 'ERR bad-url: a url holds no whitespace, quote or control character (the url is not echoed)')
|
|
144
|
+
if not re.match(r'^(https?://.|about:.|chrome://.|file://.)', url, re.IGNORECASE):
|
|
145
|
+
raise Refuse(EXIT_ARG, 'ERR bad-url: a url starts https://, http://, about:, chrome:// or file://, and a Chrome flag is never accepted here (the url is not echoed)')
|
|
146
|
+
if has_credential_param(url):
|
|
147
|
+
raise Refuse(EXIT_ARG, 'ERR secret-shaped-url: the url carries a credential-shaped parameter, and a url on argv is readable by every process on the machine')
|
|
148
|
+
return url
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def is_browser_ui_document(uri):
|
|
152
|
+
"""Chrome draws parts of its own interface as web documents, such as the address bar's dropdown
|
|
153
|
+
at chrome://omnibox-popup.top-chrome/. They are not pages and not tabs."""
|
|
154
|
+
return uri.startswith('chrome://') and uri_host(uri).endswith('.top-chrome')
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def uri_host(uri):
|
|
158
|
+
try:
|
|
159
|
+
return (urlsplit(uri).hostname or '').lower().rstrip('.')
|
|
160
|
+
except ValueError:
|
|
161
|
+
return ''
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def check_secret_destination(uri, expected_host):
|
|
165
|
+
"""typesecret's destination rule: https, default port, and the host equal to the named one, no suffix match."""
|
|
166
|
+
expected = (expected_host or '').strip().lower().rstrip('.')
|
|
167
|
+
if not expected or not re.match(r'^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$', expected):
|
|
168
|
+
raise Refuse(EXIT_ARG, 'ERR bad-argument: typesecret needs the expected host, such as accounts.example.com')
|
|
169
|
+
try:
|
|
170
|
+
parts = urlsplit(uri or '')
|
|
171
|
+
port = parts.port
|
|
172
|
+
except ValueError:
|
|
173
|
+
raise Refuse(EXIT_REFUSED, 'ERR host-mismatch: the page is not https on the expected host; nothing was typed')
|
|
174
|
+
if parts.scheme.lower() != 'https' or port not in (None, 443) or uri_host(uri) != expected:
|
|
175
|
+
raise Refuse(EXIT_REFUSED, 'ERR host-mismatch: the page is not https on the expected host; nothing was typed')
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def read_secret(stream):
|
|
179
|
+
"""All of stdin as a mutable buffer, so it can be overwritten. One line only: a second line is refused,
|
|
180
|
+
never silently dropped, because the submission is consumed on success."""
|
|
181
|
+
raw = bytearray(stream.read(SECRET_MAX_BYTES + 1))
|
|
182
|
+
if len(raw) > SECRET_MAX_BYTES:
|
|
183
|
+
wipe(raw)
|
|
184
|
+
raise Refuse(EXIT_REFUSED, 'ERR bad-secret: the value is too long; nothing was typed')
|
|
185
|
+
if raw and raw[-1] == 10:
|
|
186
|
+
raw.pop()
|
|
187
|
+
if raw and raw[-1] == 13:
|
|
188
|
+
raw.pop()
|
|
189
|
+
if not raw or 10 in raw or 13 in raw:
|
|
190
|
+
wipe(raw)
|
|
191
|
+
raise Refuse(EXIT_REFUSED, 'ERR bad-secret: the value must be one non-empty line; nothing was typed')
|
|
192
|
+
return raw
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def wipe(buffer):
|
|
196
|
+
for i in range(len(buffer)):
|
|
197
|
+
buffer[i] = 0
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def resolve_profile(home, profile_id, must_exist=True):
|
|
201
|
+
"""The profile jail: an id, inside this agent's profiles folder, with no symlink out."""
|
|
202
|
+
if not PROFILE_ID.match(profile_id or ''):
|
|
203
|
+
raise Refuse(EXIT_ARG, 'ERR bad-profile-path: a profile id is lowercase letters, digits and dashes')
|
|
204
|
+
root = os.path.realpath(os.path.join(home, '.instar', 'state', 'playwright-profiles'))
|
|
205
|
+
real = os.path.realpath(os.path.join(root, profile_id))
|
|
206
|
+
if os.path.dirname(real) != root:
|
|
207
|
+
raise Refuse(EXIT_ARG, 'ERR profile-outside-agent-home: that profile resolves outside this agent\'s profiles folder')
|
|
208
|
+
if must_exist and not os.path.isdir(real):
|
|
209
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-profile: no such profile; add --new only when the operator asked for a new one')
|
|
210
|
+
return real
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def check_outfile(home, path):
|
|
214
|
+
out = os.path.join(os.path.realpath(home), '.instar', 'state', 'xdrive', 'out') + os.sep
|
|
215
|
+
if not path or not os.path.isabs(path) or '..' in path.split(os.sep) or re.search(r'[\x00-\x1f\x7f]', path):
|
|
216
|
+
raise Refuse(EXIT_ARG, 'ERR bad-outfile: give an absolute path under .instar/state/xdrive/out/')
|
|
217
|
+
real = os.path.join(os.path.realpath(os.path.dirname(path)), os.path.basename(path))
|
|
218
|
+
if not real.startswith(out):
|
|
219
|
+
raise Refuse(EXIT_ARG, 'ERR bad-outfile: give an absolute path under .instar/state/xdrive/out/')
|
|
220
|
+
return real
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def check_extra_flags(value):
|
|
224
|
+
flags = (value or '').split()
|
|
225
|
+
for flag in flags:
|
|
226
|
+
if not ALLOWED_EXTRA_FLAGS.match(flag):
|
|
227
|
+
raise Refuse(EXIT_ARG, 'ERR bad-argument: XD_CHROME_FLAGS allows only --disable-extensions, --window-size=W,H and --lang=xx')
|
|
228
|
+
return flags
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def parse_start_time(stat_text):
|
|
232
|
+
"""Field 22 of /proc/<pid>/stat. The command name may hold spaces and parentheses, so split after the last )."""
|
|
233
|
+
return stat_text.rsplit(')', 1)[1].split()[19]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def proc_start_time(pid, proc='/proc'):
|
|
237
|
+
try:
|
|
238
|
+
with open('%s/%d/stat' % (proc, int(pid)), 'r', errors='replace') as handle:
|
|
239
|
+
return parse_start_time(handle.read())
|
|
240
|
+
except (OSError, ValueError, IndexError):
|
|
241
|
+
return None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def pick_display(socket_exists, lock_pid_alive):
|
|
245
|
+
"""The first free number: no socket, and no lock file naming a live process."""
|
|
246
|
+
for number in range(DISPLAY_FIRST, DISPLAY_LAST + 1):
|
|
247
|
+
if not socket_exists(number) and not lock_pid_alive(number):
|
|
248
|
+
return number
|
|
249
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-x-server: no free display number from 100 to 119')
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def signal_recorded(processes, read_start, kill, sleep=time.sleep, grace_s=5.0):
|
|
253
|
+
"""Stop only recorded processes whose start time still matches; a mismatch is another process."""
|
|
254
|
+
live = [p for p in processes if read_start(p['pid']) == p['start']]
|
|
255
|
+
for proc in live:
|
|
256
|
+
kill(proc['pid'], signal.SIGTERM)
|
|
257
|
+
waited = 0.0
|
|
258
|
+
while waited < grace_s and any(read_start(p['pid']) == p['start'] for p in live):
|
|
259
|
+
sleep(0.1)
|
|
260
|
+
waited += 0.1
|
|
261
|
+
for proc in live:
|
|
262
|
+
if read_start(proc['pid']) == proc['start']:
|
|
263
|
+
kill(proc['pid'], signal.SIGKILL)
|
|
264
|
+
return [p['pid'] for p in live]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def xauth_entry(hostname, number, cookie):
|
|
268
|
+
"""One MIT-MAGIC-COOKIE-1 record, family local, for this display number only."""
|
|
269
|
+
def field(data):
|
|
270
|
+
return struct.pack('>H', len(data)) + data
|
|
271
|
+
return struct.pack('>H', 256) + field(hostname.encode()) + field(str(number).encode()) + field(b'MIT-MAGIC-COOKIE-1') + field(cookie)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def xvnc_args(binary, number, auth_file):
|
|
275
|
+
return [
|
|
276
|
+
binary, ':%d' % number, '-auth', auth_file, '-nolisten', 'tcp', '-rfbport', '-1', '-SecurityTypes', 'None',
|
|
277
|
+
'-AcceptKeyEvents=0', '-AcceptPointerEvents=0', '-AcceptCutText=0', '-SendCutText=0',
|
|
278
|
+
'-AcceptSetDesktopSize=0', '-geometry', '%dx%d' % (SCREEN_W, SCREEN_H), '-depth', '24',
|
|
279
|
+
]
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def chrome_args(binary, profile_dir, url, extra):
|
|
283
|
+
return [
|
|
284
|
+
binary, '--user-data-dir=%s' % profile_dir, '--password-store=basic', '--ozone-platform=x11', '--no-first-run',
|
|
285
|
+
'--no-default-browser-check', '--force-renderer-accessibility', '--window-position=0,0',
|
|
286
|
+
'--window-size=%d,%d' % (SCREEN_W, SCREEN_H),
|
|
287
|
+
] + extra + ['--new-window', url]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def socket_folder(home, uid):
|
|
291
|
+
"""The state tree when the path fits a Unix socket, otherwise a private folder under /tmp."""
|
|
292
|
+
preferred = os.path.join(home, '.instar', 'state', 'xdrive', 'run')
|
|
293
|
+
if len(os.path.join(preferred, 'bus').encode()) <= SOCKET_PATH_LIMIT:
|
|
294
|
+
return preferred
|
|
295
|
+
digest = hashlib.sha256(home.encode()).hexdigest()[:12]
|
|
296
|
+
return '/tmp/instar-xdrive-%d-%s' % (uid, digest)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def check_socket_folder(lstat_result, uid):
|
|
300
|
+
if not stat.S_ISDIR(lstat_result.st_mode) or lstat_result.st_uid != uid or stat.S_IMODE(lstat_result.st_mode) != 0o700:
|
|
301
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-x-server: socket folder not ours')
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def sweep_outfiles(folder, now=None):
|
|
305
|
+
"""Remove outfiles older than 24 h, then the oldest past 10 minutes while over 200 MB."""
|
|
306
|
+
now = time.time() if now is None else now
|
|
307
|
+
entries = []
|
|
308
|
+
for name in os.listdir(folder):
|
|
309
|
+
path = os.path.join(folder, name)
|
|
310
|
+
info = os.lstat(path)
|
|
311
|
+
if not stat.S_ISREG(info.st_mode):
|
|
312
|
+
continue
|
|
313
|
+
if now - info.st_mtime > OUT_MAX_AGE_S:
|
|
314
|
+
os.unlink(path)
|
|
315
|
+
else:
|
|
316
|
+
entries.append((info.st_mtime, info.st_size, path))
|
|
317
|
+
total = sum(e[1] for e in entries)
|
|
318
|
+
for mtime, size, path in sorted(entries):
|
|
319
|
+
if total <= OUT_MAX_BYTES:
|
|
320
|
+
break
|
|
321
|
+
if now - mtime > OUT_MIN_AGE_S:
|
|
322
|
+
os.unlink(path)
|
|
323
|
+
total -= size
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ---------------------------------------------------------------------------------------------------
|
|
327
|
+
# The input backend. Every libX11/libXtst call lives in this class; a Wayland backend implements the
|
|
328
|
+
# same methods with coordinate_type() = 'window'. A static check fails on X calls outside it.
|
|
329
|
+
# ---------------------------------------------------------------------------------------------------
|
|
330
|
+
class X11Backend:
|
|
331
|
+
REVERT_TO_PARENT, CURRENT_TIME, IS_VIEWABLE, USE_CORE_KBD = 2, 0, 2, 0x0100
|
|
332
|
+
|
|
333
|
+
class _Attrs(ctypes.Structure):
|
|
334
|
+
_fields_ = [
|
|
335
|
+
('x', ctypes.c_int), ('y', ctypes.c_int), ('width', ctypes.c_int), ('height', ctypes.c_int),
|
|
336
|
+
('border_width', ctypes.c_int), ('depth', ctypes.c_int), ('visual', ctypes.c_void_p),
|
|
337
|
+
('root', ctypes.c_ulong), ('c_class', ctypes.c_int), ('bit_gravity', ctypes.c_int),
|
|
338
|
+
('win_gravity', ctypes.c_int), ('backing_store', ctypes.c_int), ('backing_planes', ctypes.c_ulong),
|
|
339
|
+
('backing_pixel', ctypes.c_ulong), ('save_under', ctypes.c_int), ('colormap', ctypes.c_ulong),
|
|
340
|
+
('map_installed', ctypes.c_int), ('map_state', ctypes.c_int), ('all_event_masks', ctypes.c_long),
|
|
341
|
+
('your_event_mask', ctypes.c_long), ('do_not_propagate_mask', ctypes.c_long),
|
|
342
|
+
('override_redirect', ctypes.c_int), ('screen', ctypes.c_void_p),
|
|
343
|
+
]
|
|
344
|
+
|
|
345
|
+
def __init__(self):
|
|
346
|
+
x = ctypes.CDLL('libX11.so.6')
|
|
347
|
+
t = ctypes.CDLL('libXtst.so.6')
|
|
348
|
+
P, U, I, L = ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.POINTER
|
|
349
|
+
x.XOpenDisplay.restype = P
|
|
350
|
+
x.XOpenDisplay.argtypes = [ctypes.c_char_p]
|
|
351
|
+
x.XDefaultRootWindow.restype = U
|
|
352
|
+
x.XDefaultRootWindow.argtypes = [P]
|
|
353
|
+
x.XInternAtom.restype = U
|
|
354
|
+
x.XInternAtom.argtypes = [P, ctypes.c_char_p, I]
|
|
355
|
+
x.XStringToKeysym.restype = U
|
|
356
|
+
x.XStringToKeysym.argtypes = [ctypes.c_char_p]
|
|
357
|
+
x.XKeysymToKeycode.restype = ctypes.c_ubyte
|
|
358
|
+
x.XKeysymToKeycode.argtypes = [P, U]
|
|
359
|
+
x.XQueryTree.argtypes = [P, U, L(U), L(U), L(L(U)), L(ctypes.c_uint)]
|
|
360
|
+
x.XGetWindowAttributes.argtypes = [P, U, L(self._Attrs)]
|
|
361
|
+
x.XGetWindowProperty.argtypes = [P, U, U, ctypes.c_long, ctypes.c_long, I, U, L(U), L(I), L(U), L(U), L(P)]
|
|
362
|
+
x.XGetInputFocus.argtypes = [P, L(U), L(I)]
|
|
363
|
+
x.XQueryPointer.argtypes = [P, U, L(U), L(U), L(I), L(I), L(I), L(I), L(ctypes.c_uint)]
|
|
364
|
+
x.XRaiseWindow.argtypes = [P, U]
|
|
365
|
+
x.XSetInputFocus.argtypes = [P, U, I, U]
|
|
366
|
+
x.XSync.argtypes = [P, I]
|
|
367
|
+
x.XFree.argtypes = [P]
|
|
368
|
+
x.XkbLockModifiers.argtypes = [P, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]
|
|
369
|
+
x.XkbLockGroup.argtypes = [P, ctypes.c_uint, ctypes.c_uint]
|
|
370
|
+
t.XTestFakeMotionEvent.argtypes = [P, I, I, I, U]
|
|
371
|
+
t.XTestFakeButtonEvent.argtypes = [P, ctypes.c_uint, I, U]
|
|
372
|
+
t.XTestFakeKeyEvent.argtypes = [P, ctypes.c_uint, I, U]
|
|
373
|
+
self.x, self.t = x, t
|
|
374
|
+
# Xlib's default handler exits the process. Chrome opens and closes windows constantly, so a
|
|
375
|
+
# window vanishing between two calls is ordinary: the call fails and the caller sees that.
|
|
376
|
+
self._on_error = ctypes.CFUNCTYPE(I, P, P)(lambda _display, _event: 0)
|
|
377
|
+
x.XSetErrorHandler.argtypes = [P]
|
|
378
|
+
x.XSetErrorHandler.restype = P
|
|
379
|
+
x.XSetErrorHandler(ctypes.cast(self._on_error, P))
|
|
380
|
+
self.dpy = x.XOpenDisplay(None)
|
|
381
|
+
if not self.dpy:
|
|
382
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-x-server: cannot connect to the agent display')
|
|
383
|
+
self.root = x.XDefaultRootWindow(self.dpy)
|
|
384
|
+
self.down_keys, self.down_buttons = [], []
|
|
385
|
+
|
|
386
|
+
def coordinate_type(self):
|
|
387
|
+
return 'screen'
|
|
388
|
+
|
|
389
|
+
def to_input_point(self, rect, _window):
|
|
390
|
+
return (rect[0] + rect[2] // 2, rect[1] + rect[3] // 2)
|
|
391
|
+
|
|
392
|
+
def _tree(self, window):
|
|
393
|
+
root, parent = ctypes.c_ulong(), ctypes.c_ulong()
|
|
394
|
+
kids, count = ctypes.POINTER(ctypes.c_ulong)(), ctypes.c_uint()
|
|
395
|
+
if not self.x.XQueryTree(self.dpy, window, ctypes.byref(root), ctypes.byref(parent), ctypes.byref(kids), ctypes.byref(count)):
|
|
396
|
+
return 0, []
|
|
397
|
+
found = [kids[i] for i in range(count.value)]
|
|
398
|
+
if kids:
|
|
399
|
+
self.x.XFree(ctypes.cast(kids, ctypes.c_void_p))
|
|
400
|
+
return parent.value, found
|
|
401
|
+
|
|
402
|
+
def _property(self, window, atom_name, length):
|
|
403
|
+
atom = self.x.XInternAtom(self.dpy, atom_name, 1)
|
|
404
|
+
if not atom:
|
|
405
|
+
return None, 0
|
|
406
|
+
kind, fmt, count, after, data = ctypes.c_ulong(), ctypes.c_int(), ctypes.c_ulong(), ctypes.c_ulong(), ctypes.c_void_p()
|
|
407
|
+
status = self.x.XGetWindowProperty(self.dpy, window, atom, 0, length, 0, 0, ctypes.byref(kind), ctypes.byref(fmt), ctypes.byref(count), ctypes.byref(after), ctypes.byref(data))
|
|
408
|
+
if status != 0 or not data:
|
|
409
|
+
return None, 0
|
|
410
|
+
return data, count.value
|
|
411
|
+
|
|
412
|
+
def root_string(self, atom_name):
|
|
413
|
+
data, count = self._property(self.root, atom_name, 4096)
|
|
414
|
+
if data is None:
|
|
415
|
+
return ''
|
|
416
|
+
value = ctypes.string_at(data, count).decode('utf-8', 'replace')
|
|
417
|
+
self.x.XFree(data)
|
|
418
|
+
return value
|
|
419
|
+
|
|
420
|
+
def _window_pid(self, window):
|
|
421
|
+
data, count = self._property(window, b'_NET_WM_PID', 1)
|
|
422
|
+
if data is None:
|
|
423
|
+
return None
|
|
424
|
+
value = ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong))[0] if count else None
|
|
425
|
+
self.x.XFree(data)
|
|
426
|
+
return value
|
|
427
|
+
|
|
428
|
+
def geometry(self, window):
|
|
429
|
+
attrs = self._Attrs()
|
|
430
|
+
if not self.x.XGetWindowAttributes(self.dpy, window, ctypes.byref(attrs)):
|
|
431
|
+
return None
|
|
432
|
+
return {'x': attrs.x, 'y': attrs.y, 'w': attrs.width, 'h': attrs.height,
|
|
433
|
+
'viewable': attrs.map_state == self.IS_VIEWABLE, 'override': bool(attrs.override_redirect)}
|
|
434
|
+
|
|
435
|
+
def windows_of(self, pid):
|
|
436
|
+
"""Mapped, non-override-redirect top-level windows of this process: omnibox lists and menus don't count."""
|
|
437
|
+
found = []
|
|
438
|
+
for window in self._tree(self.root)[1]:
|
|
439
|
+
geo = self.geometry(window)
|
|
440
|
+
if geo and geo['viewable'] and not geo['override'] and self._window_pid(window) == pid:
|
|
441
|
+
found.append(window)
|
|
442
|
+
return found
|
|
443
|
+
|
|
444
|
+
def top_level(self, window):
|
|
445
|
+
while window and window != self.root:
|
|
446
|
+
parent = self._tree(window)[0]
|
|
447
|
+
if parent == self.root or not parent:
|
|
448
|
+
return window
|
|
449
|
+
window = parent
|
|
450
|
+
return window
|
|
451
|
+
|
|
452
|
+
def focus_window(self, window):
|
|
453
|
+
self.x.XRaiseWindow(self.dpy, window)
|
|
454
|
+
self.x.XSetInputFocus(self.dpy, window, self.REVERT_TO_PARENT, self.CURRENT_TIME)
|
|
455
|
+
self.x.XSync(self.dpy, 0)
|
|
456
|
+
|
|
457
|
+
def focused_window(self):
|
|
458
|
+
window, revert = ctypes.c_ulong(), ctypes.c_int()
|
|
459
|
+
self.x.XGetInputFocus(self.dpy, ctypes.byref(window), ctypes.byref(revert))
|
|
460
|
+
return self.top_level(window.value) if window.value > 1 else 0
|
|
461
|
+
|
|
462
|
+
def move(self, point):
|
|
463
|
+
self.t.XTestFakeMotionEvent(self.dpy, -1, point[0], point[1], 0)
|
|
464
|
+
self.x.XSync(self.dpy, 0)
|
|
465
|
+
|
|
466
|
+
def pointer_window(self):
|
|
467
|
+
root, child = ctypes.c_ulong(), ctypes.c_ulong()
|
|
468
|
+
rx, ry, wx, wy, mask = ctypes.c_int(), ctypes.c_int(), ctypes.c_int(), ctypes.c_int(), ctypes.c_uint()
|
|
469
|
+
self.x.XQueryPointer(self.dpy, self.root, ctypes.byref(root), ctypes.byref(child), ctypes.byref(rx), ctypes.byref(ry), ctypes.byref(wx), ctypes.byref(wy), ctypes.byref(mask))
|
|
470
|
+
return (child.value, (rx.value, ry.value))
|
|
471
|
+
|
|
472
|
+
def button(self, number, down):
|
|
473
|
+
INPUT_SENT[0] = True
|
|
474
|
+
self.t.XTestFakeButtonEvent(self.dpy, number, 1 if down else 0, 0)
|
|
475
|
+
self.x.XSync(self.dpy, 0)
|
|
476
|
+
if down:
|
|
477
|
+
self.down_buttons.append(number)
|
|
478
|
+
elif number in self.down_buttons:
|
|
479
|
+
self.down_buttons.remove(number)
|
|
480
|
+
|
|
481
|
+
def key(self, keysym_name, down):
|
|
482
|
+
code = self.x.XKeysymToKeycode(self.dpy, self.x.XStringToKeysym(keysym_name.encode()))
|
|
483
|
+
if not code:
|
|
484
|
+
raise Refuse(EXIT_REFUSED, 'ERR untypable-character: the private display has no such key; typing stopped')
|
|
485
|
+
INPUT_SENT[0] = True
|
|
486
|
+
self.t.XTestFakeKeyEvent(self.dpy, code, 1 if down else 0, 0)
|
|
487
|
+
self.x.XSync(self.dpy, 0)
|
|
488
|
+
if down:
|
|
489
|
+
self.down_keys.append(code)
|
|
490
|
+
elif code in self.down_keys:
|
|
491
|
+
self.down_keys.remove(code)
|
|
492
|
+
|
|
493
|
+
def tap(self, keysym_name, shift=False, ctrl=False):
|
|
494
|
+
held = (['Control_L'] if ctrl else []) + (['Shift_L'] if shift else [])
|
|
495
|
+
for name in held:
|
|
496
|
+
self.key(name, True)
|
|
497
|
+
self.key(keysym_name, True)
|
|
498
|
+
self.key(keysym_name, False)
|
|
499
|
+
for name in reversed(held):
|
|
500
|
+
self.key(name, False)
|
|
501
|
+
|
|
502
|
+
def type_char(self, ch):
|
|
503
|
+
name, shift = us_key(ch)
|
|
504
|
+
self.tap(name, shift=shift)
|
|
505
|
+
|
|
506
|
+
def reset_modifiers(self):
|
|
507
|
+
self.x.XkbLockModifiers(self.dpy, self.USE_CORE_KBD, 0xff, 0)
|
|
508
|
+
self.x.XkbLockGroup(self.dpy, self.USE_CORE_KBD, 0)
|
|
509
|
+
self.x.XSync(self.dpy, 0)
|
|
510
|
+
|
|
511
|
+
def release_all(self):
|
|
512
|
+
for code in list(self.down_keys):
|
|
513
|
+
self.t.XTestFakeKeyEvent(self.dpy, code, 0, 0)
|
|
514
|
+
for number in list(self.down_buttons):
|
|
515
|
+
self.t.XTestFakeButtonEvent(self.dpy, number, 0, 0)
|
|
516
|
+
self.down_keys, self.down_buttons = [], []
|
|
517
|
+
self.x.XSync(self.dpy, 0)
|
|
518
|
+
|
|
519
|
+
def release_everything(self):
|
|
520
|
+
"""After an unknown outcome nothing tracked survives: release buttons 1-5 and every keycode."""
|
|
521
|
+
for number in range(1, 6):
|
|
522
|
+
self.t.XTestFakeButtonEvent(self.dpy, number, 0, 0)
|
|
523
|
+
for code in range(8, 256):
|
|
524
|
+
self.t.XTestFakeKeyEvent(self.dpy, code, 0, 0)
|
|
525
|
+
self.x.XSync(self.dpy, 0)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
# ---------------------------------------------------------------------------------------------------
|
|
529
|
+
# State and the agent display stack.
|
|
530
|
+
# ---------------------------------------------------------------------------------------------------
|
|
531
|
+
class State:
|
|
532
|
+
def __init__(self, home):
|
|
533
|
+
self.home = os.path.realpath(home)
|
|
534
|
+
self.root = os.path.join(self.home, '.instar', 'state', 'xdrive')
|
|
535
|
+
self.display_dir = os.path.join(self.root, 'display')
|
|
536
|
+
self.targets = os.path.join(self.root, 'targets')
|
|
537
|
+
self.out = os.path.join(self.root, 'out')
|
|
538
|
+
self.record = os.path.join(self.root, 'display.json')
|
|
539
|
+
self.xauth = os.path.join(self.display_dir, 'Xauthority')
|
|
540
|
+
for path in (self.root, self.display_dir, self.targets, self.out):
|
|
541
|
+
os.makedirs(path, mode=0o700, exist_ok=True)
|
|
542
|
+
os.chmod(path, 0o700)
|
|
543
|
+
|
|
544
|
+
def target_file(self, profile_id):
|
|
545
|
+
return os.path.join(self.targets, profile_id + '.json')
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def read_json(path):
|
|
549
|
+
try:
|
|
550
|
+
with open(path, 'r') as handle:
|
|
551
|
+
return json.load(handle)
|
|
552
|
+
except (OSError, ValueError):
|
|
553
|
+
return None
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def write_json(path, value):
|
|
557
|
+
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path))
|
|
558
|
+
with os.fdopen(fd, 'w') as handle:
|
|
559
|
+
json.dump(value, handle)
|
|
560
|
+
os.chmod(tmp, 0o600)
|
|
561
|
+
os.replace(tmp, path)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def boot_id():
|
|
565
|
+
with open('/proc/sys/kernel/random/boot_id') as handle:
|
|
566
|
+
return handle.read().strip()
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def find_binary(names, extra=()):
|
|
570
|
+
for folder in os.environ.get('PATH', '').split(':') + list(extra):
|
|
571
|
+
for name in names:
|
|
572
|
+
path = os.path.join(folder, name)
|
|
573
|
+
if os.access(path, os.X_OK) and not os.path.isdir(path):
|
|
574
|
+
return path
|
|
575
|
+
return None
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def launcher_path():
|
|
579
|
+
for path in ('/usr/libexec/at-spi-bus-launcher', '/usr/lib/at-spi2-core/at-spi-bus-launcher'):
|
|
580
|
+
if os.access(path, os.X_OK):
|
|
581
|
+
return path
|
|
582
|
+
return None
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def minimal_env(extra):
|
|
586
|
+
env = {'PATH': os.environ.get('PATH', '/usr/bin:/bin'), 'HOME': os.environ.get('HOME', ''), 'LANG': os.environ.get('LANG', 'C.UTF-8')}
|
|
587
|
+
env.update(extra)
|
|
588
|
+
return env
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def spawn(argv, env):
|
|
592
|
+
return subprocess.Popen(argv, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True)
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _socket_path(number):
|
|
596
|
+
return '/tmp/.X11-unix/X%d' % number
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _lock_pid(number):
|
|
600
|
+
try:
|
|
601
|
+
with open('/tmp/.X%d-lock' % number) as handle:
|
|
602
|
+
return int(handle.read().strip())
|
|
603
|
+
except (OSError, ValueError):
|
|
604
|
+
return None
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _lock_alive(number):
|
|
608
|
+
pid = _lock_pid(number)
|
|
609
|
+
return pid is not None and proc_start_time(pid) is not None
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _peer_pid(number):
|
|
613
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
614
|
+
sock.settimeout(2)
|
|
615
|
+
try:
|
|
616
|
+
sock.connect(_socket_path(number))
|
|
617
|
+
return struct.unpack('3i', sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))[0]
|
|
618
|
+
except OSError:
|
|
619
|
+
return None
|
|
620
|
+
finally:
|
|
621
|
+
sock.close()
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _display_env(state, record):
|
|
625
|
+
return {
|
|
626
|
+
'DISPLAY': ':%d' % record['display'], 'XAUTHORITY': state.xauth,
|
|
627
|
+
'DBUS_SESSION_BUS_ADDRESS': 'unix:path=%s/bus' % record['sockets'],
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def stop_stack(state, record):
|
|
632
|
+
"""Only recorded processes, each re-checked by start time. After a reboot nothing is signalled."""
|
|
633
|
+
if record and record.get('boot') == boot_id():
|
|
634
|
+
signal_recorded(record.get('processes', []), proc_start_time, os.kill)
|
|
635
|
+
if record and os.path.isdir(record.get('sockets', '')):
|
|
636
|
+
for name in os.listdir(record['sockets']):
|
|
637
|
+
path = os.path.join(record['sockets'], name)
|
|
638
|
+
if not os.path.isdir(path):
|
|
639
|
+
os.unlink(path)
|
|
640
|
+
if os.path.exists(state.record):
|
|
641
|
+
os.unlink(state.record)
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def children_of(pid):
|
|
645
|
+
found = []
|
|
646
|
+
try:
|
|
647
|
+
for task in os.listdir('/proc/%d/task' % pid):
|
|
648
|
+
with open('/proc/%d/task/%s/children' % (pid, task)) as handle:
|
|
649
|
+
found += [int(p) for p in handle.read().split()]
|
|
650
|
+
except OSError:
|
|
651
|
+
pass
|
|
652
|
+
return found
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def bound_targets(state):
|
|
656
|
+
live = []
|
|
657
|
+
for name in os.listdir(state.targets):
|
|
658
|
+
target = read_json(os.path.join(state.targets, name))
|
|
659
|
+
if target and proc_start_time(target.get('pid', 0)) == target.get('start'):
|
|
660
|
+
live.append(target)
|
|
661
|
+
return live
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def stack_problem(record):
|
|
665
|
+
"""The health contract: the first thing wrong, or None."""
|
|
666
|
+
if record.get('boot') != boot_id():
|
|
667
|
+
return 'rebooted'
|
|
668
|
+
if not record.get('processes') or record.get('display') is None:
|
|
669
|
+
return 'unfinished start'
|
|
670
|
+
for proc in record.get('processes', []):
|
|
671
|
+
if proc_start_time(proc['pid']) != proc['start']:
|
|
672
|
+
return proc['name']
|
|
673
|
+
xvnc = record['processes'][0]['pid']
|
|
674
|
+
if _lock_pid(record['display']) != xvnc or _peer_pid(record['display']) != xvnc:
|
|
675
|
+
return 'x server'
|
|
676
|
+
return None
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def check_stack(state):
|
|
680
|
+
"""Reuse a healthy stack; stop a dead one; never end a running bound Chrome from a health check."""
|
|
681
|
+
record = read_json(state.record)
|
|
682
|
+
if not record:
|
|
683
|
+
return None
|
|
684
|
+
problem = stack_problem(record)
|
|
685
|
+
if problem is None:
|
|
686
|
+
return record
|
|
687
|
+
if not record.get('processes') or record.get('display') is None:
|
|
688
|
+
stop_stack(state, record)
|
|
689
|
+
return None
|
|
690
|
+
xvnc_alive = record.get('boot') == boot_id() and proc_start_time(record['processes'][0]['pid']) == record['processes'][0]['start']
|
|
691
|
+
if xvnc_alive and bound_targets(state):
|
|
692
|
+
raise Refuse(EXIT_REFUSED, 'ERR display-unhealthy: %s' % problem)
|
|
693
|
+
stop_stack(state, record)
|
|
694
|
+
return None
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def start_stack(state):
|
|
698
|
+
xvnc = find_binary(('Xvnc', 'Xtigervnc'))
|
|
699
|
+
launcher = launcher_path()
|
|
700
|
+
dbus = find_binary(('dbus-daemon',))
|
|
701
|
+
if not xvnc or not launcher or not dbus:
|
|
702
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-x-server: Xvnc, dbus-daemon or at-spi-bus-launcher is missing; see the install line from xdrive.sh deps')
|
|
703
|
+
sockets = socket_folder(state.home, os.getuid())
|
|
704
|
+
if not os.path.exists(sockets):
|
|
705
|
+
os.makedirs(sockets, mode=0o700)
|
|
706
|
+
check_socket_folder(os.lstat(sockets), os.getuid())
|
|
707
|
+
processes = []
|
|
708
|
+
|
|
709
|
+
record = {'display': None, 'boot': boot_id(), 'sockets': sockets, 'processes': processes}
|
|
710
|
+
|
|
711
|
+
def track(name, proc):
|
|
712
|
+
# Recorded the moment it exists, so a wrapper killed mid-start leaves nothing unowned.
|
|
713
|
+
processes.append({'name': name, 'pid': proc.pid, 'start': proc_start_time(proc.pid)})
|
|
714
|
+
write_json(state.record, record)
|
|
715
|
+
|
|
716
|
+
try:
|
|
717
|
+
for _ in range(DISPLAY_LAST - DISPLAY_FIRST + 1):
|
|
718
|
+
# A socket nobody answers on is left over from a killed server, which the next server clears.
|
|
719
|
+
number = pick_display(lambda n: _peer_pid(n) is not None, _lock_alive)
|
|
720
|
+
fd = os.open(state.xauth, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
721
|
+
with os.fdopen(fd, 'wb') as handle:
|
|
722
|
+
handle.write(xauth_entry(socket.gethostname(), number, os.urandom(16)))
|
|
723
|
+
proc = spawn(xvnc_args(xvnc, number, state.xauth), minimal_env({}))
|
|
724
|
+
record['display'] = number
|
|
725
|
+
track('xvnc', proc)
|
|
726
|
+
deadline = time.time() + 10
|
|
727
|
+
while time.time() < deadline and proc.poll() is None and _peer_pid(number) != proc.pid:
|
|
728
|
+
time.sleep(0.05)
|
|
729
|
+
if proc.poll() is None and _peer_pid(number) == proc.pid and _lock_pid(number) == proc.pid:
|
|
730
|
+
break
|
|
731
|
+
if proc.poll() is None:
|
|
732
|
+
proc.kill()
|
|
733
|
+
processes.pop()
|
|
734
|
+
write_json(state.record, record)
|
|
735
|
+
else:
|
|
736
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-x-server: Xvnc did not start')
|
|
737
|
+
env = _display_env(state, record)
|
|
738
|
+
os.environ.update(env)
|
|
739
|
+
track('dbus', spawn([dbus, '--session', '--nofork', '--address=' + env['DBUS_SESSION_BUS_ADDRESS']], minimal_env({})))
|
|
740
|
+
deadline = time.time() + 10
|
|
741
|
+
while time.time() < deadline and not os.path.exists(os.path.join(sockets, 'bus')):
|
|
742
|
+
time.sleep(0.05)
|
|
743
|
+
launched = spawn([launcher, '--launch-immediately'], minimal_env(dict(env, XDG_RUNTIME_DIR=sockets)))
|
|
744
|
+
track('at-spi-bus-launcher', launched)
|
|
745
|
+
backend = X11Backend()
|
|
746
|
+
while time.time() < deadline and not backend.root_string(b'AT_SPI_BUS'):
|
|
747
|
+
time.sleep(0.05)
|
|
748
|
+
if not backend.root_string(b'AT_SPI_BUS'):
|
|
749
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-x-server: the accessibility bus did not start')
|
|
750
|
+
for pid in children_of(launched.pid):
|
|
751
|
+
processes.append({'name': 'at-spi-bus', 'pid': pid, 'start': proc_start_time(pid)})
|
|
752
|
+
write_json(state.record, record)
|
|
753
|
+
enable_accessibility()
|
|
754
|
+
return record
|
|
755
|
+
except Exception:
|
|
756
|
+
stop_stack(state, record)
|
|
757
|
+
raise
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def enable_accessibility():
|
|
761
|
+
import gi
|
|
762
|
+
gi.require_version('Gio', '2.0')
|
|
763
|
+
from gi.repository import Gio, GLib
|
|
764
|
+
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
|
765
|
+
bus.call_sync('org.a11y.Bus', '/org/a11y/bus', 'org.freedesktop.DBus.Properties', 'Set',
|
|
766
|
+
GLib.Variant('(ssv)', ('org.a11y.Status', 'IsEnabled', GLib.Variant('b', True))), None, Gio.DBusCallFlags.NONE, 5000, None)
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
# ---------------------------------------------------------------------------------------------------
|
|
770
|
+
# AT-SPI: reading and the guarded commands. Nothing here touches X directly; it goes through the backend.
|
|
771
|
+
# ---------------------------------------------------------------------------------------------------
|
|
772
|
+
class Driver:
|
|
773
|
+
def __init__(self, state, backend, target, wrapper_pid):
|
|
774
|
+
import gi
|
|
775
|
+
import warnings
|
|
776
|
+
warnings.simplefilter('ignore') # gi deprecation notes on stderr would read as driver output
|
|
777
|
+
gi.require_version('Atspi', '2.0')
|
|
778
|
+
from gi.repository import Atspi, GLib
|
|
779
|
+
self.Atspi, self.GLib = Atspi, GLib
|
|
780
|
+
Atspi.init()
|
|
781
|
+
Atspi.set_timeout(5000, 5000)
|
|
782
|
+
self.state, self.backend, self.target = state, backend, target
|
|
783
|
+
self.wrapper_pid = wrapper_pid
|
|
784
|
+
self.wrapper_start = proc_start_time(wrapper_pid) if wrapper_pid else None
|
|
785
|
+
self.interrupted = False
|
|
786
|
+
self.listener = None
|
|
787
|
+
|
|
788
|
+
# -- finding things ---------------------------------------------------------------------------
|
|
789
|
+
def app(self):
|
|
790
|
+
desktop = self.Atspi.get_desktop(0)
|
|
791
|
+
for i in range(desktop.get_child_count()):
|
|
792
|
+
child = desktop.get_child_at_index(i)
|
|
793
|
+
if child is not None and child.get_process_id() == self.target['pid']:
|
|
794
|
+
return child
|
|
795
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-atspi: this Chrome is not on the accessibility bus')
|
|
796
|
+
|
|
797
|
+
def _one_window(self):
|
|
798
|
+
windows = self.backend.windows_of(self.target['pid'])
|
|
799
|
+
if len(windows) > 1:
|
|
800
|
+
raise Refuse(EXIT_REFUSED, 'ERR multiple-windows: this Chrome has more than one window; close and relaunch')
|
|
801
|
+
if not windows:
|
|
802
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-target: the bound window is gone')
|
|
803
|
+
return windows[0]
|
|
804
|
+
|
|
805
|
+
def frame_and_document(self):
|
|
806
|
+
window = self._one_window()
|
|
807
|
+
geo = self.backend.geometry(window)
|
|
808
|
+
app = self.app()
|
|
809
|
+
chosen, documents = None, []
|
|
810
|
+
for i in range(app.get_child_count()):
|
|
811
|
+
frame = app.get_child_at_index(i)
|
|
812
|
+
if frame is None or frame.get_role() != self.Atspi.Role.FRAME:
|
|
813
|
+
continue
|
|
814
|
+
ext = frame.get_extents(self.Atspi.CoordType.SCREEN)
|
|
815
|
+
if (ext.width, ext.height) != (geo['w'], geo['h']):
|
|
816
|
+
continue
|
|
817
|
+
found = self._documents_in(frame)
|
|
818
|
+
if found:
|
|
819
|
+
chosen, documents = frame, found
|
|
820
|
+
break
|
|
821
|
+
if chosen is None:
|
|
822
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-active-document: no page document in the bound window; a browser dialog may be open, so try key Escape')
|
|
823
|
+
tabs = self.Atspi.Collection.get_matches(chosen, self._rule(roles=[self.Atspi.Role.PAGE_TAB]), self.Atspi.CollectionSortOrder.CANONICAL, 0, True)
|
|
824
|
+
showing = [d for d in documents if d.get_state_set().contains(self.Atspi.StateType.SHOWING)]
|
|
825
|
+
if len(tabs) > 1 or len(showing) > 1:
|
|
826
|
+
raise Refuse(EXIT_REFUSED, 'ERR multiple-tabs: this window has more than one tab; close and relaunch')
|
|
827
|
+
return chosen, (showing or documents)[0], window
|
|
828
|
+
|
|
829
|
+
def _documents_in(self, frame):
|
|
830
|
+
rule = self._rule(roles=[self.Atspi.Role.DOCUMENT_WEB])
|
|
831
|
+
found = []
|
|
832
|
+
for node in self.Atspi.Collection.get_matches(frame, rule, self.Atspi.CollectionSortOrder.CANONICAL, 0, True):
|
|
833
|
+
uri = self.uri(node)
|
|
834
|
+
if uri and self._top_document(node) and not is_browser_ui_document(uri):
|
|
835
|
+
found.append(node)
|
|
836
|
+
return found
|
|
837
|
+
|
|
838
|
+
def _top_document(self, document):
|
|
839
|
+
parent = document.get_parent()
|
|
840
|
+
for _ in range(200):
|
|
841
|
+
if parent is None:
|
|
842
|
+
return True
|
|
843
|
+
if parent.get_role() == self.Atspi.Role.DOCUMENT_WEB:
|
|
844
|
+
return False
|
|
845
|
+
parent = parent.get_parent()
|
|
846
|
+
return False
|
|
847
|
+
|
|
848
|
+
def _rule(self, roles=(), states=()):
|
|
849
|
+
Atspi = self.Atspi
|
|
850
|
+
return Atspi.MatchRule.new(Atspi.StateSet.new(list(states)), Atspi.CollectionMatchType.ALL, {}, Atspi.CollectionMatchType.ALL,
|
|
851
|
+
[int(r) for r in roles], Atspi.CollectionMatchType.ANY, [], Atspi.CollectionMatchType.ALL, False)
|
|
852
|
+
|
|
853
|
+
def uri(self, document):
|
|
854
|
+
try:
|
|
855
|
+
return (self.Atspi.Document.get_document_attributes(document) or {}).get('URI') or ''
|
|
856
|
+
except self.GLib.Error:
|
|
857
|
+
return ''
|
|
858
|
+
|
|
859
|
+
def same(self, a, b):
|
|
860
|
+
return a is not None and b is not None and getattr(a, 'path', 1) == getattr(b, 'path', 2)
|
|
861
|
+
|
|
862
|
+
def focused(self, frame, document):
|
|
863
|
+
"""Chrome keeps a page element's focused state while its own interface has real focus, so several
|
|
864
|
+
objects can answer at once. Browser interface wins; a document object itself is never the answer."""
|
|
865
|
+
nodes = self.Atspi.Collection.get_matches(frame, self._rule(states=[self.Atspi.StateType.FOCUSED]), self.Atspi.CollectionSortOrder.CANONICAL, 0, True)
|
|
866
|
+
nodes = [n for n in nodes if n.get_role() != self.Atspi.Role.DOCUMENT_WEB]
|
|
867
|
+
outside = [n for n in nodes if not self.inside(n, document)]
|
|
868
|
+
if outside:
|
|
869
|
+
return outside[0]
|
|
870
|
+
return nodes[-1] if nodes else None
|
|
871
|
+
|
|
872
|
+
def owning_document(self, node):
|
|
873
|
+
"""The nearest document above this element: an iframe's own document, not the top page."""
|
|
874
|
+
current = node
|
|
875
|
+
for _ in range(500):
|
|
876
|
+
if current is None:
|
|
877
|
+
return None
|
|
878
|
+
if current.get_role() == self.Atspi.Role.DOCUMENT_WEB:
|
|
879
|
+
return current
|
|
880
|
+
current = current.get_parent()
|
|
881
|
+
return None
|
|
882
|
+
|
|
883
|
+
def inside(self, node, ancestor):
|
|
884
|
+
current = node
|
|
885
|
+
for _ in range(500):
|
|
886
|
+
if current is None:
|
|
887
|
+
return False
|
|
888
|
+
if self.same(current, ancestor):
|
|
889
|
+
return True
|
|
890
|
+
current = current.get_parent()
|
|
891
|
+
return False
|
|
892
|
+
|
|
893
|
+
def in_browser_dialog(self, node):
|
|
894
|
+
roles = (self.Atspi.Role.DIALOG, self.Atspi.Role.ALERT, self.Atspi.Role.NOTIFICATION)
|
|
895
|
+
current = node
|
|
896
|
+
for _ in range(500):
|
|
897
|
+
if current is None or current.get_role() == self.Atspi.Role.DOCUMENT_WEB:
|
|
898
|
+
return False
|
|
899
|
+
if current.get_role() in roles:
|
|
900
|
+
return True
|
|
901
|
+
current = current.get_parent()
|
|
902
|
+
return False
|
|
903
|
+
|
|
904
|
+
def extents(self, node):
|
|
905
|
+
ext = node.get_extents(self.Atspi.CoordType.SCREEN)
|
|
906
|
+
return (ext.x, ext.y, ext.width, ext.height)
|
|
907
|
+
|
|
908
|
+
def char_count(self, node):
|
|
909
|
+
try:
|
|
910
|
+
return self.Atspi.Text.get_character_count(node)
|
|
911
|
+
except (self.GLib.Error, TypeError):
|
|
912
|
+
return None
|
|
913
|
+
|
|
914
|
+
# -- events -----------------------------------------------------------------------------------
|
|
915
|
+
def listen(self, pinned, on_event):
|
|
916
|
+
"""Only events about the pinned element or its own document chain stop typing: an advert
|
|
917
|
+
loading in some other iframe must not."""
|
|
918
|
+
def handle(event):
|
|
919
|
+
source = event.source
|
|
920
|
+
if self.same(source, pinned) or self.inside(pinned, source):
|
|
921
|
+
on_event(event.type)
|
|
922
|
+
self.listener = self.Atspi.EventListener.new(handle)
|
|
923
|
+
for name in ('document:load-complete', 'document:load-start', 'object:state-changed:busy', 'object:state-changed:focused'):
|
|
924
|
+
self.listener.register(name)
|
|
925
|
+
|
|
926
|
+
def pump(self):
|
|
927
|
+
context = self.GLib.MainContext.default()
|
|
928
|
+
while context.pending():
|
|
929
|
+
context.iteration(False)
|
|
930
|
+
|
|
931
|
+
# -- checks before every input ----------------------------------------------------------------
|
|
932
|
+
def forget_typed_if_page_changed(self):
|
|
933
|
+
typed = self.target.get('typed')
|
|
934
|
+
if typed:
|
|
935
|
+
try:
|
|
936
|
+
current = self.uri(self.frame_and_document()[1])
|
|
937
|
+
except Refuse:
|
|
938
|
+
return
|
|
939
|
+
if current != typed.get('uri'):
|
|
940
|
+
self.target.pop('typed', None)
|
|
941
|
+
write_json(self.state.target_file(self.target['profile']), self.target)
|
|
942
|
+
|
|
943
|
+
def wrapper_alive(self):
|
|
944
|
+
if self.wrapper_pid and proc_start_time(self.wrapper_pid) != self.wrapper_start:
|
|
945
|
+
raise Refuse(EXIT_ERROR, 'ERR driver-crash: the wrapper is gone; input stopped')
|
|
946
|
+
|
|
947
|
+
def before_input(self, window):
|
|
948
|
+
self.wrapper_alive()
|
|
949
|
+
if self.backend.focused_window() != window:
|
|
950
|
+
raise Refuse(EXIT_REFUSED, 'refused: focus left the target mid-typing (stopped)')
|
|
951
|
+
|
|
952
|
+
def post_state(self, verdict, uri_before=None):
|
|
953
|
+
time.sleep(0.5)
|
|
954
|
+
frame, document, _ = self.frame_and_document()
|
|
955
|
+
uri = self.uri(document)
|
|
956
|
+
focus = self.focused(frame, document)
|
|
957
|
+
print('URI %s' % escape_page(redact_uri(uri)))
|
|
958
|
+
print('TITLE %s' % escape_page(document.get_name()))
|
|
959
|
+
print('FOCUS %s' % (('[password field]' if self.is_masked(focus) else escape_page('%s %s' % (focus.get_role_name(), focus.get_name()))) if focus else '(none)'))
|
|
960
|
+
print('URI-CHANGED %s' % ('yes' if uri_before is not None and uri != uri_before else 'no'))
|
|
961
|
+
print(verdict)
|
|
962
|
+
|
|
963
|
+
def wait_navigation(self, before):
|
|
964
|
+
deadline = time.time() + 15
|
|
965
|
+
while time.time() < deadline:
|
|
966
|
+
self.pump()
|
|
967
|
+
try:
|
|
968
|
+
if self.uri(self.frame_and_document()[1]) != before:
|
|
969
|
+
return True
|
|
970
|
+
except Refuse:
|
|
971
|
+
pass
|
|
972
|
+
time.sleep(0.25)
|
|
973
|
+
return False
|
|
974
|
+
|
|
975
|
+
# -- commands ---------------------------------------------------------------------------------
|
|
976
|
+
def cmd_url(self):
|
|
977
|
+
frame, document, _ = self.frame_and_document()
|
|
978
|
+
print(escape_page(redact_uri(self.uri(document))))
|
|
979
|
+
return EXIT_OK
|
|
980
|
+
|
|
981
|
+
def cmd_title(self):
|
|
982
|
+
print(escape_page(self.frame_and_document()[1].get_name()))
|
|
983
|
+
return EXIT_OK
|
|
984
|
+
|
|
985
|
+
def is_masked(self, node, document_uri=None):
|
|
986
|
+
"""One rule for every output path: a password box, or the box typesecret filled, even if a
|
|
987
|
+
'show password' toggle has since made it a plain entry."""
|
|
988
|
+
if node.get_role() == self.Atspi.Role.PASSWORD_TEXT:
|
|
989
|
+
return True
|
|
990
|
+
typed = self.target.get('typed') or {}
|
|
991
|
+
if not typed:
|
|
992
|
+
return False
|
|
993
|
+
# A page can replace the box when a toggle reveals it, so while the record holds, every
|
|
994
|
+
# editable field on this document is masked, not just the one recorded.
|
|
995
|
+
return getattr(node, 'path', None) == typed.get('path') or node.get_state_set().contains(self.Atspi.StateType.EDITABLE)
|
|
996
|
+
|
|
997
|
+
def cmd_text(self, outfile):
|
|
998
|
+
path = check_outfile(self.state.home, outfile)
|
|
999
|
+
sweep_outfiles(self.state.out)
|
|
1000
|
+
_, document, _ = self.frame_and_document()
|
|
1001
|
+
uri = self.uri(document)
|
|
1002
|
+
changed = []
|
|
1003
|
+
self.listener = self.Atspi.EventListener.new(lambda event: changed.append(event.type) if self.same(event.source, document) else None)
|
|
1004
|
+
self.listener.register('document:load-complete')
|
|
1005
|
+
counts = {'nodes': 0, 'bytes': 0, 'stop': None}
|
|
1006
|
+
deadline = time.time() + max(float(os.environ.get('XD_CMD_TIMEOUT', '60')) - 5, 1)
|
|
1007
|
+
fd, tmp = tempfile.mkstemp(dir=self.state.out)
|
|
1008
|
+
try:
|
|
1009
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as out:
|
|
1010
|
+
def emit(piece):
|
|
1011
|
+
counts['bytes'] += len(piece.encode('utf-8', 'replace'))
|
|
1012
|
+
out.write(piece)
|
|
1013
|
+
|
|
1014
|
+
def walk(node, depth):
|
|
1015
|
+
if counts['stop'] or depth > 400:
|
|
1016
|
+
return
|
|
1017
|
+
counts['nodes'] += 1
|
|
1018
|
+
if counts['nodes'] % 500 == 0:
|
|
1019
|
+
self.pump()
|
|
1020
|
+
if changed or self.uri(document) != uri:
|
|
1021
|
+
raise Refuse(EXIT_CHECK, 'ERR page-changed; read again')
|
|
1022
|
+
if counts['nodes'] >= TEXT_NODE_CAP:
|
|
1023
|
+
counts['stop'] = 'node limit'
|
|
1024
|
+
elif counts['bytes'] >= TEXT_BYTE_CAP:
|
|
1025
|
+
counts['stop'] = 'size limit'
|
|
1026
|
+
elif time.time() > deadline:
|
|
1027
|
+
counts['stop'] = 'time limit'
|
|
1028
|
+
if counts['stop']:
|
|
1029
|
+
return
|
|
1030
|
+
if self.is_masked(node):
|
|
1031
|
+
emit('[password field]\n')
|
|
1032
|
+
return
|
|
1033
|
+
text = None
|
|
1034
|
+
if node.get_text_iface() is not None:
|
|
1035
|
+
text = self.Atspi.Text.get_text(node, 0, -1)
|
|
1036
|
+
children = [node.get_child_at_index(i) for i in range(node.get_child_count())]
|
|
1037
|
+
if text is None:
|
|
1038
|
+
for child in children:
|
|
1039
|
+
if child is not None:
|
|
1040
|
+
walk(child, depth + 1)
|
|
1041
|
+
return
|
|
1042
|
+
pieces = text.split('')
|
|
1043
|
+
embedded = iter(c for c in children if c is not None)
|
|
1044
|
+
emit(pieces[0])
|
|
1045
|
+
for piece in pieces[1:]:
|
|
1046
|
+
child = next(embedded, None)
|
|
1047
|
+
if child is not None:
|
|
1048
|
+
walk(child, depth + 1)
|
|
1049
|
+
emit(piece)
|
|
1050
|
+
emit('\n')
|
|
1051
|
+
|
|
1052
|
+
walk(document, 0)
|
|
1053
|
+
if counts['stop']:
|
|
1054
|
+
os.replace(tmp, path)
|
|
1055
|
+
os.chmod(path, 0o600)
|
|
1056
|
+
print('TRUNCATED at %d nodes (%s); the rest of the document was not read' % (counts['nodes'], counts['stop']))
|
|
1057
|
+
return EXIT_CHECK
|
|
1058
|
+
os.replace(tmp, path)
|
|
1059
|
+
os.chmod(path, 0o600)
|
|
1060
|
+
finally:
|
|
1061
|
+
if os.path.exists(tmp):
|
|
1062
|
+
os.unlink(tmp)
|
|
1063
|
+
print('WROTE %s' % path)
|
|
1064
|
+
return EXIT_OK
|
|
1065
|
+
|
|
1066
|
+
def matches(self, document, name, role):
|
|
1067
|
+
rule = self._rule(states=[self.Atspi.StateType.SHOWING])
|
|
1068
|
+
nodes = self.Atspi.Collection.get_matches(document, rule, self.Atspi.CollectionSortOrder.CANONICAL, 0, True)
|
|
1069
|
+
wanted, role_l = name.lower(), (role or '').lower()
|
|
1070
|
+
hits, checked = [], 0
|
|
1071
|
+
candidates = [n for n in nodes if not role_l or n.get_role_name().lower() == role_l]
|
|
1072
|
+
for node in candidates[:FIND_CANDIDATE_CAP]:
|
|
1073
|
+
checked += 1
|
|
1074
|
+
label = node.get_name() or ''
|
|
1075
|
+
if wanted in label.lower():
|
|
1076
|
+
hits.append(node)
|
|
1077
|
+
return self.without_inner_text(hits), checked, len(candidates)
|
|
1078
|
+
|
|
1079
|
+
def without_inner_text(self, hits):
|
|
1080
|
+
"""A link's own text is a child with the same name and box: one thing on the page, not two."""
|
|
1081
|
+
kept = []
|
|
1082
|
+
for node in hits:
|
|
1083
|
+
parent = node.get_parent()
|
|
1084
|
+
duplicate = any(self.same(parent, other) and self.extents(other) == self.extents(node) for other in hits)
|
|
1085
|
+
if not duplicate:
|
|
1086
|
+
kept.append(node)
|
|
1087
|
+
return kept
|
|
1088
|
+
|
|
1089
|
+
def describe(self, index, node):
|
|
1090
|
+
rect = self.extents(node)
|
|
1091
|
+
label = '[password field]' if self.is_masked(node) else (node.get_name() or '')
|
|
1092
|
+
visible = ''
|
|
1093
|
+
if not self.is_masked(node) and node.get_text_iface() is not None:
|
|
1094
|
+
visible = (self.Atspi.Text.get_text(node, 0, 200) or '').replace('', '').strip()
|
|
1095
|
+
mark = ' name≠text %s' % escape_page(visible) if visible and visible != label else ''
|
|
1096
|
+
return '%d %s %s centre %d,%d rect %d,%d,%d,%d%s' % (index, escape_page(node.get_role_name()), escape_page(label), rect[0] + rect[2] // 2, rect[1] + rect[3] // 2, rect[0], rect[1], rect[2], rect[3], mark)
|
|
1097
|
+
|
|
1098
|
+
def cmd_find(self, name, role=None):
|
|
1099
|
+
_, document, _ = self.frame_and_document()
|
|
1100
|
+
hits, checked, total = self.matches(document, name, role)
|
|
1101
|
+
for i, node in enumerate(hits, 1):
|
|
1102
|
+
print(self.describe(i, node))
|
|
1103
|
+
if checked < total:
|
|
1104
|
+
print('INCOMPLETE: %d of %d candidates checked; add a role' % (checked, total))
|
|
1105
|
+
return EXIT_CHECK
|
|
1106
|
+
return EXIT_OK if hits else EXIT_REFUSED
|
|
1107
|
+
|
|
1108
|
+
def hit_chain(self, document, point):
|
|
1109
|
+
node = self.Atspi.Component.get_accessible_at_point(document, point[0], point[1], self.Atspi.CoordType.SCREEN)
|
|
1110
|
+
chain = []
|
|
1111
|
+
for _ in range(100):
|
|
1112
|
+
if node is None:
|
|
1113
|
+
break
|
|
1114
|
+
chain.append(node)
|
|
1115
|
+
node = self.Atspi.Component.get_accessible_at_point(node, point[0], point[1], self.Atspi.CoordType.SCREEN)
|
|
1116
|
+
if node is not None and chain and self.same(node, chain[-1]):
|
|
1117
|
+
break
|
|
1118
|
+
return chain
|
|
1119
|
+
|
|
1120
|
+
def cmd_click(self, name, role=None, index=None):
|
|
1121
|
+
frame, document, window = self.frame_and_document()
|
|
1122
|
+
uri_before = self.uri(document)
|
|
1123
|
+
for attempt in (1, 2):
|
|
1124
|
+
hits, checked, total = self.matches(document, name, role)
|
|
1125
|
+
if checked < total:
|
|
1126
|
+
raise Refuse(EXIT_REFUSED, 'ERR incomplete-search: add a role')
|
|
1127
|
+
if not hits:
|
|
1128
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-match')
|
|
1129
|
+
if len(hits) > 1 and index is None:
|
|
1130
|
+
for i, node in enumerate(hits, 1):
|
|
1131
|
+
print(self.describe(i, node))
|
|
1132
|
+
raise Refuse(EXIT_REFUSED, 'ERR ambiguous-match: give an index')
|
|
1133
|
+
pick = int(index) - 1 if index is not None else 0
|
|
1134
|
+
if pick < 0 or pick >= len(hits):
|
|
1135
|
+
raise Refuse(EXIT_ARG, 'ERR bad-argument: no such index')
|
|
1136
|
+
target = hits[pick]
|
|
1137
|
+
point = self.backend.to_input_point(self.extents(target), window)
|
|
1138
|
+
geo = self.backend.geometry(window)
|
|
1139
|
+
if not (geo['x'] <= point[0] < geo['x'] + geo['w'] and geo['y'] <= point[1] < geo['y'] + geo['h']):
|
|
1140
|
+
raise Refuse(EXIT_REFUSED, 'ERR hit-test-mismatch: the element is outside the bound window')
|
|
1141
|
+
self.backend.focus_window(window)
|
|
1142
|
+
self.backend.move(point)
|
|
1143
|
+
time.sleep(0.15)
|
|
1144
|
+
chain = self.hit_chain(document, point)
|
|
1145
|
+
under, at = self.backend.pointer_window()
|
|
1146
|
+
good = any(self.same(node, target) or self.inside(node, target) for node in chain) and under == window and at == point
|
|
1147
|
+
if good:
|
|
1148
|
+
self.before_input(window)
|
|
1149
|
+
self.backend.button(1, True)
|
|
1150
|
+
self.backend.button(1, False)
|
|
1151
|
+
return self.finish_input(uri_before)
|
|
1152
|
+
if any(self.in_browser_dialog(node) for node in chain):
|
|
1153
|
+
raise Refuse(EXIT_REFUSED, 'ERR browser-dialog-operator-only')
|
|
1154
|
+
raise Refuse(EXIT_REFUSED, 'ERR hit-test-mismatch: something else is under that point; nothing was clicked')
|
|
1155
|
+
|
|
1156
|
+
def finish_input(self, uri_before):
|
|
1157
|
+
if os.environ.get('XD_EXPECT') == 'nav':
|
|
1158
|
+
moved = self.wait_navigation(uri_before)
|
|
1159
|
+
self.post_state('NAVIGATED' if moved else 'NO-NAVIGATION', uri_before)
|
|
1160
|
+
return EXIT_OK if moved else EXIT_CHECK
|
|
1161
|
+
self.post_state('DELIVERED', uri_before)
|
|
1162
|
+
return EXIT_OK
|
|
1163
|
+
|
|
1164
|
+
def pin_entry(self, frame, document):
|
|
1165
|
+
focus = self.focused(frame, document)
|
|
1166
|
+
if focus is None or not self.inside(focus, document):
|
|
1167
|
+
raise Refuse(EXIT_REFUSED, 'ERR browser-dialog-operator-only: focus is not inside the page')
|
|
1168
|
+
return focus
|
|
1169
|
+
|
|
1170
|
+
def type_guarded(self, chars, window, pinned, per_key=None):
|
|
1171
|
+
stopped = []
|
|
1172
|
+
self.listen(pinned, lambda kind: stopped.append(kind))
|
|
1173
|
+
for ch in chars:
|
|
1174
|
+
self.pump()
|
|
1175
|
+
self.before_input(window)
|
|
1176
|
+
state = pinned.get_state_set()
|
|
1177
|
+
if stopped or not state.contains(self.Atspi.StateType.FOCUSED):
|
|
1178
|
+
raise Stopped()
|
|
1179
|
+
if per_key:
|
|
1180
|
+
per_key()
|
|
1181
|
+
self.backend.type_char(ch)
|
|
1182
|
+
|
|
1183
|
+
def cmd_type(self):
|
|
1184
|
+
text = sys.stdin.read()
|
|
1185
|
+
if text.endswith('\n'):
|
|
1186
|
+
text = text[:-1]
|
|
1187
|
+
if not text:
|
|
1188
|
+
raise Refuse(EXIT_REFUSED, 'ERR bad-argument: nothing on stdin')
|
|
1189
|
+
require_typable(text)
|
|
1190
|
+
require_fits_deadline(len(text), float(os.environ.get('XD_CMD_TIMEOUT', '60')))
|
|
1191
|
+
frame, document, window = self.frame_and_document()
|
|
1192
|
+
uri_before = self.uri(document)
|
|
1193
|
+
self.backend.focus_window(window)
|
|
1194
|
+
self.backend.reset_modifiers()
|
|
1195
|
+
pinned = self.pin_entry(frame, document)
|
|
1196
|
+
if pinned.get_role() == self.Atspi.Role.PASSWORD_TEXT:
|
|
1197
|
+
raise Refuse(EXIT_REFUSED, 'ERR secret-field-use-typesecret')
|
|
1198
|
+
if not pinned.get_state_set().contains(self.Atspi.StateType.EDITABLE):
|
|
1199
|
+
raise Refuse(EXIT_REFUSED, 'ERR not-an-editable-field')
|
|
1200
|
+
self.type_guarded(text, window, pinned)
|
|
1201
|
+
return self.finish_input(uri_before)
|
|
1202
|
+
|
|
1203
|
+
def secret_destination_ok(self, pinned, expected_host):
|
|
1204
|
+
owner = self.owning_document(pinned)
|
|
1205
|
+
if owner is None:
|
|
1206
|
+
raise Refuse(EXIT_REFUSED, 'ERR host-mismatch: the box has no readable document; nothing was typed')
|
|
1207
|
+
check_secret_destination(self.uri(owner), expected_host)
|
|
1208
|
+
|
|
1209
|
+
def cmd_typesecret(self, expected_host):
|
|
1210
|
+
check_secret_destination('https://%s/' % (expected_host or '').strip().lower().rstrip('.'), expected_host)
|
|
1211
|
+
secret = read_secret(sys.stdin.buffer)
|
|
1212
|
+
try:
|
|
1213
|
+
try:
|
|
1214
|
+
text = secret.decode('ascii')
|
|
1215
|
+
except UnicodeDecodeError:
|
|
1216
|
+
raise Refuse(EXIT_REFUSED, 'ERR untypable-character: the text holds a character the private display\'s US layout cannot type; nothing was typed')
|
|
1217
|
+
require_typable(text)
|
|
1218
|
+
require_fits_deadline(len(text), float(os.environ.get('XD_CMD_TIMEOUT', '60')))
|
|
1219
|
+
frame, document, window = self.frame_and_document()
|
|
1220
|
+
self.backend.focus_window(window)
|
|
1221
|
+
self.backend.reset_modifiers()
|
|
1222
|
+
pinned = self.pin_entry(frame, document)
|
|
1223
|
+
if pinned.get_role() != self.Atspi.Role.PASSWORD_TEXT:
|
|
1224
|
+
raise Refuse(EXIT_REFUSED, 'ERR not-a-password-field')
|
|
1225
|
+
self.secret_destination_ok(pinned, expected_host)
|
|
1226
|
+
# Recorded before the first key, so a stop partway still leaves the box masked.
|
|
1227
|
+
self.target['typed'] = {'path': getattr(pinned, 'path', None), 'uri': self.uri(document)}
|
|
1228
|
+
write_json(self.state.target_file(self.target['profile']), self.target)
|
|
1229
|
+
self.before_input(window)
|
|
1230
|
+
self.backend.tap('a', ctrl=True)
|
|
1231
|
+
self.backend.tap('Delete')
|
|
1232
|
+
for _ in range(20):
|
|
1233
|
+
if self.char_count(pinned) == 0:
|
|
1234
|
+
break
|
|
1235
|
+
time.sleep(0.05)
|
|
1236
|
+
else:
|
|
1237
|
+
raise Refuse(EXIT_REFUSED, 'ERR field-not-empty: the box could not be cleared; nothing was typed')
|
|
1238
|
+
self.type_guarded(text, window, pinned, per_key=lambda: self.secret_destination_ok(pinned, expected_host))
|
|
1239
|
+
time.sleep(0.2)
|
|
1240
|
+
self.pump()
|
|
1241
|
+
self.secret_destination_ok(pinned, expected_host)
|
|
1242
|
+
if self.char_count(pinned) != len(text) or not pinned.get_state_set().contains(self.Atspi.StateType.FOCUSED):
|
|
1243
|
+
raise Stopped('refused: the value did not arrive in full')
|
|
1244
|
+
print('DELIVERED')
|
|
1245
|
+
return EXIT_OK
|
|
1246
|
+
finally:
|
|
1247
|
+
wipe(secret)
|
|
1248
|
+
text = None
|
|
1249
|
+
|
|
1250
|
+
def cmd_key(self, name):
|
|
1251
|
+
if name not in NAMED_KEYS:
|
|
1252
|
+
raise Refuse(EXIT_ARG, 'ERR bad-argument: that key is not on the list')
|
|
1253
|
+
if name == 'Escape':
|
|
1254
|
+
# Can only cancel, so it is allowed with a pop-up open or several windows showing.
|
|
1255
|
+
windows = self.backend.windows_of(self.target['pid'])
|
|
1256
|
+
if not windows:
|
|
1257
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-target: the bound window is gone')
|
|
1258
|
+
self.backend.focus_window(windows[-1])
|
|
1259
|
+
self.wrapper_alive()
|
|
1260
|
+
self.backend.tap('Escape')
|
|
1261
|
+
print('DELIVERED')
|
|
1262
|
+
return EXIT_OK
|
|
1263
|
+
frame, document, window = self.frame_and_document()
|
|
1264
|
+
uri_before = self.uri(document)
|
|
1265
|
+
self.backend.focus_window(window)
|
|
1266
|
+
focus = self.focused(frame, document)
|
|
1267
|
+
if focus is None or not self.inside(focus, document):
|
|
1268
|
+
raise Refuse(EXIT_REFUSED, 'ERR browser-dialog-operator-only')
|
|
1269
|
+
self.before_input(window)
|
|
1270
|
+
self.backend.tap(name)
|
|
1271
|
+
return self.finish_input(uri_before)
|
|
1272
|
+
|
|
1273
|
+
def cmd_nav(self, url):
|
|
1274
|
+
check_url(url)
|
|
1275
|
+
require_typable(url)
|
|
1276
|
+
frame, document, window = self.frame_and_document()
|
|
1277
|
+
before = self.uri(document)
|
|
1278
|
+
self.backend.focus_window(window)
|
|
1279
|
+
self.backend.reset_modifiers()
|
|
1280
|
+
self.before_input(window)
|
|
1281
|
+
self.backend.tap('l', ctrl=True)
|
|
1282
|
+
time.sleep(0.15)
|
|
1283
|
+
omnibox = self.focused(frame, document)
|
|
1284
|
+
if omnibox is None or self.inside(omnibox, document) or omnibox.get_role() not in (self.Atspi.Role.ENTRY, self.Atspi.Role.TEXT):
|
|
1285
|
+
raise Refuse(EXIT_REFUSED, 'ERR browser-dialog-operator-only: the address bar did not take focus; nothing was typed')
|
|
1286
|
+
self.type_guarded(url, window, omnibox)
|
|
1287
|
+
self.backend.tap('Delete')
|
|
1288
|
+
self.backend.tap('Return')
|
|
1289
|
+
loaded = []
|
|
1290
|
+
self.listener = self.Atspi.EventListener.new(lambda event: loaded.append(event.type))
|
|
1291
|
+
self.listener.register('document:load-complete')
|
|
1292
|
+
deadline = time.time() + 15
|
|
1293
|
+
while time.time() < deadline and not loaded:
|
|
1294
|
+
self.pump()
|
|
1295
|
+
time.sleep(0.1)
|
|
1296
|
+
final = self.uri(self.frame_and_document()[1])
|
|
1297
|
+
print('REQUESTED %s' % redact_uri(url))
|
|
1298
|
+
print('FINAL %s' % escape_page(redact_uri(final)))
|
|
1299
|
+
if not loaded and final == before:
|
|
1300
|
+
print('NAV-TIMEOUT')
|
|
1301
|
+
return EXIT_CHECK
|
|
1302
|
+
if not loaded:
|
|
1303
|
+
print('SAME-DOCUMENT')
|
|
1304
|
+
if uri_host(final) != uri_host(url):
|
|
1305
|
+
print('nav-landed-elsewhere')
|
|
1306
|
+
return EXIT_CHECK
|
|
1307
|
+
return EXIT_OK
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
class Stopped(Exception):
|
|
1311
|
+
"""Typing stopped partway: some keys may have arrived, so the latch stays and nothing is echoed."""
|
|
1312
|
+
|
|
1313
|
+
def __init__(self, message='refused: focus left the target mid-typing (stopped)'):
|
|
1314
|
+
super().__init__(message)
|
|
1315
|
+
self.message = message
|
|
1316
|
+
|
|
1317
|
+
|
|
1318
|
+
# ---------------------------------------------------------------------------------------------------
|
|
1319
|
+
# Binding, launch, close, and the entry point.
|
|
1320
|
+
# ---------------------------------------------------------------------------------------------------
|
|
1321
|
+
def chrome_binary():
|
|
1322
|
+
"""The binary itself, never Google's wrapper script, so the spawned pid is the browser process."""
|
|
1323
|
+
binary = '/opt/google/chrome/chrome'
|
|
1324
|
+
if not os.access(binary, os.X_OK):
|
|
1325
|
+
raise Refuse(EXIT_REFUSED, 'ERR missing-dependency: google-chrome')
|
|
1326
|
+
return binary
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
def is_browser_cmdline(raw, profile_dir):
|
|
1330
|
+
"""Chrome rewrites its process title, so /proc/<pid>/cmdline may be one space-joined string, not
|
|
1331
|
+
NUL-separated arguments. Both forms: that exact --user-data-dir, and no --type= argument."""
|
|
1332
|
+
wanted = re.escape(('--user-data-dir=%s' % profile_dir).encode())
|
|
1333
|
+
return re.search(b'(^|[\\0 ])' + wanted + b'($|[\\0 ])', raw) is not None and re.search(b'(^|[\\0 ])--type=', raw) is None
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
def browser_pids(profile_dir):
|
|
1337
|
+
"""Browser processes on this profile."""
|
|
1338
|
+
found = []
|
|
1339
|
+
for entry in os.listdir('/proc'):
|
|
1340
|
+
if not entry.isdigit():
|
|
1341
|
+
continue
|
|
1342
|
+
try:
|
|
1343
|
+
with open('/proc/%s/cmdline' % entry, 'rb') as handle:
|
|
1344
|
+
raw = handle.read()
|
|
1345
|
+
except OSError:
|
|
1346
|
+
continue
|
|
1347
|
+
if is_browser_cmdline(raw, profile_dir):
|
|
1348
|
+
found.append(int(entry))
|
|
1349
|
+
return found
|
|
1350
|
+
|
|
1351
|
+
|
|
1352
|
+
def seed_profile_prefs(profile_dir):
|
|
1353
|
+
"""Chrome is not running here. No save-password bubble, and nothing stored by Chrome."""
|
|
1354
|
+
path = os.path.join(profile_dir, 'Default', 'Preferences')
|
|
1355
|
+
os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
|
|
1356
|
+
prefs = read_json(path) or {}
|
|
1357
|
+
prefs['credentials_enable_service'] = False
|
|
1358
|
+
prefs.setdefault('profile', {})['password_manager_enabled'] = False
|
|
1359
|
+
write_json(path, prefs)
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
def load_binding(state, profile_id):
|
|
1363
|
+
if not profile_id or not PROFILE_ID.match(profile_id):
|
|
1364
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-target: set XD_PROFILE to a launched profile')
|
|
1365
|
+
target = read_json(state.target_file(profile_id))
|
|
1366
|
+
if not target or proc_start_time(target['pid']) != target['start'] or target['pid'] not in browser_pids(target['dir']):
|
|
1367
|
+
latch = os.environ.get('XD_LATCH_FILE')
|
|
1368
|
+
if latch and os.path.exists(latch):
|
|
1369
|
+
os.unlink(latch)
|
|
1370
|
+
print('latch cleared: bound Chrome gone')
|
|
1371
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-target: no live Chrome is bound to that profile')
|
|
1372
|
+
return target
|
|
1373
|
+
|
|
1374
|
+
|
|
1375
|
+
def cmd_launch(state, args):
|
|
1376
|
+
new = '--new' in args
|
|
1377
|
+
args = [a for a in args if a != '--new']
|
|
1378
|
+
if len(args) != 2:
|
|
1379
|
+
raise Refuse(EXIT_ARG, 'ERR bad-argument: launch <profileId> <url> [--new]')
|
|
1380
|
+
profile_id, url = args
|
|
1381
|
+
check_url(url)
|
|
1382
|
+
extra = check_extra_flags(os.environ.get('XD_CHROME_FLAGS'))
|
|
1383
|
+
profile_dir = resolve_profile(state.home, profile_id, must_exist=not new)
|
|
1384
|
+
if new:
|
|
1385
|
+
if os.path.exists(profile_dir):
|
|
1386
|
+
raise Refuse(EXIT_REFUSED, 'ERR profile-exists: that profile is already there; drop --new')
|
|
1387
|
+
os.makedirs(profile_dir, mode=0o700)
|
|
1388
|
+
elif stat.S_IMODE(os.stat(profile_dir).st_mode) & 0o077:
|
|
1389
|
+
raise Refuse(EXIT_REFUSED, 'ERR profile-permissions: the profile folder must be 0700')
|
|
1390
|
+
binary = chrome_binary()
|
|
1391
|
+
existing = read_json(state.target_file(profile_id))
|
|
1392
|
+
running = browser_pids(profile_dir)
|
|
1393
|
+
if existing and existing.get('pid') in running and proc_start_time(existing['pid']) == existing.get('start'):
|
|
1394
|
+
print('ALREADY-RUNNING')
|
|
1395
|
+
return EXIT_OK
|
|
1396
|
+
if running:
|
|
1397
|
+
raise Refuse(EXIT_REFUSED, 'ERR profile-in-use: another Chrome has this profile; it is never driven or closed from here')
|
|
1398
|
+
seed_profile_prefs(profile_dir)
|
|
1399
|
+
record = check_stack(state) or start_stack(state)
|
|
1400
|
+
env = _display_env(state, record)
|
|
1401
|
+
os.environ.update(env)
|
|
1402
|
+
chrome_env = minimal_env(dict(env, ACCESSIBILITY_ENABLED='1'))
|
|
1403
|
+
chrome_env.update({k: v for k, v in os.environ.items() if k.startswith('LC_')})
|
|
1404
|
+
# /opt/google/chrome/chrome is the browser process itself, so it is bound the moment it exists:
|
|
1405
|
+
# a wrapper killed from here on leaves a Chrome that close can still find.
|
|
1406
|
+
proc = spawn(chrome_args(binary, profile_dir, url, extra), chrome_env)
|
|
1407
|
+
pid = proc.pid
|
|
1408
|
+
target = {'profile': profile_id, 'dir': profile_dir, 'pid': pid, 'start': proc_start_time(pid)}
|
|
1409
|
+
write_json(state.target_file(profile_id), target)
|
|
1410
|
+
backend = X11Backend()
|
|
1411
|
+
deadline = time.time() + 15
|
|
1412
|
+
window = None
|
|
1413
|
+
while time.time() < deadline and not window and proc.poll() is None:
|
|
1414
|
+
windows = backend.windows_of(pid)
|
|
1415
|
+
window = windows[0] if windows else None
|
|
1416
|
+
time.sleep(0.1)
|
|
1417
|
+
if not window:
|
|
1418
|
+
signal_recorded([{'pid': pid, 'start': target['start']}], proc_start_time, os.kill)
|
|
1419
|
+
after_close(state, profile_id)
|
|
1420
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-atspi: Chrome started no window, so it was stopped')
|
|
1421
|
+
target['window'] = window
|
|
1422
|
+
write_json(state.target_file(profile_id), target)
|
|
1423
|
+
driver = Driver(state, backend, target, None)
|
|
1424
|
+
deadline = time.time() + 10
|
|
1425
|
+
while True:
|
|
1426
|
+
try:
|
|
1427
|
+
driver.app()
|
|
1428
|
+
break
|
|
1429
|
+
except Refuse:
|
|
1430
|
+
if time.time() > deadline:
|
|
1431
|
+
signal_recorded([{'pid': pid, 'start': target['start']}], proc_start_time, os.kill)
|
|
1432
|
+
after_close(state, profile_id)
|
|
1433
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-atspi: Chrome did not reach the accessibility bus, so it was stopped')
|
|
1434
|
+
time.sleep(0.1)
|
|
1435
|
+
ledger(state, 'launch', profile_dir)
|
|
1436
|
+
print('LAUNCHED display :%d profile %s' % (record['display'], profile_id))
|
|
1437
|
+
print('linger: %s' % linger_state())
|
|
1438
|
+
print('note: this profile\'s cookies are protected by file permissions only')
|
|
1439
|
+
return EXIT_OK
|
|
1440
|
+
|
|
1441
|
+
|
|
1442
|
+
def linger_state():
|
|
1443
|
+
try:
|
|
1444
|
+
out = subprocess.run(['loginctl', 'show-user', str(os.getuid()), '--property=Linger'], capture_output=True, text=True, timeout=5).stdout
|
|
1445
|
+
except (OSError, subprocess.SubprocessError):
|
|
1446
|
+
return 'unknown'
|
|
1447
|
+
return {'Linger=yes': 'yes', 'Linger=no': 'no'}.get(out.strip(), 'unknown')
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
def ledger(state, action, profile_dir):
|
|
1451
|
+
"""The browser ledger is a record: a failure here never stops the caller."""
|
|
1452
|
+
script = os.path.join(state.home, '.instar', 'scripts', 'browser', 'chrome-ledger.sh')
|
|
1453
|
+
try:
|
|
1454
|
+
subprocess.run([script, action, profile_dir, 'xdrive'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
|
|
1455
|
+
except (OSError, subprocess.SubprocessError):
|
|
1456
|
+
pass
|
|
1457
|
+
|
|
1458
|
+
|
|
1459
|
+
def note_first_success(state, target, command):
|
|
1460
|
+
"""A DELIVERED input followed by a clean read on the same binding, once per agent."""
|
|
1461
|
+
path = os.path.join(state.home, '.instar', 'logs', 'normal-chrome-browser-first-success.json')
|
|
1462
|
+
if command in INPUT_COMMANDS:
|
|
1463
|
+
target['delivered'] = True
|
|
1464
|
+
write_json(state.target_file(target['profile']), target)
|
|
1465
|
+
elif command in READ_COMMANDS and target.get('delivered') and not os.path.exists(path):
|
|
1466
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
1467
|
+
write_json(path, {'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'label': 'delivered + read', 'via': 'xdrive'})
|
|
1468
|
+
|
|
1469
|
+
|
|
1470
|
+
def after_close(state, profile_id):
|
|
1471
|
+
path = state.target_file(profile_id)
|
|
1472
|
+
target = read_json(path)
|
|
1473
|
+
if target:
|
|
1474
|
+
ledger(state, 'complete', target['dir'])
|
|
1475
|
+
if os.path.exists(path):
|
|
1476
|
+
os.unlink(path)
|
|
1477
|
+
if not bound_targets(state):
|
|
1478
|
+
stop_stack(state, read_json(state.record))
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
def cmd_close(state, target, force):
|
|
1482
|
+
pid, start = target['pid'], target['start']
|
|
1483
|
+
if force:
|
|
1484
|
+
signal_recorded([{'pid': pid, 'start': start}], proc_start_time, os.kill)
|
|
1485
|
+
after_close(state, target['profile'])
|
|
1486
|
+
print('CLOSED (forced): unsaved input in that window is gone')
|
|
1487
|
+
return EXIT_OK
|
|
1488
|
+
backend = X11Backend()
|
|
1489
|
+
windows = backend.windows_of(pid)
|
|
1490
|
+
if windows:
|
|
1491
|
+
backend.focus_window(windows[0])
|
|
1492
|
+
backend.tap('w', shift=True, ctrl=True)
|
|
1493
|
+
deadline = time.time() + 10
|
|
1494
|
+
while time.time() < deadline and proc_start_time(pid) == start:
|
|
1495
|
+
time.sleep(0.1)
|
|
1496
|
+
if proc_start_time(pid) == start:
|
|
1497
|
+
raise Refuse(EXIT_REFUSED, 'ERR close-blocked: a window is still open (a dialog, unsaved input or a download); nothing was killed; close --force ends it')
|
|
1498
|
+
after_close(state, target['profile'])
|
|
1499
|
+
print('CLOSED')
|
|
1500
|
+
return EXIT_OK
|
|
1501
|
+
|
|
1502
|
+
|
|
1503
|
+
READ_COMMANDS = ('url', 'title', 'text', 'find')
|
|
1504
|
+
INPUT_COMMANDS = ('click', 'type', 'typesecret', 'key', 'nav')
|
|
1505
|
+
|
|
1506
|
+
|
|
1507
|
+
def dispatch(driver, command, args):
|
|
1508
|
+
if command == 'url':
|
|
1509
|
+
return driver.cmd_url()
|
|
1510
|
+
if command == 'title':
|
|
1511
|
+
return driver.cmd_title()
|
|
1512
|
+
if command == 'text' and len(args) == 1:
|
|
1513
|
+
return driver.cmd_text(args[0])
|
|
1514
|
+
if command == 'find' and 1 <= len(args) <= 2:
|
|
1515
|
+
return driver.cmd_find(*args)
|
|
1516
|
+
if command == 'click' and 1 <= len(args) <= 3:
|
|
1517
|
+
return driver.cmd_click(*args)
|
|
1518
|
+
if command == 'type' and not args:
|
|
1519
|
+
return driver.cmd_type()
|
|
1520
|
+
if command == 'typesecret' and len(args) == 1:
|
|
1521
|
+
return driver.cmd_typesecret(args[0])
|
|
1522
|
+
if command == 'key' and len(args) == 1:
|
|
1523
|
+
return driver.cmd_key(args[0])
|
|
1524
|
+
if command == 'nav' and len(args) == 1:
|
|
1525
|
+
return driver.cmd_nav(args[0])
|
|
1526
|
+
raise Refuse(EXIT_ARG, 'ERR bad-argument: unknown command or wrong arguments')
|
|
1527
|
+
|
|
1528
|
+
|
|
1529
|
+
def run(argv):
|
|
1530
|
+
home = os.environ.get('XD_HOME')
|
|
1531
|
+
if not home or not argv:
|
|
1532
|
+
raise Refuse(EXIT_ARG, 'ERR bad-argument: run this through xdrive.sh')
|
|
1533
|
+
state = State(home)
|
|
1534
|
+
command, args = argv[0], argv[1:]
|
|
1535
|
+
if command == 'launch':
|
|
1536
|
+
return cmd_launch(state, args)
|
|
1537
|
+
profile_id = os.environ.get('XD_PROFILE', '')
|
|
1538
|
+
if command == 'close':
|
|
1539
|
+
# Close needs the binding and, unless forced, the X server. It never needs the accessibility
|
|
1540
|
+
# side, so it still works on an unhealthy stack and with several windows or tabs.
|
|
1541
|
+
record = read_json(state.record)
|
|
1542
|
+
if record:
|
|
1543
|
+
os.environ.update(_display_env(state, record))
|
|
1544
|
+
return cmd_close(state, load_binding(state, profile_id), '--force' in args)
|
|
1545
|
+
record = check_stack(state)
|
|
1546
|
+
if record is None:
|
|
1547
|
+
raise Refuse(EXIT_REFUSED, 'ERR no-target: no agent display is running; use launch')
|
|
1548
|
+
os.environ.update(_display_env(state, record))
|
|
1549
|
+
target = load_binding(state, profile_id)
|
|
1550
|
+
backend = X11Backend()
|
|
1551
|
+
if os.environ.get('XD_LATCH_SET') == '1':
|
|
1552
|
+
backend.release_everything()
|
|
1553
|
+
driver = Driver(state, backend, target, int(os.environ.get('XD_WRAPPER_PID', '0')))
|
|
1554
|
+
driver.forget_typed_if_page_changed()
|
|
1555
|
+
try:
|
|
1556
|
+
code = dispatch(driver, command, args)
|
|
1557
|
+
if code == EXIT_OK:
|
|
1558
|
+
note_first_success(state, target, command)
|
|
1559
|
+
return code
|
|
1560
|
+
finally:
|
|
1561
|
+
backend.release_all()
|
|
1562
|
+
|
|
1563
|
+
|
|
1564
|
+
def mark_partial():
|
|
1565
|
+
"""Some input went out before this stop, so the wrapper must keep the latch."""
|
|
1566
|
+
partial = os.environ.get('XD_PARTIAL_FILE')
|
|
1567
|
+
if partial and INPUT_SENT[0]:
|
|
1568
|
+
with open(partial, 'w'):
|
|
1569
|
+
pass
|
|
1570
|
+
|
|
1571
|
+
|
|
1572
|
+
def main():
|
|
1573
|
+
# A crash must not write this process's memory, which can hold a password, to a core file.
|
|
1574
|
+
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
|
1575
|
+
signal.signal(signal.SIGTERM, lambda *_: sys.exit(EXIT_ERROR))
|
|
1576
|
+
try:
|
|
1577
|
+
return run(sys.argv[1:])
|
|
1578
|
+
except Refuse as refusal:
|
|
1579
|
+
mark_partial()
|
|
1580
|
+
print(refusal.message)
|
|
1581
|
+
return refusal.code
|
|
1582
|
+
except Stopped as stop:
|
|
1583
|
+
INPUT_SENT[0] = True
|
|
1584
|
+
mark_partial()
|
|
1585
|
+
print(stop.message)
|
|
1586
|
+
return EXIT_REFUSED
|
|
1587
|
+
except Exception as err:
|
|
1588
|
+
# The type only: a message could carry page text or a value.
|
|
1589
|
+
print('ERR driver-crash: %s; read the page before any more input' % type(err).__name__)
|
|
1590
|
+
return EXIT_ERROR
|
|
1591
|
+
|
|
1592
|
+
|
|
1593
|
+
if __name__ == '__main__':
|
|
1594
|
+
sys.exit(main())
|