Skip to content

fix: Check for \r\n when reading the reply type header - #2941

Merged
michael-grunder merged 1 commit into
phpredis:developfrom
EJ-Research:fix-read-reply-type-crlf
Oct 1, 2026
Merged

michael-grunder merged 1 commit into
phpredis:developfrom
EJ-Research:fix-read-reply-type-crlf

Conversation

@EJ-Research

Copy link
Copy Markdown
Contributor

redis_read_reply_type() reads the INT, BULK and MULTIBULK header with redis_sock_get_line() and only checks for NULL. When read_timeout expires in the middle of that line, redis_sock_get_line() returns the part read so far, so :123 cut after :1 is parsed as 1. The connection stays open and the rest of the line is read as the reply to the next command.

6e13625 (#2899) added a CRLF check to redis_sock_gets(), which fixed the command specific readers. This caller was not changed, so rawCommand(), eval() and the other replies parsed by the generic reader are still affected. This PR reads the header with redis_sock_gets() instead. Because redis_sock_gets() strips the trailing \r\n, strtol() parses the same value as before.

Before and after

Tested on develop (bac0015) with PHP 8.4.18 CLI. The script at the end needs no Redis server. It starts a small fake server that pauses 1.5 s in the middle of a line, and the client uses a read_timeout of 1 s.

Case develop this PR
A. rawCommand, :123 cut after :1 returns 1 exception, disconnected
B. rawCommand, 3 element array with a length line cut returns ["aa","2"], then get('k2') returns 'cc' exception, disconnected
C. incr, :123 cut after :1 exception, disconnected exception, disconnected
D. get, error line of 4094 bytes followed by +INJECTED exception, disconnected exception, disconnected
Control, same replies sent whole correct correct

In case B the second get raises no error. It returns the last element of the previous reply as the value of k2. Cases C and D were fixed by 6e13625 and are included for reference.

Output

develop:

phpredis 6.3.0RC1, PHP 8.4.18
--- A_generic_int
  rawCommand ["X-INT"] -> returned 1  [1.0s, connected=true]
  get        ["k"]     -> RedisException: protocol error, got '2' as reply type byte  [0.5s, connected=true]
--- B_generic_multibulk
  rawCommand ["X-ARR"] -> returned ["aa","2"]  [1.5s, connected=true]
  get        ["k1"]    -> RedisException: protocol error, got 'b' as reply type byte  [0.0s, connected=true]
  get        ["k2"]    -> returned 'cc'  [0.0s, connected=true]
--- C_specific_int
  incr       ["n"]     -> RedisException: read error on connection to 127.0.0.1:37259  [1.0s, connected=false]
  get        ["k"]     -> RedisException: read error on connection to 127.0.0.1:37259  [0.5s, connected=false]
--- D_long_error_line
  get        ["k1"]    -> RedisException: read error on connection to 127.0.0.1:39795  [0.0s, connected=false]
  get        ["k2"]    -> RedisException: read error on connection to 127.0.0.1:39795  [0.0s, connected=false]
--- Z_control
  rawCommand ["X-INT"] -> returned 123  [0.0s, connected=true]
  incr       ["n"]     -> returned 123  [0.0s, connected=true]
  get        ["k"]     -> returned 'v1'  [0.0s, connected=true]

this PR:

phpredis 6.3.0RC1, PHP 8.4.18
--- A_generic_int
  rawCommand ["X-INT"] -> RedisException: read error on connection to 127.0.0.1:36153  [1.0s, connected=false]
  get        ["k"]     -> RedisException: read error on connection to 127.0.0.1:36153  [0.5s, connected=false]
--- B_generic_multibulk
  rawCommand ["X-ARR"] -> RedisException: protocol error, couldn't parse MULTI-BULK response  [1.0s, connected=false]
  get        ["k1"]    -> RedisException: read error on connection to 127.0.0.1:41979  [0.5s, connected=false]
  get        ["k2"]    -> RedisException: Redis server 127.0.0.1:41979 went away  [0.0s, connected=false, lastError=18 bytes]
--- C_specific_int
  incr       ["n"]     -> RedisException: read error on connection to 127.0.0.1:36307  [1.0s, connected=false]
  get        ["k"]     -> RedisException: read error on connection to 127.0.0.1:36307  [0.5s, connected=false]
--- D_long_error_line
  get        ["k1"]    -> RedisException: read error on connection to 127.0.0.1:42911  [0.0s, connected=false]
  get        ["k2"]    -> RedisException: read error on connection to 127.0.0.1:42911  [0.0s, connected=false]
--- Z_control
  rawCommand ["X-INT"] -> returned 123  [0.0s, connected=true]
  incr       ["n"]     -> returned 123  [0.0s, connected=true]
  get        ["k"]     -> returned 'v1'  [0.0s, connected=true]

The fake server accepts one connection only, so after phpredis disconnects the next command cannot reconnect. That comes from the test server, not from phpredis.

tests/TestRedis.php --class redis against Redis 7.4 gives the same result with and without this change: 211 passed, 20 failed, 42 skipped. The 20 failures are session tests that fail the same way on develop in my environment.

For 200 EVAL calls on one connection, strace -c counted 921 system calls on 6.3.0 and also 921 on 6.3.0 with 6e13625 and this change. When the reply is already buffered, the extra redis_check_eof() in redis_sock_gets() returns without a system call.

When the wrong reply reaches another request

I checked this with PHP's built in web server and two requests. The first request runs case B and then get('a') and get('b'). The second request runs get('c') and get('d').

Connection First request Second request
connect() get('b') returns "cc" correct
pconnect(), default settings get('b') returns "cc" correct, because the ECHO liveness check reads a stale reply, closes the socket and opens a new one
pconnect() with redis.pconnect.echo_check_liveness=0 or redis.pconnect.pooling_enabled=0 get('b') returns "cc" gets the first request's replies: get('c') returns "v-a" and get('d') returns "v-b"

Long running PHP processes (Swoole, RoadRunner, queue workers) that keep one Redis object, or a pool of them, across requests never go through that liveness check. The next user of the connection gets the leftover replies. That is where we ran into this.

6.3.0

6.3.0 has neither fix. There, a single error line longer than the reply buffer also leaves its tail on the socket. With Redis 7.4.11, eval('return redis.error_reply(ARGV[1])', [str_repeat('x', 4091) . '+INJECTED'], 0) makes the next get() on that connection return '+INJECTED'. A 6.3.x release with 6e13625 and this change would help.

Possibly the same problem in cluster code (not part of this PR)

cluster_send_direct() in cluster_library.c sends ASKING, READONLY, MULTI and DISCARD to a node and reads the rest of the +OK reply with redis_sock_gets_raw(). That helper calls redis_sock_get_line() directly, without the CRLF check. If a read timeout cuts that line, the rest of it probably stays on the node's socket and is read by the next command on that connection, the same way as above. I have not tested this path and it is outside the scope of this PR. It is worth a look in a separate change.

Reproduction script: php phpredis-repro.php
<?php
/*
 * Reply line cut short by a read timeout or by the line buffer size.
 * No Redis server needed: each case starts a small fake server (this same
 * file, run with "serve <case>") that writes fixed bytes, with a 1.5 s pause
 * in the middle of a line where noted. Client read_timeout is 1 s.
 *
 *   php phpredis-repro.php
 */

const READ_TIMEOUT = 1.0;
const PAUSE_SEC    = 1.5;

/* For each case: the commands the client sends, and for each command the
 * bytes the server writes back. null means pause. */
function cases(): array {
    return [
        // Generic reader (rawCommand, eval): ":123\r\n" cut after ":1"
        'A_generic_int' => [
            'cmds'  => [['rawCommand', ['X-INT']], ['get', ['k']]],
            'reply' => [[':1', null, "23\r\n"], ["\$2\r\nv1\r\n"]],
        ],
        // Generic reader: *3 [aa, bbbbbbbbbbbb, cc] with "$12" cut after "$1"
        'B_generic_multibulk' => [
            'cmds'  => [['rawCommand', ['X-ARR']], ['get', ['k1']], ['get', ['k2']]],
            'reply' => [["*3\r\n\$2\r\naa\r\n\$1", null, "2\r\nbbbbbbbbbbbb\r\n\$2\r\ncc\r\n"],
                        ["\$2\r\nv1\r\n"], ["\$2\r\nv2\r\n"]],
        ],
        // Command specific reader (INCR): ":123\r\n" cut after ":1"
        'C_specific_int' => [
            'cmds'  => [['incr', ['n']], ['get', ['k']]],
            'reply' => [[':1', null, "23\r\n"], ["\$2\r\nv1\r\n"]],
        ],
        // One error line longer than the line buffer, no pause:
        // 4094 bytes, then "+INJECTED"
        'D_long_error_line' => [
            'cmds'  => [['get', ['k1']], ['get', ['k2']]],
            'reply' => [['-ERR ' . str_repeat('x', 4089) . "+INJECTED\r\n"], ["\$2\r\nv2\r\n"]],
        ],
        // Control: whole replies, no pause
        'Z_control' => [
            'cmds'  => [['rawCommand', ['X-INT']], ['incr', ['n']], ['get', ['k']]],
            'reply' => [[":123\r\n"], [":123\r\n"], ["\$2\r\nv1\r\n"]],
        ],
    ];
}

/* Fake server (child process) */
if (($argv[1] ?? '') === 'serve') {
    $srv = stream_socket_server('tcp://127.0.0.1:0');
    echo substr(strrchr(stream_socket_get_name($srv, false), ':'), 1), "\n";
    fflush(STDOUT);
    $c = stream_socket_accept($srv, 10);
    foreach (cases()[$argv[2]]['reply'] as $parts) {
        readCommand($c);
        foreach ($parts as $p) {
            if ($p === null) {
                usleep((int) (PAUSE_SEC * 1e6));
                continue;
            }
            fwrite($c, $p);
            fflush($c);
        }
    }
    while (fgets($c) !== false) {
        // keep the socket open until the client closes it
    }
    exit(0);
}

/* Reads one RESP array command */
function readCommand($c): void {
    $hdr = fgets($c);
    if ($hdr === false || $hdr[0] !== '*') {
        return;
    }
    for ($i = 0, $n = (int) substr($hdr, 1); $i < $n; $i++) {
        $len = (int) substr(fgets($c), 1);
        fread($c, $len + 2);
    }
}

function show(mixed $v): string {
    return is_array($v) ? json_encode($v) : var_export($v, true);
}

/* Client */
echo 'phpredis ', phpversion('redis'), ', PHP ', PHP_VERSION, "\n";
foreach (array_keys(cases()) as $name) {
    $proc = proc_open([PHP_BINARY, __FILE__, 'serve', $name], [1 => ['pipe', 'w']], $pipes);
    $port = (int) fgets($pipes[1]);

    $r = new Redis();
    $r->connect('127.0.0.1', $port, 1.0, null, 0, READ_TIMEOUT);
    echo "--- $name\n";
    foreach (cases()[$name]['cmds'] as [$m, $args]) {
        $t = microtime(true);
        try {
            $out = 'returned ' . show($r->$m(...$args));
        } catch (Throwable $e) {
            $out = get_class($e) . ': ' . trim(substr($e->getMessage(), 0, 70));
        }
        $err = $r->getLastError();
        printf("  %-10s %-9s -> %s  [%.1fs, connected=%s%s]\n",
            $m, json_encode($args), $out, microtime(true) - $t,
            var_export($r->isConnected(), true),
            $err === null ? '' : ', lastError=' . strlen($err) . ' bytes');
    }
    $r->close();
    proc_terminate($proc, 9);
    proc_close($proc);
}

redis_read_reply_type() read the INT, BULK and MULTIBULK header with
redis_sock_get_line() and only checked for NULL. When read_timeout expires
in the middle of the line, the partial line is returned, so ":123" cut
after ":1" parses as 1 and the rest of the line is read as the reply to
the next command.

Use redis_sock_gets(), which since 6e13625 fails a line that does not
end in \r\n, disconnects and throws.
@michael-grunder
michael-grunder merged commit a0ded70 into phpredis:develop Oct 1, 2026
58 of 59 checks passed
@michael-grunder

Copy link
Copy Markdown
Member

Merged, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants