Skip to content

Commit e28a639

Browse files
committed
fix(corekit): StringField is not lossless: guessed charset, U+FFFD substitution, and a character-count length
- Decoding falls back to 'surrogateescape' instead of 'replace', so an undecodable octet is kept and re-emitted; the docstring now says the field never raises on decode, rather than claiming 'strict' raises. - Whenever re-encoding the decoded text would not reproduce its octets (a detected non-UTF-8 charset, a lossy errors scheme, a URL quoting that differs), post_process returns a DecodedString, a str subclass carrying the raw octets, which pre_process packs back verbatim. - length=-1 now resolves to the encoded octet count. Closes #1293
1 parent 11ae68e commit e28a639

2 files changed

Lines changed: 177 additions & 16 deletions

File tree

‎pcapkit/corekit/fields/strings.py‎

Lines changed: 90 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
__all__ = [
1313
'_TextField',
1414
'StringField',
15+
'DecodedString',
1516
'BitField',
1617
'PaddingField',
1718
]
@@ -101,20 +102,31 @@ class StringField(_TextField[str]):
101102
length: Field size (in bytes); if a callable is given, it should return
102103
an integer value and accept the current packet as its only argument.
103104
default: Field default value, if any.
104-
encoding: The encoding with which to decode the :obj:`bytes`.
105-
If not provided, :mod:`pcapkit` will first try detecting its encoding
106-
using |chardet|_. The fallback encoding is **UTF-8**.
107-
errors: The error handling scheme to use for the handling of decoding errors.
108-
The default is ``'strict'`` meaning that decoding errors raise a
109-
:exc:`UnicodeDecodeError`. Other possible values are ``'ignore'`` and ``'replace'``
110-
as well as any other name registered with :func:`codecs.register_error` that
111-
can handle :exc:`UnicodeDecodeError`.
105+
encoding: The encoding with which to decode the :obj:`bytes`, and to
106+
encode a :obj:`str` when packing. If not provided, :mod:`pcapkit` will
107+
first try detecting its encoding using |chardet|_. The fallback
108+
encoding is **UTF-8**, which is also the encoding a plain :obj:`str`
109+
is packed with.
110+
errors: The error handling scheme to try first when decoding and encoding.
111+
Should it fail -- ``'strict'``, the default, fails on any octet the
112+
encoding cannot decode -- the field falls back to ``'surrogateescape'``
113+
rather than raising, so an undecodable octet is kept as a lone
114+
surrogate and re-emitted as the same octet. Other possible values are
115+
``'ignore'`` and ``'replace'`` as well as any other name registered
116+
with :func:`codecs.register_error`.
112117
unquote: Whether to unquote the decoded string as a URL. Should decoding fail,
113118
the method will try again replacing ``'%'`` with ``'\x'`` then decoding the
114-
``url`` as ``'utf-8'`` with ``'replace'`` for error handling.
119+
``url`` as ``'utf-8'`` with ``'surrogateescape'`` for error handling.
115120
callback: Callback function to be called upon
116121
:meth:`self.__call__ <pcapkit.corekit.fields.field.FieldBase.__call__>`.
117122
123+
Unpacking is lossless: whenever re-encoding the decoded :obj:`str` would
124+
not reproduce the octets it came from -- a detected charset other than
125+
UTF-8, a lossy ``errors`` scheme, or a URL quoting that differs from the
126+
original -- the field returns a :class:`DecodedString`, which remembers those
127+
octets and is packed back as them. A length of ``-1`` is resolved to the
128+
number of *encoded* octets.
129+
118130
.. |chardet| replace:: ``chardet``
119131
.. _chardet: https://chardet.readthedocs.io
120132
@@ -131,6 +143,27 @@ def __init__(self, length: 'int | Callable[[dict[str, Any]], int]',
131143
self._errors = errors
132144
self._unquote = unquote
133145

146+
def _encode(self, value: 'str') -> 'bytes':
147+
"""Encode a :obj:`str` value as the field would pack it.
148+
149+
Arguments:
150+
value: Field value.
151+
152+
Returns:
153+
Encoded field value.
154+
155+
"""
156+
encoding = self._encoding or 'utf-8'
157+
if self._unquote:
158+
try:
159+
value = urllib_parse.quote(value, encoding=encoding, errors=self._errors)
160+
except UnicodeError:
161+
value = urllib_parse.quote(value, encoding=encoding, errors='surrogateescape')
162+
try:
163+
return value.encode(encoding, self._errors)
164+
except UnicodeError:
165+
return value.encode(encoding, 'surrogateescape')
166+
134167
def pre_process(self, value: 'str', packet: 'dict[str, Any]') -> 'bytes': # pylint: disable=unused-argument
135168
"""Process field value before construction (packing).
136169
@@ -142,13 +175,15 @@ def pre_process(self, value: 'str', packet: 'dict[str, Any]') -> 'bytes': # pyl
142175
Processed field value.
143176
144177
"""
145-
if self._unquote:
146-
value = urllib_parse.quote(value, encoding=self._encoding or 'utf-8', errors=self._errors)
178+
if isinstance(value, DecodedString):
179+
buffer = value.raw
180+
else:
181+
buffer = self._encode(value)
147182

148183
if self._length < 0:
149-
self._length = len(value)
184+
self._length = len(buffer)
150185
self._template = f'{self._length}s'
151-
return value.encode(self._encoding or 'utf-8', self._errors)
186+
return buffer
152187

153188
def post_process(self, value: 'bytes', packet: 'dict[str, Any]') -> 'str': # pylint: disable=unused-argument
154189
"""Process field value after parsing (unpacked).
@@ -158,23 +193,62 @@ def post_process(self, value: 'bytes', packet: 'dict[str, Any]') -> 'str': # py
158193
packet: Packet data.
159194
160195
Returns:
161-
Processed field value.
196+
Processed field value; a :class:`DecodedString` carrying ``value``
197+
if :meth:`pre_process` would not otherwise reproduce it.
162198
163199
"""
164200
if self._unquote:
165201
try:
166202
ret = urllib_parse.unquote(value, encoding=self._encoding or 'utf-8', errors=self._errors)
167203
except UnicodeError:
168-
ret = urllib_parse.unquote(value.replace(b'%', rb'\x'), encoding='utf-8', errors='replace')
204+
ret = urllib_parse.unquote(value.replace(b'%', rb'\x'), encoding='utf-8',
205+
errors='surrogateescape')
169206
else:
170207
charset = self._encoding or detect(value)
171208
try:
172209
ret = value.decode(charset, self._errors)
173210
except UnicodeError:
174-
ret = value.decode(charset, 'replace')
211+
# NOTE: A detected charset may be one ``'surrogateescape'``
212+
# cannot recover (UTF-16 cannot escape an ASCII octet), so the
213+
# fallback decodes with the field's own encoding instead.
214+
ret = value.decode(self._encoding or 'utf-8', 'surrogateescape')
215+
216+
try:
217+
lossless = self._encode(ret) == value
218+
except UnicodeError:
219+
lossless = False
220+
if not lossless:
221+
return DecodedString(ret, value)
175222
return ret
176223

177224

225+
class DecodedString(str):
226+
"""Decoded :class:`StringField` value that remembers its octets.
227+
228+
:class:`StringField` returns one when packing the decoded text would not
229+
reproduce the octets it was decoded from, so that the field packs it back
230+
as exactly those octets. It is otherwise an ordinary :obj:`str`; any string
231+
operation on it returns a plain :obj:`str`, which is then packed with the
232+
field's own encoding.
233+
234+
Args:
235+
value: Decoded text.
236+
raw: Octets ``value`` was decoded from.
237+
238+
"""
239+
240+
#: Octets the string was decoded from.
241+
raw: 'bytes'
242+
243+
def __new__(cls, value: 'str', raw: 'bytes') -> 'Self':
244+
self = super().__new__(cls, value)
245+
self.raw = raw
246+
return self
247+
248+
def __getnewargs__(self) -> 'tuple[str, bytes]': # type: ignore[override]
249+
return str(self), self.raw
250+
251+
178252
class BitField(_TextField[Dict[str, Any]]):
179253
"""Bit value for protocol fields.
180254
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# -*- coding: utf-8 -*-
2+
"""StringField packs back exactly the octets it unpacked.
3+
4+
GitHub issue #1293: :class:`~pcapkit.corekit.fields.strings.StringField` was
5+
lossy three ways. Without an ``encoding`` it decoded with the charset
6+
:func:`~pcapkit.utilities.chardet.detect` guessed and packed the text back as
7+
UTF-8; an undecodable octet fell back to ``'replace'`` and became U+FFFD even
8+
under the default ``errors='strict'``; and a length of ``-1`` was taken from
9+
the *character* count, so multi-octet text lost its tail.
10+
11+
:mod:`pcapkit` is imported inside each test, after
12+
:func:`~tests._support.reimport_once_per_class`, not at module load.
13+
14+
"""
15+
16+
import copy
17+
import pickle
18+
import unittest
19+
20+
from tests._support import reimport_once_per_class
21+
22+
23+
class TestStringFieldLossless(unittest.TestCase):
24+
"""Pin ``pack(unpack(octets)) == octets`` for :class:`StringField`."""
25+
26+
def setUp(self) -> None:
27+
reimport_once_per_class(self)
28+
29+
def roundtrip(self, octets: bytes, **kwargs: object) -> 'tuple[object, bytes]':
30+
from pcapkit.corekit.fields.strings import StringField
31+
32+
field = StringField(length=len(octets), **kwargs) # type: ignore[arg-type]
33+
value = field.unpack(octets, {})
34+
return value, field.pack(value, {})
35+
36+
def test_detected_charset_is_reused_on_pack(self) -> None:
37+
value, packed = self.roundtrip(bytes.fromhex('e974e9'))
38+
self.assertEqual(packed.hex(), 'e974e9')
39+
self.assertEqual(value, 'été')
40+
41+
def test_undecodable_octet_is_kept_under_strict(self) -> None:
42+
value, packed = self.roundtrip(bytes.fromhex('e974e9'), encoding='utf-8')
43+
self.assertEqual(packed.hex(), 'e974e9')
44+
self.assertNotIn('�', value) # type: ignore[operator]
45+
46+
def test_lossy_errors_scheme_still_round_trips(self) -> None:
47+
for errors in ('replace', 'ignore'):
48+
with self.subTest(errors=errors):
49+
_, packed = self.roundtrip(b'a\xffb', encoding='utf-8', errors=errors)
50+
self.assertEqual(packed, b'a\xffb')
51+
52+
def test_valid_text_decodes_to_a_plain_str(self) -> None:
53+
value, packed = self.roundtrip('héllo'.encode())
54+
self.assertIs(type(value), str)
55+
self.assertEqual(value, 'héllo')
56+
self.assertEqual(packed, 'héllo'.encode())
57+
58+
def test_unquote_keeps_the_original_quoting(self) -> None:
59+
value, packed = self.roundtrip(b'a%2fb%2F', unquote=True)
60+
self.assertEqual(value, 'a/b/')
61+
self.assertEqual(packed, b'a%2fb%2F')
62+
63+
def test_variable_length_counts_encoded_octets(self) -> None:
64+
from pcapkit.corekit.fields.strings import StringField
65+
66+
self.assertEqual(StringField(length=-1).pack('héllo', {}), 'héllo'.encode())
67+
68+
def test_edited_value_packs_with_the_field_encoding(self) -> None:
69+
from pcapkit.corekit.fields.strings import StringField
70+
71+
field = StringField(length=-1)
72+
value = StringField(length=3).unpack(bytes.fromhex('e974e9'), {})
73+
self.assertEqual(field.pack(value.upper(), {}), 'ÉTÉ'.encode()) # type: ignore[attr-defined]
74+
75+
def test_decoded_string_survives_copy_and_pickle(self) -> None:
76+
from pcapkit.corekit.fields.strings import StringField
77+
78+
field = StringField(length=3)
79+
value = field.unpack(bytes.fromhex('e974e9'), {})
80+
for clone in (copy.copy(value), copy.deepcopy(value), pickle.loads(pickle.dumps(value))):
81+
with self.subTest(clone=type(clone).__name__):
82+
self.assertEqual(clone, 'été')
83+
self.assertEqual(field.pack(clone, {}).hex(), 'e974e9')
84+
85+
86+
if __name__ == '__main__':
87+
unittest.main()

0 commit comments

Comments
 (0)