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