lustro-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. lustro_cli/__init__.py +29 -0
  2. lustro_cli/cli.py +2460 -0
  3. lustro_cli/client.py +434 -0
  4. lustro_cli/discovery.py +1033 -0
  5. lustro_cli/exitcodes.py +25 -0
  6. lustro_cli/mcp.py +867 -0
  7. lustro_cli/wire/__init__.py +62 -0
  8. lustro_cli/wire/_schema.json +97 -0
  9. lustro_cli/wire/cursor-envelope.schema.json +28 -0
  10. lustro_cli/wire/error-envelope.schema.json +46 -0
  11. lustro_cli/wire/golden/cursor-delta.json +91 -0
  12. lustro_cli/wire/golden/cursor-reset.json +65 -0
  13. lustro_cli/wire/golden/cursor-unchanged.json +15 -0
  14. lustro_cli/wire/golden/error-envelope.json +7 -0
  15. lustro_cli/wire/golden/export-har-websocket.json +148 -0
  16. lustro_cli/wire/golden/export-har.json +359 -0
  17. lustro_cli/wire/golden/logs-delta.json +44 -0
  18. lustro_cli/wire/golden/logs-reset.json +73 -0
  19. lustro_cli/wire/golden/logs-unchanged.json +9 -0
  20. lustro_cli/wire/golden/meta.json +12 -0
  21. lustro_cli/wire/golden/prefs-delta.json +58 -0
  22. lustro_cli/wire/golden/prefs-files.json +64 -0
  23. lustro_cli/wire/golden/prefs-reset.json +58 -0
  24. lustro_cli/wire/golden/prefs-unchanged.json +4 -0
  25. lustro_cli/wire/golden/rules-list.json +44 -0
  26. lustro_cli/wire/golden/screen-tree-views.json +596 -0
  27. lustro_cli/wire/golden/screen-tree.json +689 -0
  28. lustro_cli/wire/golden/send-result.json +7 -0
  29. lustro_cli/wire/golden/senders-list.json +6 -0
  30. lustro_cli/wire/golden/sqlite-databases.json +37 -0
  31. lustro_cli/wire/golden/sqlite-exec.json +4 -0
  32. lustro_cli/wire/golden/sqlite-query.json +109 -0
  33. lustro_cli/wire/golden/sqlite-rows.json +109 -0
  34. lustro_cli/wire/golden/sqlite-schema.json +98 -0
  35. lustro_cli/wire/golden/sqlite-tables.json +57 -0
  36. lustro_cli/wire/golden/stream-delta.json +48 -0
  37. lustro_cli/wire/golden/stream-reset.json +66 -0
  38. lustro_cli/wire/golden/stream-unchanged.json +4 -0
  39. lustro_cli/wire/golden/transaction-image.json +43 -0
  40. lustro_cli/wire/golden/transaction.json +41 -0
  41. lustro_cli/wire/golden/websocket.json +37 -0
  42. lustro_cli/wire/golden/websockets-reset.json +89 -0
  43. lustro_cli/wire/golden/work-events.json +152 -0
  44. lustro_cli/wire/golden/work-item.json +118 -0
  45. lustro_cli/wire/golden/work-items.json +129 -0
  46. lustro_cli/wire/golden/work-metrics.json +40 -0
  47. lustro_cli/wire/logs.openapi.json +622 -0
  48. lustro_cli/wire/meta.schema.json +47 -0
  49. lustro_cli/wire/network.openapi.json +2458 -0
  50. lustro_cli/wire/pagination.schema.json +20 -0
  51. lustro_cli/wire/prefs.openapi.json +699 -0
  52. lustro_cli/wire/screen.openapi.json +512 -0
  53. lustro_cli/wire/sqlite.openapi.json +1233 -0
  54. lustro_cli/wire/stream-envelope.schema.json +33 -0
  55. lustro_cli/wire/sync.py +80 -0
  56. lustro_cli/wire/work.openapi.json +1188 -0
  57. lustro_cli-0.1.0.dist-info/METADATA +585 -0
  58. lustro_cli-0.1.0.dist-info/RECORD +60 -0
  59. lustro_cli-0.1.0.dist-info/WHEEL +4 -0
  60. lustro_cli-0.1.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,1033 @@
