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