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