From 34d8d0b405928fb2401b9a3bfbf86f0a401069dd Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Tue, 29 Apr 2014 23:10:08 -0500
Subject: [PATCH] tnef: Fix major issue iterating over attr streams

The original logic would read the count of attributes in the stream and then
read the first attribute in the constructor of TnefAttributeStreamReader.
Then the iterator interface would call ::rewind() before iterating to the
first item. rewind() set the @pos attribute to zero, which would cause the
attribute count (4-byte int) to be interpreted incorrectly as part of the
first attribute.

The new logic sets the position at 4 after rewind()ing, and does not read
the first attribute twice. It also properly detects the end of the attribute
stream by the number of attributes advertised as the first four bytes of the
stream (read into the @count attribute initially).
---
 include/tnef_decoder.php | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/include/tnef_decoder.php b/include/tnef_decoder.php
index 91a5e59fe..45ee5b5c0 100644
--- a/include/tnef_decoder.php
+++ b/include/tnef_decoder.php
@@ -278,15 +278,14 @@ class TnefAttributeStreamReader extends TnefStreamReader {
         $this->push($stream);
         /* Number of attributes. */
         $this->count = $this->_geti(32);
-        $this->next();
     }
 
     function valid() {
-        return (bool) $this->current;
+        return $this->count && $this->current;
     }
 
     function rewind() {
-        $this->pos = 0;
+        $this->pos = 4;
     }
 
     protected function readPhpValue($type) {
@@ -350,10 +349,11 @@ class TnefAttributeStreamReader extends TnefStreamReader {
     }
 
     function next() {
-        $this->count--;
-
-        if ($this->length - $this->pos < 12)
+        if ($this->count <= 0) {
             return $this->current = false;
+        }
+
+        $this->count--;
 
         $have_mval = false;
         $named_id = $value = null;
@@ -391,7 +391,7 @@ class TnefAttributeStreamReader extends TnefStreamReader {
             $value = $this->readPhpValue($data_type);
         } else {
             $value = array();
-        $k = $this->_geti(32);
+            $k = $this->_geti(32);
             for ($i=0; $i < $k; $i++)
                 $value[] = $this->readPhpValue($data_type);
         }
-- 
GitLab