Internal.php 5.2 KB

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