Skip to content

Commit

Permalink
Merge pull request #52 from open-sausages/pulls/2.1/binary-database-s…
Browse files Browse the repository at this point in the history
…tore

FIX DatabaseStore binary safety (patch)
  • Loading branch information
robbieaverill authored Jun 30, 2019
2 parents 3fcebd6 + 99b4f7c commit d1932a4
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions src/Store/DatabaseStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ public function read($session_id)

if ($result && $result->numRecords()) {
$data = $result->first();
return $data['Data'];
$decoded = $this->binaryDataJsonDecode($data['Data']);
return is_null($decoded) ? $data['Data'] : $decoded;
}
}

Expand All @@ -79,7 +80,7 @@ public function write($session_id, $session_data)
ON DUPLICATE KEY UPDATE "Expiry" = %2$u, "Data" = \'%3$s\'',
Convert::raw2sql($session_id),
$expiry,
Convert::raw2sql($session_data)
Convert::raw2sql($this->binaryDataJsonEncode($session_data))
));

return true;
Expand All @@ -101,4 +102,47 @@ public function gc($maxlifetime)
$this->getNow()
));
}

/**
* Encode binary data into ASCII string (a subset of UTF-8)
*
* Silverstripe <= 4.4 does not have a binary db field implementation, so we have to store
* binary data as text
*
* @param string $data This is a binary blob
*
* @return string
*/
private function binaryDataJsonEncode($data)
{
return json_encode([
self::class,
base64_encode($data)
]);
}

/**
* Decode ASCII string into original binary data (a php string)
*
* Silverstripe <= 4.4 does not have a binary db field implementation, so we have to store
* binary data as text
*
* @param string $text
*
* @param null|string
*/
private function binaryDataJsonDecode($text)
{
$struct = json_decode($text, true, 2);

if (!is_array($struct) || count($struct) !== 2) {
return null;
}

if (!isset($struct[0]) || !isset($struct[1]) || $struct[0] !== self::class) {
return null;
}

return base64_decode($struct[1]);
}
}

0 comments on commit d1932a4

Please sign in to comment.