<?php
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Exceptions\SessionException;
class MemcachedHandler extends BaseHandler implements \SessionHandlerInterface
{
protected $memcached;
protected $keyPrefix = 'ci_session:';
protected $lockKey;
protected $sessionExpiration = 7200;
public function __construct(BaseConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
if (empty($this->savePath))
{
throw SessionException::forEmptySavepath();
}
if ($this->matchIP === true)
{
$this->keyPrefix .= $this->ipAddress . ':';
}
if (! empty($this->keyPrefix))
{
ini_set('memcached.sess_prefix', $this->keyPrefix);
}
$this->sessionExpiration = $config->sessionExpiration;
}
public function open($save_path, $name): bool
{
$this->memcached = new \Memcached();
$this->memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
$server_list = [];
foreach ($this->memcached->getServerList() as $server)
{
$server_list[] = $server['host'] . ':' . $server['port'];
}
if (! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->savePath, $matches, PREG_SET_ORDER)
)
{
$this->memcached = null;
$this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);
return false;
}
foreach ($matches as $match)
{
if (in_array($match[1] . ':' . $match[2], $server_list, true))
{
$this->logger->debug('Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]);
continue;
}
if (! $this->memcached->addServer($match[1], $match[2], $match[3] ?? 0))
{
$this->logger->error('Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.');
}
else
{
$server_list[] = $match[1] . ':' . $match[2];
}
}
if (empty($server_list))
{
$this->logger->error('Session: Memcached server pool is empty.');
return false;
}
return true;
}
public function read($sessionID): string
{
if (isset($this->memcached) && $this->lockSession($sessionID))
{
if (is_null($this->sessionID))
{
$this->sessionID = $sessionID;
}
$session_data = (string) $this->memcached->get($this->keyPrefix . $sessionID);
$this->fingerprint = md5($session_data);
return $session_data;
}
return '';
}
public function write($sessionID, $sessionData): bool
{
if (! isset($this->memcached))
{
return false;
}
elseif ($sessionID !== $this->sessionID)
{
if (! $this->releaseLock() || ! $this->lockSession($sessionID))
{
return false;
}
$this->fingerprint = md5('');
$this->sessionID = $sessionID;
}
if (isset($this->lockKey))
{
$this->memcached->replace($this->lockKey, time(), 300);
if ($this->fingerprint !== ($fingerprint = md5($sessionData)))
{
if ($this->memcached->set($this->keyPrefix . $sessionID, $sessionData, $this->sessionExpiration))
{
$this->fingerprint = $fingerprint;
return true;
}
return false;
}
return $this->memcached->touch($this->keyPrefix . $sessionID, $this->sessionExpiration);
}
return false;
}
public function close(): bool
{
if (isset($this->memcached))
{
isset($this->lockKey) && $this->memcached->delete($this->lockKey);
if (! $this->memcached->quit())
{
return false;
}
$this->memcached = null;
return true;
}
return false;
}
public function destroy($session_id): bool
{
if (isset($this->memcached, $this->lockKey))
{
$this->memcached->delete($this->keyPrefix . $session_id);
return $this->destroyCookie();
}
return false;
}
public function gc($maxlifetime): bool
{
return true;
}
protected function lockSession(string $sessionID): bool
{
if (isset($this->lockKey))
{
return $this->memcached->replace($this->lockKey, time(), 300);
}
$lock_key = $this->keyPrefix . $sessionID . ':lock';
$attempt = 0;
do
{
if ($this->memcached->get($lock_key))
{
sleep(1);
continue;
}
if (! $this->memcached->set($lock_key, time(), 300))
{
$this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID);
return false;
}
$this->lockKey = $lock_key;
break;
}
while (++ $attempt < 30);
if ($attempt === 30)
{
$this->logger->error('Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID . ' after 30 attempts, aborting.');
return false;
}
$this->lock = true;
return true;
}
protected function releaseLock(): bool
{
if (isset($this->memcached, $this->lockKey) && $this->lock)
{
if (! $this->memcached->delete($this->lockKey) &&
$this->memcached->getResultCode() !== \Memcached::RES_NOTFOUND
)
{
$this->logger->error('Session: Error while trying to free lock for ' . $this->lockKey);
return false;
}
$this->lockKey = null;
$this->lock = false;
}
return true;
}
}