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