PHP Classes

Fix for unaligned chunks

Recommend this page to a friend!

      PHP MIME Email Message Parser  >  All threads  >  Fix for unaligned chunks  >  (Un) Subscribe thread alerts  
Subject:Fix for unaligned chunks
Summary:Some mailers wraps the base64 data into chunks not mod 4
Messages:2
Author:Josep Sanz Campderrós
Date:2024-11-04 09:40:56
 

  1. Fix for unaligned chunks   Reply   Report abuse  
Picture of Josep Sanz Campderrós 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.

  2. Re: Fix for unaligned chunks   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2024-11-04 12:19:39 - In reply to message 1 from Josep Sanz Campderrós
Hello Josep,

Thank you for reporting.

Can you provide a sample MIME message that I can use to reproduce the issue?