Skip to content

Commit 019fb78

Browse files
authored
fix: AOI export crashes: FILETIME overflow and unsafe attribute escaping
Fix AOI export crashes: FILETIME overflow and unsafe attribute escaping
2 parents 2280661 + 4931c05 commit 019fb78

2 files changed

Lines changed: 85 additions & 15 deletions

File tree

‎acd/l5x/elements.py‎

Lines changed: 43 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,27 @@
1616
from acd.l5x.port_structures import PORT_STRUCTURES
1717

1818

19+
# Characters that are illegal in XML 1.0: everything outside
20+
# #x9 | #xA | #xD | #x20-#xD7FF | #xE000-#xFFFD | #x10000-#x10FFFF.
21+
_XML_ILLEGAL_RE = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff]")
22+
23+
24+
def _escape_xml_attr(value: object) -> str:
25+
"""Escape a value for use inside a double-quoted XML attribute.
26+
27+
Beyond ``html.escape``, this strips characters that are illegal in XML 1.0
28+
and encodes the legal-but-delimiting whitespace (TAB/CR/LF) as numeric
29+
character references. Some binary records decode to garbage when an offset
30+
drifts (e.g. an AOI ``Vendor`` field read with ``errors="replace"``); without
31+
this, those raw control characters and newlines land verbatim in an
32+
attribute value, producing non-well-formed L5X that breaks downstream XML
33+
parsers.
34+
"""
35+
text = _XML_ILLEGAL_RE.sub("", str(value))
36+
text = html.escape(text, quote=True)
37+
return text.replace("\t", "	").replace("\r", "
").replace("\n", "
")
38+
39+
1940
@dataclass
2041
class L5xElementBuilder:
2142
_cur: Cursor
@@ -78,7 +99,7 @@ def to_xml(self) -> str:
7899
_overrides = getattr(self, "_xml_attr_overrides", {})
79100
xml_attr_name = _overrides.get(attribute, attribute.title().replace("_", ""))
80101
attribute_list.append(
81-
f'{xml_attr_name}="{html.escape(str(attribute_value), quote=True)}"'
102+
f'{xml_attr_name}="{_escape_xml_attr(attribute_value)}"'
82103
)
83104

84105
_export_name = (
@@ -611,7 +632,7 @@ def to_xml(self) -> str:
611632
if self._comm_method is not None:
612633
conn_parts: List[str] = []
613634
for (conn_name, rpi_str, conn_type) in self._connections:
614-
safe_name = html.escape(conn_name, quote=True)
635+
safe_name = _escape_xml_attr(conn_name)
615636
# Derive InputTag / OutputTag stubs based on connection type.
616637
if conn_type == "Output":
617638
tag_stubs = (
@@ -773,7 +794,7 @@ def to_xml(self) -> str:
773794
)
774795
if rung_xmls:
775796
rll_content = f'<RLLContent>{"".join(rung_xmls)}</RLLContent>'
776-
return f'<Routine Name="{html.escape(self.name, quote=True)}" Type="{self.type}">{rll_content}</Routine>'
797+
return f'<Routine Name="{_escape_xml_attr(self.name)}" Type="{self.type}">{rll_content}</Routine>'
777798

778799

779800
@dataclass
@@ -1884,6 +1905,23 @@ def _parse_fffeff(data: bytes, offset: int):
18841905
return s, offset + 4 + length * 2
18851906

18861907

1908+
def _filetime_to_iso(ft: int) -> str:
1909+
"""Convert a Windows FILETIME (100-ns units since 1601-01-01) to ISO8601.
1910+
1911+
Returns "" for an empty or out-of-range value. Some AOI nameless records
1912+
carry a corrupt FILETIME (the variable-length field walk can drift and read
1913+
8 garbage bytes), which would otherwise overflow ``datetime`` for years
1914+
beyond 9999 and abort the whole export with ``OverflowError``.
1915+
"""
1916+
if not ft:
1917+
return ""
1918+
try:
1919+
dt = datetime(1601, 1, 1) + timedelta(microseconds=ft // 10)
1920+
except (OverflowError, OSError):
1921+
return ""
1922+
return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
1923+
1924+
18871925
def _parse_aoi_nameless(data: bytes) -> dict:
18881926
"""Extract AOI metadata from its large nameless record."""
18891927
result: dict = {}
@@ -1912,12 +1950,7 @@ def _parse_aoi_nameless(data: bytes) -> dict:
19121950
_, offset = _parse_fffeff(data, offset)
19131951

19141952
# CreatedDate FILETIME (8 bytes, Windows FILETIME in 100-ns units)
1915-
ft = struct.unpack_from("<Q", data, offset)[0]
1916-
if ft:
1917-
dt = datetime(1601, 1, 1) + timedelta(microseconds=ft // 10)
1918-
result["created_date"] = dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
1919-
else:
1920-
result["created_date"] = ""
1953+
result["created_date"] = _filetime_to_iso(struct.unpack_from("<Q", data, offset)[0])
19211954
offset += 8
19221955

19231956
# EditedBy
@@ -1934,12 +1967,7 @@ def _parse_aoi_nameless(data: bytes) -> dict:
19341967
result["revision_extension"] = rev_ext or None
19351968

19361969
# EditedDate FILETIME (always last 8 bytes)
1937-
ft = struct.unpack_from("<Q", data, len(data) - 8)[0]
1938-
if ft:
1939-
dt = datetime(1601, 1, 1) + timedelta(microseconds=ft // 10)
1940-
result["edited_date"] = dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
1941-
else:
1942-
result["edited_date"] = ""
1970+
result["edited_date"] = _filetime_to_iso(struct.unpack_from("<Q", data, len(data) - 8)[0])
19431971

19441972
return result
19451973

‎test/test_elements_helpers.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from datetime import datetime
2+
from xml.dom import minidom
3+
4+
from acd.l5x.elements import _escape_xml_attr, _filetime_to_iso
5+
6+
7+
def test_filetime_to_iso_zero_is_empty():
8+
assert _filetime_to_iso(0) == ""
9+
10+
11+
def test_filetime_to_iso_valid_roundtrip():
12+
# 2020-01-01T00:00:00.000Z expressed as a Windows FILETIME (100-ns units
13+
# since 1601-01-01).
14+
ft = int((datetime(2020, 1, 1) - datetime(1601, 1, 1)).total_seconds()) * 10_000_000
15+
assert _filetime_to_iso(ft) == "2020-01-01T00:00:00.000Z"
16+
17+
18+
def test_filetime_to_iso_out_of_range_is_empty():
19+
# A corrupt/garbage FILETIME maps to a year far beyond datetime's 9999
20+
# ceiling; it must degrade to "" rather than raising OverflowError.
21+
assert _filetime_to_iso(0xFFFFFFFFFFFFFFFF) == ""
22+
23+
24+
def test_escape_xml_attr_basic_entities():
25+
assert _escape_xml_attr('a&b<c>d"e') == "a&amp;b&lt;c&gt;d&quot;e"
26+
27+
28+
def test_escape_xml_attr_strips_illegal_control_chars():
29+
assert _escape_xml_attr("a\x00\x15\x1fb") == "ab"
30+
31+
32+
def test_escape_xml_attr_encodes_whitespace_delimiters():
33+
assert _escape_xml_attr("a\tb\nc\rd") == "a&#x9;b&#xA;c&#xD;d"
34+
35+
36+
def test_escape_xml_attr_keeps_attribute_well_formed():
37+
# A mis-parsed binary field (e.g. an AOI Vendor) with a raw newline and
38+
# control bytes must not produce non-well-formed XML.
39+
garbage = "Acme\x15Corp\nv\t1.0\ufffd"
40+
xml = f'<AOI Vendor="{_escape_xml_attr(garbage)}"/>'
41+
parsed = minidom.parseString(xml) # raises on malformed XML
42+
assert parsed.documentElement.tagName == "AOI"

0 commit comments

Comments
 (0)