php-imap icon indicating copy to clipboard operation
php-imap copied to clipboard

Error token length mismatch in readResponse

Open michalkkkd opened this issue 2 years ago • 1 comments

Describe the bug readResponse method in ImapProtocol class, parses token by 2 chars, but later checks for 2 & 3 chars. I'm not sure how to fix this in accordance with the protocol

Code to Reproduce See comments with // PROBLEM

public function readResponse(Response $response, string $tag, bool $dontParse = false): array {
        $lines = [];
        $tokens = ""; // define $tokens variable before first use
        do {
            $readAll = $this->readLine($response, $tokens, $tag, $dontParse);
            $lines[] = $tokens;
        } while (!$readAll);

        if ($dontParse) {
            // First two chars are still needed for the response code
            $tokens = [substr($tokens, 0, 2)];
            // PROBLEM this will always result in $tokens[0], having 2 chars
        }

        // last line has response code
        if ($tokens[0] == 'OK') {
            return $lines ?: [true];
            // PROBLEM So this check for BAD or BYE will never happen
        } elseif ($tokens[0] == 'NO' || $tokens[0] == 'BAD' || $tokens[0] == 'BYE') {
            throw new ImapServerErrorException();
        }

        throw new ImapBadRequestException();
    }

Expected behavior Correct handling of error tokens.

Desktop / Server (please complete the following information):

  • Version 5.2.0

michalkkkd avatar Apr 26 '23 23:04 michalkkkd

Hi @michalkkkd, thanks a lot for reporting this issue. I really appreciate it!

I just pushed a fix. I've decided to use:

$tokens = [trim(substr($tokens, 0, 3))];

Since the $tokens variable could contain string like thsese:

OK [UIDNEXT 1] Predicted next UID
NO [UNAVAILABLE] User's backend down for maintenance
BAD [COMMAND] Error

Once again, thanks for taking the time and effort to make this library better!

Best regards and happy coding,

Webklex avatar Jun 27 '23 00:06 Webklex