Session_redis_driver.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 - 2016, 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 - 2016, 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 resource
  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))
  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. if (isset($this->_lock_key))
  195. {
  196. $this->_redis->setTimeout($this->_lock_key, 300);
  197. if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE)
  198. {
  199. if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
  200. {
  201. $this->_fingerprint = $fingerprint;
  202. $this->_key_exists = TRUE;
  203. return $this->_success;
  204. }
  205. return $this->_fail();
  206. }
  207. return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']))
  208. ? $this->_success
  209. : $this->_fail();
  210. }
  211. return $this->_fail();
  212. }
  213. // ------------------------------------------------------------------------
  214. /**
  215. * Close
  216. *
  217. * Releases locks and closes connection.
  218. *
  219. * @return bool
  220. */
  221. public function close()
  222. {
  223. if (isset($this->_redis))
  224. {
  225. try {
  226. if ($this->_redis->ping() === '+PONG')
  227. {
  228. $this->_release_lock();
  229. if ($this->_redis->close() === FALSE)
  230. {
  231. return $this->_fail();
  232. }
  233. }
  234. }
  235. catch (RedisException $e)
  236. {
  237. log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
  238. }
  239. $this->_redis = NULL;
  240. return $this->_success;
  241. }
  242. return $this->_success;
  243. }
  244. // ------------------------------------------------------------------------
  245. /**
  246. * Destroy
  247. *
  248. * Destroys the current session.
  249. *
  250. * @param string $session_id Session ID
  251. * @return bool
  252. */
  253. public function destroy($session_id)
  254. {
  255. if (isset($this->_redis, $this->_lock_key))
  256. {
  257. if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1)
  258. {
  259. log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
  260. }
  261. $this->_cookie_destroy();
  262. return $this->_success;
  263. }
  264. return $this->_fail();
  265. }
  266. // ------------------------------------------------------------------------
  267. /**
  268. * Garbage Collector
  269. *
  270. * Deletes expired sessions
  271. *
  272. * @param int $maxlifetime Maximum lifetime of sessions
  273. * @return bool
  274. */
  275. public function gc($maxlifetime)
  276. {
  277. // Not necessary, Redis takes care of that.
  278. return $this->_success;
  279. }
  280. // ------------------------------------------------------------------------
  281. /**
  282. * Get lock
  283. *
  284. * Acquires an (emulated) lock.
  285. *
  286. * @param string $session_id Session ID
  287. * @return bool
  288. */
  289. protected function _get_lock($session_id)
  290. {
  291. // PHP 7 reuses the SessionHandler object on regeneration,
  292. // so we need to check here if the lock key is for the
  293. // correct session ID.
  294. if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
  295. {
  296. return $this->_redis->setTimeout($this->_lock_key, 300);
  297. }
  298. // 30 attempts to obtain a lock, in case another request already has it
  299. $lock_key = $this->_key_prefix.$session_id.':lock';
  300. $attempt = 0;
  301. do
  302. {
  303. if (($ttl = $this->_redis->ttl($lock_key)) > 0)
  304. {
  305. sleep(1);
  306. continue;
  307. }
  308. if ( ! $this->_redis->setex($lock_key, 300, time()))
  309. {
  310. log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
  311. return FALSE;
  312. }
  313. $this->_lock_key = $lock_key;
  314. break;
  315. }
  316. while (++$attempt < 30);
  317. if ($attempt === 30)
  318. {
  319. log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
  320. return FALSE;
  321. }
  322. elseif ($ttl === -1)
  323. {
  324. log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
  325. }
  326. $this->_lock = TRUE;
  327. return TRUE;
  328. }
  329. // ------------------------------------------------------------------------
  330. /**
  331. * Release lock
  332. *
  333. * Releases a previously acquired lock
  334. *
  335. * @return bool
  336. */
  337. protected function _release_lock()
  338. {
  339. if (isset($this->_redis, $this->_lock_key) && $this->_lock)
  340. {
  341. if ( ! $this->_redis->delete($this->_lock_key))
  342. {
  343. log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
  344. return FALSE;
  345. }
  346. $this->_lock_key = NULL;
  347. $this->_lock = FALSE;
  348. }
  349. return TRUE;
  350. }
  351. }