Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / exception / MWExceptionHandler.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\MediaWikiServices;
23 use Psr\Log\LogLevel;
24 use Wikimedia\Rdbms\DBError;
25
26 /**
27 * Handler class for MWExceptions
28 * @ingroup Exception
29 */
30 class MWExceptionHandler {
31 const CAUGHT_BY_HANDLER = 'mwe_handler'; // error reported by this exception handler
32 const CAUGHT_BY_OTHER = 'other'; // error reported by direct logException() call
33
34 /**
35 * @var string $reservedMemory
36 */
37 protected static $reservedMemory;
38
39 /**
40 * Error types that, if unhandled, are fatal to the request.
41 *
42 * On PHP 7, these error types may be thrown as Error objects, which
43 * implement Throwable (but not Exception).
44 *
45 * On HHVM, these invoke the set_error_handler callback, similar to how
46 * (non-fatal) warnings and notices are reported, except that after this
47 * handler runs for fatal error tpyes, script execution stops!
48 *
49 * The user will be shown an HTTP 500 Internal Server Error.
50 * As such, these should be sent to MediaWiki's "fatal" or "exception"
51 * channel. Normally, the error handler logs them to the "error" channel.
52 *
53 * @var array $fatalErrorTypes
54 */
55 protected static $fatalErrorTypes = [
56 E_ERROR,
57 E_PARSE,
58 E_CORE_ERROR,
59 E_COMPILE_ERROR,
60 E_USER_ERROR,
61
62 // E.g. "Catchable fatal error: Argument X must be Y, null given"
63 E_RECOVERABLE_ERROR,
64
65 // HHVM's FATAL_ERROR constant
66 16777217,
67 ];
68 /**
69 * @var bool $handledFatalCallback
70 */
71 protected static $handledFatalCallback = false;
72
73 /**
74 * Install handlers with PHP.
75 */
76 public static function installHandler() {
77 set_exception_handler( 'MWExceptionHandler::handleUncaughtException' );
78 set_error_handler( 'MWExceptionHandler::handleError' );
79
80 // Reserve 16k of memory so we can report OOM fatals
81 self::$reservedMemory = str_repeat( ' ', 16384 );
82 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
83 }
84
85 /**
86 * Report an exception to the user
87 * @param Exception|Throwable $e
88 */
89 protected static function report( $e ) {
90 try {
91 // Try and show the exception prettily, with the normal skin infrastructure
92 if ( $e instanceof MWException ) {
93 // Delegate to MWException until all subclasses are handled by
94 // MWExceptionRenderer and MWException::report() has been
95 // removed.
96 $e->report();
97 } else {
98 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
99 }
100 } catch ( Exception $e2 ) {
101 // Exception occurred from within exception handler
102 // Show a simpler message for the original exception,
103 // don't try to invoke report()
104 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
105 }
106 }
107
108 /**
109 * Roll back any open database transactions and log the stack trace of the exception
110 *
111 * This method is used to attempt to recover from exceptions
112 *
113 * @since 1.23
114 * @param Exception|Throwable $e
115 */
116 public static function rollbackMasterChangesAndLog( $e ) {
117 $services = MediaWikiServices::getInstance();
118 if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
119 // Rollback DBs to avoid transaction notices. This might fail
120 // to rollback some databases due to connection issues or exceptions.
121 // However, any sane DB driver will rollback implicitly anyway.
122 try {
123 $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__ );
124 } catch ( DBError $e2 ) {
125 // If the DB is unreacheable, rollback() will throw an error
126 // and the error report() method might need messages from the DB,
127 // which would result in an exception loop. PHP may escalate such
128 // errors to "Exception thrown without a stack frame" fatals, but
129 // it's better to be explicit here.
130 self::logException( $e2, self::CAUGHT_BY_HANDLER );
131 }
132 }
133
134 self::logException( $e, self::CAUGHT_BY_HANDLER );
135 }
136
137 /**
138 * Callback to use with PHP's set_exception_handler.
139 *
140 * @since 1.31
141 * @param Exception|Throwable $e
142 */
143 public static function handleUncaughtException( $e ) {
144 self::handleException( $e );
145
146 // Make sure we don't claim success on exit for CLI scripts (T177414)
147 if ( wfIsCLI() ) {
148 register_shutdown_function(
149 function () {
150 exit( 255 );
151 }
152 );
153 }
154 }
155
156 /**
157 * Exception handler which simulates the appropriate catch() handling:
158 *
159 * try {
160 * ...
161 * } catch ( Exception $e ) {
162 * $e->report();
163 * } catch ( Exception $e ) {
164 * echo $e->__toString();
165 * }
166 *
167 * @since 1.25
168 * @param Exception|Throwable $e
169 */
170 public static function handleException( $e ) {
171 self::rollbackMasterChangesAndLog( $e );
172 self::report( $e );
173 }
174
175 /**
176 * Handler for set_error_handler() callback notifications.
177 *
178 * Receive a callback from the interpreter for a raised error, create an
179 * ErrorException, and log the exception to the 'error' logging
180 * channel(s). If the raised error is a fatal error type (only under HHVM)
181 * delegate to handleFatalError() instead.
182 *
183 * @since 1.25
184 *
185 * @param int $level Error level raised
186 * @param string $message
187 * @param string|null $file
188 * @param int|null $line
189 * @return bool
190 *
191 * @see logError()
192 */
193 public static function handleError(
194 $level, $message, $file = null, $line = null
195 ) {
196 global $wgPropagateErrors;
197
198 if ( in_array( $level, self::$fatalErrorTypes ) ) {
199 return self::handleFatalError( ...func_get_args() );
200 }
201
202 // Map PHP error constant to a PSR-3 severity level.
203 // Avoid use of "DEBUG" or "INFO" levels, unless the
204 // error should evade error monitoring and alerts.
205 //
206 // To decide the log level, ask yourself: "Has the
207 // program's behaviour diverged from what the written
208 // code expected?"
209 //
210 // For example, use of a deprecated method or violating a strict standard
211 // has no impact on functional behaviour (Warning). On the other hand,
212 // accessing an undefined variable makes behaviour diverge from what the
213 // author intended/expected. PHP recovers from an undefined variables by
214 // yielding null and continuing execution, but it remains a change in
215 // behaviour given the null was not part of the code and is likely not
216 // accounted for.
217 switch ( $level ) {
218 case E_WARNING:
219 case E_CORE_WARNING:
220 case E_COMPILE_WARNING:
221 $levelName = 'Warning';
222 $severity = LogLevel::ERROR;
223 break;
224 case E_NOTICE:
225 $levelName = 'Notice';
226 $severity = LogLevel::ERROR;
227 break;
228 case E_USER_NOTICE:
229 // Used by wfWarn(), MWDebug::warning()
230 $levelName = 'Notice';
231 $severity = LogLevel::WARNING;
232 break;
233 case E_USER_WARNING:
234 // Used by wfWarn(), MWDebug::warning()
235 $levelName = 'Warning';
236 $severity = LogLevel::WARNING;
237 break;
238 case E_STRICT:
239 $levelName = 'Strict Standards';
240 $severity = LogLevel::WARNING;
241 break;
242 case E_DEPRECATED:
243 case E_USER_DEPRECATED:
244 $levelName = 'Deprecated';
245 $severity = LogLevel::WARNING;
246 break;
247 default:
248 $levelName = 'Unknown error';
249 $severity = LogLevel::ERROR;
250 break;
251 }
252
253 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
254 self::logError( $e, 'error', $severity );
255
256 // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
257 // Ignore $wgPropagateErrors if track_errors is set
258 // (which means someone is counting on regular PHP error handling behavior).
259 return !( $wgPropagateErrors || ini_get( 'track_errors' ) );
260 }
261
262 /**
263 * Dual purpose callback used as both a set_error_handler() callback and
264 * a registered shutdown function. Receive a callback from the interpreter
265 * for a raised error or system shutdown, check for a fatal error, and log
266 * to the 'fatal' logging channel.
267 *
268 * Special handling is included for missing class errors as they may
269 * indicate that the user needs to install 3rd-party libraries via
270 * Composer or other means.
271 *
272 * @since 1.25
273 *
274 * @param int|null $level Error level raised
275 * @param string|null $message Error message
276 * @param string|null $file File that error was raised in
277 * @param int|null $line Line number error was raised at
278 * @param array|null $context Active symbol table point of error
279 * @param array|null $trace Backtrace at point of error (undocumented HHVM
280 * feature)
281 * @return bool Always returns false
282 */
283 public static function handleFatalError(
284 $level = null, $message = null, $file = null, $line = null,
285 $context = null, $trace = null
286 ) {
287 // Free reserved memory so that we have space to process OOM
288 // errors
289 self::$reservedMemory = null;
290
291 if ( $level === null ) {
292 // Called as a shutdown handler, get data from error_get_last()
293 if ( static::$handledFatalCallback ) {
294 // Already called once (probably as an error handler callback
295 // under HHVM) so don't log again.
296 return false;
297 }
298
299 $lastError = error_get_last();
300 if ( $lastError !== null ) {
301 $level = $lastError['type'];
302 $message = $lastError['message'];
303 $file = $lastError['file'];
304 $line = $lastError['line'];
305 } else {
306 $level = 0;
307 $message = '';
308 }
309 }
310
311 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
312 // Only interested in fatal errors, others should have been
313 // handled by MWExceptionHandler::handleError
314 return false;
315 }
316
317 $url = WebRequest::getGlobalRequestURL();
318 $msgParts = [
319 '[{exception_id}] {exception_url} PHP Fatal Error',
320 ( $line || $file ) ? ' from' : '',
321 $line ? " line $line" : '',
322 ( $line && $file ) ? ' of' : '',
323 $file ? " $file" : '',
324 ": $message",
325 ];
326 $msg = implode( '', $msgParts );
327
328 // Look at message to see if this is a class not found failure
329 // HHVM: Class undefined: foo
330 // PHP5: Class 'foo' not found
331 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $message ) ) {
332 // phpcs:disable Generic.Files.LineLength
333 $msg = <<<TXT
334 {$msg}
335
336 MediaWiki or an installed extension requires this class but it is not embedded directly in MediaWiki's git repository and must be installed separately by the end user.
337
338 Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
339 TXT;
340 // phpcs:enable
341 }
342
343 // We can't just create an exception and log it as it is likely that
344 // the interpreter has unwound the stack already. If that is true the
345 // stacktrace we would get would be functionally empty. If however we
346 // have been called as an error handler callback *and* HHVM is in use
347 // we will have been provided with a useful stacktrace that we can
348 // log.
349 $trace = $trace ?: debug_backtrace();
350 $logger = LoggerFactory::getInstance( 'fatal' );
351 $logger->error( $msg, [
352 'fatal_exception' => [
353 'class' => ErrorException::class,
354 'message' => "PHP Fatal Error: {$message}",
355 'code' => $level,
356 'file' => $file,
357 'line' => $line,
358 'trace' => self::prettyPrintTrace( self::redactTrace( $trace ) ),
359 ],
360 'exception_id' => WebRequest::getRequestId(),
361 'exception_url' => $url,
362 'caught_by' => self::CAUGHT_BY_HANDLER
363 ] );
364
365 // Remember call so we don't double process via HHVM's fatal
366 // notifications and the shutdown hook behavior
367 static::$handledFatalCallback = true;
368 return false;
369 }
370
371 /**
372 * Generate a string representation of an exception's stack trace
373 *
374 * Like Exception::getTraceAsString, but replaces argument values with
375 * argument type or class name.
376 *
377 * @param Exception|Throwable $e
378 * @return string
379 * @see prettyPrintTrace()
380 */
381 public static function getRedactedTraceAsString( $e ) {
382 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
383 }
384
385 /**
386 * Generate a string representation of a stacktrace.
387 *
388 * @param array $trace
389 * @param string $pad Constant padding to add to each line of trace
390 * @return string
391 * @since 1.26
392 */
393 public static function prettyPrintTrace( array $trace, $pad = '' ) {
394 $text = '';
395
396 $level = 0;
397 foreach ( $trace as $level => $frame ) {
398 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
399 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
400 } else {
401 // 'file' and 'line' are unset for calls via call_user_func
402 // (T57634) This matches behaviour of
403 // Exception::getTraceAsString to instead display "[internal
404 // function]".
405 $text .= "{$pad}#{$level} [internal function]: ";
406 }
407
408 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
409 $text .= $frame['class'] . $frame['type'] . $frame['function'];
410 } elseif ( isset( $frame['function'] ) ) {
411 $text .= $frame['function'];
412 } else {
413 $text .= 'NO_FUNCTION_GIVEN';
414 }
415
416 if ( isset( $frame['args'] ) ) {
417 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
418 } else {
419 $text .= "()\n";
420 }
421 }
422
423 $level = $level + 1;
424 $text .= "{$pad}#{$level} {main}";
425
426 return $text;
427 }
428
429 /**
430 * Return a copy of an exception's backtrace as an array.
431 *
432 * Like Exception::getTrace, but replaces each element in each frame's
433 * argument array with the name of its class (if the element is an object)
434 * or its type (if the element is a PHP primitive).
435 *
436 * @since 1.22
437 * @param Exception|Throwable $e
438 * @return array
439 */
440 public static function getRedactedTrace( $e ) {
441 return static::redactTrace( $e->getTrace() );
442 }
443
444 /**
445 * Redact a stacktrace generated by Exception::getTrace(),
446 * debug_backtrace() or similar means. Replaces each element in each
447 * frame's argument array with the name of its class (if the element is an
448 * object) or its type (if the element is a PHP primitive).
449 *
450 * @since 1.26
451 * @param array $trace Stacktrace
452 * @return array Stacktrace with arugment values converted to data types
453 */
454 public static function redactTrace( array $trace ) {
455 return array_map( function ( $frame ) {
456 if ( isset( $frame['args'] ) ) {
457 $frame['args'] = array_map( function ( $arg ) {
458 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
459 }, $frame['args'] );
460 }
461 return $frame;
462 }, $trace );
463 }
464
465 /**
466 * If the exception occurred in the course of responding to a request,
467 * returns the requested URL. Otherwise, returns false.
468 *
469 * @since 1.23
470 * @return string|false
471 */
472 public static function getURL() {
473 global $wgRequest;
474 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
475 return false;
476 }
477 return $wgRequest->getRequestURL();
478 }
479
480 /**
481 * Get a message formatting the exception message and its origin.
482 *
483 * @since 1.22
484 * @param Exception|Throwable $e
485 * @return string
486 */
487 public static function getLogMessage( $e ) {
488 $id = WebRequest::getRequestId();
489 $type = get_class( $e );
490 $file = $e->getFile();
491 $line = $e->getLine();
492 $message = $e->getMessage();
493 $url = self::getURL() ?: '[no req]';
494
495 return "[$id] $url $type from line $line of $file: $message";
496 }
497
498 /**
499 * Get a normalised message for formatting with PSR-3 log event context.
500 *
501 * Must be used together with `getLogContext()` to be useful.
502 *
503 * @since 1.30
504 * @param Exception|Throwable $e
505 * @return string
506 */
507 public static function getLogNormalMessage( $e ) {
508 $type = get_class( $e );
509 $file = $e->getFile();
510 $line = $e->getLine();
511 $message = $e->getMessage();
512
513 return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
514 }
515
516 /**
517 * @param Exception|Throwable $e
518 * @return string
519 */
520 public static function getPublicLogMessage( $e ) {
521 $reqId = WebRequest::getRequestId();
522 $type = get_class( $e );
523 return '[' . $reqId . '] '
524 . gmdate( 'Y-m-d H:i:s' ) . ': '
525 . 'Fatal exception of type "' . $type . '"';
526 }
527
528 /**
529 * Get a PSR-3 log event context from an Exception.
530 *
531 * Creates a structured array containing information about the provided
532 * exception that can be used to augment a log message sent to a PSR-3
533 * logger.
534 *
535 * @param Exception|Throwable $e
536 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
537 * @return array
538 */
539 public static function getLogContext( $e, $catcher = self::CAUGHT_BY_OTHER ) {
540 return [
541 'exception' => $e,
542 'exception_id' => WebRequest::getRequestId(),
543 'exception_url' => self::getURL() ?: '[no req]',
544 'caught_by' => $catcher
545 ];
546 }
547
548 /**
549 * Get a structured representation of an Exception.
550 *
551 * Returns an array of structured data (class, message, code, file,
552 * backtrace) derived from the given exception. The backtrace information
553 * will be redacted as per getRedactedTraceAsArray().
554 *
555 * @param Exception|Throwable $e
556 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
557 * @return array
558 * @since 1.26
559 */
560 public static function getStructuredExceptionData( $e, $catcher = self::CAUGHT_BY_OTHER ) {
561 global $wgLogExceptionBacktrace;
562
563 $data = [
564 'id' => WebRequest::getRequestId(),
565 'type' => get_class( $e ),
566 'file' => $e->getFile(),
567 'line' => $e->getLine(),
568 'message' => $e->getMessage(),
569 'code' => $e->getCode(),
570 'url' => self::getURL() ?: null,
571 'caught_by' => $catcher
572 ];
573
574 if ( $e instanceof ErrorException &&
575 ( error_reporting() & $e->getSeverity() ) === 0
576 ) {
577 // Flag surpressed errors
578 $data['suppressed'] = true;
579 }
580
581 if ( $wgLogExceptionBacktrace ) {
582 $data['backtrace'] = self::getRedactedTrace( $e );
583 }
584
585 $previous = $e->getPrevious();
586 if ( $previous !== null ) {
587 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
588 }
589
590 return $data;
591 }
592
593 /**
594 * Serialize an Exception object to JSON.
595 *
596 * The JSON object will have keys 'id', 'file', 'line', 'message', and
597 * 'url'. These keys map to string values, with the exception of 'line',
598 * which is a number, and 'url', which may be either a string URL or or
599 * null if the exception did not occur in the context of serving a web
600 * request.
601 *
602 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
603 * key, mapped to the array return value of Exception::getTrace, but with
604 * each element in each frame's "args" array (if set) replaced with the
605 * argument's class name (if the argument is an object) or type name (if
606 * the argument is a PHP primitive).
607 *
608 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
609 * @code
610 * {
611 * "id": "c41fb419",
612 * "type": "MWException",
613 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
614 * "line": 704,
615 * "message": "Non-string key given",
616 * "url": "/wiki/Main_Page"
617 * }
618 * @endcode
619 *
620 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
621 * @code
622 * {
623 * "id": "dc457938",
624 * "type": "MWException",
625 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
626 * "line": 704,
627 * "message": "Non-string key given",
628 * "url": "/wiki/Main_Page",
629 * "backtrace": [{
630 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
631 * "line": 80,
632 * "function": "get",
633 * "class": "MessageCache",
634 * "type": "->",
635 * "args": ["array"]
636 * }]
637 * }
638 * @endcode
639 *
640 * @since 1.23
641 * @param Exception|Throwable $e
642 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
643 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
644 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
645 * @return string|false JSON string if successful; false upon failure
646 */
647 public static function jsonSerializeException(
648 $e, $pretty = false, $escaping = 0, $catcher = self::CAUGHT_BY_OTHER
649 ) {
650 return FormatJson::encode(
651 self::getStructuredExceptionData( $e, $catcher ),
652 $pretty,
653 $escaping
654 );
655 }
656
657 /**
658 * Log an exception to the exception log (if enabled).
659 *
660 * This method must not assume the exception is an MWException,
661 * it is also used to handle PHP exceptions or exceptions from other libraries.
662 *
663 * @since 1.22
664 * @param Exception|Throwable $e
665 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
666 */
667 public static function logException( $e, $catcher = self::CAUGHT_BY_OTHER ) {
668 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
669 $logger = LoggerFactory::getInstance( 'exception' );
670 $logger->error(
671 self::getLogNormalMessage( $e ),
672 self::getLogContext( $e, $catcher )
673 );
674
675 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
676 if ( $json !== false ) {
677 $logger = LoggerFactory::getInstance( 'exception-json' );
678 $logger->error( $json, [ 'private' => true ] );
679 }
680
681 Hooks::run( 'LogException', [ $e, false ] );
682 }
683 }
684
685 /**
686 * Log an exception that wasn't thrown but made to wrap an error.
687 *
688 * @since 1.25
689 * @param ErrorException $e
690 * @param string $channel
691 * @param string $level
692 */
693 protected static function logError(
694 ErrorException $e, $channel, $level = LogLevel::ERROR
695 ) {
696 $catcher = self::CAUGHT_BY_HANDLER;
697 // The set_error_handler callback is independent from error_reporting.
698 // Filter out unwanted errors manually (e.g. when
699 // Wikimedia\suppressWarnings is active).
700 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
701 if ( !$suppressed ) {
702 $logger = LoggerFactory::getInstance( $channel );
703 $logger->log(
704 $level,
705 self::getLogNormalMessage( $e ),
706 self::getLogContext( $e, $catcher )
707 );
708 }
709
710 // Include all errors in the json log (surpressed errors will be flagged)
711 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
712 if ( $json !== false ) {
713 $logger = LoggerFactory::getInstance( "{$channel}-json" );
714 $logger->log( $level, $json, [ 'private' => true ] );
715 }
716
717 Hooks::run( 'LogException', [ $e, $suppressed ] );
718 }
719 }