PageRenderTime 84ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/system/libraries/Session/drivers/Session_files_driver.php

https://gitlab.com/exabyte-lab/tiffinbox
PHP | 426 lines | 213 code | 51 blank | 162 comment | 27 complexity | 55c40b6a7341611ebf3c08ae3e480145 MD5 | raw file
  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 - 2019, 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 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://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. $this->php5_validate_id();
  136. return $this->_success;
  137. }
  138. // ------------------------------------------------------------------------
  139. /**
  140. * Read
  141. *
  142. * Reads session data and acquires a lock
  143. *
  144. * @param string $session_id Session ID
  145. * @return string Serialized session data
  146. */
  147. public function read($session_id)
  148. {
  149. // This might seem weird, but PHP 5.6 introduces session_reset(),
  150. // which re-reads session data
  151. if ($this->_file_handle === NULL)
  152. {
  153. $this->_file_new = ! file_exists($this->_file_path.$session_id);
  154. if (($this->_file_handle = fopen($this->_file_path.$session_id, 'c+b')) === FALSE)
  155. {
  156. log_message('error', "Session: Unable to open file '".$this->_file_path.$session_id."'.");
  157. return $this->_failure;
  158. }
  159. if (flock($this->_file_handle, LOCK_EX) === FALSE)
  160. {
  161. log_message('error', "Session: Unable to obtain lock for file '".$this->_file_path.$session_id."'.");
  162. fclose($this->_file_handle);
  163. $this->_file_handle = NULL;
  164. return $this->_failure;
  165. }
  166. // Needed by write() to detect session_regenerate_id() calls
  167. $this->_session_id = $session_id;
  168. if ($this->_file_new)
  169. {
  170. chmod($this->_file_path.$session_id, 0600);
  171. $this->_fingerprint = md5('');
  172. return '';
  173. }
  174. }
  175. // We shouldn't need this, but apparently we do ...
  176. // See https://github.com/bcit-ci/CodeIgniter/issues/4039
  177. elseif ($this->_file_handle === FALSE)
  178. {
  179. return $this->_failure;
  180. }
  181. else
  182. {
  183. rewind($this->_file_handle);
  184. }
  185. $session_data = '';
  186. for ($read = 0, $length = filesize($this->_file_path.$session_id); $read < $length; $read += self::strlen($buffer))
  187. {
  188. if (($buffer = fread($this->_file_handle, $length - $read)) === FALSE)
  189. {
  190. break;
  191. }
  192. $session_data .= $buffer;
  193. }
  194. $this->_fingerprint = md5($session_data);
  195. return $session_data;
  196. }
  197. // ------------------------------------------------------------------------
  198. /**
  199. * Write
  200. *
  201. * Writes (create / update) session data
  202. *
  203. * @param string $session_id Session ID
  204. * @param string $session_data Serialized session data
  205. * @return bool
  206. */
  207. public function write($session_id, $session_data)
  208. {
  209. // If the two IDs don't match, we have a session_regenerate_id() call
  210. // and we need to close the old handle and open a new one
  211. if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure))
  212. {
  213. return $this->_failure;
  214. }
  215. if ( ! is_resource($this->_file_handle))
  216. {
  217. return $this->_failure;
  218. }
  219. elseif ($this->_fingerprint === md5($session_data))
  220. {
  221. return ( ! $this->_file_new && ! touch($this->_file_path.$session_id))
  222. ? $this->_failure
  223. : $this->_success;
  224. }
  225. if ( ! $this->_file_new)
  226. {
  227. ftruncate($this->_file_handle, 0);
  228. rewind($this->_file_handle);
  229. }
  230. if (($length = strlen($session_data)) > 0)
  231. {
  232. for ($written = 0; $written < $length; $written += $result)
  233. {
  234. if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE)
  235. {
  236. break;
  237. }
  238. }
  239. if ( ! is_int($result))
  240. {
  241. $this->_fingerprint = md5(substr($session_data, 0, $written));
  242. log_message('error', 'Session: Unable to write data.');
  243. return $this->_failure;
  244. }
  245. }
  246. $this->_fingerprint = md5($session_data);
  247. return $this->_success;
  248. }
  249. // ------------------------------------------------------------------------
  250. /**
  251. * Close
  252. *
  253. * Releases locks and closes file descriptor.
  254. *
  255. * @return bool
  256. */
  257. public function close()
  258. {
  259. if (is_resource($this->_file_handle))
  260. {
  261. flock($this->_file_handle, LOCK_UN);
  262. fclose($this->_file_handle);
  263. $this->_file_handle = $this->_file_new = $this->_session_id = NULL;
  264. }
  265. return $this->_success;
  266. }
  267. // ------------------------------------------------------------------------
  268. /**
  269. * Destroy
  270. *
  271. * Destroys the current session.
  272. *
  273. * @param string $session_id Session ID
  274. * @return bool
  275. */
  276. public function destroy($session_id)
  277. {
  278. if ($this->close() === $this->_success)
  279. {
  280. if (file_exists($this->_file_path.$session_id))
  281. {
  282. $this->_cookie_destroy();
  283. return unlink($this->_file_path.$session_id)
  284. ? $this->_success
  285. : $this->_failure;
  286. }
  287. return $this->_success;
  288. }
  289. elseif ($this->_file_path !== NULL)
  290. {
  291. clearstatcache();
  292. if (file_exists($this->_file_path.$session_id))
  293. {
  294. $this->_cookie_destroy();
  295. return unlink($this->_file_path.$session_id)
  296. ? $this->_success
  297. : $this->_failure;
  298. }
  299. return $this->_success;
  300. }
  301. return $this->_failure;
  302. }
  303. // ------------------------------------------------------------------------
  304. /**
  305. * Garbage Collector
  306. *
  307. * Deletes expired sessions
  308. *
  309. * @param int $maxlifetime Maximum lifetime of sessions
  310. * @return bool
  311. */
  312. public function gc($maxlifetime)
  313. {
  314. if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE)
  315. {
  316. log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'.");
  317. return $this->_failure;
  318. }
  319. $ts = time() - $maxlifetime;
  320. $pattern = ($this->_config['match_ip'] === TRUE)
  321. ? '[0-9a-f]{32}'
  322. : '';
  323. $pattern = sprintf(
  324. '#\A%s'.$pattern.$this->_sid_regexp.'\z#',
  325. preg_quote($this->_config['cookie_name'])
  326. );
  327. while (($file = readdir($directory)) !== FALSE)
  328. {
  329. // If the filename doesn't match this pattern, it's either not a session file or is not ours
  330. if ( ! preg_match($pattern, $file)
  331. OR ! is_file($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)
  332. OR ($mtime = filemtime($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)) === FALSE
  333. OR $mtime > $ts)
  334. {
  335. continue;
  336. }
  337. unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file);
  338. }
  339. closedir($directory);
  340. return $this->_success;
  341. }
  342. // --------------------------------------------------------------------
  343. /**
  344. * Validate ID
  345. *
  346. * Checks whether a session ID record exists server-side,
  347. * to enforce session.use_strict_mode.
  348. *
  349. * @param string $id
  350. * @return bool
  351. */
  352. public function validateSessionId($id)
  353. {
  354. $result = is_file($this->_file_path.$id);
  355. clearstatcache(TRUE, $this->_file_path.$id);
  356. return $result;
  357. }
  358. // --------------------------------------------------------------------
  359. /**
  360. * Byte-safe strlen()
  361. *
  362. * @param string $str
  363. * @return int
  364. */
  365. protected static function strlen($str)
  366. {
  367. return (self::$func_overload)
  368. ? mb_strlen($str, '8bit')
  369. : strlen($str);
  370. }
  371. }