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.

375 lines
9.3 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 Memcached 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_memcached_driver extends CI_Session_driver implements SessionHandlerInterface {
  49. /**
  50. * Memcached instance
  51. *
  52. * @var Memcached
  53. */
  54. protected $_memcached;
  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. /**
  69. * Class constructor
  70. *
  71. * @param array $params Configuration parameters
  72. * @return void
  73. */
  74. public function __construct(&$params)
  75. {
  76. parent::__construct($params);
  77. if (empty($this->_config['save_path']))
  78. {
  79. log_message('error', 'Session: No Memcached save path configured.');
  80. }
  81. if ($this->_config['match_ip'] === TRUE)
  82. {
  83. $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
  84. }
  85. }
  86. // ------------------------------------------------------------------------
  87. /**
  88. * Open
  89. *
  90. * Sanitizes save_path and initializes connections.
  91. *
  92. * @param string $save_path Server path(s)
  93. * @param string $name Session cookie name, unused
  94. * @return bool
  95. */
  96. public function open($save_path, $name)
  97. {
  98. $this->_memcached = new Memcached();
  99. $this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE); // required for touch() usage
  100. $server_list = array();
  101. foreach ($this->_memcached->getServerList() as $server)
  102. {
  103. $server_list[] = $server['host'].':'.$server['port'];
  104. }
  105. if ( ! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->_config['save_path'], $matches, PREG_SET_ORDER))
  106. {
  107. $this->_memcached = NULL;
  108. log_message('error', 'Session: Invalid Memcached save path format: '.$this->_config['save_path']);
  109. return $this->_fail();
  110. }
  111. foreach ($matches as $match)
  112. {
  113. // If Memcached already has this server (or if the port is invalid), skip it
  114. if (in_array($match[1].':'.$match[2], $server_list, TRUE))
  115. {
  116. log_message('debug', 'Session: Memcached server pool already has '.$match[1].':'.$match[2]);
  117. continue;
  118. }
  119. if ( ! $this->_memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0))
  120. {
  121. log_message('error', 'Could not add '.$match[1].':'.$match[2].' to Memcached server pool.');
  122. }
  123. else
  124. {
  125. $server_list[] = $match[1].':'.$match[2];
  126. }
  127. }
  128. if (empty($server_list))
  129. {
  130. log_message('error', 'Session: Memcached server pool is empty.');
  131. return $this->_fail();
  132. }
  133. return $this->_success;
  134. }
  135. // ------------------------------------------------------------------------
  136. /**
  137. * Read
  138. *
  139. * Reads session data and acquires a lock
  140. *
  141. * @param string $session_id Session ID
  142. * @return string Serialized session data
  143. */
  144. public function read($session_id)
  145. {
  146. if (isset($this->_memcached) && $this->_get_lock($session_id))
  147. {
  148. // Needed by write() to detect session_regenerate_id() calls
  149. $this->_session_id = $session_id;
  150. $session_data = (string) $this->_memcached->get($this->_key_prefix.$session_id);
  151. $this->_fingerprint = md5($session_data);
  152. return $session_data;
  153. }
  154. return $this->_fail();
  155. }
  156. // ------------------------------------------------------------------------
  157. /**
  158. * Write
  159. *
  160. * Writes (create / update) session data
  161. *
  162. * @param string $session_id Session ID
  163. * @param string $session_data Serialized session data
  164. * @return bool
  165. */
  166. public function write($session_id, $session_data)
  167. {
  168. if ( ! isset($this->_memcached, $this->_lock_key))
  169. {
  170. return $this->_fail();
  171. }
  172. // Was the ID regenerated?
  173. elseif ($session_id !== $this->_session_id)
  174. {
  175. if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
  176. {
  177. return $this->_fail();
  178. }
  179. $this->_fingerprint = md5('');
  180. $this->_session_id = $session_id;
  181. }
  182. $key = $this->_key_prefix.$session_id;
  183. $this->_memcached->replace($this->_lock_key, time(), 300);
  184. if ($this->_fingerprint !== ($fingerprint = md5($session_data)))
  185. {
  186. if ($this->_memcached->set($key, $session_data, $this->_config['expiration']))
  187. {
  188. $this->_fingerprint = $fingerprint;
  189. return $this->_success;
  190. }
  191. return $this->_fail();
  192. }
  193. elseif (
  194. $this->_memcached->touch($key, $this->_config['expiration'])
  195. OR ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND && $this->_memcached->set($key, $session_data, $this->_config['expiration']))
  196. )
  197. {
  198. return $this->_success;
  199. }
  200. return $this->_fail();
  201. }
  202. // ------------------------------------------------------------------------
  203. /**
  204. * Close
  205. *
  206. * Releases locks and closes connection.
  207. *
  208. * @return bool
  209. */
  210. public function close()
  211. {
  212. if (isset($this->_memcached))
  213. {
  214. $this->_release_lock();
  215. if ( ! $this->_memcached->quit())
  216. {
  217. return $this->_fail();
  218. }
  219. $this->_memcached = NULL;
  220. return $this->_success;
  221. }
  222. return $this->_fail();
  223. }
  224. // ------------------------------------------------------------------------
  225. /**
  226. * Destroy
  227. *
  228. * Destroys the current session.
  229. *
  230. * @param string $session_id Session ID
  231. * @return bool
  232. */
  233. public function destroy($session_id)
  234. {
  235. if (isset($this->_memcached, $this->_lock_key))
  236. {
  237. $this->_memcached->delete($this->_key_prefix.$session_id);
  238. $this->_cookie_destroy();
  239. return $this->_success;
  240. }
  241. return $this->_fail();
  242. }
  243. // ------------------------------------------------------------------------
  244. /**
  245. * Garbage Collector
  246. *
  247. * Deletes expired sessions
  248. *
  249. * @param int $maxlifetime Maximum lifetime of sessions
  250. * @return bool
  251. */
  252. public function gc($maxlifetime)
  253. {
  254. // Not necessary, Memcached takes care of that.
  255. return $this->_success;
  256. }
  257. // ------------------------------------------------------------------------
  258. /**
  259. * Get lock
  260. *
  261. * Acquires an (emulated) lock.
  262. *
  263. * @param string $session_id Session ID
  264. * @return bool
  265. */
  266. protected function _get_lock($session_id)
  267. {
  268. // PHP 7 reuses the SessionHandler object on regeneration,
  269. // so we need to check here if the lock key is for the
  270. // correct session ID.
  271. if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
  272. {
  273. if ( ! $this->_memcached->replace($this->_lock_key, time(), 300))
  274. {
  275. return ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND)
  276. ? $this->_memcached->set($this->_lock_key, time(), 300)
  277. : FALSE;
  278. }
  279. }
  280. // 30 attempts to obtain a lock, in case another request already has it
  281. $lock_key = $this->_key_prefix.$session_id.':lock';
  282. $attempt = 0;
  283. do
  284. {
  285. if ($this->_memcached->get($lock_key))
  286. {
  287. sleep(1);
  288. continue;
  289. }
  290. if ( ! $this->_memcached->set($lock_key, time(), 300))
  291. {
  292. log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
  293. return FALSE;
  294. }
  295. $this->_lock_key = $lock_key;
  296. break;
  297. }
  298. while (++$attempt < 30);
  299. if ($attempt === 30)
  300. {
  301. log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
  302. return FALSE;
  303. }
  304. $this->_lock = TRUE;
  305. return TRUE;
  306. }
  307. // ------------------------------------------------------------------------
  308. /**
  309. * Release lock
  310. *
  311. * Releases a previously acquired lock
  312. *
  313. * @return bool
  314. */
  315. protected function _release_lock()
  316. {
  317. if (isset($this->_memcached, $this->_lock_key) && $this->_lock)
  318. {
  319. if ( ! $this->_memcached->delete($this->_lock_key) && $this->_memcached->getResultCode() !== Memcached::RES_NOTFOUND)
  320. {
  321. log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
  322. return FALSE;
  323. }
  324. $this->_lock_key = NULL;
  325. $this->_lock = FALSE;
  326. }
  327. return TRUE;
  328. }
  329. }