File size: 40,004 Bytes
753a521 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 | """TreeLine as an agentenv computer app, exported by REA from a desktop application capture.
Package: treeline (captured at 3.1.5-1). Capture Evidence: ev_cedd8aa6c80e75efe1fcd13be6c7886a6a3768a14213365580484c5b9b70d481.
The seed was made for the task, as saved at checkpoint seed.
"""
from __future__ import annotations
import contextlib
import copy
import hashlib
import io
import json
import math
import os
import re
import sqlite3
import struct
import subprocess
import sys
import tempfile
import zipfile
import zlib
from pathlib import Path
from xml.parsers import expat
from agentenv_protocol import add_data, get_data, reset_data
from agentenv_protocol.computer import AptSource, ComputerAppEnvironment, Download, Launch, Packages, Ready, RunScript, computer_app, linux, ready_check
from agentenv_protocol.computer.app_data import INITIAL, add, get, in_thread, keep_initial, reset
from agentenv_protocol.types import DataPart
HERE = Path(__file__).resolve().parent
SEED_HOME = "/home/user"
PATHS = ["Documents"]
DCONF = ""
TEXT_SEEDS = frozenset([])
WINDOW_CLASS = "treeline.py"
XML_SUFFIXES = (".xml", ".xbel", ".plist", ".svg", ".ui")
GROUP_HEADER = re.compile(r"^\[([^\]]+)\]$")
LINE_BREAK = re.compile(r"\r?\n")
SQLITE_HEADER = b"SQLite format 3\x00"
GVDB_HEADER = b"GVariant"
ZIP_HEADER = b"PK\x03\x04"
GZIP_HEADER = b"\x1f\x8b\x08"
XML_SPACE = "xml:space"
MAX_VIEW_BYTES = 64 * 1024 * 1024
MAX_SAFE_INTEGER = 2**53 - 1
MAX_TABLES = 64
MAX_ROWS = 500
MAX_LINES = 5000
MAX_XML_NODES = 5000
MAX_XML_DEPTH = 64
SQLITE_BUSY_S = 0.25
MAX_PARSED_BYTES = 4 * 1024 * 1024
PARSED_TOO_LARGE = "larger than the 4 MiB limit for JSON and key file views"
MAX_JSON_VIEW_DEPTH = 500
JSON_TOO_DEEP = f"nested deeper than the {MAX_JSON_VIEW_DEPTH} levels a JSON view keeps"
#: A JSON token after any whitespace, by group: an opening, a closing, a comma, a colon, a string's quote, or a number
#: or literal. Strings are read by json's scanner, since a pattern repeating per escape holds memory for each.
JSON_TOKEN = re.compile(r'[ \t\n\r]*(?:([\[{])|([\]}])|(,)|(:)|(")|(-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?'
r"|true|false|null))")
JSON_SPACE = re.compile(r"[ \t\n\r]*")
def _respelled(text: str, home: Path) -> str:
"""The seed's home path respelled to this computer's home, only where a whole path segment ends after it."""
return re.sub(re.escape(SEED_HOME) + r"(?![\w.@+~-])", lambda _: str(home), text)
def _respelled_utf16(data: bytes, home: Path) -> bytes:
"""A UTF-16 text file with a byte-order mark respelled like a text seed, its mark kept; any other bytes as given."""
for mark, codec in ((b"\xff\xfe", "utf-16-le"), (b"\xfe\xff", "utf-16-be")):
if data.startswith(mark):
try:
text = data[len(mark):].decode(codec)
except UnicodeDecodeError:
return data
return mark + _respelled(text, home).encode(codec) if SEED_HOME in text else data
return data
#: What marks a window as not yet the app's own: skipping the taskbar, as splash screens and dialogs do, or a splash type.
SPLASH_MARKS = ("_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_WINDOW_TYPE_SPLASH")
def _taskbar_window(window_class: str) -> bool:
"""Whether a top-level window of the given class that the taskbar lists is shown; a splash screen or a dialog
skips the taskbar."""
def xprop(*args: str) -> str:
done = subprocess.run(["xprop", *args], capture_output=True, text=True)
return done.stdout if done.returncode == 0 else ""
for window in re.findall(r"0x[0-9a-f]+", xprop("-root", "_NET_CLIENT_LIST").partition("#")[2]):
props = xprop("-id", window, "WM_CLASS", "_NET_WM_STATE", "_NET_WM_WINDOW_TYPE")
classes = re.findall(r'"((?:[^"\\]|\\.)*)"', props.partition("WM_CLASS")[2].split("\n", 1)[0])
if window_class in classes and not any(mark in props for mark in SPLASH_MARKS):
return True
return False
def _seed_home(home: Path) -> None:
"""Copy the captured files into this computer's home; text files, UTF-16 ones too, have the seed's home path
respelled."""
seed = HERE / "seed"
for source in sorted(seed.rglob("*")) if seed.is_dir() else []:
if not source.is_file():
continue
relative = source.relative_to(seed).as_posix()
target = home / relative
target.parent.mkdir(parents=True, exist_ok=True)
data = source.read_bytes()
if relative in TEXT_SEEDS:
data = _respelled(data.decode("utf-8"), home).encode("utf-8")
else:
data = _respelled_utf16(data, home)
target.write_bytes(data)
def _dconf(arguments: list, environment: dict) -> str:
return subprocess.run(["dconf", *arguments], env={**os.environ, **environment}, capture_output=True, text=True,
check=True).stdout
def _load_dconf(home: Path) -> None:
"""Compile the captured dconf keys into the user database without D-Bus, which is not up yet. Keys already there
stay unless captured: dconf compile reads the key files in name order and a later file wins. A failure is
reported and the app starts without them."""
if not DCONF:
return
database = home / ".config" / "dconf" / "user"
try:
database.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=database.parent) as scratch:
keyfiles = Path(scratch, "keyfiles")
keyfiles.mkdir()
if database.is_file():
profile = Path(scratch, "profile")
profile.write_text(f"file-db:{database}\n")
existing = _dconf(["dump", "/"], {"DCONF_PROFILE": str(profile)})
(keyfiles / "00-existing").write_text(existing)
(keyfiles / "01-captured").write_text(_respelled(DCONF, home))
_dconf(["compile", str(Path(scratch, "user")), str(keyfiles)], {})
os.replace(Path(scratch, "user"), database)
except (OSError, subprocess.CalledProcessError) as error:
detail = (getattr(error, "stderr", None) or "").strip().splitlines()
print(f"warning: the captured dconf settings were not loaded: {detail[-1] if detail else error}",
file=sys.stderr)
def _sqlite_text(data: bytes):
text = data.decode("utf-8", "replace")
return {"text": text, "bytes_hex": data.hex()} if "�" in text else text
def _cell(value):
if isinstance(value, bytes):
return {"blob_hex": value.hex()}
if isinstance(value, int) and abs(value) > MAX_SAFE_INTEGER:
return {"integer": str(value)}
# JSON has no infinities or negative zero; REA's SQLite reader spells them as strings.
if isinstance(value, float) and (math.isinf(value) or (value == 0 and math.copysign(1, value) < 0)):
return "Infinity" if value == math.inf else "-Infinity" if value == -math.inf else "-0"
return value
def _table(db, name: str, primary_key: list) -> dict:
quoted = '"' + name.replace('"', '""') + '"'
cursor = db.execute(f"select * from main.{quoted} not indexed limit {MAX_ROWS + 1}")
rows = [[_cell(value) for value in row] for row in cursor]
return {"columns": [column[0] for column in cursor.description], "primary_key": primary_key,
"rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS}
def _sqlite(path: Path) -> dict:
"""The database's ordinary tables, in schema order, up to REA's table and row limits."""
with contextlib.closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=SQLITE_BUSY_S)) as db:
kinds = dict(db.execute("select name, type from pragma_table_list where schema = 'main'"))
names = [name for (name,) in db.execute("select name from sqlite_schema where type = 'table'")
if kinds.get(name) == "table"]
keys = {name: [key for (key,) in db.execute(
"select name from pragma_table_info(?, 'main') where pk > 0 order by pk", (name,))]
for name in names[:MAX_TABLES]}
db.text_factory = _sqlite_text
tables = {name: _table(db, name, keys[name]) for name in names[:MAX_TABLES]}
cut = len(names) > MAX_TABLES
return {"format": "sqlite", "view": {"tables": tables, "tables_truncated": cut},
"truncated": cut or any(table["truncated"] for table in tables.values())}
def _text(text: str) -> dict:
lines = LINE_BREAK.split(text)
if lines[-1] == "":
lines.pop()
view = {"lines": lines[:MAX_LINES], "line_count": len(lines), "truncated": len(lines) > MAX_LINES}
return {"format": "text", "view": view, "truncated": view["truncated"]}
def _keyfile_line(raw: str) -> tuple:
"""A key file line as REA reads it: skip (blank or comment), group, entry or other."""
line = raw.strip()
if not line or line[0] in "#;":
return ("skip",)
header = GROUP_HEADER.match(line)
if header:
return ("group", header.group(1))
key, equals, value = line.partition("=")
return ("entry", key.strip(), value.strip()) if equals and key else ("other",)
def _each_line(text: str):
"""Each line of text as REA splits them, one at a time."""
start = 0
for line_break in LINE_BREAK.finditer(text):
yield text[start:line_break.start()]
start = line_break.end()
yield text[start:]
def _is_keyfile(text: str) -> bool:
"""REA's rule: at least one group, and nothing a key file view would drop. Lines are read one at a time, stopping
at the first it would drop."""
group = False
for line in _each_line(text):
kind = _keyfile_line(line)[0]
if kind == "other":
return False
group = group or kind == "group"
return group
def _keyfile(text: str) -> dict:
groups, group = {}, ""
for line in map(_keyfile_line, LINE_BREAK.split(text)):
if line[0] == "group":
group = line[1]
groups.setdefault(group, {})
elif line[0] == "entry":
groups.setdefault(group, {})[line[1]] = line[2]
return groups
#: XML's whitespace, which alone can be formatting between elements; Unicode's wider set is text.
XML_WHITESPACE = " \t\r\n"
PREDEFINED_ENTITIES = ("amp", "lt", "gt", "apos", "quot")
ENTITY_REFERENCE = re.compile(r"&([^#;][^;]*);")
def _expat(namespaces: bool, doctype=None):
"""An expat parser that reads a DOCTYPE as REA does: one with an internal subset, which could declare entities,
is refused, the DTD it names is never read, and a reference to an entity other than XML's five is refused where
expat would skip it. With namespaces it also enforces their rules, as REA's parser does, and without them it
reports names as the document spells them. doctype, when given, receives the declared name and identifiers."""
parser = expat.ParserCreate(namespace_separator=" " if namespaces else None)
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
def declared(name: str, system_id, public_id, internal_subset: bool) -> None:
if internal_subset:
raise ValueError("the document's DOCTYPE has an internal subset")
if doctype is not None:
doctype({"name": name, "public_id": public_id, "system_id": system_id})
def undeclared(name: str, _parameter: bool) -> None:
raise ValueError(f"the document refers to the undeclared entity {name}")
def external(*_) -> None:
raise ValueError("the document refers to an external entity")
parser.StartDoctypeDeclHandler = declared
parser.SkippedEntityHandler = undeclared
parser.ExternalEntityRefHandler = external
return parser
def _check_tag(markup: str) -> None:
"""expat leaves an undeclared entity out of an attribute value without a word when a DOCTYPE names a DTD; REA's
parser refuses it. With text taken by its own handler, a start tag is the only markup expat passes here that
starts with < and a name, and it passes it whole."""
if markup[:1] == "<" and markup[1:2] not in ("!", "?", "/"):
for name in ENTITY_REFERENCE.findall(markup):
if name not in PREDEFINED_ENTITIES:
raise ValueError(f"the document refers to the undeclared entity {name}")
def _ignore_text(_text: str) -> None:
pass
class _XmlReader:
"""REA's XML view built as expat reads: names as spelled, declarations as attributes, text split where REA's DOM
splits it (an empty CDATA section joins the text around it), and each node counted against REA's limits."""
def __init__(self) -> None:
self.remaining, self.truncated, self.root, self.doctype = MAX_XML_NODES, False, None, None
#: Per open element: its view or None when left out, whether xml:space="preserve" applies inside it, whether
#: it holds an element, and whether it holds text other than whitespace: whitespace-only text is formatting
#: only in an element that holds elements and no such text.
self.open = []
self.text, self.cdata = [], None
def read(self, text: str) -> None:
parser = _expat(False, self._doctype)
parser.buffer_text = True
parser.StartElementHandler, parser.EndElementHandler = self._start, self._end
parser.CharacterDataHandler = self._data
parser.StartCdataSectionHandler, parser.EndCdataSectionHandler = self._cdata_start, self._cdata_end
parser.CommentHandler = parser.ProcessingInstructionHandler = self._other
parser.Parse(text, True)
def _doctype(self, declared: dict) -> None:
self.doctype = declared
def _admit(self) -> bool:
"""Whether the next node inside a kept element is kept, within the node and depth limits; one past them
marks the view truncated."""
if self.open and self.open[-1][0] is None:
return False
if self.remaining <= 0 or len(self.open) > MAX_XML_DEPTH:
self.truncated = True
return False
self.remaining -= 1
return True
def _text_node(self, text: str) -> None:
if self.open and text.strip(XML_WHITESPACE):
self.open[-1][3] = True
if self._admit():
self.open[-1][0]["children"].append(text)
def _flush(self) -> None:
if self.text:
text, self.text = "".join(self.text), []
self._text_node(text)
def _data(self, text: str) -> None:
(self.text if self.cdata is None else self.cdata).append(text)
def _cdata_start(self) -> None:
self.cdata = []
def _cdata_end(self) -> None:
text, self.cdata = "".join(self.cdata), None
if text:
self._flush()
self._text_node(text)
def _other(self, *_) -> None:
"""A comment or processing instruction, counted like any node and never kept."""
self._flush()
if self.open:
self._admit()
def _start(self, name: str, attributes: dict) -> None:
self._flush()
parent = self.open[-1] if self.open else [None, False, False, False]
parent[2] = True
view = {"name": name, "attributes": attributes, "children": []} if self._admit() else None
if view is not None and parent[0] is not None:
parent[0]["children"].append(view)
space = attributes.get(XML_SPACE)
self.open.append([view, space == "preserve" if space else parent[1], False, False])
def _end(self, _name: str) -> None:
self._flush()
view, preserve, holds_element, holds_text = self.open.pop()
if view is not None and holds_element and not holds_text and not preserve:
view["children"] = [child for child in view["children"]
if not isinstance(child, str) or child.strip(XML_WHITESPACE)]
if not self.open:
self.root = view
def _xml_view(text: str):
"""REA's XML view, or None for a document REA's parser refuses: a pass with namespaces checks the document as REA's
parser does, then a pass without them reads names as spelled, as REA's view keeps them, and the DOCTYPE."""
reader = _XmlReader()
try:
check = _expat(True)
check.CharacterDataHandler, check.DefaultHandler = _ignore_text, _check_tag
check.Parse(text, True)
reader.read(text)
except (expat.ExpatError, ValueError):
return None
view = {"root": reader.root, "truncated": reader.truncated}
return view if reader.doctype is None else {"doctype": reader.doctype, **view}
def _not_json(constant: str):
raise ValueError(f"{constant} is not JSON")
class _Inexact(Exception):
"""A JSON number that REA's state view refuses, since reading it would change it."""
def _digits(text: str) -> str:
return re.split(r"[eE]", text.lstrip("-"))[0].replace(".", "").strip("0") or "0"
def _js_string(value: float) -> str:
"""How JavaScript's String() writes a finite double: an integer below 1e21 in full, any other in shortest form."""
return str(int(value)) if value.is_integer() and abs(value) < 1e21 else repr(value)
def _safe_number(text: str) -> bool:
"""lossless-json's isSafeNumber: an integer spelling within 2^53, or a float spelling that keeps its digits."""
if re.fullmatch(r"-?[0-9]+", text):
return len(text.lstrip("-")) <= 16 and abs(int(text)) <= MAX_SAFE_INTEGER
value = float(text)
if not math.isfinite(value):
return False
written = _js_string(value)
return written == text or _digits(written) == _digits(text)
def _exact_number(text: str):
"""A JSON number read only when reading it changes nothing, as REA's state view rules: its spelling and its
written-back form both safe, and not -0."""
value = float(text)
if (not _safe_number(text) or not math.isfinite(value) or not _safe_number(_js_string(value))
or (value == 0 and math.copysign(1, value) < 0)):
raise _Inexact(text)
return int(text) if re.fullmatch(r"-?[0-9]+", text) else value
_INEXACT = object()
_LEVEL_END = object()
def _number_or_mark(spelling: str):
"""A JSON number read exactly, or a mark for one REA's state view refuses."""
try:
return _exact_number(spelling)
except _Inexact:
return _INEXACT
def _holds_inexact(value) -> bool:
"""Whether a parsed JSON value still holds a marked number once duplicate keys kept their last value; one
iterator per nesting level, so no child list is copied."""
levels = [iter((value,))]
while levels:
item = next(levels[-1], _LEVEL_END)
if item is _LEVEL_END:
levels.pop()
elif item is _INEXACT:
return True
elif isinstance(item, dict):
levels.append(iter(item.values()))
elif isinstance(item, list):
levels.append(iter(item))
return False
def _deeper_than(root, limit: int) -> bool:
"""Whether a parsed JSON value nests deeper than a limit, as REA checks it: a value's depth is the number of
iterators open above it, one per nesting level, so no child list is copied."""
levels = [iter((root,))]
while levels:
item = next(levels[-1], _LEVEL_END)
if item is _LEVEL_END:
levels.pop()
elif len(levels) - 1 > limit:
return True
elif isinstance(item, dict):
levels.append(iter(item.values()))
elif isinstance(item, list):
levels.append(iter(item))
return False
def _is_json(text: str) -> bool:
"""Whether text is one JSON value as REA's state view reads it, checked a token at a time without building it or
recursing: it holds a byte per open container and one string at a time, so text too deep for Python's parser or
too large to parse into a view is still told apart from other text."""
containers, expect, empty, at = bytearray(), "value", False, 0
while True:
token = JSON_TOKEN.match(text, at)
if token is None:
break
kind, at = token.lastindex, token.end()
if kind == 5:
try:
at = json.decoder.scanstring(text, at)[1]
except ValueError:
return False
if kind == 1 and expect == "value":
containers.append(ord(text[at - 1]))
expect, empty = ("value" if text[at - 1] == "[" else "key"), True
# A closing bracket's code is its opening's plus two.
elif kind == 2 and (expect == "after" or empty) and containers and containers[-1] == ord(text[at - 1]) - 2:
containers.pop()
expect, empty = "after", False
elif kind == 3 and expect == "after" and containers:
expect = "value" if containers[-1] == ord("[") else "key"
elif kind == 4 and expect == "colon":
expect = "value"
elif kind >= 5 and (expect == "value" or (kind == 5 and expect == "key")):
expect, empty = ("colon" if expect == "key" else "after"), False
else:
return False
return expect == "after" and not containers and JSON_SPACE.fullmatch(text, at) is not None
def _json_view(text: str, size: int):
"""A JSON text's format and view, or why it has none, as REA reads it; None when it is not JSON. Text over the
parsed-view limit, or nested past Python's recursion limit, is told apart without building its value."""
if size > MAX_PARSED_BYTES:
return {"format": "json", "view": None, "error": PARSED_TOO_LARGE} if _is_json(text) else None
# The whole text must parse, and duplicate keys settle, before an inexact number makes it JSON with an error.
try:
view = json.loads(text, parse_constant=_not_json, parse_float=_number_or_mark, parse_int=_number_or_mark)
except RecursionError:
# Nesting too deep for Python to parse is far deeper than REA's view keeps, once the rest of it is JSON too.
return {"format": "json", "view": None, "error": JSON_TOO_DEEP} if _is_json(text) else None
except ValueError:
return None
if _holds_inexact(view):
return {"format": "json", "view": None,
"error": "a number in it cannot be read exactly, such as an integer above 2^53"}
if _deeper_than(view, MAX_JSON_VIEW_DEPTH):
return {"format": "json", "view": None, "error": JSON_TOO_DEEP}
return {"format": "json", "view": view, "truncated": False}
def _text_view(name: str, text: str, size: int) -> dict:
"""The format REA's state view detects for decoded text of size bytes, and its view; a JSON or key file over the
parsed-view limit is refused before its value is built."""
trimmed = re.sub(r"^[\s]+", "", text)
if name.endswith(".json") or trimmed[:1] in ("[", "{"):
view = _json_view(text, size)
if view is not None:
return view
lowered = name.lower()
# Text that opens with an element is XML if it parses, whatever the file is called, as a Freeplane map.
if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml") or re.match(r"<[A-Za-z_:]", trimmed):
view = _xml_view(text)
return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]}
if _is_keyfile(text):
if size > MAX_PARSED_BYTES:
return {"format": "keyfile", "view": None, "error": PARSED_TOO_LARGE}
return {"format": "keyfile", "view": {"groups": _keyfile(text)}, "truncated": False}
return _text(text)
def _bytes_view(name: str, data: bytes) -> dict:
"""The view of a document that is no database or archive: its text's, or none when it is binary."""
try:
text = data.decode("utf-8-sig") if b"\x00" not in data[:8192] else None
except UnicodeDecodeError:
text = None
if text is None:
return {"format": "binary", "view": None, "truncated": False}
return _text_view(name, text, len(data))
def _view(path: Path) -> dict:
"""A typed JSON view of one file in the shapes of REA's state view; truncated says the view is partial."""
too_large = {"format": None, "view": None, "error": "larger than 64 MiB, the most the view reads"}
if path.stat().st_size > MAX_VIEW_BYTES:
return too_large
with path.open("rb") as file:
data = file.read(8192)
whole = data.startswith(GZIP_HEADER) or (not data.startswith(SQLITE_HEADER) and b"\x00" not in data)
data += file.read(MAX_VIEW_BYTES + 1 - len(data)) if whole else b""
if data.startswith(SQLITE_HEADER):
return _sqlite(path)
if data.startswith(ZIP_HEADER):
with path.open("rb") as file:
return _zip(file, os.fstat(file.fileno()).st_size)
if len(data) > MAX_VIEW_BYTES:
return too_large
if data.startswith(GZIP_HEADER):
return _gzip(path.name, data)
return _bytes_view(path.name, data)
def _views(home: Path, paths: list) -> dict:
"""A view of every file under the app's paths, keyed by its home-relative path."""
files = {}
for owned in paths:
root = home / owned
candidates = [root] if root.is_file() else sorted(root.rglob("*")) if root.is_dir() else []
for path in candidates:
if path.is_file() and not path.is_symlink():
key = path.relative_to(home).as_posix()
try:
files[key] = _view(path)
except (OSError, ValueError, sqlite3.Error, RecursionError) as error:
files[key] = {"format": None, "view": None, "error": str(error)}
return files
MAX_ZIP_ENTRIES = 1000
MAX_ZIP_ENTRY_BYTES = 16 * 1024 * 1024
MAX_ZIP_BYTES = 64 * 1024 * 1024
MAX_ZIP_RATIO = 100
ZIP_READ_CHUNK = 64 * 1024
#: Small, since the end of each gzip member copies what is left of the piece it was read from.
GZIP_READ_CHUNK = 4 * 1024
ZIP_END = b"PK\x05\x06"
ZIP_CENTRAL = b"PK\x01\x02"
ZIP64_LOCATOR = b"PK\x06\x07"
ZIP64_END = b"PK\x06\x06"
#: Formats an archive entry may have whose reader needs a tool, a worker or another archive opened.
NOT_READ_INSIDE = ((SQLITE_HEADER, "sqlite", "a SQLite database"), (GVDB_HEADER, "dconf", "a dconf database"),
(ZIP_HEADER, "zip", "an archive"))
def _entry_view(name: str, data: bytes) -> dict:
"""An archive entry's format and view by the rules a file's follow; a database or an archive inside is not
read."""
for header, form, inside in NOT_READ_INSIDE:
if data.startswith(header):
return {"format": form, "view": None, "error": f"{inside} inside an archive is not read"}
return _bytes_view(name, data)
def _zip_refusal(info, spent: int):
"""Why an entry is not read, checked in REA's order, or None; spent is the archive's bytes read so far."""
if info.flag_bits & 0x1:
return "encrypted, so it is not read"
if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
return f"compressed with method {info.compress_type}, which the view does not read"
if info.file_size > MAX_ZIP_ENTRY_BYTES:
return "larger than the 16 MiB an entry's view reads"
if info.file_size > MAX_ZIP_RATIO * info.compress_size:
return f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
if spent + info.file_size > MAX_ZIP_BYTES:
return "past the 64 MiB read from one archive"
return None
def _entry_bytes(archive, info):
"""An entry's uncompressed bytes, or None when they fail its CRC-32 or are not exactly its declared size. Reading
stops one byte past that size, which data past a short declared size fills, and asks for a bounded chunk at a
time, which bounds what the decompressor expands per call, so a forged small size holds no more than that."""
probe = copy.copy(info)
probe.file_size = info.file_size + 1
data = bytearray()
try:
with archive.open(probe) as member:
while len(data) <= info.file_size:
chunk = member.read(min(probe.file_size - len(data), ZIP_READ_CHUNK))
if not chunk:
break
data += chunk
except (zipfile.BadZipFile, zlib.error, EOFError, OSError, ValueError):
return None
return data if len(data) == info.file_size else None
def _zip_entry(archive, info, refusal):
"""One entry of a zip view: its name, size and digest, and its own format and view, or why it was not read."""
entry = {"name": info.filename, "size": info.file_size, "sha256": None, "format": None, "view": None,
"view_error": refusal}
if refusal is not None:
return entry
data = _entry_bytes(archive, info)
if data is None:
return {**entry, "view_error": "its compressed data is damaged"}
view = _entry_view(info.filename, data)
return {**entry, "sha256": hashlib.sha256(data).hexdigest(), "format": view["format"],
"view": view.get("view"), "view_error": view.get("error")}
def _zip_end(file, size: int):
"""Where an archive's central directory ends, how long it is and the offset it declares, from the last end
record whose comment reaches the end of the file and, when a Zip64 locator precedes it whatever that record
holds, the Zip64 one just before the locator; None without an end record, or when sentinels defer to a
Zip64 record that is missing."""
window = min(size, 22 + 0xFFFF)
file.seek(size - window)
tail = file.read(window)
at = tail.rfind(ZIP_END, 0, len(tail) - 18)
while at >= 0 and at + 22 + int.from_bytes(tail[at + 20:at + 22], "little") != len(tail):
at = tail.rfind(ZIP_END, 0, at + 3)
if at < 0:
return None
total, length, offset = struct.unpack_from("<HII", tail, at + 10)
end = size - window + at
record = end - 20 - 56
if record < 0:
return end, length, offset
file.seek(end - 20)
if file.read(4) != ZIP64_LOCATOR:
return end, length, offset
file.seek(record)
zip64 = file.read(56)
if len(zip64) == 56 and zip64[:4] == ZIP64_END:
length, offset = struct.unpack_from("<QQ", zip64, 40)
return record, length, offset
if total == 0xFFFF or 0xFFFFFFFF in (length, offset):
return None
return end, length, offset
def _zip_unicode_path(raw: bytes, flags: int, extra: bytes):
"""An Info-ZIP Unicode Path when zip.js uses it: version 1, no UTF-8 flag, and the CRC-32 of the stored name."""
at = 0
while at + 4 <= len(extra):
kind, length = struct.unpack_from("<HH", extra, at)
if kind == 0x7075:
data = extra[at + 4:at + 4 + length]
usable = (length >= 5 and len(data) == length and data[0] == 1 and not flags & 0x800
and int.from_bytes(data[1:5], "little") == zlib.crc32(raw))
return data[5:] if usable else None
at += 4 + length
return None
def _zip_ends_in_slash(raw: bytes, flags: int, extra: bytes):
"""Whether an entry's name, as REA decodes it, ends in a slash; None when it must be UTF-8 and is not."""
utf8 = _zip_unicode_path(raw, flags, extra)
if utf8 is None and flags & 0x800:
utf8 = raw
if utf8 is None:
return raw.endswith(b"/")
try:
return utf8.decode("utf-8").endswith("/")
except UnicodeDecodeError:
return None
def _zip_directory(file, size: int, keep: int):
"""An archive's central directory read a record at a time, keeping the first file entries' records, as many as keep allows, and
counting the rest, as REA reads it: (start, declared offset, records, count), or None when it cannot be read.
Directories are told apart as zip.js tells them: a final slash, a Unix directory mode, or the MS-DOS attribute."""
located = _zip_end(file, size)
if located is None:
return None
end, length, declared = located
start = end - length
if start < 0:
return None
file.seek(start)
records, count, at = [], 0, start
while at < end:
fixed = file.read(46)
if at + 46 > end or len(fixed) < 46 or fixed[:4] != ZIP_CENTRAL:
return None
made_by, flags = struct.unpack_from("<H2xH", fixed, 4)
name_length, extra_length, comment_length = struct.unpack_from("<HHH", fixed, 28)
external = struct.unpack_from("<I", fixed, 38)[0]
rest = file.read(name_length + extra_length + comment_length)
at += 46 + name_length + extra_length + comment_length
if len(rest) < name_length + extra_length + comment_length or at > end:
return None
slash = _zip_ends_in_slash(rest[:name_length], flags, rest[name_length:name_length + extra_length])
if slash is None:
return None
if not (slash or (external >> 16) & 0o170000 == 0o040000 or (made_by >> 8 == 0 and external & 0x10)):
count += 1
if len(records) < keep:
records.append(fixed + rest)
return start, declared, records, count
class _BoundedArchive(io.RawIOBase):
"""An archive as zipfile reads it: its entries in place, then a directory of the kept records alone and end
records for them, so zipfile parses no more records than the view lists."""
def __init__(self, file, start: int, tail: bytes) -> None:
super().__init__()
self._file, self._start, self._tail, self._at = file, start, tail, 0
def readable(self) -> bool:
return True
def seekable(self) -> bool:
return True
def tell(self) -> int:
return self._at
def seek(self, offset: int, whence: int = 0) -> int:
self._at = offset + (0, self._at, self._start + len(self._tail))[whence]
return self._at
def readinto(self, buffer) -> int:
view = memoryview(buffer)
if self._at < self._start:
self._file.seek(self._at)
count = self._file.readinto(view[:self._start - self._at])
else:
chunk = self._tail[self._at - self._start:self._at - self._start + len(view)]
count = len(chunk)
view[:count] = chunk
self._at += count
return count
def _zip(file, size: int) -> dict:
"""A zip archive's file entries in archive order, up to REA's entry, size, ratio and archive limits; nothing is
extracted to disk, no archive inside is opened, and zipfile is shown only the directory records listed."""
entries, spent = [], 0
try:
directory = _zip_directory(file, size, MAX_ZIP_ENTRIES)
if directory is None:
raise zipfile.BadZipFile("no readable central directory")
start, declared, records, count = directory
kept = b"".join(records)
offset = declared if declared <= 0xFFFFFFFF else start
# zipfile follows a Zip64 locator signature wherever one sits before the end record, and the kept records
# may end in those bytes, so a real Zip64 end record and locator for them come first.
tail = (kept
+ struct.pack("<4sQ2H2I4Q", ZIP64_END, 44, 45, 45, 0, 0, len(records), len(records), len(kept), offset)
+ struct.pack("<4sIQI", ZIP64_LOCATOR, 0, offset + len(kept), 1)
+ struct.pack("<4s4H2IH", ZIP_END, 0, 0, len(records), len(records), len(kept), offset, 0))
with zipfile.ZipFile(_BoundedArchive(file, start, tail)) as archive:
for info in archive.infolist():
refusal = _zip_refusal(info, spent)
spent += info.file_size if refusal is None else 0
entries.append(_zip_entry(archive, info, refusal))
except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError, OSError, ValueError, struct.error):
return {"format": "zip", "view": None, "error": "not a readable zip archive"}
view = {"entries": entries, "entry_count": count, "truncated": count > len(entries)}
return {"format": "zip", "view": view, "truncated": view["truncated"]}
def _gunzip(data: bytes, limit: int):
"""A gzip stream's document, its members joined as REA joins them, or None once it passes limit bytes, where
decompressing stops: data after a member that starts with a zero byte is padding and ends the stream. It is read
a piece at a time, so a member's end carries over only the rest of its piece. Raises zlib.error or EOFError when
the stream is damaged or cut short."""
document, member, rest, at = bytearray(), zlib.decompressobj(16 + zlib.MAX_WBITS), b"", 0
while True:
if not rest:
if at >= len(data):
raise EOFError("the gzip stream is cut short")
rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK
document += member.decompress(rest, limit + 1 - len(document))
if len(document) > limit:
return None
if not member.eof:
rest = member.unconsumed_tail
continue
rest = member.unused_data
if not rest and at < len(data):
rest, at = data[at:at + GZIP_READ_CHUNK], at + GZIP_READ_CHUNK
if not rest or rest[0] == 0:
return bytes(document)
member = zlib.decompressobj(16 + zlib.MAX_WBITS)
def _gzip(name: str, data: bytes) -> dict:
"""A gzip file's view: its document's, decompressed within an archive entry's size and ratio limits and read by
the rules a file's follow; a database inside is not read."""
compressed = {"format": None, "compression": "gzip", "view": None}
try:
document = _gunzip(data, min(MAX_ZIP_ENTRY_BYTES, MAX_ZIP_RATIO * len(data)))
except (zlib.error, EOFError):
return {**compressed, "error": "not a readable gzip stream"}
if document is None:
return {**compressed, "error": f"expands more than {MAX_ZIP_RATIO} times, so it is not read"
if MAX_ZIP_RATIO * len(data) < MAX_ZIP_ENTRY_BYTES
else "larger than the 16 MiB a compressed document's view reads"}
for header, form, inside in NOT_READ_INSIDE:
if form != "zip" and document.startswith(header):
return {**compressed, "format": form, "error": f"{inside} inside a gzip file is not read"}
view = _zip(io.BytesIO(document), len(document)) if document.startswith(ZIP_HEADER) else _bytes_view(name, document)
return {**view, "compression": "gzip"}
@computer_app(supports=[{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64", "arm64"]}])
@linux(
packages=Packages(apt=["treeline"]),
launch=Launch(at="boot", command=["sh", "-c", "cd \"$HOME\" 2>/dev/null; exec 'treeline' \"$HOME\"/'Documents/reading-list.trln'"], window={"class": "treeline.py"}, ready=Ready(window=True)),
paths=PATHS,
skill="SKILL.md",
)
class Treeline(ComputerAppEnvironment):
"""TreeLine, launched at boot with the captured state in its home.
Declaring data hooks switches off agentenv's default data plane, so these call its helpers: the seed is kept as
the initial state, reset restores it, add writes files under PATHS, and get returns those files plus a typed JSON
view of each.
"""
def __init__(self) -> None:
super().__init__()
if not INITIAL.exists():
_seed_home(Path.home())
_load_dconf(Path.home())
keep_initial(self.paths)
@add_data
async def add_files(self, parts: list) -> None:
await add(parts, self.paths)
@get_data
async def get_files(self, write_namespace=None) -> list:
files = await get(self.paths, write_namespace)
views = await in_thread(_views, Path.home(), self.paths)
return [*files, DataPart(data={"state": views})]
@reset_data
async def reset_files(self) -> None:
await reset(self.paths)
@ready_check
def main_window_shown(self) -> bool:
"""A window of the app's class that the taskbar lists is shown, not only a splash screen or a dialog."""
return _taskbar_window(WINDOW_CLASS)
|