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.

406 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 Files 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_files_driver extends CI_Session_driver implements SessionHandlerInterface {
  49. /**
  50. * Save path
  51. *
  52. * @var string
  53. */
  54. protected $_save_path;
  55. /**
  56. * File handle
  57. *
  58. * @var resource
  59. */
  60. protected $_file_handle;
  61. /**
  62. * File name
  63. *
  64. * @var resource
  65. */
  66. protected $_file_path;
  67. /**
  68. * File new flag
  69. *
  70. * @var bool
  71. */
  72. protected $_file_new;
  73. /**
  74. * Validate SID regular expression
  75. *
  76. * @var string
  77. */
  78. protected $_sid_regexp;
  79. /**
  80. * mbstring.func_overload flag
  81. *
  82. * @var bool
  83. */
  84. protected static $func_overload;
  85. // ------------------------------------------------------------------------
  86. /**
  87. * Class constructor
  88. *
  89. * @param array $params Configuration parameters
  90. * @return void
  91. */
  92. public function __construct(&$params)
  93. {
  94. parent::__construct($params);
  95. if (isset($this->_config['save_path']))
  96. {
  97. $this->_config['save_path'] = rtrim($this->_config['save_path'], '/\\');
  98. ini_set('session.save_path', $this->_config['save_path']);
  99. }
  100. else
  101. {
  102. log_message('debug', 'Session: "sess_save_path" is empty; using "session.save_path" value from php.ini.');
  103. $this->_config['save_path'] = rtrim(ini_get('session.save_path'), '/\\');
  104. }
  105. $this->_sid_regexp = $this->_config['_sid_regexp'];
  106. isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload'));
  107. }
  108. // ------------------------------------------------------------------------
  109. /**
  110. * Open
  111. *
  112. * Sanitizes the save_path directory.
  113. *
  114. * @param string $save_path Path to session files' directory
  115. * @param string $name Session cookie name
  116. * @return bool
  117. */
  118. public function open($save_path, $name)
  119. {
  120. if ( ! is_dir($save_path))
  121. {
  122. if ( ! mkdir($save_path, 0700, TRUE))
  123. {
  124. throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not a directory, doesn't exist or cannot be created.");
  125. }
  126. }
  127. elseif ( ! is_writable($save_path))
  128. {
  129. throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not writable by the PHP process.");
  130. }
  131. $this->_config['save_path'] = $save_path;
  132. $this->_file_path = $this->_config['save_path'].DIRECTORY_SEPARATOR
  133. .$name // we'll use the session cookie name as a prefix to avoid collisions
  134. .($this->_config['match_ip'] ? md5($_SERVER['REMOTE_ADDR']) : '');
  135. return $this->_success;
  136. }
  137. // ------------------------------------------------------------------------
  138. /**
  139. * Read
  140. *
  141. * Reads session data and acquires a lock
  142. *
  143. * @param string $session_id Session ID
  144. * @return string Serialized session data
  145. */
  146. public function read($session_id)
  147. {
  148. // This might seem weird, but PHP 5.6 introduces session_reset(),
  149. // which re-reads session data
  150. if ($this->_file_handle === NULL)
  151. {
  152. $this->_file_new = ! file_exists($this->_file_path.$session_id);
  153. if (($this->_file_handle = fopen($this->_file_path.$session_id, 'c+b')) === FALSE)
  154. {
  155. log_message('error', "Session: Unable to open file '".$this->_file_path.$session_id."'.");
  156. return $this->_failure;
  157. }
  158. if (flock($this->_file_handle, LOCK_EX) === FALSE)
  159. {
  160. log_message('error', "Session: Unable to obtain lock for file '".$this->_file_path.$session_id."'.");
  161. fclose($this->_file_handle);
  162. $this->_file_handle = NULL;
  163. return $this->_failure;
  164. }
  165. // Needed by write() to detect session_regenerate_id() calls
  166. $this->_session_id = $session_id;
  167. if ($this->_file_new)
  168. {
  169. chmod($this->_file_path.$session_id, 0600);
  170. $this->_fingerprint = md5('');
  171. return '';
  172. }
  173. }
  174. // We shouldn't need this, but apparently we do ...
  175. // See https://github.com/bcit-ci/CodeIgniter/issues/4039
  176. elseif ($this->_file_handle === FALSE)
  177. {
  178. return $this->_failure;
  179. }
  180. else
  181. {
  182. rewind($this->_file_handle);
  183. }
  184. $session_data = '';
  185. for ($read = 0, $length = filesize($this->_file_path.$session_id); $read < $length; $read += self::strlen($buffer))
  186. {
  187. if (($buffer = fread($this->_file_handle, $length - $read)) === FALSE)
  188. {
  189. break;
  190. }
  191. $session_data .= $buffer;
  192. }
  193. $this->_fingerprint = md5($session_data);
  194. return $session_data;
  195. }
  196. // ------------------------------------------------------------------------
  197. /**
  198. * Write
  199. *
  200. * Writes (create / update) session data
  201. *
  202. * @param string $session_id Session ID
  203. * @param string $session_data Serialized session data
  204. * @return bool
  205. */
  206. public function write($session_id, $session_data)
  207. {
  208. // If the two IDs don't match, we have a session_regenerate_id() call
  209. // and we need to close the old handle and open a new one
  210. if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure))
  211. {
  212. return $this->_failure;
  213. }
  214. if ( ! is_resource($this->_file_handle))
  215. {
  216. return $this->_failure;
  217. }
  218. elseif ($this->_fingerprint === md5($session_data))
  219. {
  220. return ( ! $this->_file_new && ! touch($this->_file_path.$session_id))
  221. ? $this->_failure
  222. : $this->_success;
  223. }
  224. if ( ! $this->_file_new)
  225. {
  226. ftruncate($this->_file_handle, 0);
  227. rewind($this->_file_handle);
  228. }
  229. if (($length = strlen($session_data)) > 0)
  230. {
  231. for ($written = 0; $written < $length; $written += $result)
  232. {
  233. if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE)
  234. {
  235. break;
  236. }
  237. }
  238. if ( ! is_int($result))
  239. {
  240. $this->_fingerprint = md5(substr($session_data, 0, $written));
  241. log_message('error', 'Session: Unable to write data.');
  242. return $this->_failure;
  243. }
  244. }
  245. $this->_fingerprint = md5($session_data);
  246. return $this->_success;
  247. }
  248. // ------------------------------------------------------------------------
  249. /**
  250. * Close
  251. *
  252. * Releases locks and closes file descriptor.
  253. *
  254. * @return bool
  255. */
  256. public function close()
  257. {
  258. if (is_resource($this->_file_handle))
  259. {
  260. flock($this->_file_handle, LOCK_UN);
  261. fclose($this->_file_handle);
  262. $this->_file_handle = $this->_file_new = $this->_session_id = NULL;
  263. }
  264. return $this->_success;
  265. }
  266. // ------------------------------------------------------------------------
  267. /**
  268. * Destroy
  269. *
  270. * Destroys the current session.
  271. *
  272. * @param string $session_id Session ID
  273. * @return bool
  274. */
  275. public function destroy($session_id)
  276. {
  277. if ($this->close() === $this->_success)
  278. {
  279. if (file_exists($this->_file_path.$session_id))
  280. {
  281. $this->_cookie_destroy();
  282. return unlink($this->_file_path.$session_id)
  283. ? $this->_success
  284. : $this->_failure;
  285. }
  286. return $this->_success;
  287. }
  288. elseif ($this->_file_path !== NULL)
  289. {
  290. clearstatcache();
  291. if (file_exists($this->_file_path.$session_id))
  292. {
  293. $this->_cookie_destroy();
  294. return unlink($this->_file_path.$session_id)
  295. ? $this->_success
  296. : $this->_failure;
  297. }
  298. return $this->_success;
  299. }
  300. return $this->_failure;
  301. }
  302. // ------------------------------------------------------------------------
  303. /**
  304. * Garbage Collector
  305. *
  306. * Deletes expired sessions
  307. *
  308. * @param int $maxlifetime Maximum lifetime of sessions
  309. * @return bool
  310. */
  311. public function gc($maxlifetime)
  312. {
  313. if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE)
  314. {
  315. log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'.");
  316. return $this->_failure;
  317. }
  318. $ts = time() - $maxlifetime;
  319. $pattern = ($this->_config['match_ip'] === TRUE)
  320. ? '[0-9a-f]{32}'
  321. : '';
  322. $pattern = sprintf(
  323. '#\A%s'.$pattern.$this->_sid_regexp.'\z#',
  324. preg_quote($this->_config['cookie_name'])
  325. );
  326. while (($file = readdir($directory)) !== FALSE)
  327. {
  328. // If the filename doesn't match this pattern, it's either not a session file or is not ours
  329. if ( ! preg_match($pattern, $file)
  330. OR ! is_file($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)
  331. OR ($mtime = filemtime($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)) === FALSE
  332. OR $mtime > $ts)
  333. {
  334. continue;
  335. }
  336. unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file);
  337. }
  338. closedir($directory);
  339. return $this->_success;
  340. }
  341. // --------------------------------------------------------------------
  342. /**
  343. * Byte-safe strlen()
  344. *
  345. * @param string $str
  346. * @return int
  347. */
  348. protected static function strlen($str)
  349. {
  350. return (self::$func_overload)
  351. ? mb_strlen($str, '8bit')
  352. : strlen($str);
  353. }
  354. }