Skip to content

Commit 9bfaaa9

Browse files
committed
gh-162867: Make ftplib.parse227 parsing linear for malformed replies
1 parent 352cc06 commit 9bfaaa9

3 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎Lib/ftplib.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -818,7 +818,11 @@ def parse227(resp):
818818
global _227_re
819819
if _227_re is None:
820820
import re
821-
_227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)', re.ASCII)
821+
# The negative lookbehind keeps the search from retrying at every
822+
# digit of a long run, which made parsing quadratic for replies
823+
# that do not contain six comma-separated numbers (gh-162867).
824+
_227_re = re.compile(r'(?<!\d)(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)',
825+
re.ASCII)
822826
m = _227_re.search(resp)
823827
if not m:
824828
raise error_proto(resp)

‎Lib/test/test_ftplib.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1190,6 +1190,22 @@ def test__all__(self):
11901190
'ftpcp', 'test'}
11911191
support.check__all__(self, ftplib, not_exported=not_exported)
11921192

1193+
def test_parse227_long_octet(self):
1194+
# A digit boundary guard must not change the result for valid replies.
1195+
octet = '9' * 1000
1196+
self.assertEqual(
1197+
ftplib.parse227(f'227 Entering Passive Mode ({octet},2,3,4,5,6)'),
1198+
(f'{octet}.2.3.4', 1286))
1199+
1200+
def test_parse227_malformed_long_reply_is_linear(self):
1201+
# gh-162867: without a boundary guard the regex engine retried the
1202+
# match at every digit of a long run, making parsing quadratic.
1203+
resp = '227 ' + '1' * 50_000
1204+
start = time.perf_counter()
1205+
with self.assertRaises(ftplib.error_proto):
1206+
ftplib.parse227(resp)
1207+
self.assertLess(time.perf_counter() - start, 5.0)
1208+
11931209

11941210
class CommandLineTest(TestCase):
11951211
"""Tests for the ftplib command-line interface."""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix quadratic parsing time in :func:`ftplib.parse227` for malformed replies
2+
containing a long run of digits.

0 commit comments

Comments
 (0)