You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

395 lines
10 KiB

7 years ago
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 3.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * CodeIgniter Session Redis Driver
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Libraries
  44. * @category Sessions
  45. * @author Andrey Andreev
  46. * @link https://codeigniter.com/user_guide/libraries/sessions.html
  47. */
  48. class CI_Session_redis_driver extends CI_Session_driver implements SessionHandlerInterface {
  49. /**
  50. * phpRedis instance
  51. *
  52. * @var Redis
  53. */
  54. protected $_redis;
  55. /**
  56. * Key prefix
  57. *
  58. * @var string
  59. */
  60. protected $_key_prefix = 'ci_session:';
  61. /**
  62. * Lock key
  63. *
  64. * @var string
  65. */
  66. protected $_lock_key;
  67. /**
  68. * Key exists flag
  69. *
  70. * @var bool
  71. */
  72. protected $_key_exists = FALSE;
  73. // ------------------------------------------------------------------------
  74. /**
  75. * Class constructor
  76. *
  77. * @param array $params Configuration parameters
  78. * @return void
  79. */
  80. public function __construct(&$params)
  81. {
  82. parent::__construct($params);
  83. if (empty($this->_config['save_path']))
  84. {
  85. log_message('error', 'Session: No Redis save path configured.');
  86. }
  87. elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches))
  88. {
  89. isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below
  90. $this->_config['save_path'] = array(
  91. 'host' => $matches[1],
  92. 'port' => empty($matches[2]) ? NULL : $matches[2],
  93. 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL,
  94. 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL,
  95. 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL
  96. );
  97. preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1];
  98. }
  99. else
  100. {
  101. log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']);
  102. }
  103. if ($this->_config['match_ip'] === TRUE)
  104. {
  105. $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
  106. }
  107. }
  108. // ------------------------------------------------------------------------
  109. /**
  110. * Open
  111. *
  112. * Sanitizes save_path and initializes connection.
  113. *
  114. * @param string $save_path Server path
  115. * @param string $name Session cookie name, unused
  116. * @return bool
  117. */
  118. public function open($save_path, $name)
  119. {
  120. if (empty($this->_config['save_path']))
  121. {
  122. return $this->_fail();
  123. }
  124. $redis = new Redis();
  125. if ( ! $redis->connect($this->_config['save_path']['host'], $this->_config['save_path']['port'], $this->_config['save_path']['timeout']))
  126. {
  127. log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
  128. }
  129. elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password']))
  130. {
  131. log_message('error', 'Session: Unable to authenticate to Redis instance.');
  132. }
  133. elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database']))
  134. {
  135. log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']);
  136. }
  137. else
  138. {
  139. $this->_redis = $redis;
  140. return $this->_success;
  141. }
  142. return $this->_fail();
  143. }
  144. // ------------------------------------------------------------------------
  145. /**
  146. * Read
  147. *
  148. * Reads session data and acquires a lock
  149. *
  150. * @param string $session_id Session ID
  151. * @return string Serialized session data
  152. */
  153. public function read($session_id)
  154. {
  155. if (isset($this->_redis) && $this->_get_lock($session_id))
  156. {
  157. // Needed by write() to detect session_regenerate_id() calls
  158. $this->_session_id = $session_id;
  159. $session_data = $this->_redis->get($this->_key_prefix.$session_id);
  160. is_string($session_data)
  161. ? $this->_key_exists = TRUE
  162. : $session_data = '';
  163. $this->_fingerprint = md5($session_data);
  164. return $session_data;
  165. }
  166. return $this->_fail();
  167. }
  168. // ------------------------------------------------------------------------
  169. /**
  170. * Write
  171. *
  172. * Writes (create / update) session data
  173. *
  174. * @param string $session_id Session ID
  175. * @param string $session_data Serialized session data
  176. * @return bool
  177. */
  178. public function write($session_id, $session_data)
  179. {
  180. if ( ! isset($this->_redis, $this->_lock_key))
  181. {
  182. return $this->_fail();
  183. }
  184. // Was the ID regenerated?
  185. elseif ($session_id !== $this->_session_id)
  186. {
  187. if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
  188. {
  189. return $this->_fail();
  190. }
  191. $this->_key_exists = FALSE;
  192. $this->_session_id = $session_id;
  193. }
  194. $this->_redis->setTimeout($this->_lock_key, 300);
  195. if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE)
  196. {
  197. if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
  198. {
  199. $this->_fingerprint = $fingerprint;
  200. $this->_key_exists = TRUE;
  201. return $this->_success;
  202. }
  203. return $this->_fail();
  204. }
  205. return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']))
  206. ? $this->_success
  207. : $this->_fail();
  208. }
  209. // ------------------------------------------------------------------------
  210. /**
  211. * Close
  212. *
  213. * Releases locks and closes connection.
  214. *
  215. * @return bool
  216. */
  217. public function close()
  218. {
  219. if (isset($this->_redis))
  220. {
  221. try {
  222. if ($this->_redis->ping() === '+PONG')
  223. {
  224. $this->_release_lock();
  225. if ($this->_redis->close() === FALSE)
  226. {
  227. return $this->_fail();
  228. }
  229. }
  230. }
  231. catch (RedisException $e)
  232. {
  233. log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
  234. }
  235. $this->_redis = NULL;
  236. return $this->_success;
  237. }
  238. return $this->_success;
  239. }
  240. // ------------------------------------------------------------------------
  241. /**
  242. * Destroy
  243. *
  244. * Destroys the current session.
  245. *
  246. * @param string $session_id Session ID
  247. * @return bool
  248. */
  249. public function destroy($session_id)
  250. {
  251. if (isset($this->_redis, $this->_lock_key))
  252. {
  253. if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1)
  254. {
  255. log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
  256. }
  257. $this->_cookie_destroy();
  258. return $this->_success;
  259. }
  260. return $this->_fail();
  261. }
  262. // ------------------------------------------------------------------------
  263. /**
  264. * Garbage Collector
  265. *
  266. * Deletes expired sessions
  267. *
  268. * @param int $maxlifetime Maximum lifetime of sessions
  269. * @return bool
  270. */
  271. public function gc($maxlifetime)
  272. {
  273. // Not necessary, Redis takes care of that.
  274. return $this->_success;
  275. }
  276. // ------------------------------------------------------------------------
  277. /**
  278. * Get lock
  279. *
  280. * Acquires an (emulated) lock.
  281. *
  282. * @param string $session_id Session ID
  283. * @return bool
  284. */
  285. protected function _get_lock($session_id)
  286. {
  287. // PHP 7 reuses the SessionHandler object on regeneration,
  288. // so we need to check here if the lock key is for the
  289. // correct session ID.
  290. if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
  291. {
  292. return $this->_redis->setTimeout($this->_lock_key, 300);
  293. }
  294. // 30 attempts to obtain a lock, in case another request already has it
  295. $lock_key = $this->_key_prefix.$session_id.':lock';
  296. $attempt = 0;
  297. do
  298. {
  299. if (($ttl = $this->_redis->ttl($lock_key)) > 0)
  300. {
  301. sleep(1);
  302. continue;
  303. }
  304. if ( ! $this->_redis->setex($lock_key, 300, time()))
  305. {
  306. log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
  307. return FALSE;
  308. }
  309. $this->_lock_key = $lock_key;
  310. break;
  311. }
  312. while (++$attempt < 30);
  313. if ($attempt === 30)
  314. {
  315. log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
  316. return FALSE;
  317. }
  318. elseif ($ttl === -1)
  319. {
  320. log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
  321. }
  322. $this->_lock = TRUE;
  323. return TRUE;
  324. }
  325. // ------------------------------------------------------------------------
  326. /**
  327. * Release lock
  328. *
  329. * Releases a previously acquired lock
  330. *
  331. * @return bool
  332. */
  333. protected function _release_lock()
  334. {
  335. if (isset($this->_redis, $this->_lock_key) && $this->_lock)
  336. {
  337. if ( ! $this->_redis->delete($this->_lock_key))
  338. {
  339. log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
  340. return FALSE;
  341. }
  342. $this->_lock_key = NULL;
  343. $this->_lock = FALSE;
  344. }
  345. return TRUE;
  346. }
  347. }