2626from pcapkit .protocols .data .application .ftp import Response as Data_Response
2727from pcapkit .protocols .misc .raw import Raw
2828from pcapkit .protocols .schema .application .ftp import FTP as Schema_FTP
29+ from pcapkit .utilities .chardet import detect
2930from pcapkit .utilities .compat import StrEnum , auto
3031from pcapkit .utilities .exceptions import ProtocolError , UnsupportedCall
3132
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
4452class 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
205254class FTP_DATA (Raw ):
206255 """This class implements FTP data channel transmission."""
0 commit comments