Skip to content

Commit c9676c5

Browse files
authored
fix(ftp,httpv1): FTP and HTTP/1 lines do not rebuild byte for byte (#1301)
1 parent 3cffc93 commit c9676c5

6 files changed

Lines changed: 277 additions & 31 deletions

File tree

‎pcapkit/protocols/application/ftp.py‎

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from pcapkit.protocols.data.application.ftp import Response as Data_Response
2727
from pcapkit.protocols.misc.raw import Raw
2828
from pcapkit.protocols.schema.application.ftp import FTP as Schema_FTP
29+
from pcapkit.utilities.chardet import detect
2930
from pcapkit.utilities.compat import StrEnum, auto
3031
from pcapkit.utilities.exceptions import ProtocolError, UnsupportedCall
3132

@@ -36,9 +37,16 @@
3637

3738
__all__ = ['FTP', 'FTP_DATA']
3839

39-
# regex for FTP
40-
FTP_REQUEST = re.compile(rb'^(?P<cmmd>[A-Z]{3,4})( +(?P<args>.*))?\r\n$', re.I)
41-
FTP_RESPONSE = re.compile(rb'^(?P<code>[0-9]{3})(?P<more>\-)?( +(?P<args>.*))?\r\n$', re.I)
40+
# regex for FTP, per :rfc:`959#section-4` (replies) and :rfc:`959#section-5`
41+
# (commands): a command is ``<command> [<SP> <argument>] <CRLF>``, a reply line is
42+
# ``<code> [<SP> <text>] <CRLF>``, and the first line of a multi-line reply is
43+
# ``<code>-<text> <CRLF>`` with the text following the hyphen immediately. Only
44+
# the one separating SP is syntax; anything after it is the argument verbatim, so
45+
# that ``make`` writes back exactly the line that was read. ``\Z`` rather than
46+
# ``$``, which would also match before a trailing ``\n`` left outside the match.
47+
FTP_REQUEST = re.compile(rb'^(?P<cmmd>[A-Z]{3,4})(?: (?P<args>.*))?\r\n\Z', re.I)
48+
FTP_RESPONSE = re.compile(rb'^(?P<code>[0-9]{3})'
49+
rb'(?:(?P<more>-)(?P<text>.*)|(?: (?P<args>.*))?)\r\n\Z', re.I)
4250

4351

4452
class Type(EnumLookup, StrEnum):
@@ -107,26 +115,28 @@ def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_FTP':
107115
args = match.group('args')
108116

109117
cmmd_val = Enum_Command.get(cmmd)
110-
args_val = self.decode(args)
118+
args_val, charset = self._decode_args(args)
111119

112120
ftp = Data_Request(
113121
type=Type.REQUEST,
114122
cmmd=cmmd_val,
115123
args=args_val,
124+
charset=charset,
116125
) # type: Data_FTP
117126
elif (match := FTP_RESPONSE.match(data)) is not None:
118127
code = int(match.group('code'))
119128
more = bool(match.group('more'))
120-
args = match.group('args')
129+
args = match.group('text') if more else match.group('args')
121130

122131
code_val = Enum_ReturnCode.get(code)
123-
args_val = self.decode(args)
132+
args_val, charset = self._decode_args(args)
124133

125134
ftp = Data_Response(
126135
type=Type.RESPONSE,
127136
code=code_val,
128137
more=more,
129138
args=args_val,
139+
charset=charset,
130140
)
131141
else:
132142
raise ProtocolError('FTP: invalid packet format')
@@ -137,14 +147,21 @@ def make(self,
137147
code: 'Optional[Enum_ReturnCode | int | str | bytes]' = None,
138148
args: 'Optional[str | bytes]' = None,
139149
more: 'bool' = False,
150+
charset: 'Optional[str]' = None,
140151
**kwargs: 'Any') -> 'Schema_FTP':
141152
"""Make (construct) packet data.
142153
154+
The line is terminated with CRLF. Arguments of :obj:`None` write no
155+
argument and no separator; otherwise a single SP separates them from
156+
the command or code, except after the hyphen of a multi-line reply,
157+
which the text follows immediately (:rfc:`959#section-4`).
158+
143159
Args:
144160
cmmd: FTP command.
145161
code: FTP status code.
146162
args: Optional FTP command arguments and/or status messages.
147163
more: More status messages to follow for response packets.
164+
charset: Encoding for :obj:`str` arguments, **UTF-8** if not given.
148165
**kwargs: Arbitrary keyword arguments.
149166
150167
Returns:
@@ -173,10 +190,12 @@ def make(self,
173190
elif isinstance(args, bytes):
174191
suffix = args
175192
else:
176-
suffix = args.encode()
193+
suffix = args.encode(charset or 'utf-8')
177194

195+
# the separating SP, absent with no arguments and after a hyphen
196+
sep = b'' if args is None or mf else b' '
178197
return Schema_FTP(
179-
data=b'%s%s %s' % (prefix, mf, suffix),
198+
data=b'%s%s%s%s\r\n' % (prefix, mf, sep, suffix),
180199
)
181200

182201
##########################################################################
@@ -199,8 +218,38 @@ def _make_data(cls, data: 'Data_FTP') -> 'dict[str, Any]': # type: ignore[overr
199218
'code': getattr(data, 'code', None),
200219
'args': getattr(data, 'args', None),
201220
'more': getattr(data, 'more', False),
221+
'charset': getattr(data, 'charset', None),
202222
}
203223

224+
def _decode_args(self, args: 'Optional[bytes]') -> 'tuple[Optional[str], Optional[str]]':
225+
"""Decode arguments, recording how to encode them back.
226+
227+
The arguments are decoded by :meth:`self.decode
228+
<pcapkit.protocols.protocol.Protocol.decode>`. Where the result does
229+
not encode back to ``args`` as UTF-8 -- which :meth:`make` uses by
230+
default -- the detected charset is returned with it, or ``'latin-1'``
231+
(decoding again) if that does not reproduce ``args`` either, so that the
232+
original octets survive a rebuild.
233+
234+
Args:
235+
args: Raw arguments, :obj:`None` if the line carries none.
236+
237+
Returns:
238+
The decoded arguments and the charset to encode them with, the
239+
latter :obj:`None` for UTF-8.
240+
241+
"""
242+
if args is None:
243+
return None, None
244+
value = self.decode(args)
245+
for charset in (None, detect(args)):
246+
try:
247+
if value.encode(charset or 'utf-8') == args:
248+
return value, charset
249+
except (LookupError, UnicodeError):
250+
pass
251+
return args.decode('latin-1'), 'latin-1'
252+
204253

205254
class FTP_DATA(Raw):
206255
"""This class implements FTP data channel transmission."""

‎pcapkit/protocols/application/httpv1.py‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from pcapkit.protocols.data.application.httpv1 import RequestHeader as Data_RequestHeader
4141
from pcapkit.protocols.data.application.httpv1 import ResponseHeader as Data_ResponseHeader
4242
from pcapkit.protocols.schema.application.httpv1 import HTTP as Schema_HTTP
43+
from pcapkit.utilities.chardet import detect
4344
from pcapkit.utilities.compat import StrEnum, auto
4445
from pcapkit.utilities.exceptions import ProtocolError
4546

@@ -259,6 +260,7 @@ def make(self, # type: ignore[override]
259260
message: 'Optional[str | bytes]' = None,
260261
headers: 'Optional[OrderedMultiDict[str, str]]' = None,
261262
body: 'bytes' = b'',
263+
charset: 'Optional[str]' = None,
262264
**kwargs: 'Any') -> 'Schema_HTTP':
263265
"""Make (construct) packet data.
264266
@@ -273,6 +275,8 @@ def make(self, # type: ignore[override]
273275
message: HTTP status message.
274276
headers: HTTP headers.
275277
body: HTTP body.
278+
charset: Encoding for a :obj:`str` request URI or status message,
279+
**UTF-8** if not given.
276280
**kwargs: Arbitrary keyword arguments.
277281
278282
Returns:
@@ -292,7 +296,7 @@ def make(self, # type: ignore[override]
292296
meth = method.encode()
293297
else:
294298
meth = method.value.encode()
295-
uri_val = uri.encode() if isinstance(uri, str) else uri
299+
uri_val = uri.encode(charset or 'utf-8') if isinstance(uri, str) else uri
296300

297301
header_line = b'%s %s HTTP/%s\r\n' % (meth, uri_val, version)
298302
elif method is None and status is not None:
@@ -303,7 +307,7 @@ def make(self, # type: ignore[override]
303307
if message is None:
304308
msg = getattr(status, 'message', None) or getattr(status_code, 'message', b'') or b''
305309
else:
306-
msg = message.encode() if isinstance(message, str) else message
310+
msg = message.encode(charset or 'utf-8') if isinstance(message, str) else message
307311
if isinstance(msg, str):
308312
msg = msg.encode()
309313

@@ -357,8 +361,36 @@ def _make_data(cls, data: 'Data_HTTP') -> 'dict[str, Any]': # type: ignore[over
357361
'message': getattr(data.receipt, 'message', None),
358362
'headers': data.header,
359363
'body': b'' if data.body is None else data.body,
364+
'charset': getattr(data.receipt, 'charset', None),
360365
}
361366

367+
def _decode_text(self, text: 'bytes') -> 'tuple[str, Optional[str]]':
368+
"""Decode start-line text, recording how to encode it back.
369+
370+
The text is decoded by :meth:`self.decode
371+
<pcapkit.protocols.protocol.Protocol.decode>`. Where the result does
372+
not encode back to ``text`` as UTF-8 -- which :meth:`make` uses by
373+
default -- the detected charset is returned with it, or ``'latin-1'``
374+
(decoding again) if that does not reproduce ``text`` either, so that the
375+
original octets survive a rebuild.
376+
377+
Args:
378+
text: Raw request URI or status message.
379+
380+
Returns:
381+
The decoded text and the charset to encode it with, the latter
382+
:obj:`None` for UTF-8.
383+
384+
"""
385+
value = self.decode(text)
386+
for charset in (None, detect(text)):
387+
try:
388+
if value.encode(charset or 'utf-8') == text:
389+
return value, charset
390+
except (LookupError, UnicodeError):
391+
pass
392+
return text.decode('latin-1'), 'latin-1'
393+
362394
def _read_http_header(self, header: 'bytes') -> 'tuple[Data_Header, OrderedMultiDict[str, str]]':
363395
"""Read HTTP/1.* header.
364396
@@ -448,18 +480,22 @@ def _read_http_header(self, header: 'bytes') -> 'tuple[Data_Header, OrderedMulti
448480
match3 = re.match(_RE_VERSION, para1)
449481
match4 = re.match(_RE_STATUS, para2)
450482
if match1 and match2:
483+
uri, charset = self._decode_text(para2)
451484
header_line = Data_RequestHeader(
452485
type=Type.REQUEST,
453486
method=Enum_Method.get(self.decode(match1.group('method'))),
454-
uri=self.decode(para2),
487+
uri=uri,
455488
version=self.decode(match2.group('version')),
489+
charset=charset,
456490
)
457491
elif match3 and match4:
492+
message, charset = self._decode_text(para3)
458493
header_line = Data_ResponseHeader(
459494
type=Type.RESPONSE,
460495
version=self.decode(match3.group('version')),
461496
status=Enum_StatusCode.get(int(para2)),
462-
message=self.decode(para3),
497+
message=message,
498+
charset=charset,
463499
)
464500
else:
465501
raise ProtocolError('HTTP: invalid format')

‎pcapkit/protocols/data/application/ftp.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from pcapkit.protocols.data.protocol import Protocol
99

1010
if TYPE_CHECKING:
11+
from typing import Optional
12+
1113
from typing_extensions import Literal
1214

1315
from pcapkit.const.ftp.command import Command
@@ -35,11 +37,13 @@ class Request(FTP):
3537
type: 'Literal[FTP_Type.REQUEST]'
3638
#: Command.
3739
cmmd: 'Command'
38-
#: Arguments.
39-
args: 'str'
40+
#: Arguments, :obj:`None` if the command carries none.
41+
args: 'Optional[str]'
42+
#: Charset to encode :attr:`args` with, :obj:`None` for UTF-8.
43+
charset: 'Optional[str]'
4044

4145
if TYPE_CHECKING:
42-
def __init__(self, type: 'Literal[FTP_Type.REQUEST]', cmmd: 'Command', args: 'str') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
46+
def __init__(self, type: 'Literal[FTP_Type.REQUEST]', cmmd: 'Command', args: 'Optional[str]', charset: 'Optional[str]') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
4347

4448

4549
@info_final
@@ -50,10 +54,12 @@ class Response(FTP):
5054
type: 'Literal[FTP_Type.RESPONSE]'
5155
#: Return code.
5256
code: 'ReturnCode'
53-
#: Arguments.
54-
args: 'str'
57+
#: Arguments, :obj:`None` if the reply carries no text.
58+
args: 'Optional[str]'
5559
#: More data flag.
5660
more: 'bool'
61+
#: Charset to encode :attr:`args` with, :obj:`None` for UTF-8.
62+
charset: 'Optional[str]'
5763

5864
if TYPE_CHECKING:
59-
def __init__(self, type: 'Literal[FTP_Type.RESPONSE]', code: 'ReturnCode', args: 'str', more: 'bool') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
65+
def __init__(self, type: 'Literal[FTP_Type.RESPONSE]', code: 'ReturnCode', args: 'Optional[str]', more: 'bool', charset: 'Optional[str]') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin

‎pcapkit/protocols/data/application/httpv1.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from pcapkit.protocols.data.protocol import Protocol
99

1010
if TYPE_CHECKING:
11-
from typing import Any
11+
from typing import Any, Optional
1212

1313
from pcapkit.const.http.method import Method as Enum_Method
1414
from pcapkit.const.http.status_code import StatusCode as Enum_StatusCode
@@ -57,9 +57,11 @@ class RequestHeader(Header):
5757
uri: 'str'
5858
#: HTTP request version.
5959
version: 'str'
60+
#: Charset to encode :attr:`uri` with, :obj:`None` for UTF-8.
61+
charset: 'Optional[str]'
6062

6163
if TYPE_CHECKING:
62-
def __init__(self, type: 'HTTP_Type', method: 'Enum_Method', uri: 'str', version: 'str') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
64+
def __init__(self, type: 'HTTP_Type', method: 'Enum_Method', uri: 'str', version: 'str', charset: 'Optional[str]') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
6365

6466

6567
@info_final
@@ -74,6 +76,8 @@ class ResponseHeader(Header):
7476
status: 'Enum_StatusCode'
7577
#: HTTP response status message.
7678
message: 'str'
79+
#: Charset to encode :attr:`message` with, :obj:`None` for UTF-8.
80+
charset: 'Optional[str]'
7781

7882
if TYPE_CHECKING:
79-
def __init__(self, type: 'HTTP_Type', version: 'str', status: 'Enum_StatusCode', message: 'str') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
83+
def __init__(self, type: 'HTTP_Type', version: 'str', status: 'Enum_StatusCode', message: 'str', charset: 'Optional[str]') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin

0 commit comments

Comments
 (0)