Internal.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Session;
  9. use OC\Authentication\Token\IProvider;
  10. use OCP\Authentication\Exceptions\InvalidTokenException;
  11. use OCP\ILogger;
  12. use OCP\Session\Exceptions\SessionNotAvailableException;
  13. use Psr\Log\LoggerInterface;
  14. use function call_user_func_array;
  15. use function microtime;
  16. /**
  17. * Class Internal
  18. *
  19. * wrap php's internal session handling into the Session interface
  20. *
  21. * @package OC\Session
  22. */
  23. class Internal extends Session {
  24. /**
  25. * @param string $name
  26. * @throws \Exception
  27. */
  28. public function __construct(string $name,
  29. private LoggerInterface $logger) {
  30. set_error_handler([$this, 'trapError']);
  31. $this->invoke('session_name', [$name]);
  32. $this->invoke('session_cache_limiter', ['']);
  33. try {
  34. $this->startSession();
  35. } catch (\Exception $e) {
  36. setcookie($this->invoke('session_name'), '', -1, \OC::$WEBROOT ?: '/');
  37. }
  38. restore_error_handler();
  39. if (!isset($_SESSION)) {
  40. throw new \Exception('Failed to start session');
  41. }
  42. }
  43. /**
  44. * @param string $key
  45. * @param integer $value
  46. */
  47. public function set(string $key, $value) {
  48. $reopened = $this->reopen();
  49. $_SESSION[$key] = $value;
  50. if ($reopened) {
  51. $this->close();
  52. }
  53. }
  54. /**
  55. * @param string $key
  56. * @return mixed
  57. */
  58. public function get(string $key) {
  59. if (!$this->exists($key)) {
  60. return null;
  61. }
  62. return $_SESSION[$key];
  63. }
  64. /**
  65. * @param string $key
  66. * @return bool
  67. */
  68. public function exists(string $key): bool {
  69. return isset($_SESSION[$key]);
  70. }
  71. /**
  72. * @param string $key
  73. */
  74. public function remove(string $key) {
  75. if (isset($_SESSION[$key])) {
  76. unset($_SESSION[$key]);
  77. }
  78. }
  79. public function clear() {
  80. $this->reopen();
  81. $this->invoke('session_unset');
  82. $this->regenerateId();
  83. $this->invoke('session_write_close');
  84. $this->startSession(true);
  85. $_SESSION = [];
  86. }
  87. public function close() {
  88. $this->invoke('session_write_close');
  89. parent::close();
  90. }
  91. /**
  92. * Wrapper around session_regenerate_id
  93. *
  94. * @param bool $deleteOldSession Whether to delete the old associated session file or not.
  95. * @param bool $updateToken Whether to update the associated auth token
  96. * @return void
  97. */
  98. public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) {
  99. $this->reopen();
  100. $oldId = null;
  101. if ($updateToken) {
  102. // Get the old id to update the token
  103. try {
  104. $oldId = $this->getId();
  105. } catch (SessionNotAvailableException $e) {
  106. // We can't update a token if there is no previous id
  107. $updateToken = false;
  108. }
  109. }
  110. try {
  111. @session_regenerate_id($deleteOldSession);
  112. } catch (\Error $e) {
  113. $this->trapError($e->getCode(), $e->getMessage());
  114. }
  115. if ($updateToken) {
  116. // Get the new id to update the token
  117. $newId = $this->getId();
  118. /** @var IProvider $tokenProvider */
  119. $tokenProvider = \OCP\Server::get(IProvider::class);
  120. try {
  121. $tokenProvider->renewSessionToken($oldId, $newId);
  122. } catch (InvalidTokenException $e) {
  123. // Just ignore
  124. }
  125. }
  126. }
  127. /**
  128. * Wrapper around session_id
  129. *
  130. * @return string
  131. * @throws SessionNotAvailableException
  132. * @since 9.1.0
  133. */
  134. public function getId(): string {
  135. $id = $this->invoke('session_id', [], true);
  136. if ($id === '') {
  137. throw new SessionNotAvailableException();
  138. }
  139. return $id;
  140. }
  141. /**
  142. * @throws \Exception
  143. */
  144. public function reopen(): bool {
  145. if ($this->sessionClosed) {
  146. $this->startSession(false, false);
  147. $this->sessionClosed = false;
  148. return true;
  149. }
  150. return false;
  151. }
  152. /**
  153. * @param int $errorNumber
  154. * @param string $errorString
  155. * @throws \ErrorException
  156. */
  157. public function trapError(int $errorNumber, string $errorString) {
  158. if ($errorNumber & E_ERROR) {
  159. throw new \ErrorException($errorString);
  160. }
  161. }
  162. /**
  163. * @param string $functionName the full session_* function name
  164. * @param array $parameters
  165. * @param bool $silence whether to suppress warnings
  166. * @throws \ErrorException via trapError
  167. * @return mixed
  168. */
  169. private function invoke(string $functionName, array $parameters = [], bool $silence = false) {
  170. try {
  171. $timeBefore = microtime(true);
  172. if ($silence) {
  173. $result = @call_user_func_array($functionName, $parameters);
  174. } else {
  175. $result = call_user_func_array($functionName, $parameters);
  176. }
  177. $timeAfter = microtime(true);
  178. $timeSpent = $timeAfter - $timeBefore;
  179. if ($timeSpent > 0.1) {
  180. $logLevel = match (true) {
  181. $timeSpent > 25 => ILogger::ERROR,
  182. $timeSpent > 10 => ILogger::WARN,
  183. $timeSpent > 0.5 => ILogger::INFO,
  184. default => ILogger::DEBUG,
  185. };
  186. $this->logger->log(
  187. $logLevel,
  188. "Slow session operation $functionName detected",
  189. [
  190. 'parameters' => $parameters,
  191. 'timeSpent' => $timeSpent,
  192. ],
  193. );
  194. }
  195. return $result;
  196. } catch (\Error $e) {
  197. $this->trapError($e->getCode(), $e->getMessage());
  198. }
  199. }
  200. private function startSession(bool $silence = false, bool $readAndClose = true) {
  201. $sessionParams = ['cookie_samesite' => 'Lax'];
  202. if (\OC::hasSessionRelaxedExpiry()) {
  203. $sessionParams['read_and_close'] = $readAndClose;
  204. }
  205. $this->invoke('session_start', [$sessionParams], $silence);
  206. }
  207. }