Session_memcached_driver.php 9.4 KB

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