diff options
Diffstat (limited to 'system/libraries/Session/drivers')
5 files changed, 1607 insertions, 0 deletions
diff --git a/system/libraries/Session/drivers/Session_database_driver.php b/system/libraries/Session/drivers/Session_database_driver.php new file mode 100644 index 000000000..b519b782f --- /dev/null +++ b/system/libraries/Session/drivers/Session_database_driver.php @@ -0,0 +1,420 @@ +<?php +/** + * CodeIgniter + * + * An open source application development framework for PHP + * + * This content is released under the MIT License (MIT) + * + * Copyright (c) 2014 - 2017, British Columbia Institute of Technology + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 + * @filesource + */ +defined('BASEPATH') OR exit('No direct script access allowed'); + +/** + * CodeIgniter Session Database Driver + * + * @package CodeIgniter + * @subpackage Libraries + * @category Sessions + * @author Andrey Andreev + * @link https://codeigniter.com/user_guide/libraries/sessions.html + */ +class CI_Session_database_driver extends CI_Session_driver implements SessionHandlerInterface { + + /** + * DB object + * + * @var object + */ + protected $_db; + + /** + * Row exists flag + * + * @var bool + */ + protected $_row_exists = FALSE; + + /** + * Lock "driver" flag + * + * @var string + */ + protected $_platform; + + // ------------------------------------------------------------------------ + + /** + * Class constructor + * + * @param array $params Configuration parameters + * @return void + */ + public function __construct(&$params) + { + parent::__construct($params); + + $CI =& get_instance(); + isset($CI->db) OR $CI->load->database(); + $this->_db = $CI->db; + + if ( ! $this->_db instanceof CI_DB_query_builder) + { + throw new Exception('Query Builder not enabled for the configured database. Aborting.'); + } + elseif ($this->_db->pconnect) + { + throw new Exception('Configured database connection is persistent. Aborting.'); + } + elseif ($this->_db->cache_on) + { + throw new Exception('Configured database connection has cache enabled. Aborting.'); + } + + $db_driver = $this->_db->dbdriver.(empty($this->_db->subdriver) ? '' : '_'.$this->_db->subdriver); + if (strpos($db_driver, 'mysql') !== FALSE) + { + $this->_platform = 'mysql'; + } + elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE)) + { + $this->_platform = 'postgre'; + } + + // Note: BC work-around for the old 'sess_table_name' setting, should be removed in the future. + if ( ! isset($this->_config['save_path']) && ($this->_config['save_path'] = config_item('sess_table_name'))) + { + log_message('debug', 'Session: "sess_save_path" is empty; using BC fallback to "sess_table_name".'); + } + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Initializes the database connection + * + * @param string $save_path Table name + * @param string $name Session cookie name, unused + * @return bool + */ + public function open($save_path, $name) + { + if (empty($this->_db->conn_id) && ! $this->_db->db_connect()) + { + return $this->_fail(); + } + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + if ($this->_get_lock($session_id) !== FALSE) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + $this->_db + ->select('data') + ->from($this->_config['save_path']) + ->where('id', $session_id); + + if ($this->_config['match_ip']) + { + $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']); + } + + if ( ! ($result = $this->_db->get()) OR ($result = $result->row()) === NULL) + { + // PHP7 will reuse the same SessionHandler object after + // ID regeneration, so we need to explicitly set this to + // FALSE instead of relying on the default ... + $this->_row_exists = FALSE; + $this->_fingerprint = md5(''); + return ''; + } + + // PostgreSQL's variant of a BLOB datatype is Bytea, which is a + // PITA to work with, so we use base64-encoded data in a TEXT + // field instead. + $result = ($this->_platform === 'postgre') + ? base64_decode(rtrim($result->data)) + : $result->data; + + $this->_fingerprint = md5($result); + $this->_row_exists = TRUE; + return $result; + } + + $this->_fingerprint = md5(''); + return ''; + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + // Was the ID regenerated? + if (isset($this->_session_id) && $session_id !== $this->_session_id) + { + if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id)) + { + return $this->_fail(); + } + + $this->_row_exists = FALSE; + $this->_session_id = $session_id; + } + elseif ($this->_lock === FALSE) + { + return $this->_fail(); + } + + if ($this->_row_exists === FALSE) + { + $insert_data = array( + 'id' => $session_id, + 'ip_address' => $_SERVER['REMOTE_ADDR'], + 'timestamp' => time(), + 'data' => ($this->_platform === 'postgre' ? base64_encode($session_data) : $session_data) + ); + + if ($this->_db->insert($this->_config['save_path'], $insert_data)) + { + $this->_fingerprint = md5($session_data); + $this->_row_exists = TRUE; + return $this->_success; + } + + return $this->_fail(); + } + + $this->_db->where('id', $session_id); + if ($this->_config['match_ip']) + { + $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']); + } + + $update_data = array('timestamp' => time()); + if ($this->_fingerprint !== md5($session_data)) + { + $update_data['data'] = ($this->_platform === 'postgre') + ? base64_encode($session_data) + : $session_data; + } + + if ($this->_db->update($this->_config['save_path'], $update_data)) + { + $this->_fingerprint = md5($session_data); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks + * + * @return bool + */ + public function close() + { + return ($this->_lock && ! $this->_release_lock()) + ? $this->_fail() + : $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if ($this->_lock) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + $this->_db->where('id', $session_id); + if ($this->_config['match_ip']) + { + $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']); + } + + if ( ! $this->_db->delete($this->_config['save_path'])) + { + return $this->_fail(); + } + } + + if ($this->close() === $this->_success) + { + $this->_cookie_destroy(); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + return ($this->_db->delete($this->_config['save_path'], 'timestamp < '.(time() - $maxlifetime))) + ? $this->_success + : $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Get lock + * + * Acquires a lock, depending on the underlying platform. + * + * @param string $session_id Session ID + * @return bool + */ + protected function _get_lock($session_id) + { + if ($this->_platform === 'mysql') + { + $arg = md5($session_id.($this->_config['match_ip'] ? '_'.$_SERVER['REMOTE_ADDR'] : '')); + if ($this->_db->query("SELECT GET_LOCK('".$arg."', 300) AS ci_session_lock")->row()->ci_session_lock) + { + $this->_lock = $arg; + return TRUE; + } + + return FALSE; + } + elseif ($this->_platform === 'postgre') + { + $arg = "hashtext('".$session_id."')".($this->_config['match_ip'] ? ", hashtext('".$_SERVER['REMOTE_ADDR']."')" : ''); + if ($this->_db->simple_query('SELECT pg_advisory_lock('.$arg.')')) + { + $this->_lock = $arg; + return TRUE; + } + + return FALSE; + } + + return parent::_get_lock($session_id); + } + + // ------------------------------------------------------------------------ + + /** + * Release lock + * + * Releases a previously acquired lock + * + * @return bool + */ + protected function _release_lock() + { + if ( ! $this->_lock) + { + return TRUE; + } + + if ($this->_platform === 'mysql') + { + if ($this->_db->query("SELECT RELEASE_LOCK('".$this->_lock."') AS ci_session_lock")->row()->ci_session_lock) + { + $this->_lock = FALSE; + return TRUE; + } + + return FALSE; + } + elseif ($this->_platform === 'postgre') + { + if ($this->_db->simple_query('SELECT pg_advisory_unlock('.$this->_lock.')')) + { + $this->_lock = FALSE; + return TRUE; + } + + return FALSE; + } + + return parent::_release_lock(); + } +} diff --git a/system/libraries/Session/drivers/Session_files_driver.php b/system/libraries/Session/drivers/Session_files_driver.php new file mode 100644 index 000000000..8860ef667 --- /dev/null +++ b/system/libraries/Session/drivers/Session_files_driver.php @@ -0,0 +1,406 @@ +<?php +/** + * CodeIgniter + * + * An open source application development framework for PHP + * + * This content is released under the MIT License (MIT) + * + * Copyright (c) 2014 - 2017, British Columbia Institute of Technology + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 + * @filesource +*/ +defined('BASEPATH') OR exit('No direct script access allowed'); + +/** + * CodeIgniter Session Files Driver + * + * @package CodeIgniter + * @subpackage Libraries + * @category Sessions + * @author Andrey Andreev + * @link https://codeigniter.com/user_guide/libraries/sessions.html + */ +class CI_Session_files_driver extends CI_Session_driver implements SessionHandlerInterface { + + /** + * Save path + * + * @var string + */ + protected $_save_path; + + /** + * File handle + * + * @var resource + */ + protected $_file_handle; + + /** + * File name + * + * @var resource + */ + protected $_file_path; + + /** + * File new flag + * + * @var bool + */ + protected $_file_new; + + /** + * Validate SID regular expression + * + * @var string + */ + protected $_sid_regexp; + + /** + * mbstring.func_overload flag + * + * @var bool + */ + protected static $func_overload; + + // ------------------------------------------------------------------------ + + /** + * Class constructor + * + * @param array $params Configuration parameters + * @return void + */ + public function __construct(&$params) + { + parent::__construct($params); + + if (isset($this->_config['save_path'])) + { + $this->_config['save_path'] = rtrim($this->_config['save_path'], '/\\'); + ini_set('session.save_path', $this->_config['save_path']); + } + else + { + log_message('debug', 'Session: "sess_save_path" is empty; using "session.save_path" value from php.ini.'); + $this->_config['save_path'] = rtrim(ini_get('session.save_path'), '/\\'); + } + + $this->_sid_regexp = $this->_config['_sid_regexp']; + + isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload')); + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Sanitizes the save_path directory. + * + * @param string $save_path Path to session files' directory + * @param string $name Session cookie name + * @return bool + */ + public function open($save_path, $name) + { + if ( ! is_dir($save_path)) + { + if ( ! mkdir($save_path, 0700, TRUE)) + { + throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not a directory, doesn't exist or cannot be created."); + } + } + elseif ( ! is_writable($save_path)) + { + throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not writable by the PHP process."); + } + + $this->_config['save_path'] = $save_path; + $this->_file_path = $this->_config['save_path'].DIRECTORY_SEPARATOR + .$name // we'll use the session cookie name as a prefix to avoid collisions + .($this->_config['match_ip'] ? md5($_SERVER['REMOTE_ADDR']) : ''); + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + // This might seem weird, but PHP 5.6 introduces session_reset(), + // which re-reads session data + if ($this->_file_handle === NULL) + { + $this->_file_new = ! file_exists($this->_file_path.$session_id); + + if (($this->_file_handle = fopen($this->_file_path.$session_id, 'c+b')) === FALSE) + { + log_message('error', "Session: Unable to open file '".$this->_file_path.$session_id."'."); + return $this->_failure; + } + + if (flock($this->_file_handle, LOCK_EX) === FALSE) + { + log_message('error', "Session: Unable to obtain lock for file '".$this->_file_path.$session_id."'."); + fclose($this->_file_handle); + $this->_file_handle = NULL; + return $this->_failure; + } + + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + if ($this->_file_new) + { + chmod($this->_file_path.$session_id, 0600); + $this->_fingerprint = md5(''); + return ''; + } + } + // We shouldn't need this, but apparently we do ... + // See https://github.com/bcit-ci/CodeIgniter/issues/4039 + elseif ($this->_file_handle === FALSE) + { + return $this->_failure; + } + else + { + rewind($this->_file_handle); + } + + $session_data = ''; + for ($read = 0, $length = filesize($this->_file_path.$session_id); $read < $length; $read += self::strlen($buffer)) + { + if (($buffer = fread($this->_file_handle, $length - $read)) === FALSE) + { + break; + } + + $session_data .= $buffer; + } + + $this->_fingerprint = md5($session_data); + return $session_data; + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + // If the two IDs don't match, we have a session_regenerate_id() call + // and we need to close the old handle and open a new one + if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure)) + { + return $this->_failure; + } + + if ( ! is_resource($this->_file_handle)) + { + return $this->_failure; + } + elseif ($this->_fingerprint === md5($session_data)) + { + return ( ! $this->_file_new && ! touch($this->_file_path.$session_id)) + ? $this->_failure + : $this->_success; + } + + if ( ! $this->_file_new) + { + ftruncate($this->_file_handle, 0); + rewind($this->_file_handle); + } + + if (($length = strlen($session_data)) > 0) + { + for ($written = 0; $written < $length; $written += $result) + { + if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE) + { + break; + } + } + + if ( ! is_int($result)) + { + $this->_fingerprint = md5(substr($session_data, 0, $written)); + log_message('error', 'Session: Unable to write data.'); + return $this->_failure; + } + } + + $this->_fingerprint = md5($session_data); + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks and closes file descriptor. + * + * @return bool + */ + public function close() + { + if (is_resource($this->_file_handle)) + { + flock($this->_file_handle, LOCK_UN); + fclose($this->_file_handle); + + $this->_file_handle = $this->_file_new = $this->_session_id = NULL; + } + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if ($this->close() === $this->_success) + { + if (file_exists($this->_file_path.$session_id)) + { + $this->_cookie_destroy(); + return unlink($this->_file_path.$session_id) + ? $this->_success + : $this->_failure; + } + + return $this->_success; + } + elseif ($this->_file_path !== NULL) + { + clearstatcache(); + if (file_exists($this->_file_path.$session_id)) + { + $this->_cookie_destroy(); + return unlink($this->_file_path.$session_id) + ? $this->_success + : $this->_failure; + } + + return $this->_success; + } + + return $this->_failure; + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE) + { + log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'."); + return $this->_failure; + } + + $ts = time() - $maxlifetime; + + $pattern = ($this->_config['match_ip'] === TRUE) + ? '[0-9a-f]{32}' + : ''; + + $pattern = sprintf( + '#\A%s'.$pattern.$this->_sid_regexp.'\z#', + preg_quote($this->_config['cookie_name']) + ); + + while (($file = readdir($directory)) !== FALSE) + { + // If the filename doesn't match this pattern, it's either not a session file or is not ours + if ( ! preg_match($pattern, $file) + OR ! is_file($this->_config['save_path'].DIRECTORY_SEPARATOR.$file) + OR ($mtime = filemtime($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)) === FALSE + OR $mtime > $ts) + { + continue; + } + + unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file); + } + + closedir($directory); + + return $this->_success; + } + + // -------------------------------------------------------------------- + + /** + * Byte-safe strlen() + * + * @param string $str + * @return int + */ + protected static function strlen($str) + { + return (self::$func_overload) + ? mb_strlen($str, '8bit') + : strlen($str); + } +} diff --git a/system/libraries/Session/drivers/Session_memcached_driver.php b/system/libraries/Session/drivers/Session_memcached_driver.php new file mode 100644 index 000000000..2556bf0f7 --- /dev/null +++ b/system/libraries/Session/drivers/Session_memcached_driver.php @@ -0,0 +1,375 @@ +<?php +/** + * CodeIgniter + * + * An open source application development framework for PHP + * + * This content is released under the MIT License (MIT) + * + * Copyright (c) 2014 - 2017, British Columbia Institute of Technology + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 + * @filesource + */ +defined('BASEPATH') OR exit('No direct script access allowed'); + +/** + * CodeIgniter Session Memcached Driver + * + * @package CodeIgniter + * @subpackage Libraries + * @category Sessions + * @author Andrey Andreev + * @link https://codeigniter.com/user_guide/libraries/sessions.html + */ +class CI_Session_memcached_driver extends CI_Session_driver implements SessionHandlerInterface { + + /** + * Memcached instance + * + * @var Memcached + */ + protected $_memcached; + + /** + * Key prefix + * + * @var string + */ + protected $_key_prefix = 'ci_session:'; + + /** + * Lock key + * + * @var string + */ + protected $_lock_key; + + // ------------------------------------------------------------------------ + + /** + * Class constructor + * + * @param array $params Configuration parameters + * @return void + */ + public function __construct(&$params) + { + parent::__construct($params); + + if (empty($this->_config['save_path'])) + { + log_message('error', 'Session: No Memcached save path configured.'); + } + + if ($this->_config['match_ip'] === TRUE) + { + $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':'; + } + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Sanitizes save_path and initializes connections. + * + * @param string $save_path Server path(s) + * @param string $name Session cookie name, unused + * @return bool + */ + public function open($save_path, $name) + { + $this->_memcached = new Memcached(); + $this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE); // required for touch() usage + $server_list = array(); + foreach ($this->_memcached->getServerList() as $server) + { + $server_list[] = $server['host'].':'.$server['port']; + } + + if ( ! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->_config['save_path'], $matches, PREG_SET_ORDER)) + { + $this->_memcached = NULL; + log_message('error', 'Session: Invalid Memcached save path format: '.$this->_config['save_path']); + return $this->_fail(); + } + + foreach ($matches as $match) + { + // If Memcached already has this server (or if the port is invalid), skip it + if (in_array($match[1].':'.$match[2], $server_list, TRUE)) + { + log_message('debug', 'Session: Memcached server pool already has '.$match[1].':'.$match[2]); + continue; + } + + if ( ! $this->_memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0)) + { + log_message('error', 'Could not add '.$match[1].':'.$match[2].' to Memcached server pool.'); + } + else + { + $server_list[] = $match[1].':'.$match[2]; + } + } + + if (empty($server_list)) + { + log_message('error', 'Session: Memcached server pool is empty.'); + return $this->_fail(); + } + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + if (isset($this->_memcached) && $this->_get_lock($session_id)) + { + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + $session_data = (string) $this->_memcached->get($this->_key_prefix.$session_id); + $this->_fingerprint = md5($session_data); + return $session_data; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + if ( ! isset($this->_memcached, $this->_lock_key)) + { + return $this->_fail(); + } + // Was the ID regenerated? + elseif ($session_id !== $this->_session_id) + { + if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id)) + { + return $this->_fail(); + } + + $this->_fingerprint = md5(''); + $this->_session_id = $session_id; + } + + $key = $this->_key_prefix.$session_id; + + $this->_memcached->replace($this->_lock_key, time(), 300); + if ($this->_fingerprint !== ($fingerprint = md5($session_data))) + { + if ($this->_memcached->set($key, $session_data, $this->_config['expiration'])) + { + $this->_fingerprint = $fingerprint; + return $this->_success; + } + + return $this->_fail(); + } + elseif ( + $this->_memcached->touch($key, $this->_config['expiration']) + OR ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND && $this->_memcached->set($key, $session_data, $this->_config['expiration'])) + ) + { + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks and closes connection. + * + * @return bool + */ + public function close() + { + if (isset($this->_memcached)) + { + $this->_release_lock(); + if ( ! $this->_memcached->quit()) + { + return $this->_fail(); + } + + $this->_memcached = NULL; + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if (isset($this->_memcached, $this->_lock_key)) + { + $this->_memcached->delete($this->_key_prefix.$session_id); + $this->_cookie_destroy(); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + // Not necessary, Memcached takes care of that. + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Get lock + * + * Acquires an (emulated) lock. + * + * @param string $session_id Session ID + * @return bool + */ + protected function _get_lock($session_id) + { + // PHP 7 reuses the SessionHandler object on regeneration, + // so we need to check here if the lock key is for the + // correct session ID. + if ($this->_lock_key === $this->_key_prefix.$session_id.':lock') + { + if ( ! $this->_memcached->replace($this->_lock_key, time(), 300)) + { + return ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND) + ? $this->_memcached->set($this->_lock_key, time(), 300) + : FALSE; + } + } + + // 30 attempts to obtain a lock, in case another request already has it + $lock_key = $this->_key_prefix.$session_id.':lock'; + $attempt = 0; + do + { + if ($this->_memcached->get($lock_key)) + { + sleep(1); + continue; + } + + if ( ! $this->_memcached->set($lock_key, time(), 300)) + { + log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id); + return FALSE; + } + + $this->_lock_key = $lock_key; + break; + } + while (++$attempt < 30); + + if ($attempt === 30) + { + log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.'); + return FALSE; + } + + $this->_lock = TRUE; + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Release lock + * + * Releases a previously acquired lock + * + * @return bool + */ + protected function _release_lock() + { + if (isset($this->_memcached, $this->_lock_key) && $this->_lock) + { + if ( ! $this->_memcached->delete($this->_lock_key) && $this->_memcached->getResultCode() !== Memcached::RES_NOTFOUND) + { + log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key); + return FALSE; + } + + $this->_lock_key = NULL; + $this->_lock = FALSE; + } + + return TRUE; + } +} diff --git a/system/libraries/Session/drivers/Session_redis_driver.php b/system/libraries/Session/drivers/Session_redis_driver.php new file mode 100644 index 000000000..e220a2951 --- /dev/null +++ b/system/libraries/Session/drivers/Session_redis_driver.php @@ -0,0 +1,395 @@ +<?php +/** + * CodeIgniter + * + * An open source application development framework for PHP + * + * This content is released under the MIT License (MIT) + * + * Copyright (c) 2014 - 2017, British Columbia Institute of Technology + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 + * @filesource + */ +defined('BASEPATH') OR exit('No direct script access allowed'); + +/** + * CodeIgniter Session Redis Driver + * + * @package CodeIgniter + * @subpackage Libraries + * @category Sessions + * @author Andrey Andreev + * @link https://codeigniter.com/user_guide/libraries/sessions.html + */ +class CI_Session_redis_driver extends CI_Session_driver implements SessionHandlerInterface { + + /** + * phpRedis instance + * + * @var Redis + */ + protected $_redis; + + /** + * Key prefix + * + * @var string + */ + protected $_key_prefix = 'ci_session:'; + + /** + * Lock key + * + * @var string + */ + protected $_lock_key; + + /** + * Key exists flag + * + * @var bool + */ + protected $_key_exists = FALSE; + + // ------------------------------------------------------------------------ + + /** + * Class constructor + * + * @param array $params Configuration parameters + * @return void + */ + public function __construct(&$params) + { + parent::__construct($params); + + if (empty($this->_config['save_path'])) + { + log_message('error', 'Session: No Redis save path configured.'); + } + elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches)) + { + isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below + $this->_config['save_path'] = array( + 'host' => $matches[1], + 'port' => empty($matches[2]) ? NULL : $matches[2], + 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL, + 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL, + 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL + ); + + preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1]; + } + else + { + log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']); + } + + if ($this->_config['match_ip'] === TRUE) + { + $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':'; + } + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Sanitizes save_path and initializes connection. + * + * @param string $save_path Server path + * @param string $name Session cookie name, unused + * @return bool + */ + public function open($save_path, $name) + { + if (empty($this->_config['save_path'])) + { + return $this->_fail(); + } + + $redis = new Redis(); + if ( ! $redis->connect($this->_config['save_path']['host'], $this->_config['save_path']['port'], $this->_config['save_path']['timeout'])) + { + log_message('error', 'Session: Unable to connect to Redis with the configured settings.'); + } + elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password'])) + { + log_message('error', 'Session: Unable to authenticate to Redis instance.'); + } + elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database'])) + { + log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']); + } + else + { + $this->_redis = $redis; + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + if (isset($this->_redis) && $this->_get_lock($session_id)) + { + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + $session_data = $this->_redis->get($this->_key_prefix.$session_id); + + is_string($session_data) + ? $this->_key_exists = TRUE + : $session_data = ''; + + $this->_fingerprint = md5($session_data); + return $session_data; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + if ( ! isset($this->_redis, $this->_lock_key)) + { + return $this->_fail(); + } + // Was the ID regenerated? + elseif ($session_id !== $this->_session_id) + { + if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id)) + { + return $this->_fail(); + } + + $this->_key_exists = FALSE; + $this->_session_id = $session_id; + } + + $this->_redis->setTimeout($this->_lock_key, 300); + if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE) + { + if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration'])) + { + $this->_fingerprint = $fingerprint; + $this->_key_exists = TRUE; + return $this->_success; + } + + return $this->_fail(); + } + + return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration'])) + ? $this->_success + : $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks and closes connection. + * + * @return bool + */ + public function close() + { + if (isset($this->_redis)) + { + try { + if ($this->_redis->ping() === '+PONG') + { + $this->_release_lock(); + if ($this->_redis->close() === FALSE) + { + return $this->_fail(); + } + } + } + catch (RedisException $e) + { + log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage()); + } + + $this->_redis = NULL; + return $this->_success; + } + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if (isset($this->_redis, $this->_lock_key)) + { + if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1) + { + log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.'); + } + + $this->_cookie_destroy(); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + // Not necessary, Redis takes care of that. + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Get lock + * + * Acquires an (emulated) lock. + * + * @param string $session_id Session ID + * @return bool + */ + protected function _get_lock($session_id) + { + // PHP 7 reuses the SessionHandler object on regeneration, + // so we need to check here if the lock key is for the + // correct session ID. + if ($this->_lock_key === $this->_key_prefix.$session_id.':lock') + { + return $this->_redis->setTimeout($this->_lock_key, 300); + } + + // 30 attempts to obtain a lock, in case another request already has it + $lock_key = $this->_key_prefix.$session_id.':lock'; + $attempt = 0; + do + { + if (($ttl = $this->_redis->ttl($lock_key)) > 0) + { + sleep(1); + continue; + } + + if ( ! $this->_redis->setex($lock_key, 300, time())) + { + log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id); + return FALSE; + } + + $this->_lock_key = $lock_key; + break; + } + while (++$attempt < 30); + + if ($attempt === 30) + { + log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.'); + return FALSE; + } + elseif ($ttl === -1) + { + log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.'); + } + + $this->_lock = TRUE; + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Release lock + * + * Releases a previously acquired lock + * + * @return bool + */ + protected function _release_lock() + { + if (isset($this->_redis, $this->_lock_key) && $this->_lock) + { + if ( ! $this->_redis->delete($this->_lock_key)) + { + log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key); + return FALSE; + } + + $this->_lock_key = NULL; + $this->_lock = FALSE; + } + + return TRUE; + } + +} diff --git a/system/libraries/Session/drivers/index.html b/system/libraries/Session/drivers/index.html new file mode 100644 index 000000000..b702fbc39 --- /dev/null +++ b/system/libraries/Session/drivers/index.html @@ -0,0 +1,11 @@ +<!DOCTYPE html> +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> |