Merge "Http::getProxy() method to get proxy configuration"
[lhc/web/wiklou.git] / includes / session / SessionBackend.php
1 <?php
2 /**
3 * MediaWiki session backend
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Session
22 */
23
24 namespace MediaWiki\Session;
25
26 use CachedBagOStuff;
27 use Psr\Log\LoggerInterface;
28 use User;
29 use WebRequest;
30
31 /**
32 * This is the actual workhorse for Session.
33 *
34 * Most code does not need to use this class, you want \\MediaWiki\\Session\\Session.
35 * The exceptions are SessionProviders and SessionMetadata hook functions,
36 * which get an instance of this class rather than Session.
37 *
38 * The reasons for this split are:
39 * 1. A session can be attached to multiple requests, but we want the Session
40 * object to have some features that correspond to just one of those
41 * requests.
42 * 2. We want reasonable garbage collection behavior, but we also want the
43 * SessionManager to hold a reference to every active session so it can be
44 * saved when the request ends.
45 *
46 * @ingroup Session
47 * @since 1.27
48 */
49 final class SessionBackend {
50 /** @var SessionId */
51 private $id;
52
53 private $persist = false;
54 private $remember = false;
55 private $forceHTTPS = false;
56
57 /** @var array|null */
58 private $data = null;
59
60 private $forcePersist = false;
61 private $metaDirty = false;
62 private $dataDirty = false;
63
64 /** @var string Used to detect subarray modifications */
65 private $dataHash = null;
66
67 /** @var CachedBagOStuff */
68 private $store;
69
70 /** @var LoggerInterface */
71 private $logger;
72
73 /** @var int */
74 private $lifetime;
75
76 /** @var User */
77 private $user;
78
79 private $curIndex = 0;
80
81 /** @var WebRequest[] Session requests */
82 private $requests = [];
83
84 /** @var SessionProvider provider */
85 private $provider;
86
87 /** @var array|null provider-specified metadata */
88 private $providerMetadata = null;
89
90 private $expires = 0;
91 private $loggedOut = 0;
92 private $delaySave = 0;
93
94 private $usePhpSessionHandling = true;
95 private $checkPHPSessionRecursionGuard = false;
96
97 /**
98 * @param SessionId $id Session ID object
99 * @param SessionInfo $info Session info to populate from
100 * @param CachedBagOStuff $store Backend data store
101 * @param LoggerInterface $logger
102 * @param int $lifetime Session data lifetime in seconds
103 */
104 public function __construct(
105 SessionId $id, SessionInfo $info, CachedBagOStuff $store, LoggerInterface $logger, $lifetime
106 ) {
107 $phpSessionHandling = \RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' );
108 $this->usePhpSessionHandling = $phpSessionHandling !== 'disable';
109
110 if ( $info->getUserInfo() && !$info->getUserInfo()->isVerified() ) {
111 throw new \InvalidArgumentException(
112 "Refusing to create session for unverified user {$info->getUserInfo()}"
113 );
114 }
115 if ( $info->getProvider() === null ) {
116 throw new \InvalidArgumentException( 'Cannot create session without a provider' );
117 }
118 if ( $info->getId() !== $id->getId() ) {
119 throw new \InvalidArgumentException( 'SessionId and SessionInfo don\'t match' );
120 }
121
122 $this->id = $id;
123 $this->user = $info->getUserInfo() ? $info->getUserInfo()->getUser() : new User;
124 $this->store = $store;
125 $this->logger = $logger;
126 $this->lifetime = $lifetime;
127 $this->provider = $info->getProvider();
128 $this->persist = $info->wasPersisted();
129 $this->remember = $info->wasRemembered();
130 $this->forceHTTPS = $info->forceHTTPS();
131 $this->providerMetadata = $info->getProviderMetadata();
132
133 $blob = $store->get( wfMemcKey( 'MWSession', (string)$this->id ) );
134 if ( !is_array( $blob ) ||
135 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] ) ||
136 !isset( $blob['data'] ) || !is_array( $blob['data'] )
137 ) {
138 $this->data = [];
139 $this->dataDirty = true;
140 $this->metaDirty = true;
141 $this->logger->debug(
142 'SessionBackend "{session}" is unsaved, marking dirty in constructor',
143 [
144 'session' => $this->id,
145 ] );
146 } else {
147 $this->data = $blob['data'];
148 if ( isset( $blob['metadata']['loggedOut'] ) ) {
149 $this->loggedOut = (int)$blob['metadata']['loggedOut'];
150 }
151 if ( isset( $blob['metadata']['expires'] ) ) {
152 $this->expires = (int)$blob['metadata']['expires'];
153 } else {
154 $this->metaDirty = true;
155 $this->logger->debug(
156 'SessionBackend "{session}" metadata dirty due to missing expiration timestamp',
157 [
158 'session' => $this->id,
159 ] );
160 }
161 }
162 $this->dataHash = md5( serialize( $this->data ) );
163 }
164
165 /**
166 * Return a new Session for this backend
167 * @param WebRequest $request
168 * @return Session
169 */
170 public function getSession( WebRequest $request ) {
171 $index = ++$this->curIndex;
172 $this->requests[$index] = $request;
173 $session = new Session( $this, $index, $this->logger );
174 return $session;
175 }
176
177 /**
178 * Deregister a Session
179 * @private For use by \\MediaWiki\\Session\\Session::__destruct() only
180 * @param int $index
181 */
182 public function deregisterSession( $index ) {
183 unset( $this->requests[$index] );
184 if ( !count( $this->requests ) ) {
185 $this->save( true );
186 $this->provider->getManager()->deregisterSessionBackend( $this );
187 }
188 }
189
190 /**
191 * Returns the session ID.
192 * @return string
193 */
194 public function getId() {
195 return (string)$this->id;
196 }
197
198 /**
199 * Fetch the SessionId object
200 * @private For internal use by WebRequest
201 * @return SessionId
202 */
203 public function getSessionId() {
204 return $this->id;
205 }
206
207 /**
208 * Changes the session ID
209 * @return string New ID (might be the same as the old)
210 */
211 public function resetId() {
212 if ( $this->provider->persistsSessionId() ) {
213 $oldId = (string)$this->id;
214 $restart = $this->usePhpSessionHandling && $oldId === session_id() &&
215 PHPSessionHandler::isEnabled();
216
217 if ( $restart ) {
218 // If this session is the one behind PHP's $_SESSION, we need
219 // to close then reopen it.
220 session_write_close();
221 }
222
223 $this->provider->getManager()->changeBackendId( $this );
224 $this->provider->sessionIdWasReset( $this, $oldId );
225 $this->metaDirty = true;
226 $this->logger->debug(
227 'SessionBackend "{session}" metadata dirty due to ID reset (formerly "{oldId}")',
228 [
229 'session' => $this->id,
230 'oldId' => $oldId,
231 ] );
232
233 if ( $restart ) {
234 session_id( (string)$this->id );
235 \MediaWiki\quietCall( 'session_start' );
236 }
237
238 $this->autosave();
239
240 // Delete the data for the old session ID now
241 $this->store->delete( wfMemcKey( 'MWSession', $oldId ) );
242 }
243 }
244
245 /**
246 * Fetch the SessionProvider for this session
247 * @return SessionProviderInterface
248 */
249 public function getProvider() {
250 return $this->provider;
251 }
252
253 /**
254 * Indicate whether this session is persisted across requests
255 *
256 * For example, if cookies are set.
257 *
258 * @return bool
259 */
260 public function isPersistent() {
261 return $this->persist;
262 }
263
264 /**
265 * Make this session persisted across requests
266 *
267 * If the session is already persistent, equivalent to calling
268 * $this->renew().
269 */
270 public function persist() {
271 if ( !$this->persist ) {
272 $this->persist = true;
273 $this->forcePersist = true;
274 $this->metaDirty = true;
275 $this->logger->debug(
276 'SessionBackend "{session}" force-persist due to persist()',
277 [
278 'session' => $this->id,
279 ] );
280 $this->autosave();
281 } else {
282 $this->renew();
283 }
284 }
285
286 /**
287 * Make this session not persisted across requests
288 */
289 public function unpersist() {
290 if ( $this->persist ) {
291 // Close the PHP session, if we're the one that's open
292 if ( $this->usePhpSessionHandling && PHPSessionHandler::isEnabled() &&
293 session_id() === (string)$this->id
294 ) {
295 $this->logger->debug(
296 'SessionBackend "{session}" Closing PHP session for unpersist',
297 [ 'session' => $this->id ]
298 );
299 session_write_close();
300 session_id( '' );
301 }
302
303 $this->persist = false;
304 $this->forcePersist = true;
305 $this->metaDirty = true;
306
307 // Delete the session data, so the local cache-only write in
308 // self::save() doesn't get things out of sync with the backend.
309 $this->store->delete( wfMemcKey( 'MWSession', (string)$this->id ) );
310
311 $this->autosave();
312 }
313 }
314
315 /**
316 * Indicate whether the user should be remembered independently of the
317 * session ID.
318 * @return bool
319 */
320 public function shouldRememberUser() {
321 return $this->remember;
322 }
323
324 /**
325 * Set whether the user should be remembered independently of the session
326 * ID.
327 * @param bool $remember
328 */
329 public function setRememberUser( $remember ) {
330 if ( $this->remember !== (bool)$remember ) {
331 $this->remember = (bool)$remember;
332 $this->metaDirty = true;
333 $this->logger->debug(
334 'SessionBackend "{session}" metadata dirty due to remember-user change',
335 [
336 'session' => $this->id,
337 ] );
338 $this->autosave();
339 }
340 }
341
342 /**
343 * Returns the request associated with a Session
344 * @param int $index Session index
345 * @return WebRequest
346 */
347 public function getRequest( $index ) {
348 if ( !isset( $this->requests[$index] ) ) {
349 throw new \InvalidArgumentException( 'Invalid session index' );
350 }
351 return $this->requests[$index];
352 }
353
354 /**
355 * Returns the authenticated user for this session
356 * @return User
357 */
358 public function getUser() {
359 return $this->user;
360 }
361
362 /**
363 * Fetch the rights allowed the user when this session is active.
364 * @return null|string[] Allowed user rights, or null to allow all.
365 */
366 public function getAllowedUserRights() {
367 return $this->provider->getAllowedUserRights( $this );
368 }
369
370 /**
371 * Indicate whether the session user info can be changed
372 * @return bool
373 */
374 public function canSetUser() {
375 return $this->provider->canChangeUser();
376 }
377
378 /**
379 * Set a new user for this session
380 * @note This should only be called when the user has been authenticated via a login process
381 * @param User $user User to set on the session.
382 * This may become a "UserValue" in the future, or User may be refactored
383 * into such.
384 */
385 public function setUser( $user ) {
386 if ( !$this->canSetUser() ) {
387 throw new \BadMethodCallException(
388 'Cannot set user on this session; check $session->canSetUser() first'
389 );
390 }
391
392 $this->user = $user;
393 $this->metaDirty = true;
394 $this->logger->debug(
395 'SessionBackend "{session}" metadata dirty due to user change',
396 [
397 'session' => $this->id,
398 ] );
399 $this->autosave();
400 }
401
402 /**
403 * Get a suggested username for the login form
404 * @param int $index Session index
405 * @return string|null
406 */
407 public function suggestLoginUsername( $index ) {
408 if ( !isset( $this->requests[$index] ) ) {
409 throw new \InvalidArgumentException( 'Invalid session index' );
410 }
411 return $this->provider->suggestLoginUsername( $this->requests[$index] );
412 }
413
414 /**
415 * Whether HTTPS should be forced
416 * @return bool
417 */
418 public function shouldForceHTTPS() {
419 return $this->forceHTTPS;
420 }
421
422 /**
423 * Set whether HTTPS should be forced
424 * @param bool $force
425 */
426 public function setForceHTTPS( $force ) {
427 if ( $this->forceHTTPS !== (bool)$force ) {
428 $this->forceHTTPS = (bool)$force;
429 $this->metaDirty = true;
430 $this->logger->debug(
431 'SessionBackend "{session}" metadata dirty due to force-HTTPS change',
432 [
433 'session' => $this->id,
434 ] );
435 $this->autosave();
436 }
437 }
438
439 /**
440 * Fetch the "logged out" timestamp
441 * @return int
442 */
443 public function getLoggedOutTimestamp() {
444 return $this->loggedOut;
445 }
446
447 /**
448 * Set the "logged out" timestamp
449 * @param int $ts
450 */
451 public function setLoggedOutTimestamp( $ts = null ) {
452 $ts = (int)$ts;
453 if ( $this->loggedOut !== $ts ) {
454 $this->loggedOut = $ts;
455 $this->metaDirty = true;
456 $this->logger->debug(
457 'SessionBackend "{session}" metadata dirty due to logged-out-timestamp change',
458 [
459 'session' => $this->id,
460 ] );
461 $this->autosave();
462 }
463 }
464
465 /**
466 * Fetch provider metadata
467 * @protected For use by SessionProvider subclasses only
468 * @return array|null
469 */
470 public function getProviderMetadata() {
471 return $this->providerMetadata;
472 }
473
474 /**
475 * Set provider metadata
476 * @protected For use by SessionProvider subclasses only
477 * @param array|null $metadata
478 */
479 public function setProviderMetadata( $metadata ) {
480 if ( $metadata !== null && !is_array( $metadata ) ) {
481 throw new \InvalidArgumentException( '$metadata must be an array or null' );
482 }
483 if ( $this->providerMetadata !== $metadata ) {
484 $this->providerMetadata = $metadata;
485 $this->metaDirty = true;
486 $this->logger->debug(
487 'SessionBackend "{session}" metadata dirty due to provider metadata change',
488 [
489 'session' => $this->id,
490 ] );
491 $this->autosave();
492 }
493 }
494
495 /**
496 * Fetch the session data array
497 *
498 * Note the caller is responsible for calling $this->dirty() if anything in
499 * the array is changed.
500 *
501 * @private For use by \\MediaWiki\\Session\\Session only.
502 * @return array
503 */
504 public function &getData() {
505 return $this->data;
506 }
507
508 /**
509 * Add data to the session.
510 *
511 * Overwrites any existing data under the same keys.
512 *
513 * @param array $newData Key-value pairs to add to the session
514 */
515 public function addData( array $newData ) {
516 $data = &$this->getData();
517 foreach ( $newData as $key => $value ) {
518 if ( !array_key_exists( $key, $data ) || $data[$key] !== $value ) {
519 $data[$key] = $value;
520 $this->dataDirty = true;
521 $this->logger->debug(
522 'SessionBackend "{session}" data dirty due to addData(): {callers}',
523 [
524 'session' => $this->id,
525 'callers' => wfGetAllCallers( 5 ),
526 ] );
527 }
528 }
529 }
530
531 /**
532 * Mark data as dirty
533 * @private For use by \\MediaWiki\\Session\\Session only.
534 */
535 public function dirty() {
536 $this->dataDirty = true;
537 $this->logger->debug(
538 'SessionBackend "{session}" data dirty due to dirty(): {callers}',
539 [
540 'session' => $this->id,
541 'callers' => wfGetAllCallers( 5 ),
542 ] );
543 }
544
545 /**
546 * Renew the session by resaving everything
547 *
548 * Resets the TTL in the backend store if the session is near expiring, and
549 * re-persists the session to any active WebRequests if persistent.
550 */
551 public function renew() {
552 if ( time() + $this->lifetime / 2 > $this->expires ) {
553 $this->metaDirty = true;
554 $this->logger->debug(
555 'SessionBackend "{callers}" metadata dirty for renew(): {callers}',
556 [
557 'session' => $this->id,
558 'callers' => wfGetAllCallers( 5 ),
559 ] );
560 if ( $this->persist ) {
561 $this->forcePersist = true;
562 $this->logger->debug(
563 'SessionBackend "{session}" force-persist for renew(): {callers}',
564 [
565 'session' => $this->id,
566 'callers' => wfGetAllCallers( 5 ),
567 ] );
568 }
569 }
570 $this->autosave();
571 }
572
573 /**
574 * Delay automatic saving while multiple updates are being made
575 *
576 * Calls to save() will not be delayed.
577 *
578 * @return \ScopedCallback When this goes out of scope, a save will be triggered
579 */
580 public function delaySave() {
581 $this->delaySave++;
582 return new \ScopedCallback( function () {
583 if ( --$this->delaySave <= 0 ) {
584 $this->delaySave = 0;
585 $this->save();
586 }
587 } );
588 }
589
590 /**
591 * Save and persist session data, unless delayed
592 */
593 private function autosave() {
594 if ( $this->delaySave <= 0 ) {
595 $this->save();
596 }
597 }
598
599 /**
600 * Save and persist session data
601 * @param bool $closing Whether the session is being closed
602 */
603 public function save( $closing = false ) {
604 $anon = $this->user->isAnon();
605
606 if ( !$anon && $this->provider->getManager()->isUserSessionPrevented( $this->user->getName() ) ) {
607 $this->logger->debug(
608 'SessionBackend "{session}" not saving, user {user} was ' .
609 'passed to SessionManager::preventSessionsForUser',
610 [
611 'session' => $this->id,
612 'user' => $this->user,
613 ] );
614 return;
615 }
616
617 // Ensure the user has a token
618 // @codeCoverageIgnoreStart
619 if ( !$anon && !$this->user->getToken( false ) ) {
620 $this->logger->debug(
621 'SessionBackend "{session}" creating token for user {user} on save',
622 [
623 'session' => $this->id,
624 'user' => $this->user,
625 ] );
626 $this->user->setToken();
627 if ( !wfReadOnly() ) {
628 $this->user->saveSettings();
629 }
630 $this->metaDirty = true;
631 }
632 // @codeCoverageIgnoreEnd
633
634 if ( !$this->metaDirty && !$this->dataDirty &&
635 $this->dataHash !== md5( serialize( $this->data ) )
636 ) {
637 $this->logger->debug(
638 'SessionBackend "{session}" data dirty due to hash mismatch, {expected} !== {got}',
639 [
640 'session' => $this->id,
641 'expected' => $this->dataHash,
642 'got' => md5( serialize( $this->data ) ),
643 ] );
644 $this->dataDirty = true;
645 }
646
647 if ( !$this->metaDirty && !$this->dataDirty && !$this->forcePersist ) {
648 return;
649 }
650
651 $this->logger->debug(
652 'SessionBackend "{session}" save: dataDirty={dataDirty} ' .
653 'metaDirty={metaDirty} forcePersist={forcePersist}',
654 [
655 'session' => $this->id,
656 'dataDirty' => (int)$this->dataDirty,
657 'metaDirty' => (int)$this->metaDirty,
658 'forcePersist' => (int)$this->forcePersist,
659 ] );
660
661 // Persist or unpersist to the provider, if necessary
662 if ( $this->metaDirty || $this->forcePersist ) {
663 if ( $this->persist ) {
664 foreach ( $this->requests as $request ) {
665 $request->setSessionId( $this->getSessionId() );
666 $this->provider->persistSession( $this, $request );
667 }
668 if ( !$closing ) {
669 $this->checkPHPSession();
670 }
671 } else {
672 foreach ( $this->requests as $request ) {
673 if ( $request->getSessionId() === $this->id ) {
674 $this->provider->unpersistSession( $request );
675 }
676 }
677 }
678 }
679
680 $this->forcePersist = false;
681
682 if ( !$this->metaDirty && !$this->dataDirty ) {
683 return;
684 }
685
686 // Save session data to store, if necessary
687 $metadata = $origMetadata = [
688 'provider' => (string)$this->provider,
689 'providerMetadata' => $this->providerMetadata,
690 'userId' => $anon ? 0 : $this->user->getId(),
691 'userName' => User::isValidUserName( $this->user->getName() ) ? $this->user->getName() : null,
692 'userToken' => $anon ? null : $this->user->getToken(),
693 'remember' => !$anon && $this->remember,
694 'forceHTTPS' => $this->forceHTTPS,
695 'expires' => time() + $this->lifetime,
696 'loggedOut' => $this->loggedOut,
697 'persisted' => $this->persist,
698 ];
699
700 \Hooks::run( 'SessionMetadata', [ $this, &$metadata, $this->requests ] );
701
702 foreach ( $origMetadata as $k => $v ) {
703 if ( $metadata[$k] !== $v ) {
704 throw new \UnexpectedValueException( "SessionMetadata hook changed metadata key \"$k\"" );
705 }
706 }
707
708 $this->store->set(
709 wfMemcKey( 'MWSession', (string)$this->id ),
710 [
711 'data' => $this->data,
712 'metadata' => $metadata,
713 ],
714 $metadata['expires'],
715 $this->persist ? 0 : CachedBagOStuff::WRITE_CACHE_ONLY
716 );
717
718 $this->metaDirty = false;
719 $this->dataDirty = false;
720 $this->dataHash = md5( serialize( $this->data ) );
721 $this->expires = $metadata['expires'];
722 }
723
724 /**
725 * For backwards compatibility, open the PHP session when the global
726 * session is persisted
727 */
728 private function checkPHPSession() {
729 if ( !$this->checkPHPSessionRecursionGuard ) {
730 $this->checkPHPSessionRecursionGuard = true;
731 $reset = new \ScopedCallback( function () {
732 $this->checkPHPSessionRecursionGuard = false;
733 } );
734
735 if ( $this->usePhpSessionHandling && session_id() === '' && PHPSessionHandler::isEnabled() &&
736 SessionManager::getGlobalSession()->getId() === (string)$this->id
737 ) {
738 $this->logger->debug(
739 'SessionBackend "{session}" Taking over PHP session',
740 [
741 'session' => $this->id,
742 ] );
743 session_id( (string)$this->id );
744 \MediaWiki\quietCall( 'session_start' );
745 }
746 }
747 }
748
749 }