Josep Sanz Campderrós - 2024-11-04 09:40:56
Some time strangers mailers generates an encoded part for attachments in base64 wrapping the contents into chunks of size not module 4, causing an error in the decoding part.
I propose a fix to detect this cases and only decodes the mod 4 part of the message and store the other bytes into a temporary variable that can be added at the start of the next chunk to repeat the previous process (only decode the mod 4 part of the new part).
This case was detected with an email that contains a chunks of 998 bytes of base64 data in the first chunk and 997 bytes of base64 data in the others chunks.
Add the follow lines before the private functions definition:
var $body_fix_unaligned_chunks = '';
And replace the follow line:
$part['Data'] = base64_decode($this->body_buffer_position ? substr($this->body_buffer,$this->body_buffer_position) : $this->body_buffer);
By these lines:
$buffer = $this->body_buffer_position ? substr($this->body_buffer,$this->body_buffer_position) : $this->body_buffer;
$buffer = $this->body_fix_unaligned_chunks . str_replace([' ', "\n", "\r", "\t"], '', $buffer);
$this->body_fix_unaligned_chunks = '';
$remain = strlen($buffer) % 4;
if ($remain) {
$this->body_fix_unaligned_chunks = substr($buffer, -$remain);
$buffer = substr($buffer, 0, -$remain);
}
$part['Data'] = base64_decode($buffer);
With this code, the decoding action runs as expected without returning a corrupted file caused by the unaligned data in the base64 decode process.