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