Skip to content

Commit fdccbb0

Browse files
committed
sprintf(): prevent %c from getting past the check
- a run of ' in a format made the %c regex backtrack until PCRE gave up, and the check read that as "no %c", so a later %c reached sprintf() - each ' now only matches as a padding pair, so a format is scanned once, and a PCRE failure throws like a %c does
1 parent 5765e30 commit fdccbb0

2 files changed

Lines changed: 7 additions & 1 deletion

File tree

‎src/Deprecations.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,9 @@ public function sprintf(string $format): SmartArray
207207
// recreating markup after HTML encoding. Every other conversion emits only
208208
// digits/letters or the substituted string.
209209
$scan = str_replace('%%', '', $format); // %% is literal text, not a directive
210-
if (preg_match('/%(?:\'.|[^a-z])*l?c/s', $scan)) { // matches variations of %c: %lc, %1$c, %*c, %.c, %'x5c
210+
// Matches variations of %c: %lc, %1$c, %*c, %.c, %'x5c. A ' only matches as a padding pair, so
211+
// there's one way to read any format, and a false (PCRE gave up) refuses like a match does
212+
if (preg_match('/%(?:\'.|[^a-z\'%])*+l?c/s', $scan) !== 0) {
211213
throw new InvalidArgumentException("sprintf(): %c is not supported - it converts numbers to raw characters after HTML encoding");
212214
}
213215

‎tests/Unit/DeprecationsTest.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,10 @@ public function testSprintfRejectsPercentC(string $class): void
306306
$sa = $class::new([60, 62]);
307307

308308
$formats = ['%c', '%1$c', '%2$c', "%'x5c", '%-5c', '%lc', '%1$lc', '%5.2lc', "%'\n3c", '%*c', '%1$*c', '%.c', '%.*c'];
309+
310+
// a long run of ' padding flags before a %c: the regex has to read each ' one way, or PCRE
311+
// gives up on this format and the %c gets through
312+
$formats[] = '%' . str_repeat("'", 28) . 'sx %1$c';
309313
foreach ($formats as $format) {
310314
try {
311315
$sa->sprintf($format);

0 commit comments

Comments
 (0)