1
+ """Endpoint and token discovery for the Lustro CLI.
2
+
3
+ Resolution order (first that yields a value wins, per field):
4
+
5
+ 1. Explicit ``--token`` / ``--host`` / ``--port`` flags.
6
+ 2. ``LUSTRO_TOKEN`` environment variable (token only).
7
+ 3. With ``--package``, the app's private ``lustro_debug`` prefs, through ``adb
8
+ [-s <serial>] shell run-as <pkg> cat``. They hold the token, and the host and
9
+ port of the app's last bind: each process of the app writes its token, and
10
+ each bind its host and port. One adb call reads them, the app's uid, and
11
+ the listening sockets of the device (:func:`read_app`), where the dump of
12
+ the log in 4 grows with the amount of log on the device, and takes seconds
13
+ when its buffers are full. A build that is not debuggable fails ``run-as``,
14
+ and an app that has not written the prefs yet has none: step 4 then gives
15
+ what they did not.
16
+ 4. The ``LustroToken`` logcat ready-line: ``adb [-s <serial>] logcat -d -v
17
+ threadtime -s LustroToken`` parsed for the most recent
18
+ ``Lustro ready endpoint=http://<host>:<port> token=<token>``, with the
19
+ process ID of the line (without ``--package``, this is the first source for
20
+ host/port/token, including a fallback port). With ``--package``, only the
21
+ lines of that app's current process count: the lines with one of the process
22
+ IDs of ``pidof <pkg>``, which :func:`app_process_uids` reads with their uids.
23
+ Without it, the last line counts, whatever app logged it.
24
+ 5. (best effort, without ``--package``) the ``run-as`` read of step 3, of the
25
+ prefs of the app in the foreground, because Lustro listens only while its app
26
+ is in the foreground. This is what finds the app on a device that drops Info
27
+ logs (``log.tag`` set to ``E``, for example), which drops the ready line. It
28
+ also replaces a ready line whose app does not listen on the line's port, or
29
+ whose process has ended, when the app in the foreground listens on its port.
30
+
31
+ If none of these determine the endpoint/token, a clear, actionable error is
32
+ raised. :func:`diagnose` first looks for the cause, with the exit code of each:
33
+ no device, an app that is not installed, an installed build without the Lustro
34
+ runtime, or an app that is not running or not in the foreground. A token from
35
+ the ready line can be stale, when the app was installed again and the device
36
+ dropped the new line. A token from the prefs can be stale too: until a new
37
+ process of the app writes its token, they keep the one of its last process.
38
+ :func:`token_from_prefs` reads the current one, for a client to retry with
39
+ after a 401.
40
+
41
+ A token that steps 3 to 5 find goes only to a server of the app that owns it:
42
+ the app of the prefs, or the process that logged the line. Any app can log a
43
+ line with the tag, and bind the app's port while the app is in the background.
44
+ :func:`withheld` compares the uid that listens on the port of the device with
45
+ the owner's uid, and the endpoint's ``owner`` carries what it needs.
46
+
47
+ The port that these give is the app's port. On a device, the CLI reaches it
48
+ through an ``adb forward``, whose local port can differ: :func:`forwarded_ports`
49
+ finds it in ``adb forward --list``.
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import os
55
+ import re
56
+ import shlex
57
+ import struct
58
+ import subprocess
59
+ import time
60
+ from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Tuple
61
+
62
+ from . import exitcodes
63
+ from .client import GUARD_SECONDS, LustroError
64
+
65
+ # Matches the single machine-parseable line Lustro logs at tag LustroToken:
66
+ # Lustro ready endpoint=http://127.0.0.1:8080 token=AbC123...
67
+ # Tolerant of a logcat prefix (date/pid/tag) before the message.
68
+ _READY_LINE = re.compile(
69
+ r"Lustro\s+ready\s+endpoint=(?P<scheme>https?)://(?P<host>[^\s:/]+):(?P<port>\d+)\s+token=(?P<token>\S+)"
70
+ )
71
+
72
+ # One ``adb forward --list`` line: ``<serial> tcp:<local port> tcp:<device port>``.
73
+ _FORWARD_LINE = re.compile(r"^(?P<serial>\S+)\s+tcp:(?P<local>\d+)\s+tcp:(?P<remote>\d+)\s*$")
74
+
75
+ DEFAULT_HOST = "127.0.0.1"
76
+ DEFAULT_PORT = 8080
77
+
78
+ # Hosts that the computer reaches through an adb forward. An app that binds
79
+ # 0.0.0.0 on the device listens on its loopback too.
80
+ LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1", "0.0.0.0")
81
+
82
+
83
+ class Owner(NamedTuple):
84
+ """The app that owns a token that the CLI found, and what :func:`withheld` needs to
85
+ check a server before the CLI sends it the token.
86
+
87
+ ``uid`` is the uid of the app's processes: the one that ``run-as`` runs with, for a
88
+ token from the prefs, or the one of the process that logged the ready line (``pid``),
89
+ for a token from the log. It is ``None`` when adb can't tell. ``name`` is the app's
90
+ package, ``None`` for the process of a line without ``--package``. ``prefs`` are the
91
+ prefs that gave the token. ``net`` is the text of ``/proc/net/tcp`` and
92
+ ``/proc/net/tcp6``, read in the same adb call as the uid, at ``read_at``, a
93
+ ``time.monotonic()`` value."""
94
+
95
+ uid: Optional[int] = None
96
+ name: Optional[str] = None
97
+ pid: Optional[str] = None
98
+ prefs: Optional["Prefs"] = None
99
+ net: Optional[str] = None
100
+ read_at: Optional[float] = None
101
+
102
+
103
+ class Endpoint(NamedTuple):
104
+ """A resolved Lustro endpoint. ``owner`` is set for a token that the CLI found and must
105
+ check before it sends it (see :func:`withheld`)."""
106
+
107
+ host: str
108
+ port: int
109
+ token: Optional[str]
110
+ scheme: str = "http"
111
+ owner: Optional[Owner] = None
112
+
113
+ @property
114
+ def base_url(self) -> str:
115
+ return "{}://{}:{}".format(self.scheme, self.host, self.port)
116
+
117
+
118
+ class DiscoveryError(Exception):
119
+ """Raised when the endpoint/token cannot be determined, or the app cannot be
120
+ reached. ``exit_code`` is the code of the cause, from :mod:`exitcodes`."""
121
+
122
+ def __init__(self, message: str, exit_code: int = exitcodes.NOT_REACHABLE) -> None:
123
+ super().__init__(message)
124
+ self.exit_code = exit_code
125
+
126
+
127
+ def parse_ready_line(text: str) -> Optional[Endpoint]:
128
+ """Parse the *most recent* ``Lustro ready ...`` line from a logcat dump.
129
+
130
+ Returns ``None`` if no ready line is present. The last match wins so that a
131
+ rebind (e.g. onto a fallback port) supersedes earlier lines.
132
+ """
133
+ last: Optional[Endpoint] = None
134
+ for match in _READY_LINE.finditer(text):
135
+ last = Endpoint(
136
+ host=match.group("host"),
137
+ port=int(match.group("port")),
138
+ token=match.group("token"),
139
+ scheme=match.group("scheme"),
140
+ )
141
+ return last
142
+
143
+
144
+ def _adb_base(device: Optional[str]) -> List[str]:
145
+ cmd = ["adb"]
146
+ if device:
147
+ cmd += ["-s", device]
148
+ return cmd
149
+
150
+
151
+ def _run(cmd: List[str], timeout: float = 10.0) -> Optional[str]:
152
+ """Run a command, returning stdout text or ``None`` on any failure.
153
+
154
+ Failures (missing adb, no device, non-zero exit) are swallowed so discovery
155
+ can fall through to the next source.
156
+ """
157
+ out = _run_bytes(cmd, timeout)
158
+ return None if out is None else out.decode("utf-8", "replace")
159
+
160
+
161
+ def _run_bytes(cmd: List[str], timeout: float = 10.0) -> Optional[bytes]:
162
+ """:func:`_run`, with stdout as the bytes that the command wrote."""
163
+ try:
164
+ proc = subprocess.run(
165
+ cmd,
166
+ # Not the CLI's stdin: for `lustro mcp` it carries the client's messages,
167
+ # and `adb shell` can forward its stdin to the device.
168
+ stdin=subprocess.DEVNULL,
169
+ stdout=subprocess.PIPE,
170
+ stderr=subprocess.PIPE,
171
+ timeout=timeout,
172
+ check=False,
173
+ )
174
+ except (OSError, subprocess.SubprocessError):
175
+ return None
176
+ if proc.returncode != 0:
177
+ return None
178
+ return proc.stdout
179
+
180
+
181
+ # The status of a command that could not start, as a shell gives it.
182
+ _NOT_FOUND = 127
183
+
184
+
185
+ def _run_status(cmd: List[str], timeout: float = 10.0) -> Tuple[int, str]:
186
+ """Run a command, returning its exit status and its stdout and stderr together.
187
+
188
+ The status is 127 when the command is not installed, and -1 when it could not
189
+ run for another reason or did not finish in time.
190
+ """
191
+ try:
192
+ proc = subprocess.run(
193
+ cmd,
194
+ stdin=subprocess.DEVNULL,
195
+ stdout=subprocess.PIPE,
196
+ stderr=subprocess.STDOUT,
197
+ timeout=timeout,
198
+ check=False,
199
+ )
200
+ except FileNotFoundError:
201
+ return _NOT_FOUND, ""
202
+ except (OSError, subprocess.SubprocessError):
203
+ return -1, ""
204
+ return proc.returncode, proc.stdout.decode("utf-8", "replace")
205
+
206
+
207
+ def discover_from_logcat(
208
+ device: Optional[str] = None, package: Optional[str] = None, pids: Optional[List[str]] = None
209
+ ) -> Optional[Endpoint]:
210
+ """Discover the endpoint+token by dumping the ``LustroToken`` logcat buffer. The
211
+ endpoint's ``owner`` has the PID of the process that logged the line, which the
212
+ ``threadtime`` format gives, and no uid.
213
+
214
+ With ``package``, only the lines of that app's current process count: the last
215
+ line in the buffer can be another app's, and the line of an earlier process of
216
+ the app can have a port and a token that are no longer valid. ``pids`` are the
217
+ app's process IDs, when the caller has them. An app that does not run, or whose
218
+ process adb can't tell, gives ``None``.
219
+ """
220
+ if package:
221
+ pids = app_pids(package, device) if pids is None else pids
222
+ if not pids:
223
+ return None
224
+ # One dump with the PID of each line, not one `logcat --pid` per process: pidof
225
+ # can print an old process that still exits, and the last line in the buffer,
226
+ # which is the newest, must win.
227
+ out = _run(_adb_base(device) + ["logcat", "-d", "-v", "threadtime", "-s", "LustroToken"])
228
+ if out is None:
229
+ return None
230
+ last: Optional[Endpoint] = None
231
+ for line in out.splitlines():
232
+ pid = _line_pid(line)
233
+ if package and pid not in (pids or []):
234
+ continue
235
+ endpoint = parse_ready_line(line)
236
+ if endpoint is not None:
237
+ last = endpoint._replace(owner=Owner(pid=pid))
238
+ return last
239
+
240
+
241
+ # A ``threadtime`` line: ``<date> <time> <pid> <tid> <level> <tag>: <message>``.
242
+ _THREADTIME_PID = re.compile(r"^\s*\S+\s+\S+\s+(?P<pid>\d+)\s+\d+\s")
243
+
244
+
245
+ def _line_pid(line: str) -> Optional[str]:
246
+ match = _THREADTIME_PID.match(line)
247
+ return match.group("pid") if match else None
248
+
249
+
250
+ class Prefs(NamedTuple):
251
+ """What the app's ``lustro_debug`` prefs hold: the token, and the host and the
252
+ port of its last bind, ``None`` for an app that stored none."""
253
+
254
+ token: str
255
+ host: Optional[str]
256
+ port: Optional[int]
257
+
258
+
259
+ def parse_prefs(text: str) -> Optional[Prefs]:
260
+ """The token, the host, and the port in the text of the ``lustro_debug`` prefs file,
261
+ or ``None`` when it holds no token."""
262
+ # Prefs XML: <string name="lustro_token">AbC123...</string>
263
+ match = re.search(r'<string\s+name="lustro_token">\s*([^<\s]+)\s*</string>', text)
264
+ if not match:
265
+ return None
266
+ host = re.search(r'<string\s+name="lustro_host">\s*([^<\s]+)\s*</string>', text)
267
+ port = re.search(r'<int\s+name="lustro_port"\s+value="(\d+)"', text)
268
+ return Prefs(
269
+ token=match.group(1),
270
+ host=host.group(1) if host else None,
271
+ port=int(port.group(1)) if port else None,
272
+ )
273
+
274
+
275
+ # Separates the outputs of the commands that one ``adb shell`` call runs.
276
+ _PART = "--lustro-part--"
277
+ _PREFS_PATH = "shared_prefs/lustro_debug.xml"
278
+ _PROC_NET = "cat /proc/net/tcp /proc/net/tcp6 2>/dev/null"
279
+
280
+
281
+ def _shell_parts(commands: List[str], device: Optional[str]) -> Optional[List[str]]:
282
+ """Runs ``commands`` one after the other in one ``adb shell`` call, which costs one
283
+ round trip to the device, and returns the output of each, or ``None`` when adb fails."""
284
+ script = "".join("{}; echo; echo {}; ".format(command, _PART) for command in commands) + "true"
285
+ out = _run(_adb_base(device) + ["shell", script])
286
+ if out is None:
287
+ return None
288
+ parts = [""]
289
+ for line in out.splitlines(keepends=True):
290
+ if line.strip() == _PART:
291
+ parts.append("")
292
+ else:
293
+ parts[-1] += line
294
+ if len(parts) <= len(commands):
295
+ return None
296
+ # Without the line end that the echo before each separator adds.
297
+ return [part[:-1] if part.endswith("\n") else part for part in parts[: len(commands)]]
298
+
299
+
300
+ def _number(text: str) -> Optional[int]:
301
+ word = text.strip()
302
+ return int(word) if word.isdigit() else None
303
+
304
+
305
+ def _net(text: str) -> Optional[str]:
306
+ """The text of ``/proc/net/tcp`` and ``tcp6``, or ``None`` when the device did not let
307
+ the shell read them."""
308
+ return text if "local_address" in text else None
309
+
310
+
311
+ class AppRead(NamedTuple):
312
+ """What one adb call reads about an app. ``uid`` is the uid that ``run-as`` runs the
313
+ app's commands with, ``None`` when ``run-as`` fails, as for a build that is not
314
+ debuggable. ``prefs`` are its ``lustro_debug`` prefs, ``None`` when they hold no token.
315
+ ``net`` is ``/proc/net/tcp`` and ``tcp6``. ``read_at`` is the ``time.monotonic()`` of the read."""
316
+
317
+ uid: Optional[int]
318
+ prefs: Optional[Prefs]
319
+ net: Optional[str]
320
+ read_at: float = 0.0
321
+
322
+ def owner(self, name: str) -> Owner:
323
+ """The owner of the token in these prefs: the app ``name``."""
324
+ return Owner(self.uid, name, None, self.prefs, self.net, self.read_at)
325
+
326
+
327
+ # The real uid in /proc/<pid>/status: ``Uid:`` and the real, effective, saved, and file
328
+ # system uids, separated by tabs.
329
+ _STATUS_UID = re.compile(r"^Uid:\s+(\d+)", re.MULTILINE)
330
+
331
+
332
+ def read_app(package: str, device: Optional[str] = None) -> Optional[AppRead]:
333
+ """The app's prefs, its uid, and the sockets of the device, in one adb call, or
334
+ ``None`` when adb fails.
335
+
336
+ The uid comes from ``run-as``, which runs with the app's uid: the ``cat`` that reads
337
+ the prefs also reads its own ``/proc/self/status``. It does not come from the app's
338
+ processes: ``pidof`` finds them by name, and another app can give its process any
339
+ name, with ``android:process`` in its manifest. A process of the app in another
340
+ user, such as a work profile, has another uid and its own prefs."""
341
+ quoted = shlex.quote(package)
342
+ parts = _shell_parts(
343
+ ["run-as {} cat {} /proc/self/status 2>/dev/null".format(quoted, _PREFS_PATH), _PROC_NET], device
344
+ )
345
+ if parts is None:
346
+ return None
347
+ uid = _STATUS_UID.search(parts[0])
348
+ return AppRead(
349
+ uid=int(uid.group(1)) if uid else None,
350
+ prefs=parse_prefs(parts[0]),
351
+ net=_net(parts[1]),
352
+ read_at=time.monotonic(),
353
+ )
354
+
355
+
356
+ def app_process_uids(package: str, device: Optional[str] = None) -> Optional[Dict[str, Optional[int]]]:
357
+ """The uid of each process with the name ``package``, by its PID, ``None`` for a
358
+ process whose uid ``stat`` can't read, in one adb call, or ``None`` when adb fails."""
359
+ out = _run(
360
+ _adb_base(device)
361
+ + ["shell", "for p in $(pidof {}); do echo $p $(stat -c %u /proc/$p 2>/dev/null); done".format(
362
+ shlex.quote(package)
363
+ )]
364
+ )
365
+ if out is None:
366
+ return None
367
+ uids: Dict[str, Optional[int]] = {}
368
+ for line in out.splitlines():
369
+ fields = line.split()
370
+ if fields and fields[0].isdigit():
371
+ uids[fields[0]] = int(fields[1]) if len(fields) > 1 and fields[1].isdigit() else None
372
+ return uids
373
+
374
+
375
+ def read_process(pid: str, device: Optional[str] = None) -> Owner:
376
+ """The owner of a ready line that process ``pid`` logged: its uid, ``None`` when it has
377
+ ended, and ``/proc/net/tcp`` and ``tcp6``, in one adb call."""
378
+ if not pid.isdigit():
379
+ return Owner(pid=pid)
380
+ parts = _shell_parts(["stat -c %u /proc/{} 2>/dev/null".format(pid), _PROC_NET], device)
381
+ if parts is None:
382
+ return Owner(pid=pid)
383
+ return Owner(uid=_number(parts[0]), pid=pid, net=_net(parts[1]), read_at=time.monotonic())
384
+
385
+
386
+ def read_net(device: Optional[str] = None) -> Optional[str]:
387
+ """``/proc/net/tcp`` and ``tcp6`` of the device, or ``None`` when adb can't read them."""
388
+ parts = _shell_parts([_PROC_NET], device)
389
+ return None if parts is None else _net(parts[0])
390
+
391
+
392
+ # The resumed activity in ``dumpsys activity activities``, which releases name
393
+ # ``topResumedActivity=``, ``mResumedActivity:``, or ``ResumedActivity:``, then
394
+ # ``ActivityRecord{<hash> u0 <package>/<activity> ...}``.
395
+ _RESUMED_ACTIVITY = re.compile(
396
+ r"(?:top|m)?ResumedActivity[=:]\s*ActivityRecord\{[^}]*?\s(?P<package>[A-Za-z0-9_.]+)/"
397
+ )
398
+
399
+
400
+ def foreground_package(device: Optional[str] = None) -> Optional[str]:
401
+ """The package of the app in the foreground, or ``None`` when adb can't tell."""
402
+ out = _run(_adb_base(device) + ["shell", "dumpsys activity activities | grep ResumedActivity"])
403
+ match = _RESUMED_ACTIVITY.search(out or "")
404
+ return match.group("package") if match else None
405
+
406
+
407
+ # Every build with the Lustro runtime has assets under this directory, and a build
408
+ # with only the no-op artifacts has none.
409
+ RUNTIME_ASSET_ENTRY = "assets/lustro/"
410
+
411
+
412
+ def package_paths(package: str, device: Optional[str] = None) -> Optional[List[str]]:
413
+ """The paths of the package's APKs on the device: empty when it is not installed,
414
+ and ``None`` when adb can't tell.
415
+
416
+ ``pm path`` prints nothing for a package that is not installed, and exits 1 on
417
+ newer releases. An error text, such as the one of a package manager that does
418
+ not run yet while the device boots, or an adb that fails, says nothing about
419
+ the package.
420
+ """
421
+ status, out = _run_status(_adb_base(device) + ["shell", "pm", "path", package])
422
+ lines = [line.strip() for line in out.splitlines() if line.strip()]
423
+ if not lines:
424
+ return [] if status in (0, 1) else None
425
+ paths = [line[len("package:") :] for line in lines if line.startswith("package:")]
426
+ return paths or None
427
+
428
+
429
+ # The ZIP records that :func:`zip_entry_names` reads. The end of central directory
430
+ # record (EOCD) is 22 bytes and a comment of up to 65535 bytes, at the end of the file.
431
+ _EOCD_SIGNATURE = b"PK\x05\x06"
432
+ _EOCD_SIZE = 22
433
+ _EOCD_SEARCH = _EOCD_SIZE + 0xFFFF
434
+ _CENTRAL_ENTRY_SIGNATURE = b"PK\x01\x02"
435
+ _CENTRAL_ENTRY_SIZE = 46
436
+ # Far above the central directory of a large APK, which is less than 1 MB: a larger
437
+ # size is a damaged record, and its read would copy most of the APK.
438
+ _MAX_CENTRAL_DIRECTORY = 16 * 1024 * 1024
439
+
440
+
441
+ def zip_entry_names(read_tail: Callable[[int], Optional[bytes]]) -> Optional[List[str]]:
442
+ """The entry names in the central directory of a ZIP, or ``None`` when it can't
443
+ be read. ``read_tail(n)`` gives the last ``n`` bytes of the file, or the whole
444
+ file when it is smaller.
445
+
446
+ The central directory ends where the EOCD starts: in an APK, the signing block
447
+ comes before it. One read of 64 KB gets the EOCD, and the central directory of
448
+ most APKs with it. A second read gets a central directory that is larger. A
449
+ ZIP64 file, which an APK can't be, gets ``None``.
450
+ """
451
+ tail = read_tail(_EOCD_SEARCH)
452
+ if tail is None or len(tail) < _EOCD_SIZE:
453
+ return None
454
+ # The comment can contain the signature, so the EOCD is the one whose comment ends the file.
455
+ eocd = tail.rfind(_EOCD_SIGNATURE, 0, len(tail) - _EOCD_SIZE + len(_EOCD_SIGNATURE))
456
+ while eocd >= 0 and eocd + _EOCD_SIZE + struct.unpack_from("<H", tail, eocd + 20)[0] != len(tail):
457
+ eocd = tail.rfind(_EOCD_SIGNATURE, 0, eocd)
458
+ if eocd < 0:
459
+ return None
460
+ entries, size = struct.unpack_from("<HI", tail, eocd + 10)
461
+ if size == 0xFFFFFFFF or size > _MAX_CENTRAL_DIRECTORY:
462
+ return None
463
+ if size <= eocd:
464
+ directory = tail[eocd - size : eocd]
465
+ else:
466
+ whole = read_tail(size + len(tail) - eocd)
467
+ if whole is None or len(whole) != size + len(tail) - eocd:
468
+ return None
469
+ directory = whole[:size]
470
+ names = []
471
+ offset = 0
472
+ while len(names) < entries:
473
+ if offset + _CENTRAL_ENTRY_SIZE > size or directory[offset : offset + 4] != _CENTRAL_ENTRY_SIGNATURE:
474
+ return None
475
+ name_length, extra_length, comment_length = struct.unpack_from("<HHH", directory, offset + 28)
476
+ start = offset + _CENTRAL_ENTRY_SIZE
477
+ names.append(directory[start : start + name_length].decode("utf-8", "replace"))
478
+ offset = start + name_length + extra_length + comment_length
479
+ return names
480
+
481
+
482
+ def apk_has_runtime(apk: str, device: Optional[str] = None) -> Optional[bool]:
483
+ """Whether the installed APK at ``apk`` on the device contains the Lustro runtime,
484
+ or ``None`` when adb can't tell.
485
+
486
+ It reads the entry names from the APK's central directory, with ``tail -c``
487
+ through ``adb exec-out``, which does not change binary bytes. Toybox ``tail`` is
488
+ on every API level, and API 28 emulator images have no ``unzip``. A ``grep`` of
489
+ the whole APK is not reliable: the toybox ``grep`` of API 30 to 33 finds no
490
+ match after a NUL byte on the same line, and a ZIP has such bytes before each
491
+ entry name.
492
+ """
493
+
494
+ def read_tail(size: int) -> Optional[bytes]:
495
+ return _run_bytes(
496
+ _adb_base(device) + ["exec-out", "tail -c {} {}".format(size, shlex.quote(apk))], timeout=30.0
497
+ )
498
+
499
+ names = zip_entry_names(read_tail)
500
+ if names is None:
501
+ return None
502
+ return any(name.startswith(RUNTIME_ASSET_ENTRY) for name in names)
503
+
504
+
505
+ def app_pids(package: str, device: Optional[str] = None) -> Optional[List[str]]:
506
+ """The process IDs of ``package`` on the device, or ``None`` when adb can't tell.
507
+ ``|| true`` because pidof exits 1 when it finds none."""
508
+ out = _run(_adb_base(device) + ["shell", "pidof {} || true".format(shlex.quote(package))])
509
+ if out is None:
510
+ return None
511
+ return [pid for pid in out.split() if pid.isdigit()]
512
+
513
+
514
+ def is_running(package: str, device: Optional[str] = None) -> Optional[bool]:
515
+ """Whether a process of ``package`` runs on the device, or ``None`` when adb can't tell."""
516
+ pids = app_pids(package, device)
517
+ return None if pids is None else bool(pids)
518
+
519
+
520
+ class AdbMissing(DiscoveryError):
521
+ """adb is not installed, or not on the PATH."""
522
+
523
+
524
+ def device_problem(device: Optional[str] = None) -> Optional[DiscoveryError]:
525
+ """Why adb reaches no device, or ``None`` when it reaches one or can't tell.
526
+
527
+ ``adb get-state`` prints ``device`` for a device that adb can use, and fails for no
528
+ device, more than one with none selected, and a device that is offline or not
529
+ authorized.
530
+ """
531
+ status, out = _run_status(_adb_base(device) + ["get-state"])
532
+ if status == _NOT_FOUND:
533
+ return AdbMissing(
534
+ "adb is not installed, or not on the PATH, so the CLI can't find the app on a device. Install the "
535
+ "Android SDK Platform-Tools, or pass --token and --port for a server that adb does not reach.",
536
+ exitcodes.NO_DEVICE,
537
+ )
538
+ # adb can print its own lines first, such as "* daemon started successfully", or
539
+ # the restart of a server of another adb version: the state is the last line.
540
+ lines = [line.strip() for line in out.splitlines() if line.strip()]
541
+ if status < 0 or (status == 0 and lines and lines[-1] == "device"):
542
+ return None
543
+ said = " ".join(out.split()) or "adb get-state exited with status {}".format(status)
544
+ if "more than one" in said:
545
+ return DiscoveryError(
546
+ "more than one device is connected ({}): pass --device SERIAL, or set ANDROID_SERIAL. `adb devices` "
547
+ "lists them.".format(said),
548
+ exitcodes.USAGE,
549
+ )
550
+ return DiscoveryError(
551
+ "no device that adb can use ({}): connect a device or start an emulator. `adb devices` lists each one "
552
+ "with its state, which must be `device`, not `offline` or `unauthorized`.".format(said),
553
+ exitcodes.NO_DEVICE,
554
+ )
555
+
556
+
557
+ def diagnose(
558
+ device: Optional[str] = None, package: Optional[str] = None, *, adb_required: bool = True
559
+ ) -> Optional[DiscoveryError]:
560
+ """Why the app's server can't be reached, as far as adb can tell, or ``None``.
561
+
562
+ The checks go from the device to the app: is there a device, is the app
563
+ installed, does its build contain the Lustro runtime, does it run, and is it in
564
+ the foreground. Without ``package``, the app is the one in the foreground, and
565
+ only its runtime is checked: that app can be the launcher, or another app, so
566
+ an app without the runtime there gets the code of an app that is not reachable.
567
+ With ``adb_required`` false, a computer without adb gets ``None``: the CLI then
568
+ connects to a server on the computer, not on a device.
569
+ """
570
+ problem = device_problem(device)
571
+ if problem is not None:
572
+ return None if isinstance(problem, AdbMissing) and not adb_required else problem
573
+ app = package or foreground_package(device)
574
+ if not app:
575
+ return None
576
+ paths = package_paths(app, device)
577
+ if paths is None:
578
+ return None
579
+ if not paths:
580
+ if package:
581
+ return DiscoveryError(
582
+ "{} is not installed on the device: install a debug build that uses the Lustro artifacts, and "
583
+ "start it.".format(package),
584
+ exitcodes.NOT_INSTALLED,
585
+ )
586
+ return None
587
+ apk = next((path for path in paths if path.endswith("/base.apk")), None)
588
+ if apk is not None and apk_has_runtime(apk, device) is False:
589
+ code = exitcodes.NO_RUNTIME if package else exitcodes.NOT_REACHABLE
590
+ return DiscoveryError(_no_runtime_message(app, from_foreground=not package), code)
591
+ if not package:
592
+ return None
593
+ if is_running(package, device) is False:
594
+ return DiscoveryError(
595
+ "{} is not running: start it. Lustro listens while the app is in the foreground.".format(package),
596
+ exitcodes.NOT_REACHABLE,
597
+ )
598
+ front = foreground_package(device)
599
+ if front is not None and front != package:
600
+ return DiscoveryError(
601
+ "{} runs, but {} is in the foreground: bring the app to the front. Lustro listens only while its app "
602
+ "is in the foreground, and a locked screen stops it.".format(package, front),
603
+ exitcodes.NOT_REACHABLE,
604
+ )
605
+ return None
606
+
607
+
608
+ # A listening socket in /proc/net/tcp and /proc/net/tcp6. A line is
609
+ # ``<sl>: <local address>:<port> <remote address>:<port> <state> ... <uid> ...``,
610
+ # with the port in hex, and the uid in the eighth column.
611
+ _TCP_LISTEN = "0A"
612
+ _TCP_UID_COLUMN = 7
613
+
614
+
615
+ def parse_listening_uids(text: str, port: int) -> List[int]:
616
+ """The uids of the sockets in ``/proc/net/tcp`` or ``/proc/net/tcp6`` text that
617
+ listen on TCP ``port``, in the order of the lines, each once."""
618
+ suffix = ":{:04X}".format(port)
619
+ uids: List[int] = []
620
+ for line in text.splitlines():
621
+ fields = line.split()
622
+ if len(fields) <= _TCP_UID_COLUMN or fields[3] != _TCP_LISTEN or not fields[1].upper().endswith(suffix):
623
+ continue
624
+ if fields[_TCP_UID_COLUMN].isdigit() and int(fields[_TCP_UID_COLUMN]) not in uids:
625
+ uids.append(int(fields[_TCP_UID_COLUMN]))
626
+ return uids
627
+
628
+
629
+ # A line of ``pm list packages -U``: ``package:<name> uid:<uid>``, with one uid for
630
+ # each user that has the app, comma-separated, such as ``uid:10773,9510773``.
631
+ _PACKAGE_UIDS = re.compile(r"^package:(?P<package>\S+)\s+uid:(?P<uids>[\d,]+)\s*$")
632
+
633
+ # A package in ``dumpsys package packages``: ``Package [<name>] (<hash>):``, and some
634
+ # lines later its app ID, the uid in user 0, as ``userId=<id>`` (``appId=`` on newer
635
+ # releases). The uid in user N is N * 100000 + the app ID.
636
+ _DUMPSYS_PACKAGE = re.compile(r"^\s*Package \[(?P<package>[^\]]+)\]")
637
+ _DUMPSYS_APP_ID = re.compile(r"^\s*(?:userId|appId)=(?P<id>\d+)")
638
+ _PER_USER_RANGE = 100000
639
+
640
+
641
+ def packages_of_uid(uid: int, device: Optional[str] = None) -> List[str]:
642
+ """The packages that have ``uid``: more than one for a shared uid, and none when
643
+ adb can't tell, as for a uid that is not an app's.
644
+
645
+ ``pm list packages -U`` lists them from API 26. It can print an error first, such
646
+ as a ``SecurityException`` for a user that the shell can't access, and then the
647
+ packages of the other users. An older ``pm`` prints ``Unknown option: -U``: then
648
+ ``dumpsys package packages`` gives the app ID of each package."""
649
+ _, out = _run_status(_adb_base(device) + ["shell", "pm", "list", "packages", "-U"])
650
+ listed = [match for match in (_PACKAGE_UIDS.match(line.strip()) for line in out.splitlines()) if match]
651
+ if listed:
652
+ return _unique(match.group("package") for match in listed if str(uid) in match.group("uids").split(","))
653
+ packages = []
654
+ current = None
655
+ for line in (_run(_adb_base(device) + ["shell", "dumpsys", "package", "packages"]) or "").splitlines():
656
+ package = _DUMPSYS_PACKAGE.match(line)
657
+ app_id = _DUMPSYS_APP_ID.match(line) if current else None
658
+ if package:
659
+ current = package.group("package")
660
+ elif app_id:
661
+ if int(app_id.group("id")) == uid % _PER_USER_RANGE:
662
+ packages.append(current)
663
+ current = None
664
+ return _unique(packages)
665
+
666
+
667
+ def _unique(items: Iterable[str]) -> List[str]:
668
+ return list(dict.fromkeys(items))
669
+
670
+
671
+ _WITHHELD_HINT = (
672
+ "To send a token to a server that you choose, pass --token, and --port with the local port of an adb "
673
+ "forward that you made."
674
+ )
675
+
676
+
677
+ class TokenWithheld(LustroError):
678
+ """The CLI found a token and did not send it: it could not tell that the server on the
679
+ port is a server of the app that owns the token (see :func:`withheld`)."""
680
+
681
+ def __init__(self, message: str, hint: Optional[str] = None, error: str = "token_withheld") -> None:
682
+ super().__init__(error, message, hint=hint)
683
+
684
+
685
+ class PortHeld(TokenWithheld):
686
+ """Another app listens on the port of the device where the CLI would send the token,
687
+ such as another app with Lustro whose server did not close yet."""
688
+
689
+ def __init__(self, port: int, owner: Owner, holder_uid: int) -> None:
690
+ self.port = port
691
+ self.owner = owner
692
+ self.holder_uid = holder_uid
693
+ self.holder_packages: List[str] = []
694
+ self.owner_packages: List[str] = [owner.name] if owner.name else []
695
+ super().__init__(self.describe(), error="port_held")
696
+
697
+ def name_apps(self, device: Optional[str]) -> None:
698
+ """Names the app that holds the port, and the app of a log line, from ``pm``."""
699
+ self.holder_packages = packages_of_uid(self.holder_uid, device)
700
+ if not self.owner_packages and self.owner.uid is not None:
701
+ self.owner_packages = packages_of_uid(self.owner.uid, device)
702
+ self.message = self.describe()
703
+
704
+ def describe(self, *, waits: bool = True) -> str:
705
+ """The message. ``waits`` adds that ``lustro ready`` waits until the app gets the port."""
706
+ if self.holder_packages:
707
+ other = "{} (uid {})".format(", ".join(self.holder_packages), self.holder_uid)
708
+ else:
709
+ other = "a process with uid {}".format(self.holder_uid)
710
+ app = ", ".join(self.owner_packages) or "the app that logged the LustroToken line"
711
+ message = (
712
+ "port {port} of the device is held by {other}, not by {app} (uid {uid}), so the CLI did not send it "
713
+ "the token of {app}. Both apps use port {port}: the server of {app} binds it when the other app's "
714
+ "server closes, which it does when that app goes to the background."
715
+ ).format(port=self.port, other=other, app=app, uid=self.owner.uid)
716
+ if waits:
717
+ package = self.owner_packages[0] if len(self.owner_packages) == 1 else "<package>"
718
+ message += " `lustro ready --package {}` waits for that.".format(package)
719
+ return message + " To prevent this, give each app with Lustro on the device its own serverPort."
720
+
721
+
722
+ def withheld(owner: Owner, host: str, port: int, net: Optional[str]) -> Optional[LustroError]:
723
+ """Why the CLI must not send the token of ``owner`` to the server at ``host``:``port``,
724
+ or ``None`` when that server is the owner's. ``net`` is ``/proc/net/tcp`` and ``tcp6``
725
+ of the device.
726
+
727
+ The server is the owner's when each socket that listens on ``port`` of the device has
728
+ the owner's uid. The host is loopback, which the CLI reaches through an adb forward,
729
+ or the address of the device on a network, which the runtime writes in the ready
730
+ line. A token from the prefs goes to a host that is not loopback only when the prefs
731
+ name that host and port: a ready line of another app can name any host. When nothing
732
+ listens, the error is ``connection_failed``, as the connection's would be.
733
+ """
734
+ app = owner.name or "the app that logged the LustroToken line"
735
+ prefs = owner.prefs
736
+ if prefs is not None and host not in LOOPBACK_HOSTS and (prefs.host, prefs.port) != (host, port):
737
+ return TokenWithheld(
738
+ "the prefs of {} name {}:{}, not {}:{}, so the CLI did not send their token to {}:{}".format(
739
+ app, prefs.host, prefs.port, host, port, host, port
740
+ ),
741
+ hint=_WITHHELD_HINT,
742
+ )
743
+ if owner.uid is None:
744
+ if owner.pid is not None:
745
+ return TokenWithheld(
746
+ "the process that logged the last LustroToken line, PID {}, has ended, so the CLI did not send its "
747
+ "token: start the app, and bring it to the front".format(owner.pid)
748
+ )
749
+ return TokenWithheld(
750
+ "adb can't tell the uid of {}, so the CLI did not send its token".format(app), hint=_WITHHELD_HINT
751
+ )
752
+ listeners = None if net is None else parse_listening_uids(net, port)
753
+ if listeners is None:
754
+ return TokenWithheld(
755
+ "adb can't tell which app listens on port {} of the device, so the CLI did not send the token of {} "
756
+ "there".format(port, app),
757
+ hint=_WITHHELD_HINT,
758
+ )
759
+ if not listeners:
760
+ return LustroError(
761
+ "connection_failed",
762
+ "nothing listens on port {} of the device, so the CLI did not send the token of {} there".format(port, app),
763
+ hint="Is the app running and foregrounded? Lustro listens only while its app is in the foreground.",
764
+ )
765
+ others = [uid for uid in listeners if uid != owner.uid]
766
+ if others:
767
+ return PortHeld(port, owner, others[0])
768
+ return None
769
+
770
+
771
+ class TokenGuard:
772
+ """Checks, before a client sends the token of ``endpoint.owner``, that the server on the
773
+ endpoint's port of the device is the owner's (see :func:`withheld`), and raises the
774
+ error when it is not. The first check uses ``/proc/net`` from discovery while it is
775
+ younger than ``GUARD_SECONDS``, and each later check reads it again: when the app goes
776
+ to the background, its server closes, and another app can bind the port."""
777
+
778
+ def __init__(self, endpoint: Endpoint, device: Optional[str] = None) -> None:
779
+ if endpoint.owner is None:
780
+ raise ValueError("an endpoint without an owner needs no check")
781
+ self.owner = endpoint.owner
782
+ self.host = endpoint.host
783
+ self.port = endpoint.port
784
+ self.device = device
785
+ self._net = endpoint.owner.net
786
+ self._read_at = endpoint.owner.read_at
787
+
788
+ def __call__(self) -> float:
789
+ """Raises when the server on the port is not the owner's. Returns the
790
+ ``time.monotonic()`` of the read that it checked."""
791
+ net, read_at, self._net = self._net, self._read_at, None
792
+ if net is None or read_at is None or time.monotonic() - read_at >= GUARD_SECONDS:
793
+ read_at = time.monotonic()
794
+ net = read_net(self.device)
795
+ error = withheld(self.owner, self.host, self.port, net)
796
+ if error is None:
797
+ return read_at
798
+ if isinstance(error, PortHeld):
799
+ error.name_apps(self.device)
800
+ raise error
801
+
802
+ def token_from_prefs(self, package: Optional[str] = None) -> Optional[str]:
803
+ """The token in the prefs of ``package``, or of the app in the foreground, when that
804
+ app's server is the one on the port (see :func:`token_from_prefs`), for a retry after
805
+ a 401. Later checks then check that app: its token is the one that the client sends."""
806
+ found = _owned_prefs(self.host, self.port, self.device, package)
807
+ if found is None:
808
+ return None
809
+ token, self.owner = found
810
+ return token
811
+
812
+
813
+ def _owned_prefs(
814
+ host: str, port: int, device: Optional[str], package: Optional[str]
815
+ ) -> Optional[Tuple[str, Owner]]:
816
+ """The token in the prefs of ``package``, or of the app in the foreground, and its owner,
817
+ when the server at ``host``:``port`` is that app's (see :func:`withheld`)."""
818
+ app = package or foreground_package(device)
819
+ read = read_app(app, device) if app else None
820
+ if not app or read is None or read.prefs is None:
821
+ return None
822
+ owner = read.owner(app)
823
+ if withheld(owner, host, port, read.net) is not None:
824
+ return None
825
+ return read.prefs.token, owner
826
+
827
+
828
+ def token_from_prefs(
829
+ device: Optional[str] = None, package: Optional[str] = None, endpoint: Optional[Endpoint] = None
830
+ ) -> Optional[str]:
831
+ """The token in the prefs of ``package``, or of the app in the foreground. For an
832
+ ``endpoint`` with an ``owner``, only when the server at the endpoint is that app's (see
833
+ :func:`withheld`): the app in the foreground can be another app than the one that
834
+ logged the ready line."""
835
+ if endpoint is not None and endpoint.owner is not None:
836
+ found = _owned_prefs(endpoint.host, endpoint.port, device, package)
837
+ return None if found is None else found[0]
838
+ app = package or foreground_package(device)
839
+ read = read_app(app, device) if app else None
840
+ return None if read is None or read.prefs is None else read.prefs.token
841
+
842
+
843
+ def parse_forwards(text: str, device_port: int) -> List[Tuple[str, int]]:
844
+ """The device serial and the local port of each forward to ``tcp:<device_port>``
845
+ in ``adb forward --list`` output, in the order that adb lists them."""
846
+ forwards = []
847
+ for line in text.splitlines():
848
+ match = _FORWARD_LINE.match(line)
849
+ if match and int(match.group("remote")) == device_port:
850
+ forwards.append((match.group("serial"), int(match.group("local"))))
851
+ return forwards
852
+
853
+
854
+ def forwarded_ports(device_port: int, device: Optional[str] = None) -> List[int]:
855
+ """The local ports of the ``adb forward``s to ``tcp:<device_port>`` on the
856
+ selected device, in the order that adb lists them. Empty when there is none,
857
+ or adb can't tell.
858
+
859
+ ``adb forward --list`` lists the forwards of every device, so this asks adb
860
+ which device it selects: ``device``, else ``ANDROID_SERIAL``, else the only one.
861
+ """
862
+ forwards = parse_forwards(_run(["adb", "forward", "--list"]) or "", device_port)
863
+ if not forwards:
864
+ return []
865
+ serial = _run(_adb_base(device) + ["get-serialno"])
866
+ if not serial:
867
+ return []
868
+ return [local for listed, local in forwards if listed == serial.strip()]
869
+
870
+
871
+ def resolve(
872
+ *,
873
+ host: Optional[str] = None,
874
+ port: Optional[int] = None,
875
+ token: Optional[str] = None,
876
+ device: Optional[str] = None,
877
+ package: Optional[str] = None,
878
+ env: Optional[dict] = None,
879
+ check_app: bool = True,
880
+ ) -> Endpoint:
881
+ """Resolve the active endpoint+token following the documented order.
882
+
883
+ Explicit args take precedence; otherwise ``LUSTRO_TOKEN`` (token). With
884
+ ``package``, the app's prefs come next (host/port/token), then the logcat
885
+ ready line of the app's current process for what the prefs did not give.
886
+ Without it, the last logcat ready line comes next, then the prefs of the app
887
+ in the foreground. Defaults for host/port are filled in last. Raises
888
+ :class:`DiscoveryError` if no token can be determined from any source: with
889
+ the cause that :func:`diagnose` finds, or, with ``check_app`` false, without
890
+ those adb calls, for a caller that tries again.
891
+
892
+ A token that this finds, with a port that it finds too, gets an ``owner`` on
893
+ the endpoint, which a client checks before it sends the token (see
894
+ :class:`TokenGuard`). A port from ``port`` is a local port, and a ``host`` that
895
+ is not loopback is the user's choice: these get no check. Without ``package``,
896
+ a ready line whose app does not listen on its port, or whose process has
897
+ ended, gives way to the prefs of the app in the foreground when that app's
898
+ server listens on the port that its prefs name.
899
+ """
900
+ env = os.environ if env is None else env
901
+
902
+ r_host = host
903
+ r_port = port
904
+ r_token = token
905
+
906
+ # LUSTRO_TOKEN env (token only).
907
+ if r_token is None:
908
+ env_token = env.get("LUSTRO_TOKEN")
909
+ if env_token:
910
+ r_token = env_token
911
+
912
+ checks = r_token is None and port is None and (host is None or host in LOOPBACK_HOSTS)
913
+ owner: Optional[Owner] = None
914
+
915
+ def missing() -> bool:
916
+ return r_token is None or r_host is None or r_port is None
917
+
918
+ def take(found_host: Optional[str], found_port: Optional[int], found_token: Optional[str], found: Owner) -> None:
919
+ nonlocal r_host, r_port, r_token, owner
920
+ if r_token is None and found_token:
921
+ r_token = found_token
922
+ owner = found
923
+ if r_host is None:
924
+ r_host = found_host
925
+ if r_port is None:
926
+ r_port = found_port
927
+
928
+ if package:
929
+ # The app's prefs: one adb call, where the dump of the log takes seconds on a
930
+ # device with a full log buffer. They are the named app's own. Each process of
931
+ # the app writes its token, and each bind its host and port, so while its server
932
+ # listens they are the current process's; before that, a connection to them
933
+ # fails or gets 401, and the caller tries again or prints the cause. A build that
934
+ # is not debuggable fails run-as, and an app that has not written them yet has
935
+ # none: the log line gives those. The same call reads the uid and the sockets that
936
+ # the check of the token needs.
937
+ app = read_app(package, device) if missing() else None
938
+ if app is not None and app.prefs is not None:
939
+ take(app.prefs.host, app.prefs.port, app.prefs.token, app.owner(package))
940
+ if missing():
941
+ # The PIDs that keep the app's lines, with the uid of each: the uid of the
942
+ # process that logged the line is the owner's.
943
+ uids = app_process_uids(package, device)
944
+ line = discover_from_logcat(device, package, None if uids is None else list(uids))
945
+ if line is not None:
946
+ pid = line.owner.pid if line.owner is not None else None
947
+ uid = uids.get(pid or "") if uids is not None else None
948
+ # The sockets of the read of the prefs, which the guard reads again when
949
+ # the dump of the log took longer than a check holds.
950
+ read = (app.net, app.read_at) if app is not None else (None, None)
951
+ take(line.host, line.port, line.token, Owner(uid, package, pid, None, *read))
952
+ else:
953
+ if missing():
954
+ line = discover_from_logcat(device)
955
+ if line is not None:
956
+ pid = line.owner.pid if line.owner is not None else None
957
+ take(line.host, line.port, line.token, read_process(pid, device) if checks and pid else Owner(pid=pid))
958
+ line_owner = owner
959
+ line_host = r_host or DEFAULT_HOST
960
+ if checks and line_owner is not None and withheld(line_owner, line_host, r_port, line_owner.net):
961
+ fallback = _from_foreground(host, device)
962
+ if fallback is not None and (line_owner.uid is None or fallback[1] is None):
963
+ found = fallback[0]
964
+ r_host, r_port, r_token, owner = found.host, found.port, found.token, found.owner
965
+ # The prefs of the app in the foreground, for whatever the log line didn't give:
966
+ # a device that drops Info logs drops the line. They have the host and port of
967
+ # the last bind too, unless the app predates storing them, so a token from
968
+ # --token or LUSTRO_TOKEN still gets the app's own port.
969
+ if missing():
970
+ app_name = foreground_package(device)
971
+ app = read_app(app_name, device) if app_name else None
972
+ if app is not None and app.prefs is not None:
973
+ prefs = app.prefs
974
+ take(prefs.host, prefs.port, prefs.token, app.owner(app_name))
975
+
976
+ # Fill host/port defaults last.
977
+ if r_host is None:
978
+ r_host = DEFAULT_HOST
979
+ if r_port is None:
980
+ r_port = DEFAULT_PORT
981
+
982
+ if not r_token:
983
+ cause = diagnose(device, package) if check_app else None
984
+ if cause is not None:
985
+ raise cause
986
+ raise DiscoveryError(
987
+ "no token: set --token or LUSTRO_TOKEN, or ensure the app is "
988
+ "running in the foreground and `adb logcat -d -s LustroToken` shows the ready line "
989
+ "(`Lustro ready endpoint=http://<host>:<port> token=<token>`). "
990
+ "A device with `adb shell getprop log.tag` set to E drops that line: "
991
+ "`adb shell setprop log.tag.LustroToken I` lets it through until the device "
992
+ "restarts. For a debuggable app, `--package <id>` reads the token through run-as. "
993
+ "For a device, also try `--device <serial>`."
994
+ )
995
+
996
+ return Endpoint(host=r_host, port=int(r_port), token=r_token, owner=owner if checks else None)
997
+
998
+
999
+ def _from_foreground(
1000
+ host: Optional[str], device: Optional[str]
1001
+ ) -> Optional[Tuple[Endpoint, Optional[LustroError]]]:
1002
+ """The endpoint in the prefs of the app in the foreground, with its owner, and why the
1003
+ CLI must not send it the token (see :func:`withheld`), or ``None`` without such prefs.
1004
+ ``host`` is the one from --host, when it is given."""
1005
+ app_name = foreground_package(device)
1006
+ app = read_app(app_name, device) if app_name else None
1007
+ if app is None or app.prefs is None:
1008
+ return None
1009
+ endpoint = Endpoint(
1010
+ host=host or app.prefs.host or DEFAULT_HOST,
1011
+ port=app.prefs.port or DEFAULT_PORT,
1012
+ token=app.prefs.token,
1013
+ owner=app.owner(app_name),
1014
+ )
1015
+ return endpoint, withheld(endpoint.owner, endpoint.host, endpoint.port, app.net)
1016
+
1017
+
1018
+ def _no_runtime_message(package: str, *, from_foreground: bool) -> str:
1019
+ """The error for an app whose APK has no Lustro runtime. Without --package, the app
1020
+ is the one in the foreground, which is the launcher when the user's app is closed."""
1021
+ causes = (
1022
+ "a build with the -noop artifacts, which have no server and log nothing, or a build from before the app "
1023
+ "added Lustro. Install a debug build that uses the Lustro artifacts, and start it"
1024
+ )
1025
+ if from_foreground:
1026
+ return (
1027
+ "the app in the foreground, {pkg}, does not contain the Lustro runtime: its APK has no {entry} entries. "
1028
+ "If it is your app, it is {causes}. If it is not, start your app. Pass --package <id> to check your app."
1029
+ ).format(pkg=package, entry=RUNTIME_ASSET_ENTRY, causes=causes)
1030
+ return (
1031
+ "the installed build of {pkg} does not contain the Lustro runtime: its APK has no {entry} entries. "
1032
+ "It is {causes}."
1033
+ ).format(pkg=package, entry=RUNTIME_ASSET_ENTRY, causes=causes)