From 03f0af5812a419073aed355b757d2917b8ba9f12 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 16:00:29 +0530 Subject: [PATCH 01/53] fix(site): harden php-compat's image, memory, control files and mounts - Pull the pinned scanner tag before each check, so a host never keeps an outdated image under a rebuilt tag; a local copy serves when the pull fails, and a local build (no registry digest) is used as is. A failed first pull says why (Docker's first stderr line). - Mount code the site's php container gets from mounts below /var/www (user compose files) read-only at the same place; a mount that can't be reproduced, or a stopped site whose compose files mount code there, is tool_error. - Refuse a value for --estimate and --cancel (`--estimate=false` read as true). - With no PHP memory limit, size the report budget by the host's free memory instead of a fixed 1 GiB, and raise a limit that is too small when the host has the memory. - Keep cancel requests, their guards and estimate locks in one directory per kind, so no site name collides with another site's file. - Answer a --cancel that arrives while a failed scan cleans up, so both report cancelled. - Collapse `//` in the public dir, scan php release layouts through current/, follow an app link that points at an old Docker root through the volume, and say in the table that WordPress core is not checked. - Widen the estimate for dense many-file trees (COMPAT_SECONDS_PER_BATCH=0.5, COMPAT_HIGH_FACTOR=2.5). --- features/php-compat.feature | 64 ++++++- src/helper/Site_PHP_Compat.php | 296 +++++++++++++++++++++++++++++---- 2 files changed, 328 insertions(+), 32 deletions(-) diff --git a/features/php-compat.feature b/features/php-compat.feature index 8a9e37e8..534e2a0a 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -209,6 +209,68 @@ Feature: Check the PHP compatibility of a site's code And the JSON field "status" in STDOUT should be "ok" And the JSON field "safe_to_upgrade" in STDOUT should be "false" + Scenario: --estimate and --cancel take no value + Given the site "bh-site-command-181.test" exists, created with "--type=php" + When I run 'bin/ee site php-compat bh-site-command-181.test --php=8.4 --estimate=false' + Then the command should fail + And STDERR should contain "--estimate doesn't take a value." + When I run 'bin/ee site php-compat bh-site-command-181.test --cancel=false' + Then the command should fail + And STDERR should contain "--cancel doesn't take a value." + And the docker container "ee-php-compat-bh-site-command-181.test" should not exist + + Scenario: Deleting a site stops its running check and removes what php-compat kept for it + Given the compat-scanner image is available + And the site "bh-site-command-191.test" exists, created with "--type=php" + And the directory "{SITES_DIR}/bh-site-command-191.test/app/htdocs/bulk" holds 5000 generated PHP files + When I run 'bin/ee site php-compat bh-site-command-191.test --php=8.4 --estimate --format=json' + Then the command should succeed + And the file "{EE_ROOT_DIR}/tmp/php-compat/.estimate-lock/bh-site-command-191.test" should exist + When I start 'bin/ee site php-compat bh-site-command-191.test --php=8.4 --format=json' in the background + And I wait up to 120 seconds until the command "docker inspect -f '{{.State.Running}}' ee-php-compat-bh-site-command-191.test | grep -qx true" succeeds + And I run 'bin/ee site delete bh-site-command-191.test --yes' + Then the command should succeed + And the site "bh-site-command-191.test" should not exist + And the docker container "ee-php-compat-bh-site-command-191.test" should not exist + And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-191.test" should not exist + And the file "{EE_ROOT_DIR}/tmp/php-compat/.estimate-lock/bh-site-command-191.test" should not exist + And the file "{EE_ROOT_DIR}/tmp/php-compat/.cancel-lock/bh-site-command-191.test" should not exist + And the file "{EE_ROOT_DIR}/tmp/php-compat/.cancel/bh-site-command-191.test" should not exist + When I wait up to 120 seconds for the background command to finish + Then the JSON field "status" in STDOUT should be "cancelled" + + Scenario: A check started under nohup survives a hangup + Given the compat-scanner image is available + And the site "bh-site-command-183.test" exists, created with "--type=php" + And the directory "{SITES_DIR}/bh-site-command-183.test/app/htdocs/bulk" holds 5000 generated PHP files + When I start 'nohup bin/ee site php-compat bh-site-command-183.test --php=8.4 --format=json' in the background + And I wait up to 120 seconds until the command "docker inspect -f '{{.State.Running}}' ee-php-compat-bh-site-command-183.test | grep -qx true" succeeds + And I run 'pkill -HUP -f "site php-compat bh-site-command-183.test --php=8.4 --format=json"' + And I wait for the next second + Then the background command should still be running + When I wait up to 900 seconds for the background command to finish + Then the command should succeed + And the JSON field "status" in STDOUT should be "ok" + + @wp + Scenario: Code mounted into the php container by a user compose file is checked too + Given the compat-scanner image is available + And the site "bh-site-command-190.test" exists, created with "--type=wp" + And I write "/*\nTheme Name: Mounted Fixture\nVersion: 1.0\n*/\n" to the file "{SITES_DIR}/bh-site-command-190.test/theme-src/style.css" + And I write "site = $site_data->site_url; + $this->site = $site_data->site_url; + // `--estimate=false` is the string "false": only a bare flag (or --no-) is a switch. + foreach ( [ 'estimate', 'cancel' ] as $key ) { + if ( ! is_bool( get_flag_value( $assoc_args, $key, false ) ) ) { + EE::error( "--$key doesn't take a value." ); + } + } $this->target = (string) get_flag_value( $assoc_args, 'php', '' ); - $this->estimate = (bool) get_flag_value( $assoc_args, 'estimate', false ); - $this->cancel = (bool) get_flag_value( $assoc_args, 'cancel', false ); + $this->estimate = true === get_flag_value( $assoc_args, 'estimate', false ); + $this->cancel = true === get_flag_value( $assoc_args, 'cancel', false ); $format = get_flag_value( $assoc_args, 'format', 'table' ); $output = get_flag_value( $assoc_args, 'output', null ); $timeout = get_flag_value( $assoc_args, 'timeout', null ); @@ -191,10 +211,15 @@ public function run( $site_data, array $assoc_args, $dispatch = null ) { if ( 'ok' !== $result['doc']['status'] && $this->cancel_requested() ) { $result = $this->cancelled(); } + $this->result_status = $result['doc']['status']; } } finally { $this->cleanup(); } + if ( $this->late_cancel ) { + // The request came while this scan cleaned up; --cancel reads its removal as stopped, so say the same. + $result = $this->doc( 'cancelled' ); + } if ( 'json' === $format ) { echo self::encode( $result['doc'] ) . "\n"; @@ -337,8 +362,13 @@ protected function run_scan( $site_data, $timeout, $output ) { } } - if ( ! $this->ensure_image( $image ) ) { - return $this->doc( 'tool_error', 'image pull failed' ); + $pull = $this->ensure_image( $image ); + if ( null !== $pull ) { + return $this->doc( 'tool_error', $pull ); + } + $mounts = $this->extra_mounts( $site_data, $code ); + if ( is_string( $mounts ) ) { + return $this->doc( 'tool_error', $mounts ); } $out = $this->make_temp_dir(); @@ -389,7 +419,7 @@ protected function run_scan( $site_data, $timeout, $output ) { try { self::raise_memory_limit(); $raw = \EE\Site\Utils\get_container_file_contents( $file, $out, self::REPORT_MAX ); - if ( self::decode_cost( $raw ) > $this->memory_available() ) { + if ( ! $this->make_room( self::decode_cost( $raw ) ) ) { return $this->doc( 'tool_error', sprintf( 'the report (%s) needs more memory to read than is available', self::size( strlen( $raw ) ) ) ); } $report = json_decode( $raw, true, 512, self::JSON_UTF8 ); @@ -452,8 +482,13 @@ protected function run_estimate( $site_data ) { if ( ! $locked ) { return $this->doc( 'busy' ); } - if ( ! $this->ensure_image( $image ) ) { - return $this->doc( 'tool_error', 'image pull failed' ); + $pull = $this->ensure_image( $image ); + if ( null !== $pull ) { + return $this->doc( 'tool_error', $pull ); + } + $mounts = $this->extra_mounts( $site_data, $code ); + if ( is_string( $mounts ) ) { + return $this->doc( 'tool_error', $mounts ); } $run = $this->docker( $this->docker_run_args( 'estimate', $image, $site_data, $code ), self::ESTIMATE_TIMEOUT + self::PROCESS_MARGIN, true ); @@ -491,6 +526,9 @@ protected function run_cancel( $site_data ) { $name = 'ee-php-compat-' . $this->site; $marker = $this->cancel_path( $parent ); $stopped = false; + if ( null === $marker ) { + return $this->doc( 'tool_error', 'could not create the temporary directory' ); + } $this->hold_cancel_guard( $marker ); if ( ! $this->lock_site( $site_data->site_fs_path ) ) { @@ -555,10 +593,31 @@ protected function run_cancel( $site_data ) { * * @param string $parent temp_parent(). * - * @return string + * @return string|null */ protected function cancel_path( $parent ) { - return "$parent/.cancel-{$this->site}"; + return $this->control_path( $parent, 'cancel' ); + } + + /** + * A per-site control file, one directory per kind, so no site name can collide with another site's file of another kind. + * + * @param string $parent temp_parent(). + * @param string $kind cancel, cancel-lock or estimate-lock. + * + * @return string|null + */ + protected function control_path( $parent, $kind ) { + return $this->own_dir( "$parent/.$kind" ) ? "$parent/.$kind/{$this->site}" : null; + } + + /** + * @param string $marker cancel_path(). + * + * @return string The guard file of that request. + */ + protected static function guard_path( $marker ) { + return dirname( $marker, 2 ) . '/.cancel-lock/' . basename( $marker ); } /** @@ -568,7 +627,7 @@ protected function cancel_path( $parent ) { * @param string $marker cancel_path(). */ protected function hold_cancel_guard( $marker ) { - $guard = @fopen( "$marker.lock", 'c' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + $guard = $this->own_dir( dirname( self::guard_path( $marker ) ) ) ? @fopen( self::guard_path( $marker ), 'c' ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. if ( false === $guard ) { return; } @@ -592,7 +651,7 @@ protected function hold_cancel_guard( $marker ) { */ protected function clear_stale_cancel() { // Not created here: a --cancel creates it before its request, so while it is missing any request is a live one. - $guard = @fopen( $this->cancel_marker . '.lock', 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing is handled. + $guard = @fopen( self::guard_path( $this->cancel_marker ), 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing is handled. if ( false === $guard ) { return; } @@ -610,7 +669,8 @@ protected function clear_stale_cancel() { */ protected function request_cancel( $marker ) { $token = bin2hex( random_bytes( 8 ) ); - $tmp = "$marker.$token"; + // A leading dot: never a site name. + $tmp = dirname( $marker ) . '/.' . basename( $marker ) . ".$token"; if ( false === @file_put_contents( $tmp, $token ) || ! @rename( $tmp, $marker ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- reported as tool_error. @unlink( $tmp ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged return null; @@ -712,6 +772,11 @@ public function docker_run_args( $mode, $image, $site_data, $code, $out = null, '-e', 'COMPAT_SITE=' . $this->site, '-e', 'COMPAT_IMAGE=' . $image, '-e', 'COMPAT_REPORT_MAX=' . self::REPORT_MAX, '--mount', "type=bind,src=$code,dst=/var/www,readonly" ); + if ( 'estimate' === $mode ) { + // The byte model misses PHPCS's per-file cost on dense many-file trees (2x short seen): more per batch, wider top end. + array_push( $args, '-e', 'COMPAT_SECONDS_PER_BATCH=' . self::ESTIMATE_SECONDS_PER_BATCH, '-e', 'COMPAT_HIGH_FACTOR=' . self::ESTIMATE_HIGH_FACTOR ); + } + $args = array_merge( $args, $this->extra_mounts ); if ( 'scan' === $mode ) { array_push( $args, '--mount', "type=bind,src=$out,dst=/out" ); } @@ -740,7 +805,13 @@ protected function image() { * @return string|null Real path, or null when it isn't a directory. */ protected function code_dir( $site_fs_path ) { - $real = realpath( $site_fs_path . '/app' ); + $app = $site_fs_path . '/app'; + $real = realpath( $app ); + if ( false === $real && is_link( $app ) && preg_match( '#/volumes/([A-Za-z0-9][A-Za-z0-9_.-]*)/_data/?$#D', (string) readlink( $app ), $m ) ) { + // The link holds Docker's root dir of when the volume was made; ask Docker where the volume is now. + $run = $this->docker( [ 'docker', 'volume', 'inspect', '--format', '{{.Mountpoint}}', $m[1] ], 60 ); + $real = 0 === $run['code'] && '' !== trim( $run['stdout'] ) ? realpath( trim( $run['stdout'] ) ) : false; + } return ( false !== $real && is_dir( $real ) ) ? $real : null; } @@ -761,7 +832,10 @@ protected function resolve_layout( $site_data, $code ) { $this->scan_path = $served; if ( 'wp' !== $site_data->site_type ) { - // The scanner checks all of htdocs for php sites, whatever the root. + // The scanner checks all of htdocs for php sites, whatever the root; through current/ it skips the old releases. + if ( is_link( "$code/$rel/current" ) ) { + $this->scan_path = "$served/current"; + } $this->looked_in = $app . 'htdocs'; return null; } @@ -780,6 +854,52 @@ protected function resolve_layout( $site_data, $code ) { return null === $detail ? null : $this->doc( 'tool_error', $detail ); } + /** + * Code the site's php container gets from mounts below /var/www (docker-compose-custom.yml, user-docker-compose/), mounted + * read-only at the same place so the scanner sees what PHP runs. + * + * @param object $site_data Site record. + * @param string $code Real path of the site's app/. + * + * @return array|string --mount arguments, or a tool_error detail. + */ + protected function extra_mounts( $site_data, $code ) { + $this->extra_mounts = []; + $ps = $this->docker( [ 'docker', 'ps', '-q', '--no-trunc', '--filter', 'label=io.easyengine.site=' . $this->site, '--filter', 'label=com.docker.compose.service=php' ], 60 ); + $ids = 0 === $ps['code'] ? preg_split( '/\s+/', trim( $ps['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ) : []; + if ( ! $ids ) { + // Not running (a disabled site): only its compose files say what it mounts. + foreach ( array_merge( [ $site_data->site_fs_path . '/docker-compose-custom.yml' ], (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yml' ), (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yaml' ) ) as $file ) { + $text = is_file( $file ) ? @file_get_contents( $file ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable counts as none. + if ( false !== $text && false !== strpos( $text, '/var/www/' ) ) { + return "$file mounts code below /var/www, which this check can only see while the site runs; enable the site and run it again"; + } + } + + return []; + } + $inspect = $this->docker( [ 'docker', 'inspect', '--format', '{{json .Mounts}}', $ids[0] ], 60 ); + $mounts = 0 === $inspect['code'] ? json_decode( trim( $inspect['stdout'] ), true ) : null; + if ( ! is_array( $mounts ) ) { + return 'could not read the mounts of the site\'s php container'; + } + foreach ( $mounts as $mount ) { + $dst = isset( $mount['Destination'] ) ? rtrim( (string) $mount['Destination'], '/' ) : ''; + if ( 0 !== strpos( $dst, '/var/www/' ) ) { + continue; + } + $src = isset( $mount['Source'] ) ? (string) $mount['Source'] : ''; + // The mount point is in the htdocs volume (Docker made it there), so the read-only bind below can use it. + if ( '' === $src || false !== strpbrk( $src . $dst, ",\"\n\r" ) || ! file_exists( $src ) || null === self::resolve_in( $code, substr( $dst, strlen( '/var/www/' ) ) ) ) { + return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', which this check can\'t mount'; + } + EE::debug( "php-compat: also mounting $src at $dst" ); + array_push( $this->extra_mounts, '--mount', "type=bind,src=$src,dst=$dst,readonly" ); + } + + return $this->extra_mounts; + } + /** * The root nginx serves (main.conf), or the public directory in EE's record when that can't be read. * @@ -788,12 +908,13 @@ protected function resolve_layout( $site_data, $code ) { * @return string Path under /var/www/htdocs. */ protected function served_root( $site_data ) { - $db = rtrim( (string) $site_data->site_container_fs_path, '/' ); + // `--public-dir=a//b` is stored as given; the scanner refuses `//`. + $db = rtrim( preg_replace( '#/+#', '/', (string) $site_data->site_container_fs_path ), '/' ); $db = '' === $db ? '/var/www/htdocs' : $db; $conf = $this->nginx_conf; $text = is_file( $conf ) && filesize( $conf ) <= self::CONFIG_MAX ? @file_get_contents( $conf ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. // Exactly one root, as EE writes it; anything else is a config this check doesn't guess at. - $root = ( false !== $text && 1 === preg_match_all( '/^\s*root\s+([^\s;]+)\s*;/m', $text, $m ) ) ? rtrim( $m[1][0], '/' ) : null; + $root = ( false !== $text && 1 === preg_match_all( '/^\s*root\s+([^\s;]+)\s*;/m', $text, $m ) ) ? rtrim( preg_replace( '#/+#', '/', $m[1][0] ), '/' ) : null; if ( null === $root || ! preg_match( self::ROOT_PATTERN, $root ) ) { EE::debug( "php-compat: no usable root in $conf; using the public directory $db" ); return $db; @@ -1203,8 +1324,9 @@ protected function lock_site( $site_fs_path ) { */ protected function lock_estimate() { $parent = $this->temp_parent(); - // Not in the per-site directory, whose leftovers a scan removes; a site name never starts with a dot. - $handle = null === $parent ? false : @fopen( "$parent/.estimate-{$this->site}.lock", 'c' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + $path = null === $parent ? null : $this->control_path( $parent, 'estimate-lock' ); + // Not in the per-site directory, whose leftovers a scan removes. + $handle = null === $path ? false : @fopen( $path, 'c' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. if ( false === $handle ) { return null; } @@ -1264,23 +1386,53 @@ protected function container_gone( $name ) { } /** - * Pull on first use; most servers never run a check, so a fresh install doesn't pull it. + * Pull the pinned tag before each check, so a host never keeps an outdated image under it (a tag can be rebuilt); a local + * copy serves when the pull fails. Most servers never run a check, so a fresh install doesn't pull it. * * @param string $image Image with tag. * - * @return bool Whether it is present. + * @return string|null tool_error detail, or null when the image is there. */ protected function ensure_image( $image ) { - if ( 0 === $this->docker( [ 'docker', 'image', 'inspect', '--format', '{{.Id}}', $image ], 60 )['code'] ) { - return true; + $inspect = $this->docker( [ 'docker', 'image', 'inspect', '--format', '{{.Id}} {{len .RepoDigests}}', $image ], 60 ); + $present = 0 === $inspect['code']; + // Built here, never pulled (no registry digest): a local test build, which a pull would replace. + if ( $present && preg_match( '/^\S+ 0$/', trim( $inspect['stdout'] ) ) ) { + EE::debug( "Using the local build of $image." ); + + return null; } EE::debug( "Pulling $image." ); - if ( 0 !== $this->docker( [ 'docker', 'pull', $image ], self::PULL_TIMEOUT )['code'] ) { - return false; + $pull = $this->docker( [ 'docker', 'pull', '--quiet', $image ], $present ? self::REPULL_TIMEOUT : self::PULL_TIMEOUT, true ); + if ( 0 === $pull['code'] && ! $pull['timed_out'] ) { + $this->remove_other_tags( $image ); + + return null; } - $this->remove_other_tags( $image ); + $why = $pull['timed_out'] ? 'timed out after ' . ( $present ? self::REPULL_TIMEOUT : self::PULL_TIMEOUT ) . ' s' : self::first_line( $pull['stderr'] ); + if ( $present ) { + EE::debug( "Could not pull $image ($why); using the local copy." ); - return true; + return null; + } + + return 'image pull failed' . ( '' === $why ? '' : ": $why" ); + } + + /** + * @param string $text Command output. + * + * @return string Its first non-empty line, cleaned and capped, for a one-line detail. + */ + protected static function first_line( $text ) { + foreach ( preg_split( '/\r?\n/', (string) $text ) as $line ) { + $line = trim( $line ); + if ( '' !== $line ) { + return self::clean( strlen( $line ) > 200 ? substr( $line, 0, 200 ) . '...' : $line ); + } + } + + return ''; } /** @@ -1342,7 +1494,7 @@ protected function make_temp_dir() { $this->register_cleanup(); clearstatcache( true, $dir ); // Without root (macOS), Docker Desktop's file sharing maps the owner itself. - if ( is_link( $dir ) || ! is_dir( $dir ) || ! chmod( $dir, 0700 ) || ( 0 === self::euid() && ! ( chown( $dir, 33 ) && chgrp( $dir, 33 ) ) ) ) { + if ( is_link( $dir ) || ! is_dir( $dir ) || ! chmod( $dir, 0700 ) || ( 0 === self::euid() && ! ( chown( $dir, 33 ) && chgrp( $dir, 33 ) ) ) || ( null === self::euid() && ! ( @chown( $dir, 33 ) && @chgrp( $dir, 33 ) ) && 0 === fileowner( $dir ) ) ) { return null; } $real = realpath( $dir ); @@ -1674,12 +1826,45 @@ protected static function decode_cost( $raw ) { } /** - * @return int Bytes the report may still take: up to MEMORY_FLOOR when there is no limit. + * @return int Bytes the report may still take: what the limit leaves, or with no limit what the host has free. */ protected function memory_available() { $limit = self::bytes( ini_get( 'memory_limit' ) ); + if ( $limit > 0 ) { + return $limit - memory_get_usage(); + } + $free = $this->host_memory_available(); - return ( $limit > 0 ? $limit : self::MEMORY_FLOOR ) - memory_get_usage(); + return null === $free ? self::MEMORY_FLOOR - memory_get_usage() : $free; + } + + /** + * Raise the limit so a report that needs more than MEMORY_FLOOR can be read when the host has the memory. + * + * @param int $cost decode_cost() of the report. + * + * @return bool Whether the report now fits. + */ + protected function make_room( $cost ) { + if ( $cost <= $this->memory_available() ) { + return true; + } + $free = $this->host_memory_available(); + if ( self::bytes( ini_get( 'memory_limit' ) ) <= 0 || null === $free || $cost > $free ) { + return false; + } + ini_set( 'memory_limit', (string) ( memory_get_usage( true ) + $cost + 67108864 ) ); + + return $cost <= $this->memory_available(); + } + + /** + * @return int|null MemAvailable of the host, or null when it can't be read (not Linux). + */ + protected function host_memory_available() { + $info = @file_get_contents( '/proc/meminfo' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- null when missing. + + return false !== $info && preg_match( '/^MemAvailable:\s+(\d+) kB$/m', $info, $m ) ? (int) $m[1] * 1024 : null; } /** @@ -2018,7 +2203,9 @@ protected function table_lines( array $doc, $report ) { } $tool = isset( $doc['tool']['phpcompatibility'] ) && is_string( $doc['tool']['phpcompatibility'] ) ? ' ' . self::clean( $doc['tool']['phpcompatibility'] ) : ''; - yield "This is static analysis with PHPCompatibility$tool. Its coverage isn't complete and it can't see breakage that only shows at runtime."; + // WordPress core is never checked: its own release notes say which PHP versions it supports. + $scope = $this->wp_layout ? ' WordPress core is not checked: make sure your WordPress version supports this PHP version.' : ''; + yield "This is static analysis with PHPCompatibility$tool.$scope Its coverage isn't complete and it can't see breakage that only shows at runtime."; } /** @@ -2307,6 +2494,46 @@ protected function register_cleanup() { } } + /** + * For `ee site delete`: stop a running check of the site, then remove everything php-compat keeps for it. + * + * @param object $site_data Site record. + * @param callable|null $dispatch Signal dispatcher, as for run(). + * + * @return string|null Why the check couldn't be stopped, or null. + */ + public function stop_for_delete( $site_data, $dispatch = null ) { + $this->site = $site_data->site_url; + $this->dispatch = $dispatch; + $parent = rtrim( $this->temp_base(), '/' ) . '/' . self::TEMP_DIR; + // Nothing to do, and no temp directory created, for a site never checked. + if ( ! file_exists( $parent ) && false === $this->container_status( 'ee-php-compat-' . $this->site ) ) { + return null; + } + try { + $result = $this->run_cancel( $site_data ); + } finally { + $this->cleanup(); + } + if ( 'tool_error' === $result['doc']['status'] ) { + return $result['doc']['detail']; + } + $parent = $this->temp_parent(); + if ( null !== $parent ) { + $files = [ "$parent/.cancel/{$this->site}", "$parent/.cancel-lock/{$this->site}", "$parent/.estimate-lock/{$this->site}" ]; + // Names site-command v3.11.0 used. + array_push( $files, "$parent/.cancel-{$this->site}", "$parent/.cancel-{$this->site}.lock", "$parent/.estimate-{$this->site}.lock" ); + foreach ( $files as $file ) { + @unlink( $file ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- usually missing. + } + if ( is_dir( "$parent/{$this->site}" ) && ! is_link( "$parent/{$this->site}" ) ) { + $this->remove_tree( "$parent/{$this->site}" ); + } + } + + return null; + } + /** * Remove a scan container that may still exist, then, once it is gone, the temporary directory; release the lock. Safe to call twice. */ @@ -2335,6 +2562,13 @@ public function cleanup() { @unlink( $this->output_tmp ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged $this->output_tmp = null; } + // Still holding the lock: a --cancel that came during cleanup gets the same answer as this scan prints. An ok result + // stands; its request is then left for --cancel to read as not_running. + if ( null !== $this->result_status && ! in_array( $this->result_status, [ 'ok', 'cancelled' ], true ) && $this->cancel_requested() ) { + @unlink( $this->cancel_marker ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged + $this->cancel_marker = null; + $this->late_cancel = true; + } if ( null !== $this->lock ) { flock( $this->lock, LOCK_UN ); fclose( $this->lock ); From 4e2938a980d545f9a1940535e510c43099fd236e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 16:02:37 +0530 Subject: [PATCH 02/53] fix(site): coordinate php-compat with site delete, restore and signals - `ee site delete` stops a running php-compat check first and removes what php-compat keeps for the site (temp dir, cancel and estimate files, also the v3.11.0 names); a check that can't be stopped keeps the site. - `ee site restore` takes the site directory's lock php-compat scans under, so it refuses while a check runs and a check started during a restore reports busy. - Site commands keep a hangup ignored when started under nohup, and php-compat prints what a signal does instead of the site types' rollback text. --- src/helper/Site_Backup_Restore.php | 26 ++++++++++++++++++++++++++ src/helper/class-ee-site.php | 27 +++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/helper/Site_Backup_Restore.php b/src/helper/Site_Backup_Restore.php index b000c3ed..7167b0a0 100644 --- a/src/helper/Site_Backup_Restore.php +++ b/src/helper/Site_Backup_Restore.php @@ -120,6 +120,11 @@ class Site_Backup_Restore { // WordPress root the running backup excludes core from ('' = core is archived). private $backup_wp_root = null; + /** + * @var resource|null The site directory's lock while a restore runs, so no php-compat scan reads app/ meanwhile. + */ + private $scan_lock; + // stderr of the last failed `rclone lsf`. private $rclone_error = ''; @@ -2531,9 +2536,30 @@ private function check_and_install( $command, $name ) { } } + /** + * Take the site directory's lock, which `ee site php-compat` holds while it scans app/, for the rest of the restore, which + * replaces app/; the lock goes with the process. + */ + private function hold_scan_lock() { + $handle = @fopen( $this->site_data['site_fs_path'], 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- without it the scanner's container name still shows a check. + if ( false === $handle ) { + return; + } + if ( ! flock( $handle, LOCK_EX | LOCK_NB, $would_block ) ) { + fclose( $handle ); + if ( $would_block ) { + EE::error( sprintf( 'A php-compat check of %1$s is running and reads the files a restore replaces. Wait for it to finish or stop it with `ee site php-compat %1$s --cancel`, then run the restore again.', $this->site_data['site_url'] ) ); + } + + return; + } + $this->scan_lock = $handle; + } + private function pre_restore_check() { $this->pre_backup_restore_checks(); + $this->hold_scan_lock(); // Only with the lock held: a restore refused by another run's lock must leave that run's download dir alone. $this->restore_in_progress = true; diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 3a9a9cd8..22b106c4 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -102,7 +102,10 @@ public function __construct() { // A PHP without pcntl, or with it in disable_functions (fatal on PHP 8), only loses the rollback on signals. if ( function_exists( 'pcntl_signal' ) ) { pcntl_signal( SIGTERM, [ $this, 'rollback' ] ); - pcntl_signal( SIGHUP, [ $this, 'rollback' ] ); + // Started under nohup: keep ignoring a hangup, as the user asked. + if ( SIG_IGN !== pcntl_signal_get_handler( SIGHUP ) ) { + pcntl_signal( SIGHUP, [ $this, 'rollback' ] ); + } pcntl_signal( SIGUSR1, [ $this, 'rollback' ] ); pcntl_signal( SIGINT, [ $this, 'rollback' ] ); } else { @@ -245,6 +248,15 @@ public function delete( $args, $assoc_args ) { \EE::confirm( sprintf( 'Are you sure you want to delete %s?', $this->site_data['site_url'] ), $assoc_args ); + // A running php-compat check mounts the site's code: stop it first, and drop what php-compat keeps for the site. + $compat = ( new Site_PHP_Compat() )->stop_for_delete( + (object) $this->site_data, + function_exists( 'pcntl_signal_dispatch' ) ? 'pcntl_signal_dispatch' : null + ); + if ( null !== $compat ) { + \EE::error( sprintf( 'Could not stop the php-compat check of %s (%s). Nothing was deleted.', $this->site_data['site_url'], $compat ) ); + } + if ( $this->site_data['site_ssl'] ) { $all_domains = array_unique( array_merge( explode( ',', $this->site_data['alias_domains'] ), @@ -3351,7 +3363,18 @@ public function php_compat( $args, $assoc_args ) { $args = auto_site_name( $args, 'site', 'php-compat' ); $this->site_data = get_site_info( $args, false, true, false ); $this->php_compat_check = new Site_PHP_Compat(); - // Dispatched from this class's scope: the SIGTERM/SIGINT handlers are the site type's protected rollback(). + // A check changes nothing to roll back: on a signal, say what happens and exit; the shutdown handler stops the check. + if ( function_exists( 'pcntl_signal' ) ) { + $stop = function () { + \EE::warning( 'Stopping the check: removing its container and temporary files.' ); + exit( 1 ); + }; + foreach ( [ SIGTERM, SIGINT, SIGUSR1, SIGHUP ] as $signal ) { + if ( SIGHUP !== $signal || SIG_IGN !== pcntl_signal_get_handler( SIGHUP ) ) { + pcntl_signal( $signal, $stop ); + } + } + } $this->php_compat_check->run( $this->site_data, $assoc_args, From 7bac36c71f57bcda9d7d2f1bc08dff627948ec5b Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 17:00:12 +0530 Subject: [PATCH 03/53] fix(site): find WordPress in its own directory through the served index.php A site whose index.php loads WordPress from a subdirectory (`require __DIR__ . '/wp/wp-blog-header.php'`, core and wp-content in htdocs/wp, no wp-cli.yml) got no_code_found. Read where the served index.php loads wp-blog-header.php from (`__DIR__`, `dirname( __FILE__ )`, a relative or /var/www path) and take that directory as the WordPress root, ahead of a stale copy in the served root. An index.php that loads it from a place this can't read, or from a directory without WordPress, is tool_error, never no_code_found. --- features/php-compat.feature | 20 ++++++++ src/helper/Site_PHP_Compat.php | 91 ++++++++++++++++++++++++++-------- 2 files changed, 91 insertions(+), 20 deletions(-) diff --git a/features/php-compat.feature b/features/php-compat.feature index 534e2a0a..178a527b 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -271,6 +271,26 @@ Feature: Check the PHP compatibility of a site's code And the JSON field "status" in STDOUT should be "tool_error" And the JSON field "detail" in STDOUT should contain "user-docker-compose/mount.yml mounts code below /var/www, which this check can only see while the site runs" + @wp + Scenario: WordPress in its own directory is found through the index.php nginx serves + Given the compat-scanner image is available + And the site "bh-site-command-192.test" exists, created with "--type=wp" + # Core and wp-content in htdocs/wp, loaded by htdocs/index.php; no wp-cli.yml. + When I run 'cd {SITES_DIR}/bh-site-command-192.test/app/htdocs && mkdir wp && mv wp-admin wp-includes wp-content wp-*.php index.php license.txt readme.html xmlrpc.php wp/ && printf " index.php && chown -R 33:33 .' + Then the command should succeed + And I write " {SITES_DIR}/bh-site-command-192.test/app/htdocs/index.php' + And I run 'bin/ee site php-compat bh-site-command-192.test --php=8.4 --format=json' + Then the command should succeed + And the JSON field "status" in STDOUT should be "tool_error" + And the JSON field "detail" in STDOUT should contain "can't resolve where htdocs/index.php loads WordPress (wp-blog-header.php) from" + Scenario: An html site is refused Given the html site "bh-site-command-182.test" exists When I run 'bin/ee site php-compat bh-site-command-182.test --php=8.4' diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 4ed0a02a..1cade20f 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -842,6 +842,9 @@ protected function resolve_layout( $site_data, $code ) { $this->wp_layout = true; $root = $this->wp_root( $code, $rel ); + if ( is_string( $root ) && 0 === strpos( $root, '!' ) ) { + return $this->doc( 'tool_error', substr( $root, 1 ) ); + } if ( null === $root ) { // No WordPress found here; a wp-config that moves its code elsewhere still rules out no_code_found. $root = $rel; @@ -927,15 +930,25 @@ protected function served_root( $site_data ) { } /** - * WordPress root relative to app/: the served root or its current/ (as backup finds it), else wp-cli.yml's path. + * WordPress root relative to app/: where the served index.php loads WordPress from, the served root or its current/ (as + * backup finds it), else wp-cli.yml's path. * * @param string $code Real path of the site's app/. * @param string $rel Served root relative to app/. * - * @return string|null + * @return string|null The root, null when none is found, or `!` when the served index.php loads WordPress from + * somewhere this check can't follow. */ protected function wp_root( $code, $rel ) { + $loader = $this->index_wp_root( $code, $rel ); $candidates = \EE\Site\Utils\get_wp_root_candidates( $rel ); + if ( false === $loader ) { + return "!can't resolve where {$rel}/index.php loads WordPress (wp-blog-header.php) from"; + } + if ( null !== $loader ) { + // What is actually served wins over a stale copy in the root. + array_unshift( $candidates, $loader ); + } foreach ( array_unique( [ $rel, 'htdocs' ] ) as $dir ) { $path = $this->wp_cli_path( $code, $dir ); if ( null !== $path ) { @@ -952,7 +965,62 @@ protected function wp_root( $code, $rel ) { } } - return null; + return null === $loader ? null : "!{$rel}/index.php loads WordPress from {$loader}, which holds no WordPress"; + } + + /** + * The directory the served index.php loads wp-blog-header.php from (WordPress in its own directory), read without + * running it. + * + * @param string $code Real path of the site's app/. + * @param string $rel Served root relative to app/. + * + * @return string|false|null Relative to app/; null when index.php doesn't load WordPress, false when it does but not in + * a form this check reads. + */ + protected function index_wp_root( $code, $rel ) { + $index = self::resolve_in( $code, "$rel/index.php" ); + $source = null === $index ? null : $this->read_site_file( $code, "$rel/index.php" ); + $php = null === $source ? '' : self::php_code( $source ); + if ( false === stripos( $php, 'wp-blog-header.php' ) ) { + return null; + } + if ( ! preg_match( '/\b(?:require|include)(?:_once)?\(?(?:(__DIR__|dirname\(__FILE__\))\.)?([\'"])([^\'"$]*?)wp-blog-header\.php\2\)?;/i', $php, $m ) ) { + return false; + } + $path = $m[3]; + if ( '/' === substr( $path, 0, 1 ) && '' === $m[1] ) { + if ( 0 !== strpos( $path, '/var/www/' ) ) { + return false; + } + $path = substr( $path, strlen( '/var/www/' ) ); + } else { + // __DIR__, or a relative path, which PHP-FPM resolves from the script's own directory. That is the real one, which + // only matters for `..`; otherwise the served path keeps a current/ link for the scanner's release handling. + $base = preg_match( '#(^|/)\.\.(/|$)#', $path ) ? dirname( substr( $index, strlen( $code ) + 1 ) ) : $rel; + $path = $base . '/' . $path; + } + $path = trim( preg_replace( '#/+#', '/', preg_replace( '#(^|/)\.(?=/|$)#', '$1', $path ) ), '/' ); + + return '' === $path ? false : $path; + } + + /** + * PHP source without whitespace, comments or inline HTML, for static reads. + * + * @param string $source PHP source. + * + * @return string + */ + protected static function php_code( $source ) { + $code = ''; + foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. + if ( ! is_array( $token ) || ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG, T_CLOSE_TAG, T_INLINE_HTML ], true ) ) { + $code .= is_array( $token ) ? $token[1] : $token; + } + } + + return $code; } /** @@ -1091,23 +1159,6 @@ protected function wp_config_files( $code, $root, $abspath ) { return $files; } - /** - * PHP source without whitespace, comments or inline HTML, for static reads. - * - * @param string $source PHP source. - * - * @return string - */ - protected static function php_code( $source ) { - $code = ''; - foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. - if ( ! is_array( $token ) || ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG, T_CLOSE_TAG, T_INLINE_HTML ], true ) ) { - $code .= is_array( $token ) ? $token[1] : $token; - } - } - - return $code; - } /** * Plain defines of the directory constants in a PHP file, read without running it. From a6ec26b3c4bcde1b91d8c857df967508c6e3a561 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 17:22:20 +0530 Subject: [PATCH 04/53] fix(site): close the gaps review found in php-compat's hardening - A served index.php that names a loader directory is the only WordPress-root candidate; one without WordPress is tool_error, and a linked index.php resolves __DIR__ from its real directory. Loaders are read from require/include tokens only. - Refuse (tool_error) a mount over the WordPress files outside wp-content, which the host-side reads can't see; a failed `docker ps` is tool_error, not "no container"; a stopped site's compose files are judged by their volume targets (parsed, interpolated targets refused). - Never decode a report larger than the host's free memory, whatever PHP's limit. - `ee site delete` keeps the site lock until it ends and waits for a running estimate before removing its lock file. - php-compat ignores a hangup (PHP can't see nohup's ignore), so a check is never left half-stopped; other site commands keep their rollback. - Restore refuses when the scan lock can't be taken and the scanner container runs. - Behat: restore /dev/null after every scenario; assert the hangup reaches the check. --- features/bootstrap/FeatureContext.php | 7 ++ features/php-compat.feature | 8 +- src/helper/Site_Backup_Restore.php | 19 ++-- src/helper/Site_PHP_Compat.php | 130 +++++++++++++++++++++++--- src/helper/class-ee-site.php | 18 ++-- 5 files changed, 150 insertions(+), 32 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 42811091..8a05baa5 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -488,6 +488,13 @@ public function prepareScenario( BeforeScenarioScope $scope ) */ public function cleanupScenario(AfterScenarioScope $scope) { + // A failed --output check could have replaced /dev/null with a file; never leave the runner without it. + clearstatcache( true, '/dev/null' ); + $null = @lstat( '/dev/null' ); + if ( ! $null || 0020000 !== ( $null['mode'] & 0170000 ) || 259 !== $null['rdev'] ) { + @unlink( '/dev/null' ); + exec( 'mknod -m 666 /dev/null c 1 3' ); + } $this->commands = []; chdir($this->ee_path); diff --git a/features/php-compat.feature b/features/php-compat.feature index 178a527b..d2dd8827 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -239,14 +239,16 @@ Feature: Check the PHP compatibility of a site's code When I wait up to 120 seconds for the background command to finish Then the JSON field "status" in STDOUT should be "cancelled" - Scenario: A check started under nohup survives a hangup + Scenario: A hangup doesn't stop a running check Given the compat-scanner image is available And the site "bh-site-command-183.test" exists, created with "--type=php" And the directory "{SITES_DIR}/bh-site-command-183.test/app/htdocs/bulk" holds 5000 generated PHP files When I start 'nohup bin/ee site php-compat bh-site-command-183.test --php=8.4 --format=json' in the background And I wait up to 120 seconds until the command "docker inspect -f '{{.State.Running}}' ee-php-compat-bh-site-command-183.test | grep -qx true" succeeds - And I run 'pkill -HUP -f "site php-compat bh-site-command-183.test --php=8.4 --format=json"' - And I wait for the next second + # [s] keeps pkill's own shell out of the match. + And I run 'pkill -HUP -f "[s]ite php-compat bh-site-command-183.test --php=8.4 --format=json"' + Then the command should succeed + When I wait for the next second Then the background command should still be running When I wait up to 900 seconds for the background command to finish Then the command should succeed diff --git a/src/helper/Site_Backup_Restore.php b/src/helper/Site_Backup_Restore.php index 7167b0a0..35d249ba 100644 --- a/src/helper/Site_Backup_Restore.php +++ b/src/helper/Site_Backup_Restore.php @@ -2541,19 +2541,20 @@ private function check_and_install( $command, $name ) { * replaces app/; the lock goes with the process. */ private function hold_scan_lock() { - $handle = @fopen( $this->site_data['site_fs_path'], 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- without it the scanner's container name still shows a check. - if ( false === $handle ) { + $message = sprintf( 'A php-compat check of %1$s is running and reads the files a restore replaces. Wait for it to finish or stop it with `ee site php-compat %1$s --cancel`, then run the restore again.', $this->site_data['site_url'] ); + $handle = @fopen( $this->site_data['site_fs_path'], 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + if ( false !== $handle && flock( $handle, LOCK_EX | LOCK_NB, $would_block ) ) { + $this->scan_lock = $handle; + return; } - if ( ! flock( $handle, LOCK_EX | LOCK_NB, $would_block ) ) { + if ( false !== $handle ) { fclose( $handle ); - if ( $would_block ) { - EE::error( sprintf( 'A php-compat check of %1$s is running and reads the files a restore replaces. Wait for it to finish or stop it with `ee site php-compat %1$s --cancel`, then run the restore again.', $this->site_data['site_url'] ) ); - } - - return; } - $this->scan_lock = $handle; + // Without the lock (held, or no flock here), the scanner's container still shows a running check. + if ( ! empty( $would_block ) || 'running' === \EE_DOCKER::container_status( 'ee-php-compat-' . $this->site_data['site_url'] ) ) { + EE::error( $message ); + } } private function pre_restore_check() { diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 3d102777..7398410d 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -81,6 +81,12 @@ class Site_PHP_Compat { /** @var string|null Status of this scan's result, so cleanup() knows whether a late --cancel can still be honoured. */ protected $result_status; + /** @var resource|null The site lock `ee site delete` keeps until it ends. */ + protected $delete_lock; + + /** @var resource|null An estimate lock held while `ee site delete` removes it. */ + protected $estimate_lock; + /** @var bool Whether cleanup() took a --cancel request that arrived after the scan's last check. */ protected $late_cancel = false; @@ -869,13 +875,21 @@ protected function resolve_layout( $site_data, $code ) { protected function extra_mounts( $site_data, $code ) { $this->extra_mounts = []; $ps = $this->docker( [ 'docker', 'ps', '-q', '--no-trunc', '--filter', 'label=io.easyengine.site=' . $this->site, '--filter', 'label=com.docker.compose.service=php' ], 60 ); - $ids = 0 === $ps['code'] ? preg_split( '/\s+/', trim( $ps['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ) : []; + if ( 0 !== $ps['code'] ) { + return 'could not list the site\'s php container: ' . self::first_line( $ps['stderr'] ); + } + $ids = preg_split( '/\s+/', trim( $ps['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ); if ( ! $ids ) { // Not running (a disabled site): only its compose files say what it mounts. foreach ( array_merge( [ $site_data->site_fs_path . '/docker-compose-custom.yml' ], (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yml' ), (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yaml' ) ) as $file ) { - $text = is_file( $file ) ? @file_get_contents( $file ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable counts as none. - if ( false !== $text && false !== strpos( $text, '/var/www/' ) ) { - return "$file mounts code below /var/www, which this check can only see while the site runs; enable the site and run it again"; + $targets = is_file( $file ) ? self::compose_targets( $file ) : []; + if ( null === $targets ) { + return "could not read the volumes in $file; enable the site so this check can see its mounts"; + } + foreach ( $targets as $target ) { + if ( ! is_string( $target ) || false !== strpos( $target, '$' ) || 0 === strpos( rtrim( $target, '/' ) . '/', '/var/www/' ) ) { + return "$file mounts code below /var/www, which this check can only see while the site runs; enable the site and run it again"; + } } } @@ -896,6 +910,10 @@ protected function extra_mounts( $site_data, $code ) { if ( '' === $src || false !== strpbrk( $src . $dst, ",\"\n\r" ) || ! file_exists( $src ) || null === self::resolve_in( $code, substr( $dst, strlen( '/var/www/' ) ) ) ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', which this check can\'t mount'; } + // The WordPress root and its config are read on the host before the scan: only a mount inside wp-content leaves them as read. + if ( $this->wp_layout && ! preg_match( '#/wp-content(/|$)#', $dst ) ) { + return 'the site\'s php container mounts ' . self::clean( $dst ) . ' over the WordPress files, which this check reads before it scans'; + } EE::debug( "php-compat: also mounting $src at $dst" ); array_push( $this->extra_mounts, '--mount', "type=bind,src=$src,dst=$dst,readonly" ); } @@ -903,6 +921,43 @@ protected function extra_mounts( $site_data, $code ) { return $this->extra_mounts; } + /** + * Container paths the volumes of the services in a compose file mount at (short `src:dst[:mode]` or long form). + * + * @param string $file Compose file. + * + * @return array|null Targets (any value that isn't a plain path is returned as is, to be refused), or null when the + * file can't be parsed. + */ + protected static function compose_targets( $file ) { + try { + $doc = \Symfony\Component\Yaml\Yaml::parseFile( $file ); + } catch ( \Exception $e ) { + return null; + } + if ( null === $doc ) { + return []; + } + if ( ! is_array( $doc ) || ( isset( $doc['services'] ) && ! is_array( $doc['services'] ) ) ) { + return null; + } + $targets = []; + foreach ( isset( $doc['services'] ) ? $doc['services'] : [] as $service ) { + foreach ( is_array( $service ) && isset( $service['volumes'] ) ? (array) $service['volumes'] : [] as $volume ) { + if ( is_array( $volume ) ) { + $targets[] = isset( $volume['target'] ) ? $volume['target'] : null; + } elseif ( is_string( $volume ) ) { + $parts = explode( ':', $volume ); + $targets[] = count( $parts ) > 1 ? $parts[1] : $parts[0]; + } else { + $targets[] = null; + } + } + } + + return $targets; + } + /** * The root nginx serves (main.conf), or the public directory in EE's record when that can't be read. * @@ -946,8 +1001,8 @@ protected function wp_root( $code, $rel ) { return "!can't resolve where {$rel}/index.php loads WordPress (wp-blog-header.php) from"; } if ( null !== $loader ) { - // What is actually served wins over a stale copy in the root. - array_unshift( $candidates, $loader ); + // What is actually served is the only candidate: a stale copy elsewhere must not stand in for it. + $candidates = [ $loader ]; } foreach ( array_unique( [ $rel, 'htdocs' ] ) as $dir ) { $path = $this->wp_cli_path( $code, $dir ); @@ -992,9 +1047,10 @@ protected function index_wp_root( $code, $rel ) { } $path = substr( $path, strlen( '/var/www/' ) ); } else { - // __DIR__, or a relative path, which PHP-FPM resolves from the script's own directory. That is the real one, which - // only matters for `..`; otherwise the served path keeps a current/ link for the scanner's release handling. - $base = preg_match( '#(^|/)\.\.(/|$)#', $path ) ? dirname( substr( $index, strlen( $code ) + 1 ) ) : $rel; + // __DIR__, or a relative path, which PHP-FPM resolves from the script's own directory: the real one. The served + // path stands in for it (keeping a current/ link for the scanner) only when it is that same directory and no `..`. + $real = dirname( substr( $index, strlen( $code ) + 1 ) ); + $base = ! preg_match( '#(^|/)\.\.(/|$)#', $path ) && self::resolve_in( $code, $rel ) === dirname( $index ) ? $rel : $real; $path = $base . '/' . $path; } $path = trim( preg_replace( '#/+#', '/', preg_replace( '#(^|/)\.(?=/|$)#', '$1', $path ) ), '/' ); @@ -2005,11 +2061,15 @@ protected function memory_available() { * @return bool Whether the report now fits. */ protected function make_room( $cost ) { + $free = $this->host_memory_available(); + // Never past what the host has free, whatever PHP's limit allows. + if ( null !== $free && $cost > $free ) { + return false; + } if ( $cost <= $this->memory_available() ) { return true; } - $free = $this->host_memory_available(); - if ( self::bytes( ini_get( 'memory_limit' ) ) <= 0 || null === $free || $cost > $free ) { + if ( self::bytes( ini_get( 'memory_limit' ) ) <= 0 || null === $free ) { return false; } ini_set( 'memory_limit', (string) ( memory_get_usage( true ) + $cost + 67108864 ) ); @@ -2671,13 +2731,22 @@ public function stop_for_delete( $site_data, $dispatch = null ) { } try { $result = $this->run_cancel( $site_data ); + if ( 'tool_error' !== $result['doc']['status'] ) { + // Kept until this process ends, so no new check of the site starts while it is deleted. + $kept = $this->lock; + $this->lock = null; + } } finally { $this->cleanup(); } if ( 'tool_error' === $result['doc']['status'] ) { return $result['doc']['detail']; } - $parent = $this->temp_parent(); + $this->delete_lock = $kept; + $parent = $this->temp_parent(); + if ( null !== $parent && ! $this->wait_for_estimate( $parent ) ) { + return 'an estimate of the site is still running'; + } if ( null !== $parent ) { $files = [ "$parent/.cancel/{$this->site}", "$parent/.cancel-lock/{$this->site}", "$parent/.estimate-lock/{$this->site}" ]; // Names site-command v3.11.0 used. @@ -2693,6 +2762,43 @@ public function stop_for_delete( $site_data, $dispatch = null ) { return null; } + /** + * Wait for a running estimate of the site to end (it holds its lock file), so its file isn't removed under it. + * + * @param string $parent temp_parent(). + * + * @return bool Whether none runs now. + */ + protected function wait_for_estimate( $parent ) { + $handle = @fopen( "$parent/.estimate-lock/{$this->site}", 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing: none ran. + if ( false === $handle ) { + return true; + } + $until = microtime( true ) + $this->estimate_wait(); + while ( ! flock( $handle, LOCK_EX | LOCK_NB, $would_block ) ) { + if ( ! $would_block || microtime( true ) >= $until ) { + fclose( $handle ); + + return ! $would_block; + } + usleep( 100000 ); + if ( function_exists( 'pcntl_signal_dispatch' ) ) { + null === $this->dispatch ? pcntl_signal_dispatch() : call_user_func( $this->dispatch ); + } + } + // Unlinked by the caller while still locked, so a new estimate gets a new file. + $this->estimate_lock = $handle; + + return true; + } + + /** + * @return int Seconds `ee site delete` waits for a running estimate: its whole time limit. + */ + protected function estimate_wait() { + return self::ESTIMATE_TIMEOUT + self::PROCESS_MARGIN; + } + /** * Remove a scan container that may still exist, then, once it is gone, the temporary directory; release the lock. Safe to call twice. */ diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 22b106c4..226b6261 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -102,10 +102,7 @@ public function __construct() { // A PHP without pcntl, or with it in disable_functions (fatal on PHP 8), only loses the rollback on signals. if ( function_exists( 'pcntl_signal' ) ) { pcntl_signal( SIGTERM, [ $this, 'rollback' ] ); - // Started under nohup: keep ignoring a hangup, as the user asked. - if ( SIG_IGN !== pcntl_signal_get_handler( SIGHUP ) ) { - pcntl_signal( SIGHUP, [ $this, 'rollback' ] ); - } + pcntl_signal( SIGHUP, [ $this, 'rollback' ] ); pcntl_signal( SIGUSR1, [ $this, 'rollback' ] ); pcntl_signal( SIGINT, [ $this, 'rollback' ] ); } else { @@ -3369,11 +3366,16 @@ public function php_compat( $args, $assoc_args ) { \EE::warning( 'Stopping the check: removing its container and temporary files.' ); exit( 1 ); }; - foreach ( [ SIGTERM, SIGINT, SIGUSR1, SIGHUP ] as $signal ) { - if ( SIGHUP !== $signal || SIG_IGN !== pcntl_signal_get_handler( SIGHUP ) ) { - pcntl_signal( $signal, $stop ); + foreach ( [ SIGTERM, SIGINT, SIGUSR1 ] as $signal ) { + pcntl_signal( $signal, $stop ); + } + // A lost terminal doesn't stop a check (PHP can't see nohup's ignore); it ends and cleans up on its own, or with --cancel. + pcntl_signal( + SIGHUP, + function () { + \EE::debug( 'Hangup received; the check goes on. Stop it with --cancel.' ); } - } + ); } $this->php_compat_check->run( $this->site_data, From 3156cd50b039b69e3980e0c887442959b6111670 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 17:28:54 +0530 Subject: [PATCH 05/53] fix(site): read php-compat's WordPress loader as one unconditional include Take the operand of the require/include in index.php from the shared expression-bounded reader, and accept it as the loader only when it is a statement of its own outside any block; a loader in an if, a ternary or after an alternative-syntax block is tool_error. --- src/helper/Site_PHP_Compat.php | 39 +++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 0336f832..81c96738 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -1069,27 +1069,19 @@ protected function index_wp_root( $code, $rel ) { * loads it in another form; null when none does. */ public static function loaded_from( $source, $file ) { - $tokens = []; - foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. - if ( ! is_array( $token ) || ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG, T_CLOSE_TAG, T_INLINE_HTML ], true ) ) { - $tokens[] = is_array( $token ) ? $token : [ null, $token ]; - } - } $name = preg_quote( $file, '/' ); - foreach ( $tokens as $i => $token ) { - if ( ! in_array( $token[0], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { - continue; - } - $operand = ''; - $names = false; - for ( $j = $i + 1; isset( $tokens[ $j ] ) && ';' !== $tokens[ $j ][1]; $j++ ) { - $operand .= $tokens[ $j ][1]; - $names = $names || ( T_CONSTANT_ENCAPSED_STRING === $tokens[ $j ][0] && preg_match( "/(^['\"]|\\/){$name}['\"]\$/", $tokens[ $j ][1] ) ); + foreach ( self::include_operands( $source, $alone ) as $k => $operand ) { + $text = ''; + $names = false; + foreach ( $operand as $token ) { + $text .= $token[1]; + $names = $names || ( T_CONSTANT_ENCAPSED_STRING === $token[0] && preg_match( "/(^['\"]|\\/){$name}['\"]\$/", $token[1] ) ); } if ( ! $names ) { continue; } - if ( ! preg_match( "/^\\(?(?:(__DIR__|dirname\\(__FILE__\\))\\.)?(['\"])([^'\"\$\\\\]*?){$name}\\2\\)?\$/i", $operand, $m ) ) { + // Only a statement of its own, outside any block, says where WordPress always comes from. + if ( ! $alone[ $k ] || ! preg_match( "/^\\(?(?:(__DIR__|dirname\\(__FILE__\\))\\.)?(['\"])([^'\"\$\\\\]*?){$name}\\2\\)?\$/i", $text, $m ) ) { return false; } @@ -1267,7 +1259,7 @@ public static function includes( $source, $suffix ) { * * @return array[] Lists of [ type, text ] tokens, without whitespace and comments. */ - public static function include_operands( $source ) { + public static function include_operands( $source, &$alone = null ) { $tokens = []; foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. if ( ! is_array( $token ) || ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ], true ) ) { @@ -1275,10 +1267,23 @@ public static function include_operands( $source ) { } } $operands = []; + $alone = []; + $blocks = 0; + $alt = false; foreach ( $tokens as $i => $token ) { + if ( null === $token[0] && '{' === $token[1] || in_array( $token[0], [ T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ], true ) ) { + $blocks++; + } elseif ( null === $token[0] && '}' === $token[1] ) { + $blocks--; + } elseif ( in_array( $token[0], [ T_ENDIF, T_ENDWHILE, T_ENDFOR, T_ENDFOREACH, T_ENDSWITCH, T_ENDDECLARE ], true ) ) { + // Alternative-syntax blocks before it: whether it runs isn't read here. + $alt = true; + } if ( ! in_array( $token[0], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { continue; } + $before = $i > 0 ? $tokens[ $i - 1 ] : [ T_OPEN_TAG, '' ]; + $alone[] = ! $alt && 0 === $blocks && ( in_array( $before[0], [ T_OPEN_TAG, T_INLINE_HTML ], true ) || ( null === $before[0] && in_array( $before[1], [ ';', '}' ], true ) ) ); $operand = []; $depth = 0; $ternary = 0; From 63d0bf39b44c4b6a955217a7534ef34af7ab5784 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 18:39:20 +0530 Subject: [PATCH 06/53] fix(site): read compose files without symfony/yaml and pass over defines after WordPress boots - The release phar ships no symfony/yaml, so a disabled site with user compose files died with "Class Symfony\Component\Yaml\Yaml not found". Read them line by line instead: short volume entries and `target:` keys are judged by their destination, `source:` lines and environment entries pass, and any other line naming /var/www, or any interpolation, means the check can't run on the stopped site (tool_error). - A define after an unconditional, top-level `require_once ABSPATH . 'wp-settings.php';` never takes effect, so it is passed over and the site is scanned normally; after a load that may not run, what follows stays unresolved. --- src/helper/Site_PHP_Compat.php | 89 +++++++++++++++++++--------------- 1 file changed, 50 insertions(+), 39 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 81c96738..32f81fda 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -882,14 +882,12 @@ protected function extra_mounts( $site_data, $code ) { if ( ! $ids ) { // Not running (a disabled site): only its compose files say what it mounts. foreach ( array_merge( [ $site_data->site_fs_path . '/docker-compose-custom.yml' ], (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yml' ), (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yaml' ) ) as $file ) { - $targets = is_file( $file ) ? self::compose_targets( $file ) : []; - if ( null === $targets ) { - return "could not read the volumes in $file; enable the site so this check can see its mounts"; + $mounts = is_file( $file ) ? self::compose_mounts_code( $file ) : false; + if ( null === $mounts ) { + return "could not read $file; enable the site to check mounted code"; } - foreach ( $targets as $target ) { - if ( ! is_string( $target ) || false !== strpos( $target, '$' ) || 0 === strpos( rtrim( $target, '/' ) . '/', '/var/www/' ) ) { - return "$file mounts code below /var/www, which this check can only see while the site runs; enable the site and run it again"; - } + if ( $mounts ) { + return "$file mounts code below /var/www, which this check can only see while the site runs; enable the site and run it again"; } } @@ -922,40 +920,46 @@ protected function extra_mounts( $site_data, $code ) { } /** - * Container paths the volumes of the services in a compose file mount at (short `src:dst[:mode]` or long form). + * Whether a compose file may mount anything below /var/www, read without a YAML parser (the release phar has none). + * Only lines that can't name such a mount are passed over: short volume entries (`- src:dst[:mode]`) and `target:` + * keys are judged by their destination, `source:` lines are fine; any other line that mentions /var/www, and any `$` + * (interpolation), counts as one. * * @param string $file Compose file. * - * @return array|null Targets (any value that isn't a plain path is returned as is, to be refused), or null when the - * file can't be parsed. + * @return bool|null True when it may, false when it doesn't, null when it can't be read. */ - protected static function compose_targets( $file ) { - try { - $doc = \Symfony\Component\Yaml\Yaml::parseFile( $file ); - } catch ( \Exception $e ) { + protected static function compose_mounts_code( $file ) { + $text = @file_get_contents( $file ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- null when unreadable. + if ( false === $text ) { return null; } - if ( null === $doc ) { - return []; - } - if ( ! is_array( $doc ) || ( isset( $doc['services'] ) && ! is_array( $doc['services'] ) ) ) { - return null; - } - $targets = []; - foreach ( isset( $doc['services'] ) ? $doc['services'] : [] as $service ) { - foreach ( is_array( $service ) && isset( $service['volumes'] ) ? (array) $service['volumes'] : [] as $volume ) { - if ( is_array( $volume ) ) { - $targets[] = isset( $volume['target'] ) ? $volume['target'] : null; - } elseif ( is_string( $volume ) ) { - $parts = explode( ':', $volume ); - $targets[] = count( $parts ) > 1 ? $parts[1] : $parts[0]; - } else { - $targets[] = null; - } + foreach ( preg_split( '/\r\n|\r|\n/', $text ) as $line ) { + $line = trim( $line ); + if ( '' === $line || '#' === $line[0] ) { + continue; + } + if ( false !== strpos( $line, '$' ) ) { + return true; + } + if ( false === strpos( $line, '/var/www' ) || preg_match( '/^-?\s*source:\s/', $line ) ) { + continue; + } + $target = null; + if ( preg_match( '/^-?\s*target:\s*([\'"]?)([^\'"#\s]+)\1\s*$/', $line, $m ) ) { + $target = $m[2]; + } elseif ( preg_match( '/^-\s*([\'"]?)([^\'"#\s:]+):([^\'"#\s:]+)(?::(?:ro|rw|z|Z|cached|delegated|consistent)(?:,[a-z]+)*)?\1\s*$/', $line, $m ) ) { + $target = $m[3]; + } elseif ( preg_match( '/^-\s*[A-Za-z_][A-Za-z0-9_]*=/', $line ) ) { + // An environment entry (`- NAME=value`), not a volume. + continue; + } + if ( null === $target || 0 === strpos( rtrim( $target, '/' ) . '/', '/var/www/' ) ) { + return true; } } - return $targets; + return false; } /** @@ -1372,12 +1376,19 @@ public static function dir_defines( $source ) { $token_is = function ( $at, array $kinds ) use ( $types ) { return isset( $types[ $at ] ) && in_array( $types[ $at ][0], $kinds, true ); }; - // Once wp-settings.php is loaded, WordPress has set these constants: a later define never takes effect. + // Once wp-settings.php is loaded, WordPress has set these constants: whatever comes after never takes effect, so it is + // passed over. After a load of it that may not run (in a block, after `if (…)`), what follows is unresolved. $booted = PHP_INT_MAX; - if ( preg_match_all( '/\b(?:require|include)(?:_once)?[^;]*wp-settings\.php/i', $code, $boots, PREG_OFFSET_CAPTURE ) ) { + $maybe = PHP_INT_MAX; + if ( preg_match_all( '/\b(?:require|include)(?:_once)?[^;]*wp-settings\.php[\'"]\)?;/i', $code, $boots, PREG_OFFSET_CAPTURE ) ) { foreach ( $boots[0] as $boot ) { - if ( $token_is( $boot[1], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ] ) ) { - $booted = min( $booted, $boot[1] ); + $at = $boot[1]; + if ( ! $token_is( $at, [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ] ) ) { + continue; + } + $maybe = min( $maybe, $at ); + if ( 0 === $depths[ $at ] && ( 0 === $at || in_array( $code[ $at - 1 ], [ ';', '}' ], true ) ) ) { + $booted = min( $booted, $at ); } } } @@ -1386,12 +1397,12 @@ public static function dir_defines( $source ) { foreach ( $matches as $match ) { $name = $match[5][0]; $at = $match[0][1]; - if ( ! $token_is( $at, [ T_IF, T_STRING ] ) || ! $token_is( $match[4][1], [ T_CONSTANT_ENCAPSED_STRING ] ) ) { + if ( ! $token_is( $at, [ T_IF, T_STRING ] ) || ! $token_is( $match[4][1], [ T_CONSTANT_ENCAPSED_STRING ] ) || $at > $booted ) { continue; } // A statement of its own: after `if (…)`, `else` or `:` it may never run. $own = 0 === $at || in_array( $code[ $at - 1 ], [ ';', '}' ], true ); - if ( ! $own || $at > $booted || ( '' !== $match[2][0] && $match[2][0] !== $name ) || 0 !== $depths[ $at ] || isset( $found[ $name ] ) ) { + if ( ! $own || $at > $maybe || ( '' !== $match[2][0] && $match[2][0] !== $name ) || 0 !== $depths[ $at ] || isset( $found[ $name ] ) ) { return $name; } $found[ $name ] = $match[6][0]; @@ -1415,7 +1426,7 @@ function ( $a, $b ) { $at = $use[1]; // A bare constant, or a string that is exactly its name (constant( 'X' )); other text in strings doesn't count. $quoted = isset( $types[ $at - 1 ] ) && T_CONSTANT_ENCAPSED_STRING === $types[ $at - 1 ][0] && 1 === preg_match( '/^([\'"])' . $use[0] . '\1$/D', $types[ $at - 1 ][1] ); - if ( ! $token_is( $at, [ T_STRING ] ) && ! $quoted ) { + if ( ( ! $token_is( $at, [ T_STRING ] ) && ! $quoted ) || $at > $booted ) { continue; } // Uses come in order, so the spans before this one can be skipped for good. From c86c9cfa731765e84b2642c751302bc5470a9b6e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 18:52:06 +0530 Subject: [PATCH 07/53] fix(site): name the directory php-compat's wp scan covers in its no-code text The scanner now checks everything in the WordPress directory but core, not only wp-content, so the no_code_found text names that directory. The Behat fixture empties htdocs and moves wp-config.php away, which gives no_code_found on both the old and the new scanner image. --- features/php-compat.feature | 6 ++++-- src/helper/Site_PHP_Compat.php | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/features/php-compat.feature b/features/php-compat.feature index 30d034bd..e64180df 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -199,10 +199,12 @@ Feature: Check the PHP compatibility of a site's code Scenario: Without wp-content the message names the directory checked, and a release layout under htdocs is found Given the compat-scanner image is available And the site "bh-site-command-189.test" exists, created with "--type=wp" - When I run 'mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content-off' + # Nothing at all to check: WordPress moved out of htdocs, and no wp-config.php. + When I run 'mkdir {SITES_DIR}/bh-site-command-189.test/app/off && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/* {SITES_DIR}/bh-site-command-189.test/app/wp-config.php {SITES_DIR}/bh-site-command-189.test/app/off/' And I run 'cd {SITES_DIR}/bh-site-command-189.test && {EE} site php-compat --php=8.4' Then the command should succeed - And STDOUT should contain "No PHP code found to check in bh-site-command-189.test. Looked for plugins, themes and other WordPress code in {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content. The check follows the directory nginx serves (root in {SITES_DIR}/bh-site-command-189.test/config/nginx/conf.d/main.conf)" + And STDOUT should contain "No PHP code found to check in bh-site-command-189.test. Looked in {SITES_DIR}/bh-site-command-189.test/app/htdocs: everything there except WordPress core, wp-content included. The check follows the directory nginx serves (root in {SITES_DIR}/bh-site-command-189.test/config/nginx/conf.d/main.conf)" + When I run 'mv {SITES_DIR}/bh-site-command-189.test/app/off/wp-config.php {SITES_DIR}/bh-site-command-189.test/app/ && mv {SITES_DIR}/bh-site-command-189.test/app/off/* {SITES_DIR}/bh-site-command-189.test/app/htdocs/ && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content-off' # A CI/CD deploy: WordPress in releases/1, current links to it, wp-cli.yml points there, the record still says htdocs. When I run 'cd {SITES_DIR}/bh-site-command-189.test/app/htdocs && mkdir -p releases/1 && mv wp-content-off releases/1/wp-content && mv wp-admin wp-includes index.php wp-settings.php releases/1/ && ln -s /var/www/htdocs/releases/1 current && printf "path: current/\n" > wp-cli.yml' And I write "scan_path = '/var/www/' . $root; - $this->looked_in = $app . $root . '/wp-content'; + $this->looked_in = $app . $root; EE::debug( "php-compat: WordPress root $root (nginx root $served)" ); $detail = $this->check_wp_dirs( $code, $root, $app ); @@ -1177,7 +1177,7 @@ protected function check_wp_dirs( $code, $root, $app ) { // The scanner checks /wp-content: point it at the parent of this one. $content = substr( $real, strlen( $code ) + 1 ); $this->scan_path = '/var/www/' . dirname( $content ); - $this->looked_in = $app . $content; + $this->looked_in = $app . dirname( $content ); continue; } $what = 'WP_CONTENT_DIR' === $name ? 'plugins and themes' : ( 'WP_PLUGIN_DIR' === $name ? 'plugins' : 'must-use plugins' ); @@ -2524,7 +2524,7 @@ protected function no_code_text() { return "$text Looked for PHP files in $dir."; } - return "$text Looked for plugins, themes and other WordPress code in $dir. The check follows the directory nginx serves (root in {$this->nginx_conf}), its current/ and wp-cli.yml's path:."; + return "$text Looked in $dir: everything there except WordPress core, wp-content included. The check follows the directory nginx serves (root in {$this->nginx_conf}), its current/ and wp-cli.yml's path:."; } /** From 73c3ad20fc2ca5a54c17b85b6c7a8ea823d678c5 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 19:01:32 +0530 Subject: [PATCH 08/53] fix(site): read php-compat's WordPress config from one token pass and refuse what it can't follow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of the hardening found ways to scan other code than WordPress loads. One tokenised pass per PHP file now gives its defines, includes and anything it can't read: - `const WP_CONTENT_DIR = …`, a computed define() name, eval(), short open tags, and a define after a top-level return/exit are unresolved (tool_error). Constant names are case-sensitive; `@define`, `\define`, a trailing comma and a later use of its own value are read. - Files wp-config.php includes are followed (as far as their paths can be named, outside function and class bodies, before wp-settings.php); one that can't be named is tool_error, and a define in a file loaded only under a condition is unresolved. The served index.php is read for defines too. - Any WP_CONTENT_DIR other than the default is tool_error: re-pointing the scan at a moved wp-content's parent dropped the WordPress root and its wp-config.php. - When index.php loads WordPress from a subdirectory, PHP elsewhere in the served root (other than the live release) is tool_error; index.php that can't be read, or that includes something it can't name, is tool_error; wp-load.php counts as a loader; alternative-syntax blocks are tracked; include operands are bounded (linear time). - EE's own admin-tools mount is neither refused nor scanned; a /var/www mount from another source than app/ is tool_error. - main.conf without a single plain root, an app/ link that can't be resolved, and an auto_prepend_file in .user.ini or the site's php.ini are tool_error. - Site files are read with a hard size cap through one handle (PHP files 256 KiB), and path text with control characters is refused. - php sites are scanned as nginx serves them, old releases included. --- features/php-compat.feature | 2 +- src/helper/Site_PHP_Compat.php | 755 ++++++++++++++++++++++----------- 2 files changed, 516 insertions(+), 241 deletions(-) diff --git a/features/php-compat.feature b/features/php-compat.feature index e64180df..a188290d 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -206,7 +206,7 @@ Feature: Check the PHP compatibility of a site's code And STDOUT should contain "No PHP code found to check in bh-site-command-189.test. Looked in {SITES_DIR}/bh-site-command-189.test/app/htdocs: everything there except WordPress core, wp-content included. The check follows the directory nginx serves (root in {SITES_DIR}/bh-site-command-189.test/config/nginx/conf.d/main.conf)" When I run 'mv {SITES_DIR}/bh-site-command-189.test/app/off/wp-config.php {SITES_DIR}/bh-site-command-189.test/app/ && mv {SITES_DIR}/bh-site-command-189.test/app/off/* {SITES_DIR}/bh-site-command-189.test/app/htdocs/ && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content-off' # A CI/CD deploy: WordPress in releases/1, current links to it, wp-cli.yml points there, the record still says htdocs. - When I run 'cd {SITES_DIR}/bh-site-command-189.test/app/htdocs && mkdir -p releases/1 && mv wp-content-off releases/1/wp-content && mv wp-admin wp-includes index.php wp-settings.php releases/1/ && ln -s /var/www/htdocs/releases/1 current && printf "path: current/\n" > wp-cli.yml' + When I run 'cd {SITES_DIR}/bh-site-command-189.test/app/htdocs && mkdir -p releases/1 && for f in *; do [ "$f" = releases ] || mv "$f" releases/1/; done && mv releases/1/wp-content-off releases/1/wp-content && ln -s /var/www/htdocs/releases/1 current && printf "path: current/\n" > wp-cli.yml' And I write "/wp-content. const DIR_CONSTANTS = [ 'WP_CONTENT_DIR', 'WP_PLUGIN_DIR', 'WPMU_PLUGIN_DIR' ]; @@ -338,6 +340,9 @@ protected function run_scan( $site_data, $timeout, $output ) { $this->looked_in = $site_data->site_fs_path . '/app'; return $this->doc( 'no_code_found' ); } + if ( false === $code ) { + return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); + } $layout = $this->resolve_layout( $site_data, $code ); if ( null !== $layout ) { return $layout; @@ -473,6 +478,9 @@ protected function run_estimate( $site_data ) { $this->looked_in = $site_data->site_fs_path . '/app'; return $this->doc( 'no_code_found' ); } + if ( false === $code ) { + return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); + } $layout = $this->resolve_layout( $site_data, $code ); if ( null !== $layout ) { return $layout; @@ -808,18 +816,24 @@ protected function image() { * * @param string $site_fs_path Site directory. * - * @return string|null Real path, or null when it isn't a directory. + * @return string|null|false Real path; null when there is no app/ at all; false when app/ is there but can't be resolved. */ protected function code_dir( $site_fs_path ) { - $app = $site_fs_path . '/app'; + $app = $site_fs_path . '/app'; + if ( ! is_link( $app ) && ! file_exists( $app ) ) { + return null; + } $real = realpath( $app ); - if ( false === $real && is_link( $app ) && preg_match( '#/volumes/([A-Za-z0-9][A-Za-z0-9_.-]*)/_data/?$#D', (string) readlink( $app ), $m ) ) { + if ( false === $real && is_link( $app ) ) { + if ( ! preg_match( '#/volumes/([A-Za-z0-9][A-Za-z0-9_.-]*)/_data/?$#D', (string) readlink( $app ), $m ) ) { + return false; + } // The link holds Docker's root dir of when the volume was made; ask Docker where the volume is now. $run = $this->docker( [ 'docker', 'volume', 'inspect', '--format', '{{.Mountpoint}}', $m[1] ], 60 ); $real = 0 === $run['code'] && '' !== trim( $run['stdout'] ) ? realpath( trim( $run['stdout'] ) ) : false; } - return ( false !== $real && is_dir( $real ) ) ? $real : null; + return ( false !== $real && is_dir( $real ) ) ? $real : false; } /** @@ -833,15 +847,19 @@ protected function code_dir( $site_fs_path ) { protected function resolve_layout( $site_data, $code ) { $this->nginx_conf = $site_data->site_fs_path . self::NGINX_CONF; $served = $this->served_root( $site_data ); - $rel = ltrim( substr( $served, strlen( '/var/www' ) ), '/' ); - $app = $site_data->site_fs_path . '/app/'; + if ( null === $served ) { + return $this->doc( 'tool_error', "can't tell which directory nginx serves: {$this->nginx_conf} has no single plain root" ); + } + $rel = ltrim( substr( $served, strlen( '/var/www' ) ), '/' ); + $app = $site_data->site_fs_path . '/app/'; $this->scan_path = $served; + $prepend = $this->prepended( $site_data, $code, $rel ); + if ( null !== $prepend ) { + return $this->doc( 'tool_error', $prepend ); + } if ( 'wp' !== $site_data->site_type ) { - // The scanner checks all of htdocs for php sites, whatever the root; through current/ it skips the old releases. - if ( is_link( "$code/$rel/current" ) ) { - $this->scan_path = "$served/current"; - } + // The scanner checks all of htdocs for php sites, whatever the root nginx serves. $this->looked_in = $app . 'htdocs'; return null; } @@ -859,10 +877,97 @@ protected function resolve_layout( $site_data, $code ) { $this->looked_in = $app . $root; EE::debug( "php-compat: WordPress root $root (nginx root $served)" ); - $detail = $this->check_wp_dirs( $code, $root, $app ); + // WordPress in a subdirectory of what nginx serves: the scan covers that subdirectory only. + if ( 0 === strpos( $root, "$rel/" ) ) { + $outside = $this->php_outside( $code, $rel, $root ); + if ( null !== $outside ) { + return $this->doc( 'tool_error', "nginx serves $app$rel, which holds PHP outside the WordPress directory $app$root (" . self::clean( $outside ) . "); this check can't scan that layout yet" ); + } + } + + $detail = $this->check_wp_dirs( $code, $root, $app, $rel ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); } + /** + * The first PHP entry in the served root outside the WordPress directory, besides index.php and wp-config.php. + * + * @param string $code Real path of the site's app/. + * @param string $rel Served root relative to app/. + * @param string $root WordPress root relative to app/, below $rel. + * + * @return string|null Its path relative to the served root; a link or an over-large tree counts too. + */ + protected function php_outside( $code, $rel, $root ) { + $dir = self::resolve_in( $code, $rel ); + $wp = self::resolve_in( $code, $root ); + $skip = [ 'index.php', 'wp-config.php', explode( '/', substr( $root, strlen( $rel ) + 1 ) )[0] ]; + $seen = 0; + foreach ( null === $dir || null === $wp ? [] : array_diff( (array) @scandir( $dir ), [ '.', '..', false ] ) as $entry ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable lists nothing. + if ( in_array( $entry, $skip, true ) ) { + continue; + } + $path = "$dir/$entry"; + if ( is_link( $path ) || ( is_file( $path ) && self::php_name( $entry ) ) ) { + return $entry; + } + if ( ! is_dir( $path ) ) { + continue; + } + try { + // The WordPress directory itself (e.g. releases/ behind current/) is what the scan covers. + $tree = new \RecursiveCallbackFilterIterator( + new \RecursiveDirectoryIterator( $path, \FilesystemIterator::SKIP_DOTS ), + function ( $item ) use ( $wp ) { + return $item->getPathname() !== $wp; + } + ); + foreach ( new \RecursiveIteratorIterator( $tree ) as $item ) { + if ( ++$seen > 20000 || $item->isLink() || ( $item->isFile() && self::php_name( $item->getFilename() ) ) ) { + return $entry . '/' . substr( $item->getPathname(), strlen( $path ) + 1 ); + } + } + } catch ( \Exception $e ) { + return $entry; + } + } + + return null; + } + + /** + * @param string $name File name. + * + * @return bool Whether PHP code may be in it (the extensions the scanner checks). + */ + protected static function php_name( $name ) { + return 1 === preg_match( '/\.(php[0-9]?|phtml|inc|module|install|theme)$/i', $name ); + } + + /** + * A file PHP runs before every request (auto_prepend_file in the served root's .user.ini or the site's php.ini files), + * which can set what WordPress loads before wp-config.php does. + * + * @param object $site_data Site record. + * @param string $code Real path of the site's app/. + * @param string $rel Served root relative to app/. + * + * @return string|null tool_error detail. + */ + protected function prepended( $site_data, $code, $rel ) { + $files = [ "$rel/.user.ini" => $this->read_site_file( $code, "$rel/.user.ini" ) ]; + foreach ( (array) glob( $site_data->site_fs_path . '/config/php/php/conf.d/*.ini' ) as $ini ) { + $files[ $ini ] = is_file( $ini ) && filesize( $ini ) <= self::CONFIG_MAX ? (string) @file_get_contents( $ini ) : ''; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable counts as empty. + } + foreach ( $files as $file => $text ) { + if ( null !== $text && preg_match( '/^[ \t]*auto_prepend_file[ \t]*=[ \t]*([^;\r\n]*)/mi', $text, $m ) && ! in_array( strtolower( trim( $m[1], " \t\"'" ) ), [ '', 'none' ], true ) ) { + return "$file sets auto_prepend_file, which runs before WordPress; this check can't tell what it changes"; + } + } + + return null; + } + /** * Code the site's php container gets from mounts below /var/www (docker-compose-custom.yml, user-docker-compose/), mounted * read-only at the same place so the scanner sees what PHP runs. @@ -898,12 +1003,24 @@ protected function extra_mounts( $site_data, $code ) { if ( ! is_array( $mounts ) ) { return 'could not read the mounts of the site\'s php container'; } + $admin = realpath( EE_ROOT_DIR . '/admin-tools' ); foreach ( $mounts as $mount ) { $dst = isset( $mount['Destination'] ) ? rtrim( (string) $mount['Destination'], '/' ) : ''; + $src = isset( $mount['Source'] ) ? (string) $mount['Source'] : ''; + if ( '/var/www' === $dst ) { + // The code itself: it must be the volume app/ points at, or the scan would read other files than PHP runs. + if ( realpath( $src ) !== $code ) { + return 'the site\'s php container gets /var/www from ' . self::clean( $src ) . ', not the site\'s app/ (' . $code . ')'; + } + continue; + } if ( 0 !== strpos( $dst, '/var/www/' ) ) { continue; } - $src = isset( $mount['Source'] ) ? (string) $mount['Source'] : ''; + // EE's own admin tools (ee site admin-tools): not the site's code. + if ( '/var/www/htdocs/ee-admin' === $dst && false !== $admin && realpath( $src ) === $admin ) { + continue; + } // The mount point is in the htdocs volume (Docker made it there), so the read-only bind below can use it. if ( '' === $src || false !== strpbrk( $src . $dst, ",\"\n\r" ) || ! file_exists( $src ) || null === self::resolve_in( $code, substr( $dst, strlen( '/var/www/' ) ) ) ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', which this check can\'t mount'; @@ -963,11 +1080,11 @@ protected static function compose_mounts_code( $file ) { } /** - * The root nginx serves (main.conf), or the public directory in EE's record when that can't be read. + * The root nginx serves (main.conf), or the public directory in EE's record when main.conf can't be read. * * @param object $site_data Site record. * - * @return string Path under /var/www/htdocs. + * @return string|null Path under /var/www/htdocs; null when main.conf is there but has no single plain root. */ protected function served_root( $site_data ) { // `--public-dir=a//b` is stored as given; the scanner refuses `//`. @@ -975,11 +1092,14 @@ protected function served_root( $site_data ) { $db = '' === $db ? '/var/www/htdocs' : $db; $conf = $this->nginx_conf; $text = is_file( $conf ) && filesize( $conf ) <= self::CONFIG_MAX ? @file_get_contents( $conf ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $text ) { + EE::debug( "php-compat: $conf can't be read; using the public directory $db" ); + return $db; + } // Exactly one root, as EE writes it; anything else is a config this check doesn't guess at. - $root = ( false !== $text && 1 === preg_match_all( '/^\s*root\s+([^\s;]+)\s*;/m', $text, $m ) ) ? rtrim( preg_replace( '#/+#', '/', $m[1][0] ), '/' ) : null; + $root = 1 === preg_match_all( '/^\s*root\s+([^\s;]+)\s*;/m', $text, $m ) ? rtrim( preg_replace( '#/+#', '/', $m[1][0] ), '/' ) : null; if ( null === $root || ! preg_match( self::ROOT_PATTERN, $root ) ) { - EE::debug( "php-compat: no usable root in $conf; using the public directory $db" ); - return $db; + return null; } if ( $root !== $db ) { EE::warning( sprintf( "EE's record of %s has %s as its public directory, but nginx serves %s (root in %s). Checking what nginx serves.", $this->site, $db, $root, $conf ) ); @@ -1002,16 +1122,17 @@ protected function wp_root( $code, $rel ) { $loader = $this->index_wp_root( $code, $rel ); $candidates = \EE\Site\Utils\get_wp_root_candidates( $rel ); if ( false === $loader ) { - return "!can't resolve where {$rel}/index.php loads WordPress (wp-blog-header.php) from"; + return "!can't resolve where {$rel}/index.php loads WordPress from"; } if ( null !== $loader ) { // What is actually served is the only candidate: a stale copy elsewhere must not stand in for it. $candidates = [ $loader ]; - } - foreach ( array_unique( [ $rel, 'htdocs' ] ) as $dir ) { - $path = $this->wp_cli_path( $code, $dir ); - if ( null !== $path ) { - $candidates[] = $path; + } else { + foreach ( array_unique( [ $rel, 'htdocs' ] ) as $dir ) { + $path = $this->wp_cli_path( $code, $dir ); + if ( null !== $path ) { + $candidates[] = $path; + } } } $candidates = array_values( array_unique( $candidates ) ); @@ -1028,19 +1149,21 @@ protected function wp_root( $code, $rel ) { } /** - * The directory the served index.php loads wp-blog-header.php from (WordPress in its own directory), read without - * running it. + * The directory the served index.php loads WordPress (wp-blog-header.php or wp-load.php) from, read without running it. * * @param string $code Real path of the site's app/. * @param string $rel Served root relative to app/. * - * @return string|false|null Relative to app/; null when index.php doesn't load WordPress, false when it does but not in - * a form this check reads. + * @return string|false|null Relative to app/; null when index.php doesn't load WordPress (or isn't there), false when it + * may but not in a form this check reads, or can't be read. */ protected function index_wp_root( $code, $rel ) { - $index = self::resolve_in( $code, "$rel/index.php" ); - $source = null === $index ? null : $this->read_site_file( $code, "$rel/index.php" ); - $loads = null === $source ? null : self::loaded_from( $source, 'wp-blog-header.php' ); + $index = self::resolve_in( $code, "$rel/index.php" ); + if ( null === $index ) { + return null; + } + $source = $this->read_site_file( $code, "$rel/index.php", self::PHP_SOURCE_MAX ); + $loads = null === $source ? false : self::loaded_from( $source, 'wp-blog-header.php' ); if ( ! is_array( $loads ) ) { return $loads; } @@ -1063,36 +1186,42 @@ protected function index_wp_root( $code, $rel ) { } /** - * Where a require or include statement loads $file from, read from its tokens: the string in front of the name, with - * `__DIR__ .` or `dirname( __FILE__ ) .` before it or nothing. + * Where a PHP file loads WordPress (wp-blog-header.php or wp-load.php) from, read from its tokens: the string in front of + * the name, with `__DIR__ .` or `dirname( __FILE__ ) .` before it or nothing. * * @param string $source PHP source. - * @param string $file File name, e.g. wp-blog-header.php. + * @param string $file Kept for callers; wp-blog-header.php and wp-load.php are both looked for. * - * @return array|false|null [ directory part, whether it is from the file's own directory ]; false when a statement - * loads it in another form; null when none does. + * @return array|false|null [ directory part, whether it is from the file's own directory ]; false when it loads WordPress + * in another form, or includes something this check can't resolve; null when it doesn't. */ - public static function loaded_from( $source, $file ) { - $name = preg_quote( $file, '/' ); - foreach ( self::include_operands( $source, $alone ) as $k => $operand ) { - $text = ''; - $names = false; - foreach ( $operand as $token ) { - $text .= $token[1]; - $names = $names || ( T_CONSTANT_ENCAPSED_STRING === $token[0] && preg_match( "/(^['\"]|\\/){$name}['\"]\$/", $token[1] ) ); + public static function loaded_from( $source, $file = 'wp-blog-header.php' ) { + $php = self::analyse_php( $source ); + if ( null !== $php['halt_reason'] ) { + return false; + } + $found = null; + foreach ( $php['includes'] as $include ) { + if ( $include['in_func'] ) { + continue; } - if ( ! $names ) { + $names = preg_match( '/wp-(blog-header|load)\b/i', $include['expr'] ); + if ( ! $names && $include['static'] ) { continue; } - // Only a statement of its own, outside any block, says where WordPress always comes from. - if ( ! $alone[ $k ] || ! preg_match( "/^\\(?(?:(__DIR__|dirname\\(__FILE__\\))\\.)?(['\"])([^'\"\$\\\\]*?){$name}\\2\\)?\$/i", $text, $m ) ) { + // Loading WordPress, or something this check can't name: only a plain, unconditional statement is read. + if ( null !== $found || ! $names || ! $include['alone'] || $include['overlong'] + || ! preg_match( '/^\(?(?:(__DIR__|dirname\(__FILE__\))\.)?([\'"])([^\'"$\\\\]*?)wp-(?:blog-header|load)\.php\2\)?$/i', $include['expr'], $m ) ) { return false; } - - return [ $m[3], '' !== $m[1] ]; + // PHP joins `__DIR__ . 'wp/…'` as written: a sibling, not a child. + if ( '' !== $m[1] && '' !== $m[3] && '/' !== $m[3][0] ) { + return false; + } + $found = [ $m[3], '' !== $m[1] ]; } - return null; + return $found; } /** @@ -1124,38 +1253,72 @@ protected function wp_cli_path( $code, $dir ) { } /** - * Refuses a verdict when wp-config moves the code WordPress loads where the scanner doesn't look. - * - * The scanner checks /wp-content with plugins/ and mu-plugins/ in it, so only a content directory named - * wp-content can be followed (by scanning its parent). + * Refuses a verdict when the config WordPress loads moves its code where the scanner doesn't look: reads wp-config.php, + * the files it includes (as far as they can be named without running anything) and the served index.php. * * @param string $code Real path of the site's app/. * @param string $root WordPress root relative to app/. * @param string $app The site's app/ path with a trailing slash, for messages. + * @param string $rel Served root relative to app/. * * @return string|null tool_error detail, or null when the scan covers what WordPress loads. */ - protected function check_wp_dirs( $code, $root, $app ) { + protected function check_wp_dirs( $code, $root, $app, $rel ) { $abspath = self::resolve_in( $code, $root ); - $values = []; + $content = $root . '/wp-content'; + $queue = []; foreach ( $this->wp_config_files( $code, $root, $abspath ) as $file ) { - $source = $this->read_site_file( $code, $file ); + $queue[] = [ $file, false, true ]; + } + // The served index.php runs before WordPress too; its own includes are WordPress', not followed here. + $index = self::resolve_in( $code, "$rel/index.php" ); + if ( null !== $index ) { + $queue[] = [ substr( $index, strlen( $code ) + 1 ), false, false ]; + } + $values = []; + $seen = []; + while ( $queue ) { + list( $file, $conditional, $follow ) = array_shift( $queue ); + if ( isset( $seen[ $file ] ) ) { + continue; + } + $seen[ $file ] = true; + if ( count( $seen ) > 50 ) { + return "the config of WordPress includes more files than this check follows (from $app$file)"; + } + $source = $this->read_site_file( $code, $file, self::PHP_SOURCE_MAX ); if ( null === $source ) { return "can't read $app$file, so this check can't tell which plugins and themes WordPress loads"; } - $found = self::dir_defines( $source ); - if ( is_string( $found ) ) { - return "can't resolve $found in $app$file, so this check can't tell which plugins and themes WordPress loads. It follows only define( '$found', <__DIR__, dirname( __FILE__ ), dirname( __DIR__ ), ABSPATH or WP_CONTENT_DIR> . '' ) or a /var/www path"; + $php = self::analyse_php( $source ); + if ( null !== $php['unresolved'] ) { + return "can't resolve {$php['unresolved']} in $app$file, so this check can't tell which plugins and themes WordPress loads. It follows only define( 'WP_CONTENT_DIR', <__DIR__, dirname( __FILE__ ), dirname( __DIR__ ), ABSPATH or WP_CONTENT_DIR> . '' ) or a /var/www path, before wp-settings.php is loaded"; } - foreach ( $found as $name => $expr ) { + foreach ( $php['defines'] as $name => $expr ) { + if ( $conditional ) { + return "can't resolve $name in $app$file: that file is loaded only under a condition"; + } if ( isset( $values[ $name ] ) ) { return "can't resolve $name in $app$file: it is defined more than once"; } $values[ $name ] = [ $expr, $file ]; } + foreach ( $follow ? $php['includes'] : [] as $include ) { + if ( $include['in_func'] || $include['after_boot'] || $include['boot'] ) { + continue; + } + $target = $include['overlong'] ? null : $this->dir_value( $code, $include['expr'], $file, $abspath, $content, true ); + if ( null === $target ) { + return "can't follow the include `" . self::clean( substr( $include['expr'], 0, 80 ) ) . "` in $app$file, so this check can't tell which plugins and themes WordPress loads"; + } + $real = self::resolve_in( $code, $target ); + if ( null !== $real && is_file( $real ) ) { + // A missing file only warns (include) or stops the site (require): either way it defines nothing. + $queue[] = [ substr( $real, strlen( $code ) + 1 ), $conditional || ! $include['alone'], true ]; + } + } } - $content = $root . '/wp-content'; foreach ( self::DIR_CONSTANTS as $name ) { if ( ! isset( $values[ $name ] ) ) { continue; @@ -1173,13 +1336,6 @@ protected function check_wp_dirs( $code, $root, $app ) { if ( self::resolve_in( $code, $default ) === $real ) { continue; } - if ( 'WP_CONTENT_DIR' === $name && 'wp-content' === basename( $real ) ) { - // The scanner checks /wp-content: point it at the parent of this one. - $content = substr( $real, strlen( $code ) + 1 ); - $this->scan_path = '/var/www/' . dirname( $content ); - $this->looked_in = $app . dirname( $content ); - continue; - } $what = 'WP_CONTENT_DIR' === $name ? 'plugins and themes' : ( 'WP_PLUGIN_DIR' === $name ? 'plugins' : 'must-use plugins' ); return "WordPress loads $what from $app$dir ($name in $app$file); this check can't scan that layout yet"; } @@ -1188,8 +1344,7 @@ protected function check_wp_dirs( $code, $root, $app ) { } /** - * The wp-config.php WordPress loads (in its directory, else the parent without wp-settings.php), and Bedrock's - * config/application.php beside that parent when there is one. Paths relative to app/. + * The wp-config.php WordPress loads: in its directory, else the parent without wp-settings.php. Relative to app/. * * @param string $code Real path of the site's app/. * @param string $root WordPress root relative to app/. @@ -1218,17 +1373,8 @@ protected function wp_config_files( $code, $root, $abspath ) { if ( null === $config ) { return []; } - $real = self::resolve_in( $code, $config ); - $files = [ substr( $real, strlen( $code ) + 1 ) ]; - // Bedrock: config/ beside the loader's directory; app/wp-config.php has no such parent. - $dir = dirname( dirname( $files[0] ) ); - $app_config = ( '.' === $dir ? '' : "$dir/" ) . 'config/application.php'; - // Only when the loader includes it: a stale copy WordPress never reads says nothing. - if ( '.' !== dirname( $files[0] ) && null !== self::resolve_in( $code, $app_config ) && self::includes( (string) $this->read_site_file( $code, $files[0] ), 'config/application.php' ) ) { - $files[] = $app_config; - } - return $files; + return [ substr( self::resolve_in( $code, $config ), strlen( $code ) + 1 ) ]; } /** @@ -1240,12 +1386,11 @@ protected function wp_config_files( $code, $root, $abspath ) { * @return bool */ public static function includes( $source, $suffix ) { - foreach ( self::include_operands( $source ) as $operand ) { - foreach ( $operand as $token ) { - if ( T_CONSTANT_ENCAPSED_STRING !== $token[0] ) { - continue; - } - $path = substr( $token[1], 1, -1 ); + foreach ( self::analyse_php( $source )['includes'] as $include ) { + if ( $include['overlong'] ) { + return true; + } + foreach ( $include['strings'] as $path ) { if ( $path === $suffix || substr( $path, -strlen( $suffix ) - 1 ) === "/$suffix" ) { return true; } @@ -1256,97 +1401,79 @@ public static function includes( $source, $suffix ) { } /** - * The operand tokens of every require and include, each ending where PHP ends that expression: at `;`, `,`, `=>`, `?>` - * or a `:` that closes no `?` of the operand, or at a bracket that closes one opened before it. + * Plain defines of the directory constants in a PHP file, read without running it. * * @param string $source PHP source. * - * @return array[] Lists of [ type, text ] tokens, without whitespace and comments. + * @return array|string Constant => value expression (whitespace and comments removed), or what the file does with a + * directory constant that can't be read this way. */ - public static function include_operands( $source, &$alone = null ) { - $tokens = []; - foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. - if ( ! is_array( $token ) || ! in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ], true ) ) { - $tokens[] = is_array( $token ) ? [ $token[0], $token[1] ] : [ null, $token ]; - } - } - $operands = []; - $alone = []; - $blocks = 0; - $alt = false; - foreach ( $tokens as $i => $token ) { - if ( null === $token[0] && '{' === $token[1] || in_array( $token[0], [ T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ], true ) ) { - $blocks++; - } elseif ( null === $token[0] && '}' === $token[1] ) { - $blocks--; - } elseif ( in_array( $token[0], [ T_ENDIF, T_ENDWHILE, T_ENDFOR, T_ENDFOREACH, T_ENDSWITCH, T_ENDDECLARE ], true ) ) { - // Alternative-syntax blocks before it: whether it runs isn't read here. - $alt = true; - } - if ( ! in_array( $token[0], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { - continue; - } - $before = $i > 0 ? $tokens[ $i - 1 ] : [ T_OPEN_TAG, '' ]; - $alone[] = ! $alt && 0 === $blocks && ( in_array( $before[0], [ T_OPEN_TAG, T_INLINE_HTML ], true ) || ( null === $before[0] && in_array( $before[1], [ ';', '}' ], true ) ) ); - $operand = []; - $depth = 0; - $ternary = 0; - for ( $j = $i + 1; isset( $tokens[ $j ] ); $j++ ) { - list( $type, $text ) = $tokens[ $j ]; - $open = null === $type && in_array( $text, [ '(', '[', '{' ], true ) || in_array( $type, [ T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ], true ); - $close = null === $type && in_array( $text, [ ')', ']', '}' ], true ); - if ( $close && 0 === $depth ) { - break; - } - if ( 0 === $depth && ( in_array( $type, [ T_CLOSE_TAG, T_INLINE_HTML, T_DOUBLE_ARROW ], true ) || ( null === $type && in_array( $text, [ ';', ',' ], true ) ) ) ) { - break; - } - if ( 0 === $depth && null === $type && ':' === $text ) { - if ( 0 === $ternary ) { - break; - } - $ternary--; - } elseif ( 0 === $depth && null === $type && '?' === $text ) { - $ternary++; - } - $depth += $open ? 1 : ( $close ? -1 : 0 ); - $operand[] = $tokens[ $j ]; - } - $operands[] = $operand; - } + public static function dir_defines( $source ) { + $php = self::analyse_php( $source ); - return $operands; + return null === $php['unresolved'] ? $php['defines'] : $php['unresolved']; } /** - * Plain defines of the directory constants in a PHP file, read without running it. + * Reads a PHP file's tokens once, without running it: the plain defines of the directory constants, anything else it + * does with them, and its includes. + * + * A define counts only as a statement of its own outside any block (braced or `if (…): … endif;`), or in its own + * `if ( ! defined( 'X' ) )` guard, before wp-settings.php is loaded; after that load nothing changes them any more, so + * the rest is passed over. After a load that may not run, a top-level return/exit or __halt_compiler, a define is + * unresolved. `const X = …`, a computed define name, eval() and any other use of a name are unresolved too. * * @param string $source PHP source. * - * @return array|string Constant => value expression (whitespace and comments removed), or the name of a constant - * the file sets or uses in any other way. + * @return array 'defines' (name => value expression), 'unresolved' (string|null), 'halt_reason' (string|null) and + * 'includes' (each: expr, strings, static, alone, in_func, boot, after_boot, overlong). */ - public static function dir_defines( $source ) { - $skip = [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG, T_CLOSE_TAG, T_INLINE_HTML ]; - $tokens = []; - foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. - if ( ! is_array( $token ) || ! in_array( $token[0], $skip, true ) ) { - $tokens[] = is_array( $token ) ? $token : [ null, $token ]; - } + public static function analyse_php( $source ) { + $result = [ + 'defines' => [], + 'unresolved' => null, + 'halt_reason' => null, + 'includes' => [], + ]; + // Short open tags depend on the site's php.ini, not this one's: such a file can't be read reliably here. + if ( false === stripos( $source, ' list( $type, $text ) ) { - $depths[ strlen( $code ) ] = $level; - $types[ strlen( $code ) ] = [ $type, $text ]; - $code .= $text; + $body = false; + for ( $i = 0; $i < $n; $i++ ) { + list( $type, $text ) = $t[ $i ]; + $depth[ $i ] = $level; + $func[ $i ] = in_array( 'f', $stack, true ); + $prev = $i > 0 ? $t[ $i - 1 ] : [ T_OPEN_TAG, '' ]; + $start[ $i ] = in_array( $prev[0], $tags, true ) || ( null === $prev[0] && in_array( $prev[1], [ ';', '}', '{' ], true ) ); + if ( in_array( $type, $bodies, true ) ) { + $body = true; + } if ( in_array( $type, $opens, true ) ) { $header = $parens; } elseif ( null === $type && '(' === $text ) { @@ -1356,115 +1483,252 @@ public static function dir_defines( $source ) { $parens--; if ( $header === $parens ) { $header = null; - if ( isset( $tokens[ $i + 1 ] ) && ':' === $tokens[ $i + 1 ][1] ) { + if ( isset( $t[ $i + 1 ] ) && null === $t[ $i + 1 ][0] && ':' === $t[ $i + 1 ][1] ) { $level++; + $stack[] = 'a'; } } } elseif ( in_array( $type, $ends, true ) ) { $level--; + array_pop( $stack ); } elseif ( ( null === $type && '{' === $text ) || in_array( $type, [ T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ], true ) ) { $level++; + $stack[] = $body && null === $type ? 'f' : 'b'; + $body = false; } elseif ( null === $type && '}' === $text ) { $level--; + array_pop( $stack ); + } elseif ( null === $type && ';' === $text ) { + $body = false; } } - $names = implode( '|', self::DIR_CONSTANTS ); - $spans = []; - $found = []; - // Only real tokens count: text inside a string is never a define, a check or a use. - $token_is = function ( $at, array $kinds ) use ( $types ) { - return isset( $types[ $at ] ) && in_array( $types[ $at ][0], $kinds, true ); - }; - // Once wp-settings.php is loaded, WordPress has set these constants: whatever comes after never takes effect, so it is - // passed over. After a load of it that may not run (in a block, after `if (…)`), what follows is unresolved. + // Includes, each operand ending where PHP ends the expression; the wp-settings.php load; top-level return/exit. $booted = PHP_INT_MAX; $maybe = PHP_INT_MAX; - if ( preg_match_all( '/\b(?:require|include)(?:_once)?[^;]*wp-settings\.php[\'"]\)?;/i', $code, $boots, PREG_OFFSET_CAPTURE ) ) { - foreach ( $boots[0] as $boot ) { - $at = $boot[1]; - if ( ! $token_is( $at, [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ] ) ) { - continue; + $halt = PHP_INT_MAX; + $static = [ T_CONSTANT_ENCAPSED_STRING, T_DIR, T_FILE ]; + for ( $i = 0; $i < $n; $i++ ) { + $type = $t[ $i ][0]; + if ( in_array( $type, [ T_RETURN, T_EXIT, T_HALT_COMPILER ], true ) && 0 === $depth[ $i ] && $i < $halt ) { + $halt = $i; + $result['halt_reason'] = $t[ $i ][1]; + } + if ( T_EVAL === $type && ! $func[ $i ] && null === $result['unresolved'] ) { + $result['unresolved'] = 'eval()'; + } + if ( ! in_array( $type, $includes, true ) ) { + continue; + } + $expr = ''; + $strings = []; + $is_fixed = true; + $nest = 0; + $ternary = 0; + $overlong = false; + for ( $j = $i + 1; $j < $n; $j++ ) { + list( $jt, $jx ) = $t[ $j ]; + $open = ( null === $jt && in_array( $jx, [ '(', '[', '{' ], true ) ) || in_array( $jt, [ T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ], true ); + $close = null === $jt && in_array( $jx, [ ')', ']', '}' ], true ); + if ( ( $close && 0 === $nest ) || ( 0 === $nest && ( in_array( $jt, [ T_CLOSE_TAG, T_INLINE_HTML, T_DOUBLE_ARROW ], true ) || ( null === $jt && in_array( $jx, [ ';', ',' ], true ) ) ) ) ) { + break; + } + if ( 0 === $nest && null === $jt && ':' === $jx ) { + if ( 0 === $ternary ) { + break; + } + $ternary--; + } elseif ( 0 === $nest && null === $jt && '?' === $jx ) { + $ternary++; + } + if ( $j - $i > 256 ) { + $overlong = true; + break; + } + $nest += $open ? 1 : ( $close ? -1 : 0 ); + $expr .= $jx; + if ( T_CONSTANT_ENCAPSED_STRING === $jt ) { + $strings[] = substr( $jx, 1, -1 ); } - $maybe = min( $maybe, $at ); - if ( 0 === $depths[ $at ] && ( 0 === $at || in_array( $code[ $at - 1 ], [ ';', '}' ], true ) ) ) { - $booted = min( $booted, $at ); + $named = T_STRING === $jt && in_array( strtolower( $jx ), [ 'dirname', 'abspath' ], true ); + $is_fixed = $is_fixed && ( in_array( $jt, $static, true ) || $named || ( null === $jt && in_array( $jx, [ '(', ')', '.' ], true ) ) ); + } + $boot = false; + foreach ( $strings as $string ) { + $boot = $boot || 'wp-settings.php' === basename( $string ); + } + $alone = $start[ $i ] && 0 === $depth[ $i ]; + if ( $boot && ! $func[ $i ] ) { + $maybe = min( $maybe, $i ); + if ( $alone ) { + $booted = min( $booted, $i ); } } + $result['includes'][] = [ + 'index' => $i, + 'expr' => $expr, + 'strings' => $strings, + 'static' => $is_fixed && ! $overlong, + 'alone' => $alone, + 'in_func' => $func[ $i ], + 'boot' => $boot, + 'overlong' => $overlong, + ]; } - // A top-level define, also inside its own `if ( ! defined( 'X' ) )` guard. - preg_match_all( "/(?:\\bif\\(!defined\\((['\"])($names)\\1\\)\\)(\\{)?)?\\bdefine\\((['\"])($names)\\4,(.*?)\\);(?(3)\\})/i", $code, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ); - foreach ( $matches as $match ) { - $name = $match[5][0]; - $at = $match[0][1]; - if ( ! $token_is( $at, [ T_IF, T_STRING ] ) || ! $token_is( $match[4][1], [ T_CONSTANT_ENCAPSED_STRING ] ) || $at > $booted ) { + foreach ( $result['includes'] as $k => $include ) { + $result['includes'][ $k ]['after_boot'] = $include['index'] > $booted || $include['index'] > $halt; + } + if ( null !== $result['unresolved'] ) { + return $result; + } + + // Defines, defined() checks and every other mention of a directory constant, up to where WordPress has booted. + $names = self::DIR_CONSTANTS; + $covered = []; + $at = []; + $stop = min( $maybe, $halt ); + $end = min( $n, $booted ); + $sig = function ( $k ) use ( $t ) { + return isset( $t[ $k ] ) ? $t[ $k ] : [ null, '' ]; + }; + for ( $i = 0; $i < $end; $i++ ) { + list( $type, $text ) = $t[ $i ]; + if ( T_CONST === $type && T_STRING === $sig( $i + 1 )[0] && in_array( $sig( $i + 1 )[1], $names, true ) ) { + $result['unresolved'] = $sig( $i + 1 )[1]; + return $result; + } + $before = $sig( $i - 1 ); + $method = in_array( $before[0], [ T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_FUNCTION, T_NEW ], true ) || ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) && T_NULLSAFE_OBJECT_OPERATOR === $before[0] ); + // PHP 8 reads `\define` as one name token. + $global = defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $type; + if ( ( T_STRING !== $type && ! $global ) || $method || '(' !== $sig( $i + 1 )[1] ) { continue; } - // A statement of its own: after `if (…)`, `else` or `:` it may never run. - $own = 0 === $at || in_array( $code[ $at - 1 ], [ ';', '}' ], true ); - if ( ! $own || $at > $maybe || ( '' !== $match[2][0] && $match[2][0] !== $name ) || 0 !== $depths[ $at ] || isset( $found[ $name ] ) ) { - return $name; + $call = ltrim( strtolower( $text ), '\\' ); + if ( 'defined' === $call && T_CONSTANT_ENCAPSED_STRING === $sig( $i + 2 )[0] ) { + $covered[ $i + 2 ] = true; + continue; } - $found[ $name ] = $match[6][0]; - $spans[] = [ $at, $at + strlen( $match[0][0] ) ]; - } - preg_match_all( "/\\bdefined\\((['\"])(?:$names)\\1\\)/i", $code, $checks, PREG_OFFSET_CAPTURE ); - foreach ( $checks[0] as $check ) { - if ( $token_is( $check[1], [ T_STRING ] ) ) { - $spans[] = [ $check[1], $check[1] + strlen( $check[0] ) ]; + if ( 'define' !== $call ) { + continue; } - } - usort( - $spans, - function ( $a, $b ) { - return $a[0] - $b[0]; + $arg = $sig( $i + 2 ); + if ( T_CONSTANT_ENCAPSED_STRING !== $arg[0] || ! in_array( $sig( $i + 3 )[1], [ ',' ], true ) ) { + // define( $name, … ), define( 'A' . 'B', … ): the name can't be read here. + $result['unresolved'] = 'a define() whose name is not a plain string'; + return $result; } - ); - preg_match_all( "/\\b(?:$names)\\b/", $code, $uses, PREG_OFFSET_CAPTURE ); - $next = 0; - foreach ( $uses[0] as $use ) { - $at = $use[1]; - // A bare constant, or a string that is exactly its name (constant( 'X' )); other text in strings doesn't count. - $quoted = isset( $types[ $at - 1 ] ) && T_CONSTANT_ENCAPSED_STRING === $types[ $at - 1 ][0] && 1 === preg_match( '/^([\'"])' . $use[0] . '\1$/D', $types[ $at - 1 ][1] ); - if ( ( ! $token_is( $at, [ T_STRING ] ) && ! $quoted ) || $at > $booted ) { + $name = substr( $arg[1], 1, -1 ); + if ( ! in_array( $name, $names, true ) ) { continue; } - // Uses come in order, so the spans before this one can be skipped for good. - while ( isset( $spans[ $next ] ) && $spans[ $next ][1] <= $at ) { - $next++; + $covered[ $i + 2 ] = true; + // The value runs to the `)` that closes the call; a trailing comma is allowed. + $nest = 0; + $value = ''; + for ( $j = $i + 4; $j < $n; $j++ ) { + list( $jt, $jx ) = $t[ $j ]; + if ( null === $jt && ')' === $jx && 0 === $nest ) { + break; + } + $nest += ( null === $jt && '(' === $jx ) ? 1 : ( ( null === $jt && ')' === $jx ) ? -1 : 0 ); + $covered[ $j ] = true; + $value .= $jx; + } + $value = rtrim( $value, ',' ); + $after = $sig( $j + 1 ); + // The statement starts at the define, or at an `@` or `\` in front of it. + $s = in_array( $before[1], [ '@', '\\' ], true ) ? $i - 1 : $i; + $guard = self::guarded( $t, $depth, $start, $s, $name, $j + 1 ); + $plain = $start[ $s ] && 0 === $depth[ $s ]; + if ( ( ! $plain && ! $guard ) || $s > $stop || isset( $result['defines'][ $name ] ) || ! ( ( null === $after[0] && ';' === $after[1] ) || T_CLOSE_TAG === $after[0] ) ) { + $result['unresolved'] = $name; + return $result; + } + $result['defines'][ $name ] = $value; + $at[ $name ] = $i; + } + for ( $i = 0; $i < $end; $i++ ) { + list( $type, $text ) = $t[ $i ]; + if ( isset( $covered[ $i ] ) ) { + continue; } - $covered = false; - for ( $i = $next; isset( $spans[ $i ] ) && $spans[ $i ][0] <= $at; $i++ ) { - $covered = $covered || $at < $spans[ $i ][1]; + $before = $sig( $i - 1 ); + $member = in_array( $before[0], [ T_OBJECT_OPERATOR, T_DOUBLE_COLON ], true ) || ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) && T_NULLSAFE_OBJECT_OPERATOR === $before[0] ); + $name = T_STRING === $type && ! $member ? $text : ( T_CONSTANT_ENCAPSED_STRING === $type ? substr( $text, 1, -1 ) : null ); + if ( null === $name || ! in_array( $name, $names, true ) ) { + continue; } - if ( ! $covered ) { - return $use[0]; + // A use after the file's own plain define of that constant reads what it set. + if ( T_STRING === $type && isset( $at[ $name ] ) && $i > $at[ $name ] ) { + continue; } + $result['unresolved'] = $name; + return $result; } - return $found; + return $result; } /** - * A directory constant's value relative to app/, from the plain forms dir_defines() returns. + * Whether the define at $s sits in its own `if ( ! defined( 'X' ) )` guard: unbraced, or braced around it alone. * - * @param string $code Real path of the site's app/. - * @param string $expr Value expression. - * @param string $file File it is defined in, relative to app/ (real). - * @param string|null $abspath Real WordPress root. - * @param string $content WP_CONTENT_DIR relative to app/. + * @param array $t Tokens. + * @param int[] $depth Block depth per token. + * @param bool[] $start Statement start per token. + * @param int $s First token of the define statement. + * @param string $name Constant name. + * @param int $after Token after the define's `)`. + * + * @return bool + */ + protected static function guarded( array $t, array $depth, array $start, $s, $name, $after ) { + $braced = $s > 0 && null === $t[ $s - 1 ][0] && '{' === $t[ $s - 1 ][1]; + $g = $s - ( $braced ? 1 : 0 ) - 8; + $want = [ [ T_IF ], '(', '!', [ T_STRING, 'defined' ], '(', [ T_CONSTANT_ENCAPSED_STRING ], ')', ')' ]; + if ( $g < 0 ) { + return false; + } + foreach ( $want as $k => $w ) { + $tok = $t[ $g + $k ]; + $ok = is_array( $w ) ? $tok[0] === $w[0] && ( ! isset( $w[1] ) || strtolower( $tok[1] ) === $w[1] ) : ( null === $tok[0] && $tok[1] === $w ); + if ( ! $ok ) { + return false; + } + } + if ( substr( $t[ $g + 5 ][1], 1, -1 ) !== $name || ! $start[ $g ] || 0 !== $depth[ $g ] ) { + return false; + } + // Braced: the block holds this define alone. + return ! $braced || ( isset( $t[ $after + 1 ] ) && null === $t[ $after + 1 ][0] && '}' === $t[ $after + 1 ][1] ); + } + + /** + * A directory constant's (or include's) value relative to app/, from the plain forms dir_defines() returns. + * + * @param string $code Real path of the site's app/. + * @param string $expr Value expression. + * @param string $file File it is in, relative to app/ (real). + * @param string|null $abspath Real WordPress root. + * @param string $content WP_CONTENT_DIR relative to app/. + * @param bool $relative Whether a relative string counts from the file's directory (an include path). * * @return string|null */ - protected function dir_value( $code, $expr, $file, $abspath, $content ) { + protected function dir_value( $code, $expr, $file, $abspath, $content, $relative = false ) { $string = '\'[^\'\\\\]*\'|"[^"\\\\$]*"'; + $expr = preg_match( '/^\((.*)\)$/s', $expr, $outer ) ? $outer[1] : $expr; if ( preg_match( "/^($string)$/", $expr, $m ) ) { $path = substr( $m[1], 1, -1 ); - if ( 0 !== strpos( $path . '/', '/var/www/' ) ) { + if ( $relative && '' !== $path && '/' !== $path[0] ) { + $base = dirname( $file ); + $base = '.' === $base ? '' : $base; + } elseif ( 0 !== strpos( $path . '/', '/var/www/' ) ) { return null; + } else { + $base = ''; + $path = substr( $path, strlen( '/var/www/' ) ); } - $base = ''; - $path = substr( $path, strlen( '/var/www/' ) ); } elseif ( preg_match( "/^(__DIR__|dirname\\(__FILE__\\)|dirname\\(__DIR__\\)|dirname\\(dirname\\(__FILE__\\)\\)|ABSPATH|WP_CONTENT_DIR)\\.($string)$/i", $expr, $m ) ) { $dir = dirname( $file ); // dirname() of app/ itself is outside the site. @@ -1472,12 +1736,12 @@ protected function dir_value( $code, $expr, $file, $abspath, $content ) { return null; } $base = [ - '__dir__' => $dir, - 'dirname(__file__)' => $dir, - 'dirname(__dir__)' => dirname( $dir ), - 'dirname(dirname(__file__))' => dirname( $dir ), - 'abspath' => null === $abspath ? null : substr( $abspath, strlen( $code ) + 1 ), - 'wp_content_dir' => $content, + '__dir__' => $dir, + 'dirname(__file__)' => $dir, + 'dirname(__dir__)' => dirname( $dir ), + 'dirname(dirname(__file__))' => dirname( $dir ), + 'abspath' => null === $abspath ? null : substr( $abspath, strlen( $code ) + 1 ), + 'wp_content_dir' => $content, ][ strtolower( $m[1] ) ]; if ( null === $base ) { return null; @@ -1503,21 +1767,28 @@ function ( $part ) { } /** - * A file under app/, read the way the scanner container sees it, never from outside app/. + * A file under app/, read the way the scanner container sees it, never from outside app/, never more than $max bytes. * * @param string $code Real path of the site's app/. * @param string $rel Path relative to app/. + * @param int $max Size cap. * * @return string|null */ - protected function read_site_file( $code, $rel ) { + protected function read_site_file( $code, $rel, $max = self::CONFIG_MAX ) { $path = self::resolve_in( $code, $rel ); - if ( null === $path || ! is_file( $path ) || filesize( $path ) > self::CONFIG_MAX ) { + if ( null === $path ) { return null; } - $text = @file_get_contents( $path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + $handle = @fopen( $path, 'rb' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- null when unreadable. + if ( false === $handle ) { + return null; + } + $stat = fstat( $handle ); + $text = $stat && 0100000 === ( $stat['mode'] & 0170000 ) ? stream_get_contents( $handle, $max + 1 ) : false; + fclose( $handle ); - return false === $text ? null : $text; + return false === $text || strlen( $text ) > $max ? null : $text; } /** @@ -1529,6 +1800,10 @@ protected function read_site_file( $code, $rel ) { * @return string|null Real host path inside app/, or null when it doesn't exist or leaves app/. */ public static function resolve_in( $code, $rel ) { + // Path text from the site's files: a NUL or another control character is never a real path here. + if ( preg_match( '/[\x00-\x1F\x7F]/', $rel ) ) { + return null; + } $todo = array_values( array_filter( explode( '/', $rel ), 'strlen' ) ); $done = []; $hops = 0; @@ -1547,7 +1822,7 @@ public static function resolve_in( $code, $rel ) { $path = $code . '/' . implode( '/', array_merge( $done, [ $part ] ) ); if ( is_link( $path ) ) { $target = readlink( $path ); - if ( false === $target || ++$hops > 40 ) { + if ( false === $target || ++$hops > 40 || preg_match( '/[\x00-\x1F\x7F]/', $target ) ) { return null; } if ( '/' === substr( $target, 0, 1 ) ) { From dd3cab83daea95f2171835d8b658b78705c4e452 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:05:19 +0530 Subject: [PATCH 09/53] fix(site): keep the delete's php-compat lock until the delete ends ee site delete called stop_for_delete() on a temporary Site_PHP_Compat, so the site lock it keeps was released as soon as the call returned and a new check could start while the site was deleted. Keep the instance on the command. Also pass a dispatcher closure created in the command's scope: the bare 'pcntl_signal_dispatch' string ran the protected rollback() handlers from Site_PHP_Compat's scope, which threw on PHP 8 and dropped the signal with a warning on 7.4. --- src/helper/class-ee-site.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 498ee40c..a52217fa 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -92,7 +92,7 @@ abstract class EE_Site_Command { private static $le_renewal_started = false; /** - * @var Site_PHP_Compat|null $php_compat_check The running `site php-compat`, cleaned up on a fatal error or a signal. + * @var Site_PHP_Compat|null $php_compat_check The running `site php-compat` (or the one `site delete` keeps the lock with), cleaned up on a fatal error or a signal. */ private $php_compat_check; @@ -246,9 +246,14 @@ public function delete( $args, $assoc_args ) { \EE::confirm( sprintf( 'Are you sure you want to delete %s?', $this->site_data['site_url'] ), $assoc_args ); // A running php-compat check mounts the site's code: stop it first, and drop what php-compat keeps for the site. - $compat = ( new Site_PHP_Compat() )->stop_for_delete( + // Kept on $this: the site lock it holds must last until this process ends. + $this->php_compat_check = new Site_PHP_Compat(); + $compat = $this->php_compat_check->stop_for_delete( (object) $this->site_data, - function_exists( 'pcntl_signal_dispatch' ) ? 'pcntl_signal_dispatch' : null + // Dispatched in this class's scope, where the protected rollback() handlers can be called. + function () { + pcntl_signal_dispatch(); + } ); if ( null !== $compat ) { \EE::error( sprintf( 'Could not stop the php-compat check of %s (%s). Nothing was deleted.', $this->site_data['site_url'], $compat ) ); From cd155e1ea381296f0f7776b400e05ae14907681b Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:07:24 +0530 Subject: [PATCH 10/53] fix(site): keep a php-compat check running when the terminal hangs up A lost terminal sends SIGHUP to the whole foreground process group. ee handled it, but the docker client it spawned got it too and, with its default signal proxy, passed it on to the scanner, which died (exit 129, tool_error). nohup didn't help: PHP's handler replaced the ignore and the child got the default disposition back on exec. Ignore SIGHUP instead of handling it, so the docker client inherits the ignore, and run the scanner with --sig-proxy=false, as the client otherwise installs its own handler and forwards the signal. Ctrl+C and SIGTERM still stop the check through ee's handlers and cleanup. Also log the result before printing it: PHP stops at an echo to a terminal that is gone, which lost the ee.log line. --- src/helper/Site_PHP_Compat.php | 6 ++++-- src/helper/class-ee-site.php | 10 +++------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 599e3e80..0c19f850 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -227,6 +227,8 @@ public function run( $site_data, array $assoc_args, $dispatch = null ) { $result = $this->doc( 'cancelled' ); } + // Before printing: PHP stops at an echo to a terminal that is gone. + $this->log_result( $result['doc'], microtime( true ) - $started ); if ( 'json' === $format ) { echo self::encode( $result['doc'] ) . "\n"; } elseif ( $this->cancel ) { @@ -240,7 +242,6 @@ public function run( $site_data, array $assoc_args, $dispatch = null ) { } } - $this->log_result( $result['doc'], microtime( true ) - $started ); delem_log( 'site php-compat end' ); } @@ -762,7 +763,8 @@ protected function cancel_wait() { * @return string[] */ public function docker_run_args( $mode, $image, $site_data, $code, $out = null, $timeout = null ) { - $args = [ 'docker', 'run', '--rm', '--init' ]; + // No --sig-proxy: the client would pass a terminal's SIGHUP on to the scanner. + $args = [ 'docker', 'run', '--rm', '--init', '--sig-proxy=false' ]; if ( 'scan' === $mode ) { array_push( $args, '--name', 'ee-php-compat-' . $this->site ); } diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index a52217fa..7fbf2f1d 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3386,13 +3386,9 @@ public function php_compat( $args, $assoc_args ) { foreach ( [ SIGTERM, SIGINT, SIGUSR1 ] as $signal ) { pcntl_signal( $signal, $stop ); } - // A lost terminal doesn't stop a check (PHP can't see nohup's ignore); it ends and cleans up on its own, or with --cancel. - pcntl_signal( - SIGHUP, - function () { - \EE::debug( 'Hangup received; the check goes on. Stop it with --cancel.' ); - } - ); + // A lost terminal doesn't stop a check; it ends and cleans up on its own, or with --cancel. Ignored rather than + // handled, so the docker client inherits the ignore (a handled signal is reset to the default on exec). + pcntl_signal( SIGHUP, SIG_IGN ); } $this->php_compat_check->run( $this->site_data, From 34005fee43697fcf00f5e814bb932682a1b80337 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:07:50 +0530 Subject: [PATCH 11/53] test(site): hang up the docker client too in the php-compat hangup scenario A lost terminal hangs up the whole job; the scenario only signalled the ee process, so it could not catch a scanner killed through the docker client. --- features/php-compat.feature | 3 +++ 1 file changed, 3 insertions(+) diff --git a/features/php-compat.feature b/features/php-compat.feature index e64180df..75b392ca 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -253,6 +253,9 @@ Feature: Check the PHP compatibility of a site's code # [s] keeps pkill's own shell out of the match. And I run 'pkill -HUP -f "[s]ite php-compat bh-site-command-183.test --php=8.4 --format=json"' Then the command should succeed + # A lost terminal hangs up the whole job, the docker client too. + When I run 'pkill -HUP -f "[d]ocker run .*--name ee-php-compat-bh-site-command-183.test "' + Then the command should succeed When I wait for the next second Then the background command should still be running When I wait up to 900 seconds for the background command to finish From f947a64e5ce1808fb7afb6164738eac55571662d Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:10:42 +0530 Subject: [PATCH 12/53] fix(site): bound php-compat's cancel guard wait and tell a failed docker inspect apart - A --cancel or `ee site delete` waited with no deadline for the per-site cancel guard, so a first --cancel stuck on a hung docker daemon blocked them forever. The wait now ends after twice the cancel wait with tool_error "another cancel of the site is still running". - container_status() read every failed `docker inspect` (daemon restarting, API error, no timeout) as "no container", so cleanup() could remove /out under a running scanner and --cancel or a delete could report not_running. Only Docker's "no such object" now means none; any other failure or a timeout is "unknown", which is never taken as gone and stops a new scan with tool_error. - cleanup() runs twice per scan (run()'s finally and the shutdown handler). The second call no longer honours a late cancel: by then the lock is released, and it could remove a request written for the next scan. --- src/helper/Site_PHP_Compat.php | 35 +++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 0c19f850..4b031666 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -361,6 +361,9 @@ protected function run_scan( $site_data, $timeout, $output ) { if ( 'running' === $status ) { return $this->doc( 'busy' ); } + if ( 'unknown' === $status ) { + return $this->doc( 'tool_error', "could not check the container $name" ); + } if ( 'exited' === $status ) { EE::debug( "Removing the leftover container $name." ); // Known limit: a container whose --rm is still in progress can't be removed again, which reads as this tool_error. @@ -536,7 +539,9 @@ protected function run_cancel( $site_data ) { if ( null === $marker ) { return $this->doc( 'tool_error', 'could not create the temporary directory' ); } - $this->hold_cancel_guard( $marker ); + if ( ! $this->hold_cancel_guard( $marker ) ) { + return $this->doc( 'tool_error', 'another cancel of the site is still running' ); + } if ( ! $this->lock_site( $site_data->site_fs_path ) ) { // A scan holds the lock: ask it to stop, then wait until it has removed its container, cleaned up and let go. @@ -632,17 +637,24 @@ protected static function guard_path( $marker ) { * --cancel waits for the first, so it never replaces a request the first still waits on. * * @param string $marker cancel_path(). + * + * @return bool False when another --cancel still holds it after twice cancel_wait() (e.g. stuck on a hung docker). */ protected function hold_cancel_guard( $marker ) { $guard = $this->own_dir( dirname( self::guard_path( $marker ) ) ) ? @fopen( self::guard_path( $marker ), 'c' ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. if ( false === $guard ) { - return; + return true; } - // Polled, so signals still reach the handlers; the holder ends within cancel_wait() and its sweep. + // Polled, so signals still reach the handlers. + $until = microtime( true ) + 2 * $this->cancel_wait(); while ( ! flock( $guard, LOCK_EX | LOCK_NB, $would_block ) ) { if ( ! $would_block ) { fclose( $guard ); - return; + return true; + } + if ( microtime( true ) >= $until ) { + fclose( $guard ); + return false; } usleep( 100000 ); if ( function_exists( 'pcntl_signal_dispatch' ) ) { @@ -650,6 +662,8 @@ protected function hold_cancel_guard( $marker ) { } } $this->cancel_guard = $guard; + + return true; } /** @@ -1628,10 +1642,15 @@ protected function lock_estimate() { /** * @param string $name Container name. * - * @return string|false running, exited, or false when there is none. + * @return string|false running, exited, unknown (docker failed or timed out), or false when there is none. */ protected function container_status( $name ) { - return \EE_DOCKER::container_status( $name ); + $run = $this->docker( [ 'docker', 'inspect', '--format', '{{.State.Running}}', $name ], 60 ); + if ( 0 === $run['code'] ) { + return 'true' === trim( $run['stdout'] ) ? 'running' : 'exited'; + } + // Only Docker's own answer means none: a daemon that fails or hangs may still run it. + return 1 === $run['code'] && preg_match( '/no such (object|container)/i', $run['stderr'] ) ? false : 'unknown'; } /** @@ -2908,6 +2927,8 @@ public function cleanup() { fclose( $this->cancel_guard ); $this->cancel_guard = null; } - $this->cleaning = false; + // Without the lock, a request that comes now is for another scan: a second cleanup() leaves it. + $this->cancel_marker = null; + $this->cleaning = false; } } From af5629031b865ead7acd46db3530a532e31df7ea Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:14:00 +0530 Subject: [PATCH 13/53] fix(site): open php-compat and restore lock files close-on-exec Every child process (docker pull/inspect/rm, rm -rf, rclone, rsync) inherited the flock'ed handles, so when ee was SIGKILLed or OOM-killed mid-check or mid-restore, an orphaned child kept the site locked until it ended, and php-compat, --cancel, delete and restore all read that as a running check. The site, estimate and cancel-guard locks and restore's site lock are now opened with fopen's "e" flag (O_CLOEXEC). A killed scan's container is still found by its name. --- src/helper/Site_Backup_Restore.php | 2 +- src/helper/Site_PHP_Compat.php | 13 +++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/helper/Site_Backup_Restore.php b/src/helper/Site_Backup_Restore.php index f7e7fb95..4afd2c6d 100644 --- a/src/helper/Site_Backup_Restore.php +++ b/src/helper/Site_Backup_Restore.php @@ -2586,7 +2586,7 @@ private function check_and_install( $command, $name ) { */ private function hold_scan_lock() { $message = sprintf( 'A php-compat check of %1$s is running and reads the files a restore replaces. Wait for it to finish or stop it with `ee site php-compat %1$s --cancel`, then run the restore again.', $this->site_data['site_url'] ); - $handle = @fopen( $this->site_data['site_fs_path'], 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + $handle = @fopen( $this->site_data['site_fs_path'], 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. if ( false !== $handle && flock( $handle, LOCK_EX | LOCK_NB, $would_block ) ) { $this->scan_lock = $handle; diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 4b031666..e0a5acc4 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -552,7 +552,7 @@ protected function run_cancel( $site_data ) { $grace = min( self::CANCEL_GRACE, $this->cancel_wait() ); $locked = $this->wait_for_site_lock( $site_data->site_fs_path, $grace ); if ( ! $locked ) { - // Untaken: a killed scan's docker client (it inherits the lock) or a frozen scan holds the lock. The id is read + // Untaken: a frozen scan holds the lock. The id is read // first: no scan starts a container while the request stays, so a later scan's container is never this id. $id = $this->running_container_id( $name ); if ( null !== $id && $token === $this->read_cancel( $marker ) ) { @@ -641,7 +641,7 @@ protected static function guard_path( $marker ) { * @return bool False when another --cancel still holds it after twice cancel_wait() (e.g. stuck on a hung docker). */ protected function hold_cancel_guard( $marker ) { - $guard = $this->own_dir( dirname( self::guard_path( $marker ) ) ) ? @fopen( self::guard_path( $marker ), 'c' ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + $guard = $this->own_dir( dirname( self::guard_path( $marker ) ) ) ? @fopen( self::guard_path( $marker ), 'ce' ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. if ( false === $guard ) { return true; } @@ -672,7 +672,7 @@ protected function hold_cancel_guard( $marker ) { */ protected function clear_stale_cancel() { // Not created here: a --cancel creates it before its request, so while it is missing any request is a live one. - $guard = @fopen( self::guard_path( $this->cancel_marker ), 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing is handled. + $guard = @fopen( self::guard_path( $this->cancel_marker ), 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing is handled. if ( false === $guard ) { return; } @@ -1592,7 +1592,8 @@ public static function resolve_in( $code, $rel ) { * @return bool False when another php-compat run holds it. */ protected function lock_site( $site_fs_path ) { - $handle = @fopen( $site_fs_path, 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + // Close-on-exec: a child (docker pull, rm) must not keep the lock after this process is killed. + $handle = @fopen( $site_fs_path, 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. if ( false === $handle ) { EE::debug( "Could not open $site_fs_path to lock it; relying on the container name." ); @@ -1620,7 +1621,7 @@ protected function lock_estimate() { $parent = $this->temp_parent(); $path = null === $parent ? null : $this->control_path( $parent, 'estimate-lock' ); // Not in the per-site directory, whose leftovers a scan removes. - $handle = null === $path ? false : @fopen( $path, 'c' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + $handle = null === $path ? false : @fopen( $path, 'ce' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. if ( false === $handle ) { return null; } @@ -2854,7 +2855,7 @@ public function stop_for_delete( $site_data, $dispatch = null ) { * @return bool Whether none runs now. */ protected function wait_for_estimate( $parent ) { - $handle = @fopen( "$parent/.estimate-lock/{$this->site}", 'r' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing: none ran. + $handle = @fopen( "$parent/.estimate-lock/{$this->site}", 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing: none ran. if ( false === $handle ) { return true; } From d974e34dacde20d12c5276ed3801c2d84922174e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:16:39 +0530 Subject: [PATCH 14/53] fix(site): tell a restore apart from a php-compat check Restore held the same exclusive site-directory lock as a scan, so during a restore a scan said a check was already running, --cancel wrote a request, waited 60 s and failed, and `ee site delete` was refused for a check that didn't exist. Estimates never looked at that lock and could list app/ while the restore swapped it. - Restore now holds the lock shared; php-compat runs hold it exclusive. When php-compat can't get the lock and only shared holders have it, a scan, an estimate and --cancel return tool_error "a restore of the site is running" at once, and --cancel writes no request. A delete during a restore is refused with that reason. - An estimate checks for a restore after taking its own lock, and restore refuses to start while an estimate holds that lock, so the two never overlap. - Restore takes the lock before it creates the download dir, so a refused restore no longer leaves an empty EE_BACKUP_DIR/ behind. --- src/helper/Site_Backup_Restore.php | 12 +++++-- src/helper/Site_PHP_Compat.php | 50 ++++++++++++++++++++++++++++-- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/helper/Site_Backup_Restore.php b/src/helper/Site_Backup_Restore.php index 4afd2c6d..8c2ace2d 100644 --- a/src/helper/Site_Backup_Restore.php +++ b/src/helper/Site_Backup_Restore.php @@ -411,6 +411,9 @@ public function restore( $args, $assoc_args = [] ) { $this->rclone_config_path = $this->resolve_restore_path( $backup_id ); } + // Before the download dir: a restore refused here leaves nothing behind. + $this->hold_scan_lock(); + // Only once the id is valid: a refused --id left an empty download dir behind (BKP-22). if ( ! $this->fs->exists( $backup_dir ) ) { $this->fs->mkdir( $backup_dir ); @@ -2582,13 +2585,17 @@ private function check_and_install( $command, $name ) { /** * Take the site directory's lock, which `ee site php-compat` holds while it scans app/, for the rest of the restore, which - * replaces app/; the lock goes with the process. + * replaces app/; the lock goes with the process. Shared: php-compat holds it exclusive, so it can tell a restore from a check. */ private function hold_scan_lock() { $message = sprintf( 'A php-compat check of %1$s is running and reads the files a restore replaces. Wait for it to finish or stop it with `ee site php-compat %1$s --cancel`, then run the restore again.', $this->site_data['site_url'] ); $handle = @fopen( $this->site_data['site_fs_path'], 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. - if ( false !== $handle && flock( $handle, LOCK_EX | LOCK_NB, $would_block ) ) { + if ( false !== $handle && flock( $handle, LOCK_SH | LOCK_NB, $would_block ) ) { $this->scan_lock = $handle; + // After taking the lock: an estimate takes its own first, then looks for a restore. + if ( Site_PHP_Compat::estimate_running( $this->site_data['site_url'] ) ) { + EE::error( sprintf( 'A php-compat estimate of %s is running and reads the files a restore replaces. Wait for it to finish (about two minutes at most), then run the restore again.', $this->site_data['site_url'] ) ); + } return; } @@ -2604,7 +2611,6 @@ private function hold_scan_lock() { private function pre_restore_check() { $this->pre_backup_restore_checks(); - $this->hold_scan_lock(); // Only with the lock held: a restore refused by another run's lock must leave that run's download dir alone. $this->restore_in_progress = true; diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index e0a5acc4..4513f186 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -349,7 +349,7 @@ protected function run_scan( $site_data, $timeout, $output ) { // Two EE runs can't both pass the container check below and then clear each other's directory as a leftover. if ( ! $this->lock_site( $site_data->site_fs_path ) ) { - return $this->doc( 'busy' ); + return $this->restore_running( $site_data->site_fs_path ) ? $this->doc( 'tool_error', 'a restore of the site is running' ) : $this->doc( 'busy' ); } $parent = $this->temp_parent(); if ( null !== $parent ) { @@ -492,6 +492,10 @@ protected function run_estimate( $site_data ) { if ( ! $locked ) { return $this->doc( 'busy' ); } + // Taken before this check, so a restore starting now sees the estimate lock (Site_Backup_Restore::hold_scan_lock()). + if ( $this->restore_running( $site_data->site_fs_path ) ) { + return $this->doc( 'tool_error', 'a restore of the site is running' ); + } $pull = $this->ensure_image( $image ); if ( null !== $pull ) { return $this->doc( 'tool_error', $pull ); @@ -543,7 +547,12 @@ protected function run_cancel( $site_data ) { return $this->doc( 'tool_error', 'another cancel of the site is still running' ); } - if ( ! $this->lock_site( $site_data->site_fs_path ) ) { + $locked = $this->lock_site( $site_data->site_fs_path ); + if ( ! $locked && $this->restore_running( $site_data->site_fs_path ) ) { + // No check runs during a restore: nothing to stop, and no request to leave. + return $this->doc( 'tool_error', 'a restore of the site is running' ); + } + if ( ! $locked ) { // A scan holds the lock: ask it to stop, then wait until it has removed its container, cleaned up and let go. $token = $this->request_cancel( $marker ); if ( null === $token ) { @@ -1614,6 +1623,43 @@ protected function lock_site( $site_fs_path ) { return true; } + /** + * A restore holds the site directory shared and every php-compat run exclusive, so only shared holders mean a restore. + * Briefly locks it when no one holds it. + * + * @param string $site_fs_path Site directory. + * + * @return bool + */ + protected function restore_running( $site_fs_path ) { + $handle = @fopen( $site_fs_path, 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- none then. + if ( false === $handle ) { + return false; + } + $restore = flock( $handle, LOCK_SH | LOCK_NB ) && ! flock( $handle, LOCK_EX | LOCK_NB ); + fclose( $handle ); + + return $restore; + } + + /** + * For `ee site restore`: whether an estimate of the site runs now (it holds its lock file exclusive). + * + * @param string $site Site name. + * + * @return bool + */ + public static function estimate_running( $site ) { + $handle = @fopen( EE_ROOT_DIR . '/tmp/' . self::TEMP_DIR . "/.estimate-lock/$site", 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing: none ran. + if ( false === $handle ) { + return false; + } + $running = ! flock( $handle, LOCK_SH | LOCK_NB ); + fclose( $handle ); + + return $running; + } + /** * @return bool|null False when another estimate of the site holds the lock; null when the lock file can't be made. */ From fd407ea8444760360dbfe5af7146767541f5defd Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:17:10 +0530 Subject: [PATCH 15/53] fix(site): take php-compat's estimate lock after the image pull An estimate held its lock across the scanner image pull (up to 300 s, 1800 s on a first pull), but `ee site delete` waits only for the estimate's own time limit (180 s), so a delete during a slow pull was refused. The lock is now taken once the image is there, and delete logs that it is waiting for an estimate instead of waiting silently. --- src/helper/Site_PHP_Compat.php | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 4513f186..de35f81c 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -484,6 +484,11 @@ protected function run_estimate( $site_data ) { if ( false !== strpbrk( $code, ',"' ) ) { return $this->doc( 'tool_error', 'the site code path has a comma or a quote' ); } + // Before the lock: `ee site delete` waits only for the estimate's own time limit, not for a slow pull. + $pull = $this->ensure_image( $image ); + if ( null !== $pull ) { + return $this->doc( 'tool_error', $pull ); + } // One estimate per site at a time; it never waits for a scan. $locked = $this->lock_estimate(); if ( null === $locked ) { @@ -496,10 +501,6 @@ protected function run_estimate( $site_data ) { if ( $this->restore_running( $site_data->site_fs_path ) ) { return $this->doc( 'tool_error', 'a restore of the site is running' ); } - $pull = $this->ensure_image( $image ); - if ( null !== $pull ) { - return $this->doc( 'tool_error', $pull ); - } $mounts = $this->extra_mounts( $site_data, $code ); if ( is_string( $mounts ) ) { return $this->doc( 'tool_error', $mounts ); @@ -2905,8 +2906,13 @@ protected function wait_for_estimate( $parent ) { if ( false === $handle ) { return true; } - $until = microtime( true ) + $this->estimate_wait(); + $until = microtime( true ) + $this->estimate_wait(); + $logged = false; while ( ! flock( $handle, LOCK_EX | LOCK_NB, $would_block ) ) { + if ( $would_block && ! $logged ) { + EE::log( "Waiting for the running php-compat estimate of {$this->site} to finish." ); + $logged = true; + } if ( ! $would_block || microtime( true ) >= $until ) { fclose( $handle ); From 4962273d18d7bc32ab29fb11ae5ed012919d1d8b Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:17:35 +0530 Subject: [PATCH 16/53] fix(site): don't refuse a site delete over php-compat's temporary directory Once EE_ROOT_DIR/tmp/php-compat existed, every `ee site delete` went through php-compat's --cancel path, which returns tool_error when that directory (or its parent or .cancel dir) is a link or belongs to another user. Every delete on the host was then refused, even for sites never checked. Now no check can run with such a directory, so delete only removes a container of the site by name, warns that the directory is left as it is, and goes on. The early return also no longer follows a link. --- src/helper/Site_PHP_Compat.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index de35f81c..e2cc14f1 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -2857,8 +2857,19 @@ public function stop_for_delete( $site_data, $dispatch = null ) { $this->site = $site_data->site_url; $this->dispatch = $dispatch; $parent = rtrim( $this->temp_base(), '/' ) . '/' . self::TEMP_DIR; + $name = 'ee-php-compat-' . $this->site; // Nothing to do, and no temp directory created, for a site never checked. - if ( ! file_exists( $parent ) && false === $this->container_status( 'ee-php-compat-' . $this->site ) ) { + if ( ! file_exists( $parent ) && ! is_link( $parent ) && false === $this->container_status( $name ) ) { + return null; + } + $usable = $this->temp_parent(); + if ( null === $usable || null === $this->cancel_path( $usable ) ) { + // No check can run with these directories (a link, another owner): only a container can be left, and is stopped by name. + EE::warning( "Leaving $parent as it is: not a directory of this user with mode 0700." ); + if ( false !== $this->container_status( $name ) && ! $this->container_gone( $name ) ) { + return "could not remove the container $name"; + } + return null; } try { From ed41fee7662c9f60d3bdf1f13127537f0e7780b7 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:18:32 +0530 Subject: [PATCH 17/53] fix(site): keep scanner tags another php-compat check is about to use After a successful pull, a check removed every other compat-scanner tag that no container used. A check that had passed its own pull but not yet started `docker run` has no container, so with two EE builds on different pins (during `ee cli update`, or a stable phar next to a dev checkout) its image could be removed under it, and its `docker run` then pulled it again or failed offline. Every check now holds a shared host-wide lock (tmp/php-compat/.image-lock) from before its pull until it ends. Old tags are removed only when the pulling check can take that lock exclusive, i.e. no other check is running; otherwise they stay for the next pull or the migration's image prune. --- src/helper/Site_PHP_Compat.php | 45 ++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index e2cc14f1..48ab382c 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -114,6 +114,9 @@ class Site_PHP_Compat { /** @var resource|null Lock on the site directory while a scan runs, or on the site's estimate lock file while an estimate runs. */ protected $lock; + /** @var resource|null Shared host-wide lock while this check uses the scanner image, so no other check removes its tag. */ + protected $image_lock; + /** @var array|null --output directory as validated: path, dev, ino. */ protected $output_dir; @@ -372,6 +375,7 @@ protected function run_scan( $site_data, $timeout, $output ) { } } + $this->hold_image(); $pull = $this->ensure_image( $image ); if ( null !== $pull ) { return $this->doc( 'tool_error', $pull ); @@ -485,6 +489,7 @@ protected function run_estimate( $site_data ) { return $this->doc( 'tool_error', 'the site code path has a comma or a quote' ); } // Before the lock: `ee site delete` waits only for the estimate's own time limit, not for a slow pull. + $this->hold_image(); $pull = $this->ensure_image( $image ); if ( null !== $pull ) { return $this->doc( 'tool_error', $pull ); @@ -1788,6 +1793,30 @@ protected static function first_line( $text ) { * @param string $image The pinned image with its tag, never removed. */ protected function remove_other_tags( $image ) { + // Only with no other check running: one between its pull and its `docker run` has no container that keeps its tag. + if ( null !== $this->image_lock ) { + flock( $this->image_lock, LOCK_UN ); + $alone = flock( $this->image_lock, LOCK_EX | LOCK_NB ); + if ( ! $alone ) { + flock( $this->image_lock, LOCK_SH ); + EE::debug( 'Keeping the other ' . self::IMAGE . ' tags: another check is running.' ); + + return; + } + } + try { + $this->remove_unused_tags( $image ); + } finally { + if ( null !== $this->image_lock ) { + flock( $this->image_lock, LOCK_SH ); + } + } + } + + /** + * @param string $image The pinned image with its tag, never removed. + */ + protected function remove_unused_tags( $image ) { $list = $this->docker( [ 'docker', 'image', 'ls', '--format', '{{.Tag}}', self::IMAGE ], 60 ); if ( 0 !== $list['code'] ) { EE::debug( 'Could not list the ' . self::IMAGE . ' tags.' ); @@ -1811,6 +1840,18 @@ protected function remove_other_tags( $image ) { } } + /** + * Hold the host-wide image lock shared until cleanup(); without it (no usable temp directory) old tags are removed as before. + */ + protected function hold_image() { + $parent = $this->temp_parent(); + $handle = null === $parent ? false : @fopen( "$parent/.image-lock", 'ce' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + // Blocks only while another check removes old tags. + if ( false !== $handle && flock( $handle, LOCK_SH ) ) { + $this->image_lock = $handle; + } + } + /** * This run's /out: a new random directory in a root-only per-site directory, after removing what a killed run left there. * @@ -2991,6 +3032,10 @@ public function cleanup() { fclose( $this->cancel_guard ); $this->cancel_guard = null; } + if ( null !== $this->image_lock ) { + fclose( $this->image_lock ); + $this->image_lock = null; + } // Without the lock, a request that comes now is for another scan: a second cleanup() leaves it. $this->cancel_marker = null; $this->cleaning = false; From 4cb83fb23041135c44805bd39e8f1330fe1951ac Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:19:24 +0530 Subject: [PATCH 18/53] test(site): never remove a healthy /dev/null in the Behat hooks The AfterScenario hook and the "/dev/null should still be the null device" step unlinked /dev/null and ran `mknod c 1 3` whenever its rdev wasn't 259, Linux's number for 1:3. On another OS, or for any character device with other numbers, that replaced a healthy device. /dev/null is now recreated only on Linux and only when it is no character device at all (the case a broken --output check leaves). The step still fails on a wrong device; it checks the numbers only on Linux. --- features/bootstrap/FeatureContext.php | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 8a05baa5..7eb8c6b6 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -490,11 +490,7 @@ public function cleanupScenario(AfterScenarioScope $scope) { // A failed --output check could have replaced /dev/null with a file; never leave the runner without it. clearstatcache( true, '/dev/null' ); - $null = @lstat( '/dev/null' ); - if ( ! $null || 0020000 !== ( $null['mode'] & 0170000 ) || 259 !== $null['rdev'] ) { - @unlink( '/dev/null' ); - exec( 'mknod -m 666 /dev/null c 1 3' ); - } + self::repairDevNull( @lstat( '/dev/null' ) ); $this->commands = []; chdir($this->ee_path); @@ -998,12 +994,27 @@ public function devNullShouldStillBeTheNullDevice() { clearstatcache( true, '/dev/null' ); $stat = @lstat( '/dev/null' ); - if ( $stat && 0020000 === ( $stat['mode'] & 0170000 ) && 259 === $stat['rdev'] ) { + // 259 is 1:3, the null device's numbers on Linux only. + if ( $stat && 0020000 === ( $stat['mode'] & 0170000 ) && ( 'Linux' !== PHP_OS_FAMILY || 259 === $stat['rdev'] ) ) { + return; + } + self::repairDevNull( $stat ); + throw new Exception( '/dev/null was replaced: ' . var_export( $stat, true ) ); + } + + /** + * Recreate /dev/null only on Linux and only when it is no character device at all (e.g. replaced by a file), so a + * healthy one is never removed. + * + * @param array|false $stat lstat() of /dev/null. + */ + private static function repairDevNull( $stat ) + { + if ( 'Linux' !== PHP_OS_FAMILY || ( $stat && 0020000 === ( $stat['mode'] & 0170000 ) ) ) { return; } @unlink( '/dev/null' ); exec( 'mknod -m 666 /dev/null c 1 3' ); - throw new Exception( '/dev/null was replaced (restored now): ' . var_export( $stat, true ) ); } /** From 466bbf834c2334d45388672bedbe015acbbab6b5 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:21:27 +0530 Subject: [PATCH 19/53] fix(site): remove an interrupted php-compat estimate's container Without --sig-proxy, Ctrl+C or a SIGTERM no longer reaches the scanner through the docker client, and a timed-out estimate only ever stopped the client. A scan's container is removed by name in cleanup(), but an estimate's has no name and kept running until it finished. Estimates now carry a per-run label, and cleanup() removes a container with that label unless the run ended on its own. --- src/helper/Site_PHP_Compat.php | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 48ab382c..e316897e 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -114,6 +114,9 @@ class Site_PHP_Compat { /** @var resource|null Lock on the site directory while a scan runs, or on the site's estimate lock file while an estimate runs. */ protected $lock; + /** @var string|null Label value of this estimate's container while cleanup() may have to remove it. */ + protected $estimate_label; + /** @var resource|null Shared host-wide lock while this check uses the scanner image, so no other check removes its tag. */ protected $image_lock; @@ -511,7 +514,13 @@ protected function run_estimate( $site_data ) { return $this->doc( 'tool_error', $mounts ); } - $run = $this->docker( $this->docker_run_args( 'estimate', $image, $site_data, $code ), self::ESTIMATE_TIMEOUT + self::PROCESS_MARGIN, true ); + // The client ignores signals (no --sig-proxy) and a timeout stops only the client: cleanup() removes the container by label. + $this->estimate_label = bin2hex( random_bytes( 8 ) ); + $run = $this->docker( $this->docker_run_args( 'estimate', $image, $site_data, $code ), self::ESTIMATE_TIMEOUT + self::PROCESS_MARGIN, true ); + if ( null !== $run['code'] ) { + // Ended on its own: --rm removed it. + $this->estimate_label = null; + } if ( $run['timed_out'] ) { return $this->doc( 'tool_error', 'timed out after ' . self::ESTIMATE_TIMEOUT . ' s' ); } @@ -809,6 +818,9 @@ public function docker_run_args( $mode, $image, $site_data, $code, $out = null, '-e', 'COMPAT_SITE=' . $this->site, '-e', 'COMPAT_IMAGE=' . $image, '-e', 'COMPAT_REPORT_MAX=' . self::REPORT_MAX, '--mount', "type=bind,src=$code,dst=/var/www,readonly" ); + if ( 'estimate' === $mode && null !== $this->estimate_label ) { + array_push( $args, '--label', 'ee-php-compat-estimate=' . $this->estimate_label ); + } if ( 'estimate' === $mode ) { // The byte model misses PHPCS's per-file cost on dense many-file trees (2x short seen): more per batch, wider top end. array_push( $args, '-e', 'COMPAT_SECONDS_PER_BATCH=' . self::ESTIMATE_SECONDS_PER_BATCH, '-e', 'COMPAT_HIGH_FACTOR=' . self::ESTIMATE_HIGH_FACTOR ); @@ -3002,6 +3014,14 @@ public function cleanup() { $this->temp_dir = null; } } + if ( null !== $this->estimate_label ) { + $label = 'label=ee-php-compat-estimate=' . $this->estimate_label; + $this->estimate_label = null; + $ids = $this->docker( [ 'docker', 'ps', '-aq', '--filter', $label ], 60 ); + foreach ( preg_split( '/\s+/', trim( $ids['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ) as $id ) { + $this->docker( [ 'docker', 'rm', '-f', $id ], 60 ); + } + } if ( null !== $this->temp_dir ) { $dir = $this->temp_dir; $this->temp_dir = null; From 86003368d192c7d785174d42147d3c6a7d250a2c Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:24:24 +0530 Subject: [PATCH 20/53] fix(site): keep the site lock in delete's php-compat fallback and poll the image lock - When php-compat's directory is unusable, `ee site delete` now also keeps the site lock for the rest of the delete, as its normal path does. It waits for a scan whose container it just removed, and stops at once for a restore. - The shared scanner image lock is taken with a polled, bounded wait (60 s, signals dispatched) instead of a blocking flock(), so a frozen holder can't hang a check. --- src/helper/Site_PHP_Compat.php | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index e316897e..a6df850f 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -1858,10 +1858,24 @@ protected function remove_unused_tags( $image ) { protected function hold_image() { $parent = $this->temp_parent(); $handle = null === $parent ? false : @fopen( "$parent/.image-lock", 'ce' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. - // Blocks only while another check removes old tags. - if ( false !== $handle && flock( $handle, LOCK_SH ) ) { - $this->image_lock = $handle; + if ( false === $handle ) { + return; } + // Held exclusive only while another check removes old tags; polled, so signals still reach the handlers. + $until = microtime( true ) + 60; + while ( ! flock( $handle, LOCK_SH | LOCK_NB, $would_block ) ) { + if ( ! $would_block || microtime( true ) >= $until ) { + fclose( $handle ); + EE::debug( 'Going on without the scanner image lock.' ); + + return; + } + usleep( 100000 ); + if ( function_exists( 'pcntl_signal_dispatch' ) ) { + null === $this->dispatch ? pcntl_signal_dispatch() : call_user_func( $this->dispatch ); + } + } + $this->image_lock = $handle; } /** @@ -2922,6 +2936,17 @@ public function stop_for_delete( $site_data, $dispatch = null ) { if ( false !== $this->container_status( $name ) && ! $this->container_gone( $name ) ) { return "could not remove the container $name"; } + // A scan whose container was just removed lets go of the site lock as it ends; kept as below. + if ( ! $this->lock_site( $site_data->site_fs_path ) ) { + if ( $this->restore_running( $site_data->site_fs_path ) ) { + return 'a restore of the site is running'; + } + if ( ! $this->wait_for_site_lock( $site_data->site_fs_path, $this->cancel_wait() ) ) { + return 'the running check did not stop within ' . $this->cancel_wait() . ' s'; + } + } + $this->delete_lock = $this->lock; + $this->lock = null; return null; } From 4160c35885cf1343d162a05b6351a464b38863e6 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Tue, 24 Nov 2026 21:26:28 +0530 Subject: [PATCH 21/53] fix(site): never call a site safe when its config runs code the scan doesn't read - A file wp-config.php includes (a local config, a Composer autoloader) that lies outside the scanned WordPress directory, or in a part the scanner skips, is tool_error: it is code the site runs. Inside the directory the scanner reads it. - With WordPress in a subdirectory, the served index.php is outside the scan: it may only load WordPress (literal defines and the loader require), anything else is tool_error. - The help text and the no-code message say what a WordPress scan covers: the WordPress directory's PHP except core and the directories the scanner skips; the Behat scenarios follow the loader message and the new wording. --- features/php-compat.feature | 6 +-- src/helper/Site_PHP_Compat.php | 79 +++++++++++++++++++++++++++++++--- src/helper/class-ee-site.php | 2 +- 3 files changed, 77 insertions(+), 10 deletions(-) diff --git a/features/php-compat.feature b/features/php-compat.feature index f47ca8a3..e55c9dd7 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -196,14 +196,14 @@ Feature: Check the PHP compatibility of a site's code And STDOUT should not contain "Safe to upgrade" @wp - Scenario: Without wp-content the message names the directory checked, and a release layout under htdocs is found + Scenario: With nothing to check the message names the directory checked, and a release layout under htdocs is found Given the compat-scanner image is available And the site "bh-site-command-189.test" exists, created with "--type=wp" # Nothing at all to check: WordPress moved out of htdocs, and no wp-config.php. When I run 'mkdir {SITES_DIR}/bh-site-command-189.test/app/off && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/* {SITES_DIR}/bh-site-command-189.test/app/wp-config.php {SITES_DIR}/bh-site-command-189.test/app/off/' And I run 'cd {SITES_DIR}/bh-site-command-189.test && {EE} site php-compat --php=8.4' Then the command should succeed - And STDOUT should contain "No PHP code found to check in bh-site-command-189.test. Looked in {SITES_DIR}/bh-site-command-189.test/app/htdocs: everything there except WordPress core, wp-content included. The check follows the directory nginx serves (root in {SITES_DIR}/bh-site-command-189.test/config/nginx/conf.d/main.conf)" + And STDOUT should contain "No PHP code found to check in bh-site-command-189.test. Looked in {SITES_DIR}/bh-site-command-189.test/app/htdocs: its PHP code except WordPress core, uploads, caches and other skipped directories. The check follows the directory nginx serves (root in {SITES_DIR}/bh-site-command-189.test/config/nginx/conf.d/main.conf)" When I run 'mv {SITES_DIR}/bh-site-command-189.test/app/off/wp-config.php {SITES_DIR}/bh-site-command-189.test/app/ && mv {SITES_DIR}/bh-site-command-189.test/app/off/* {SITES_DIR}/bh-site-command-189.test/app/htdocs/ && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content-off' # A CI/CD deploy: WordPress in releases/1, current links to it, wp-cli.yml points there, the record still says htdocs. When I run 'cd {SITES_DIR}/bh-site-command-189.test/app/htdocs && mkdir -p releases/1 && for f in *; do [ "$f" = releases ] || mv "$f" releases/1/; done && mv releases/1/wp-content-off releases/1/wp-content && ln -s /var/www/htdocs/releases/1 current && printf "path: current/\n" > wp-cli.yml' @@ -299,7 +299,7 @@ Feature: Check the PHP compatibility of a site's code And I run 'bin/ee site php-compat bh-site-command-192.test --php=8.4 --format=json' Then the command should succeed And the JSON field "status" in STDOUT should be "tool_error" - And the JSON field "detail" in STDOUT should contain "can't resolve where htdocs/index.php loads WordPress (wp-blog-header.php) from" + And the JSON field "detail" in STDOUT should contain "can't resolve where htdocs/index.php loads WordPress from" Scenario: An html site is refused Given the html site "bh-site-command-182.test" exists diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index f03b6b5b..2e421cf4 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -98,7 +98,7 @@ class Site_PHP_Compat { /** @var string|null The site's nginx config path, for the no_code_found text; null when app/ is missing. */ protected $nginx_conf; - /** @var bool Whether the scan looks at WordPress code (wp-content) rather than all of htdocs. */ + /** @var bool Whether this is a WordPress scan (its WordPress directory, core left out) rather than all of htdocs. */ protected $wp_layout = false; /** @var string|null Cancel request file a scan watches once it holds the site lock. */ @@ -926,6 +926,11 @@ protected function resolve_layout( $site_data, $code ) { if ( null !== $outside ) { return $this->doc( 'tool_error', "nginx serves $app$rel, which holds PHP outside the WordPress directory $app$root (" . self::clean( $outside ) . "); this check can't scan that layout yet" ); } + // The served index.php isn't scanned there: it may only load WordPress. + $index = $this->read_site_file( $code, "$rel/index.php", self::PHP_SOURCE_MAX ); + if ( null !== $index && ! self::only_loads_wordpress( $index ) ) { + return $this->doc( 'tool_error', "$app$rel/index.php does more than load WordPress, and it is outside the scanned directory $app$root; this check can't scan that layout yet" ); + } } $detail = $this->check_wp_dirs( $code, $root, $app, $rel ); @@ -1179,7 +1184,7 @@ protected function wp_root( $code, $rel ) { } } $candidates = array_values( array_unique( $candidates ) ); - // In order; a WordPress directory without wp-content may still load code from elsewhere (WP_CONTENT_DIR). + // In order; a WordPress directory may have no wp-content when WP_CONTENT_DIR moves it (refused later). foreach ( $candidates as $candidate ) { foreach ( [ 'wp-content', 'wp-settings.php' ] as $marker ) { if ( null !== self::resolve_in( $code, $candidate . '/' . $marker ) ) { @@ -1318,8 +1323,9 @@ protected function check_wp_dirs( $code, $root, $app, $rel ) { if ( null !== $index ) { $queue[] = [ substr( $index, strlen( $code ) + 1 ), false, false ]; } - $values = []; - $seen = []; + $values = []; + $seen = []; + $included = []; while ( $queue ) { list( $file, $conditional, $follow ) = array_shift( $queue ); if ( isset( $seen[ $file ] ) ) { @@ -1357,11 +1363,20 @@ protected function check_wp_dirs( $code, $root, $app, $rel ) { $real = self::resolve_in( $code, $target ); if ( null !== $real && is_file( $real ) ) { // A missing file only warns (include) or stops the site (require): either way it defines nothing. - $queue[] = [ substr( $real, strlen( $code ) + 1 ), $conditional || ! $include['alone'], true ]; + $queue[] = [ substr( $real, strlen( $code ) + 1 ), $conditional || ! $include['alone'], true ]; + $included[] = $real; } } } + // What the config includes is code the site runs: only what the scanner reads (its directory, minus what it skips) is covered. + foreach ( array_unique( $included ) as $real ) { + if ( ! self::scanned_by_wp_scan( $real, $abspath ) ) { + $file = substr( $real, strlen( $code ) + 1 ); + return "WordPress's config loads $app$file, which is outside the scanned directory $app$root (or in a part the scan skips); this check can't scan that layout yet"; + } + } + foreach ( self::DIR_CONSTANTS as $name ) { if ( ! isset( $values[ $name ] ) ) { continue; @@ -1386,6 +1401,58 @@ protected function check_wp_dirs( $code, $root, $app, $rel ) { return null; } + /** + * Whether a wp scan of the WordPress directory reads this file: inside it, outside core and the directories the scanner + * skips by name (uploads, cache, upgrade, languages, upgrade-temp-backup at a content root's top; node_modules, .git). + * + * @param string $real Real host path of the file. + * @param string|null $abspath Real WordPress root. + * + * @return bool + */ + protected static function scanned_by_wp_scan( $real, $abspath ) { + if ( null === $abspath || 0 !== strpos( $real, $abspath . '/' ) ) { + return false; + } + $parts = explode( '/', substr( $real, strlen( $abspath ) + 1 ) ); + if ( in_array( $parts[0], [ 'wp-admin', 'wp-includes' ], true ) || array_intersect( $parts, [ 'node_modules', '.git' ] ) ) { + return false; + } + // A content root's top-level skips: wp-content/uploads/…, and the same under any other directory's first level. + return ! ( count( $parts ) > 2 && in_array( $parts[1], [ 'uploads', 'cache', 'upgrade', 'languages', 'upgrade-temp-backup' ], true ) ); + } + + /** + * Whether a served index.php does nothing but load WordPress: literal defines and one require/include of + * wp-blog-header.php or wp-load.php. + * + * @param string $source PHP source. + * + * @return bool + */ + public static function only_loads_wordpress( $source ) { + $code = ''; + foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. + if ( is_array( $token ) && in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG ], true ) ) { + continue; + } + if ( is_array( $token ) && in_array( $token[0], [ T_CLOSE_TAG, T_INLINE_HTML ], true ) ) { + // Only trailing whitespace may follow the code. + if ( '' !== trim( $token[1], " \t\r\n?>" ) ) { + return false; + } + continue; + } + $code .= ( '' !== $code && is_array( $token ) && T_STRING === $token[0] && preg_match( '/\w$/', $code ) ) ? ' ' . $token[1] : ( is_array( $token ) ? $token[1] : $token ); + } + $quoted = "(?:'[^'\\\\]*'|\"[^\"\\\\\$]*\")"; + $literal = "(?:true|false|null|-?\\d+|$quoted)"; + $define = "@?\\\\?define\\((?:'[A-Za-z0-9_]+'|\"[A-Za-z0-9_]+\"),$literal\\);"; + $load = "(?:require|include)(?:_once)?\\(?(?:(?:__DIR__|dirname\\(__FILE__\\))\\.)?(?:'[^'\\\\\$]*wp-(?:blog-header|load)\\.php'|\"[^\"\\\\\$]*wp-(?:blog-header|load)\\.php\")\\)?;"; + + return 1 === preg_match( "/^(?:$define)*$load(?:$define)*\$/i", $code ); + } + /** * The wp-config.php WordPress loads: in its directory, else the parent without wp-settings.php. Relative to app/. * @@ -2935,7 +3002,7 @@ protected function no_code_text() { return "$text Looked for PHP files in $dir."; } - return "$text Looked in $dir: everything there except WordPress core, wp-content included. The check follows the directory nginx serves (root in {$this->nginx_conf}), its current/ and wp-cli.yml's path:."; + return "$text Looked in $dir: its PHP code except WordPress core, uploads, caches and other skipped directories. The check follows the directory nginx serves (root in {$this->nginx_conf}), its current/ and wp-cli.yml's path:."; } /** diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 7fbf2f1d..fbbf2cc0 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3309,7 +3309,7 @@ public function sync( $args, $assoc_args ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: plugins, themes, mu-plugins, drop-ins and other code under wp-content for WordPress sites (not WordPress core), everything under htdocs for PHP sites. It ends with a verdict: safe to upgrade (every file checked, no errors), not safe (at least one error), or can't confirm (some files couldn't be checked). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core) with wp-config.php and the files it includes; for PHP sites, everything under htdocs. A layout it can't read with certainty (a moved wp-content, code mounted or included from elsewhere) gets no verdict. It ends with a verdict: safe to upgrade (every file checked, no errors), not safe (at least one error), or can't confirm (some files couldn't be checked). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * From e079cbd96a7556a54e6af98c3660165b8272467f Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 13:34:41 +0530 Subject: [PATCH 22/53] fix(site): give php-compat verdicts only for layouts it recognises in full Replace the general PHP reader (include following, block and halt tracking) with exact recognisers, and refuse anything else with the reason: - WordPress at the served root or below it, loaded by WordPress's own index.php (4.9 to 6.x forms); a WordPress root's own index.php must be stock too, and a linked index.php elsewhere is refused. - wp-config.php is checked statement by statement: defines and guarded defines with pure values, the ABSPATH guard, the wp-settings.php load last, EE's HTTPS block, proxy snippets setting allowed $_SERVER keys, allowed variables and ini_set keys, EE's --vip includes, and local configs inside the scanned directory. Directory constants only at their default; WPINC, TEMPLATEPATH, STYLESHEETPATH, WP_LANG_DIR, PLUGINDIR and MUPLUGINDIR never. - All of app/ is walked (time-bounded): any PHP or link outside the WordPress root, a nested install or a link to an ancestor is refused; old releases nginx doesn't serve and dot-directories are passed over. - auto_prepend_file, auto_append_file, opcache.preload, include_path, user_ini.filename and zend.multibyte are checked in every .user.ini, php.ini, conf.d and FPM file; only a prepended file the scan reads is accepted. - nginx files may not set PHP_VALUE, another SCRIPT_FILENAME or DOCUMENT_ROOT, include other files, or add a root, alias or fastcgi_pass outside main.conf and EE's own admin-tools.conf. - The php container must have EE's mounts, its image's command, entrypoint and environment, plus EE's own variables. - Files are read only when they are regular files, so a FIFO no longer hangs the check. --- features/php-compat.feature | 28 +- src/helper/Site_PHP_Compat.php | 1340 +++++++++++-------------- src/helper/Site_PHP_Compat_Layout.php | 824 +++++++++++++++ src/helper/class-ee-site.php | 2 +- 4 files changed, 1428 insertions(+), 766 deletions(-) create mode 100644 src/helper/Site_PHP_Compat_Layout.php diff --git a/features/php-compat.feature b/features/php-compat.feature index e55c9dd7..7ac2e195 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -188,24 +188,24 @@ Feature: Check the PHP compatibility of a site's code Then the command should succeed And the JSON field "status" in STDOUT should be "tool_error" And the JSON field "safe_to_upgrade" in STDOUT should be null - And the JSON field "detail" in STDOUT should contain "WordPress loads plugins and themes from {SITES_DIR}/bh-site-command-188.test/app/htdocs/content (WP_CONTENT_DIR in {SITES_DIR}/bh-site-command-188.test/app/wp-config.php); this check can't scan that layout yet" + And the JSON field "detail" in STDOUT should contain "{SITES_DIR}/bh-site-command-188.test/app/wp-config.php sets WP_CONTENT_DIR to {SITES_DIR}/bh-site-command-188.test/app/htdocs/content" And the docker container "ee-php-compat-bh-site-command-188.test" should not exist When I run 'bin/ee site php-compat bh-site-command-188.test --php=8.4' Then the command should succeed - And STDOUT should match "/^The check of bh-site-command-188\.test for PHP 8\.4 didn't finish: WordPress loads plugins and themes from /" + And STDOUT should match "/^The check of bh-site-command-188\.test for PHP 8\.4 didn't finish: \S+\/app\/wp-config\.php sets WP_CONTENT_DIR to /" And STDOUT should not contain "Safe to upgrade" @wp Scenario: With nothing to check the message names the directory checked, and a release layout under htdocs is found Given the compat-scanner image is available And the site "bh-site-command-189.test" exists, created with "--type=wp" - # Nothing at all to check: WordPress moved out of htdocs, and no wp-config.php. - When I run 'mkdir {SITES_DIR}/bh-site-command-189.test/app/off && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/* {SITES_DIR}/bh-site-command-189.test/app/wp-config.php {SITES_DIR}/bh-site-command-189.test/app/off/' + # Nothing at all to check: WordPress moved out of app/ altogether. + When I run 'mkdir {SITES_DIR}/bh-site-command-189.test/off && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/* {SITES_DIR}/bh-site-command-189.test/app/wp-config.php {SITES_DIR}/bh-site-command-189.test/off/' And I run 'cd {SITES_DIR}/bh-site-command-189.test && {EE} site php-compat --php=8.4' Then the command should succeed And STDOUT should contain "No PHP code found to check in bh-site-command-189.test. Looked in {SITES_DIR}/bh-site-command-189.test/app/htdocs: its PHP code except WordPress core, uploads, caches and other skipped directories. The check follows the directory nginx serves (root in {SITES_DIR}/bh-site-command-189.test/config/nginx/conf.d/main.conf)" - When I run 'mv {SITES_DIR}/bh-site-command-189.test/app/off/wp-config.php {SITES_DIR}/bh-site-command-189.test/app/ && mv {SITES_DIR}/bh-site-command-189.test/app/off/* {SITES_DIR}/bh-site-command-189.test/app/htdocs/ && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content-off' - # A CI/CD deploy: WordPress in releases/1, current links to it, wp-cli.yml points there, the record still says htdocs. + When I run 'mv {SITES_DIR}/bh-site-command-189.test/off/* {SITES_DIR}/bh-site-command-189.test/app/htdocs/ && rmdir {SITES_DIR}/bh-site-command-189.test/off && mv {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content {SITES_DIR}/bh-site-command-189.test/app/htdocs/wp-content-off' + # A CI/CD deploy: WordPress and its wp-config.php in releases/1, current links to it, wp-cli.yml points there, the record still says htdocs. When I run 'cd {SITES_DIR}/bh-site-command-189.test/app/htdocs && mkdir -p releases/1 && for f in *; do [ "$f" = releases ] || mv "$f" releases/1/; done && mv releases/1/wp-content-off releases/1/wp-content && ln -s /var/www/htdocs/releases/1 current && printf "path: current/\n" > wp-cli.yml' And I write " index.php && chown -R 33:33 .' + # Core and wp-content in htdocs/wp, loaded by htdocs/index.php; wp-config.php one level up, where WordPress looks; no wp-cli.yml. + When I run 'cd {SITES_DIR}/bh-site-command-192.test/app/htdocs && mkdir wp && mv wp-admin wp-includes wp-content wp-*.php index.php license.txt readme.html xmlrpc.php wp/ && mv ../wp-config.php ./ && printf " index.php && chown -R 33:33 .' Then the command should succeed And I write " {SITES_DIR}/bh-site-command-192.test/app/htdocs/index.php' And I run 'bin/ee site php-compat bh-site-command-192.test --php=8.4 --format=json' Then the command should succeed And the JSON field "status" in STDOUT should be "tool_error" - And the JSON field "detail" in STDOUT should contain "can't resolve where htdocs/index.php loads WordPress from" + And the JSON field "detail" in STDOUT should contain "htdocs/index.php isn't WordPress's own index.php" + # PHP beside WordPress that the scan of htdocs/wp wouldn't read gives no verdict either. + When I run 'printf " {SITES_DIR}/bh-site-command-192.test/app/htdocs/index.php && printf " {SITES_DIR}/bh-site-command-192.test/app/htdocs/tool.php' + And I run 'bin/ee site php-compat bh-site-command-192.test --php=8.4 --format=json' + Then the command should succeed + And the JSON field "status" in STDOUT should be "tool_error" + And the JSON field "detail" in STDOUT should contain "htdocs/tool.php is PHP outside the WordPress directory" Scenario: An html site is refused Given the html site "bh-site-command-182.test" exists diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 2e421cf4..462c233c 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -9,6 +9,8 @@ use function EE\Utils\delem_log; use function EE\Utils\get_flag_value; +require_once __DIR__ . '/Site_PHP_Compat_Layout.php'; + /** * `ee site php-compat`: runs the compat-scanner image against a site's code and prints its verdict or estimate. * @@ -60,7 +62,14 @@ class Site_PHP_Compat { // Size cap for PHP files read on the host (wp-config.php and what it includes, index.php): tokens take ~500x the bytes. const PHP_SOURCE_MAX = 262144; // Constants that move the code WordPress loads away from /wp-content. - const DIR_CONSTANTS = [ 'WP_CONTENT_DIR', 'WP_PLUGIN_DIR', 'WPMU_PLUGIN_DIR' ]; + /** Longest php-compat lists the site's files for (PHP outside WordPress, links, .user.ini files). */ + const WALK_SECONDS = 120; + + /** EE's own config/nginx/custom/admin-tools.conf (site-type-wp templates/config/nginx/admin-tools.conf.mustache). */ + const ADMIN_TOOLS_CONF = "# ee-admin pages\nlocation ^~ /ee-admin/ {\n\troot /var/www/htdocs ;\n\tlocation ~ \\.php$ {\n\t\ttry_files \$uri =404;\n\t\tinclude fastcgi_params;\n\t\tfastcgi_pass php;\n\t}\n}\n"; + + /** WordPress's own files beside wp-admin/ and wp-includes/, which the scanner never reads (compat-scanner CORE_FILES). */ + const CORE_FILES = [ 'index.php', 'wp-activate.php', 'wp-blog-header.php', 'wp-comments-post.php', 'wp-config-sample.php', 'wp-cron.php', 'wp-links-opml.php', 'wp-load.php', 'wp-login.php', 'wp-mail.php', 'wp-settings.php', 'wp-signup.php', 'wp-trackback.php', 'xmlrpc.php' ]; /** @var string Site name. */ protected $site = ''; @@ -880,7 +889,8 @@ protected function code_dir( $site_fs_path ) { } /** - * Picks the scanner's path argument from the root nginx serves, and refuses a WordPress layout the scanner can't check. + * Picks the scanner's path argument from the root nginx serves, and gives no verdict unless this check recognises the + * whole layout (INTERFACE.md, "Allowlist (v4.16.0 r3)" and its revision): anything else is tool_error with the reason. * * @param object $site_data Site record. * @param string $code Real path of the site's app/. @@ -889,94 +899,309 @@ protected function code_dir( $site_fs_path ) { */ protected function resolve_layout( $site_data, $code ) { $this->nginx_conf = $site_data->site_fs_path . self::NGINX_CONF; + $this->wp_layout = false; $served = $this->served_root( $site_data ); - if ( null === $served ) { - return $this->doc( 'tool_error', "can't tell which directory nginx serves: {$this->nginx_conf} has no single plain root" ); + if ( '!' === $served[0] ) { + return $this->doc( 'tool_error', substr( $served, 1 ) ); } $rel = ltrim( substr( $served, strlen( '/var/www' ) ), '/' ); $app = $site_data->site_fs_path . '/app/'; $this->scan_path = $served; - $prepend = $this->prepended( $site_data, $code, $rel ); - if ( null !== $prepend ) { - return $this->doc( 'tool_error', $prepend ); + $detail = $this->server_config_check( $site_data ); + if ( null !== $detail ) { + return $this->doc( 'tool_error', $detail ); } if ( 'wp' !== $site_data->site_type ) { // The scanner checks all of htdocs for php sites, whatever the root nginx serves. $this->looked_in = $app . 'htdocs'; - return null; + $htdocs = self::resolve_in( $code, 'htdocs' ); + $user_ini = []; + $error = null === $htdocs ? null : $this->walk_tree( + $htdocs, + function ( $path, $name, $type ) use ( &$user_ini ) { + if ( '.user.ini' === $name ) { + $user_ini[] = [ $path, $type ]; + } + return 'dir' === $type; + } + ); + $detail = null !== $error ? "can't look through {$app}htdocs for .user.ini files: $error" : $this->prepend_check( $site_data, $code, $user_ini, null ); + return null === $detail ? null : $this->doc( 'tool_error', $detail ); } $this->wp_layout = true; - $root = $this->wp_root( $code, $rel ); - if ( is_string( $root ) && 0 === strpos( $root, '!' ) ) { - return $this->doc( 'tool_error', substr( $root, 1 ) ); - } - if ( null === $root ) { - // No WordPress found here; a wp-config that moves its code elsewhere still rules out no_code_found. - $root = $rel; + $layout = $this->wp_layout_of( $code, $rel, $app ); + if ( is_string( $layout ) ) { + return $this->doc( 'tool_error', $layout ); } + $root = $layout['root']; $this->scan_path = '/var/www/' . $root; $this->looked_in = $app . $root; EE::debug( "php-compat: WordPress root $root (nginx root $served)" ); - // WordPress in a subdirectory of what nginx serves: the scan covers that subdirectory only. - if ( 0 === strpos( $root, "$rel/" ) ) { - $outside = $this->php_outside( $code, $rel, $root ); - if ( null !== $outside ) { - return $this->doc( 'tool_error', "nginx serves $app$rel, which holds PHP outside the WordPress directory $app$root (" . self::clean( $outside ) . "); this check can't scan that layout yet" ); - } - // The served index.php isn't scanned there: it may only load WordPress. - $index = $this->read_site_file( $code, "$rel/index.php", self::PHP_SOURCE_MAX ); - if ( null !== $index && ! self::only_loads_wordpress( $index ) ) { - return $this->doc( 'tool_error', "$app$rel/index.php does more than load WordPress, and it is outside the scanned directory $app$root; this check can't scan that layout yet" ); + $allowed = []; + $index = self::resolve_in( $code, "$rel/index.php" ); + if ( null !== $index ) { + $allowed[] = $index; + } + if ( null !== $layout['abspath'] ) { + $config = $this->check_wp_config( $code, $root, $layout['abspath'], $app ); + if ( is_string( $config ) ) { + return $this->doc( 'tool_error', $config ); } + $allowed = array_merge( $allowed, $config ); + } + $walk = $this->app_walk( $code, $rel, $root, $layout['abspath'], $allowed ); + if ( is_string( $walk ) ) { + return $this->doc( 'tool_error', str_replace( "$code/", $app, $walk ) ); } + $detail = $this->prepend_check( $site_data, $code, $walk, $layout ); - $detail = $this->check_wp_dirs( $code, $root, $app, $rel ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); } /** - * The first PHP entry in the served root outside the WordPress directory, besides index.php and wp-config.php. + * Where WordPress is, in one of the accepted shapes: at the served root or below it, loaded by WordPress's own index.php; + * or, with no served index.php, at its current/ or wp-cli.yml's path: (as backup finds it). The WordPress root's own + * index.php must be WordPress's too. * * @param string $code Real path of the site's app/. * @param string $rel Served root relative to app/. - * @param string $root WordPress root relative to app/, below $rel. + * @param string $app The site's app/ with a trailing slash, for messages. * - * @return string|null Its path relative to the served root; a link or an over-large tree counts too. + * @return array|string [ root (relative to app/, as served), abspath (real WordPress root, or null when there is none) ], + * or a tool_error detail. */ - protected function php_outside( $code, $rel, $root ) { - $dir = self::resolve_in( $code, $rel ); - $wp = self::resolve_in( $code, $root ); - $skip = [ 'index.php', 'wp-config.php', explode( '/', substr( $root, strlen( $rel ) + 1 ) )[0] ]; - $seen = 0; - foreach ( null === $dir || null === $wp ? [] : array_diff( (array) @scandir( $dir ), [ '.', '..', false ] ) as $entry ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable lists nothing. - if ( in_array( $entry, $skip, true ) ) { - continue; + protected function wp_layout_of( $code, $rel, $app ) { + $index = $this->site_file( $code, "$rel/index.php", self::PHP_SOURCE_MAX ); + if ( 'bad' === $index['state'] ) { + return "can't read $app$rel/index.php: it {$index['detail']}"; + } + $root = null; + if ( 'ok' === $index['state'] ) { + // __DIR__ is the real directory: a linked index.php elsewhere would load another WordPress. + if ( dirname( $index['real'] ) !== self::resolve_in( $code, $rel ) ) { + return "$app$rel/index.php is a link to " . self::clean( str_replace( "$code/", $app, $index['real'] ) ) . ', so it loads WordPress from another directory than nginx serves'; } - $path = "$dir/$entry"; - if ( is_link( $path ) || ( is_file( $path ) && self::php_name( $entry ) ) ) { - return $entry; + $loader = Site_PHP_Compat_Layout::index_loader( $index['source'] ); + if ( is_string( $loader ) ) { + return "$app$rel/index.php isn't WordPress's own index.php (" . self::clean( $loader ) . '); this check only gives a verdict when the served index.php just loads WordPress'; } - if ( ! is_dir( $path ) ) { - continue; + $root = '' === $loader['sub'] ? $rel : "$rel/{$loader['sub']}"; + if ( null === $this->wp_abspath( $code, $root ) ) { + return "$app$rel/index.php loads WordPress from $app$root, which holds no WordPress"; + } + } elseif ( null !== $this->wp_abspath( $code, $rel ) ) { + return "$app$rel holds WordPress but no index.php"; + } else { + $candidates = array_slice( \EE\Site\Utils\get_wp_root_candidates( $rel ), 1 ); + foreach ( array_unique( [ $rel, 'htdocs' ] ) as $dir ) { + $path = $this->wp_cli_path( $code, $dir ); + if ( null !== $path && 0 === strpos( $path, "$rel/" ) ) { + $candidates[] = $path; + } + } + foreach ( array_unique( $candidates ) as $candidate ) { + if ( null !== $this->wp_abspath( $code, $candidate ) ) { + $root = $candidate; + break; + } + } + if ( null === $root ) { + // No WordPress: fine when there is no PHP at all (the scanner then finds nothing to check). + return [ 'root' => $rel, 'abspath' => null ]; + } + } + $abspath = $this->wp_abspath( $code, $root ); + // The resolved WordPress root must be inside the resolved served root. + $top = self::resolve_in( $code, $rel ); + if ( null === $top || 0 !== strpos( $abspath . '/', $top . '/' ) ) { + return "WordPress in $app$root resolves to " . self::clean( str_replace( "$code/", $app, $abspath ) ) . ", outside the directory nginx serves ($app$rel)"; + } + if ( $root !== $rel ) { + $own = $this->site_file( $code, "$root/index.php", self::PHP_SOURCE_MAX ); + $own = 'ok' === $own['state'] ? Site_PHP_Compat_Layout::index_loader( $own['source'] ) : 'it ' . ( 'bad' === $own['state'] ? $own['detail'] : 'is missing' ); + if ( is_string( $own ) || '' !== $own['sub'] ) { + return "$app$root/index.php isn't WordPress's own index.php (" . self::clean( is_string( $own ) ? $own : 'it loads WordPress from elsewhere' ) . ')'; + } + } + + return [ 'root' => $root, 'abspath' => $abspath ]; + } + + /** + * @param string $code Real path of the site's app/. + * @param string $root Directory relative to app/. + * + * @return string|null Its real path when it holds WordPress (a regular wp-settings.php). + */ + protected function wp_abspath( $code, $root ) { + $settings = self::resolve_in( $code, "$root/wp-settings.php" ); + + return null !== $settings && is_file( $settings ) && ! is_link( $settings ) ? dirname( $settings ) : null; + } + + /** + * Reads the wp-config.php WordPress loads, and the files it loads, against the config grammar. + * + * @param string $code Real path of the site's app/. + * @param string $root WordPress root relative to app/. + * @param string $abspath Real WordPress root. + * @param string $app The site's app/ with a trailing slash, for messages. + * + * @return string[]|string Real paths of the config files read, or a tool_error detail. + */ + protected function check_wp_config( $code, $root, $abspath, $app ) { + $config = $this->wp_config_files( $code, $root, $abspath ); + if ( ! $config ) { + return []; + } + $file = $this->site_file( $code, $config[0], self::PHP_SOURCE_MAX ); + if ( 'ok' !== $file['state'] ) { + return "can't read $app{$config[0]}: " . ( 'bad' === $file['state'] ? $file['detail'] : 'it is gone' ); + } + $read = [ $file['real'] ]; + $resolve = function ( $path ) use ( $code, $abspath, &$read ) { + if ( 0 !== strpos( $path, "$code/" ) ) { + return [ 'state' => 'bad', 'detail' => 'is outside the site\'s files' ]; + } + $found = $this->site_file( $code, substr( $path, strlen( $code ) + 1 ), self::PHP_SOURCE_MAX ); + if ( 'ok' === $found['state'] ) { + $read[] = $found['real']; + $found['scanned'] = self::scanned_by_wp_scan( $found['real'], $abspath ); + } + return $found; + }; + $error = Site_PHP_Compat_Layout::check_config( + $file['source'], + [ + 'root' => $abspath, + 'dir' => dirname( $file['real'] ), + 'file' => $file['real'], + 'boot' => true, + 'resolve' => $resolve, + ] + ); + if ( null !== $error ) { + // Messages name the site's app/ path, not the volume's. + return self::clean( str_replace( "$code/", $app, $error ) ); + } + + return $read; + } + + /** + * Walks all of app/ (no links followed, time-bounded) for what the scan of the WordPress root would miss: any code file + * or link outside it (besides the served index.php, the config files read, its own `current` link, dot-directories and + * old releases nginx doesn't serve), and inside it a link to one of its own ancestors or a nested WordPress install. + * + * @param string $code Real path of the site's app/. + * @param string $rel Served root relative to app/. + * @param string $root WordPress root relative to app/ (as served). + * @param string|null $abspath Real WordPress root, or null when there is none. + * @param string[] $allowed Real paths of PHP files already checked. + * + * @return array|string The .user.ini files found ([ path, type ] each), or a tool_error detail (host paths). + */ + protected function app_walk( $code, $rel, $root, $abspath, array $allowed ) { + $top = (string) self::resolve_in( $code, $rel ); + // The live release: the WordPress root or its ancestor directly in a releases/ directory. + $releases = null; + for ( $dir = $abspath; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { + if ( 'releases' === basename( dirname( $dir ) ) ) { + $releases = dirname( $dir ); + break; } - try { - // The WordPress directory itself (e.g. releases/ behind current/) is what the scan covers. - $tree = new \RecursiveCallbackFilterIterator( - new \RecursiveDirectoryIterator( $path, \FilesystemIterator::SKIP_DOTS ), - function ( $item ) use ( $wp ) { - return $item->getPathname() !== $wp; + } + $user_ini = []; + $found = null; + $error = $this->walk_tree( + $code, + function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $releases, &$user_ini, &$found ) { + $inside = null !== $abspath && 0 === strpos( $path . '/', $abspath . '/' ); + if ( '.user.ini' === $name ) { + $user_ini[] = [ $path, $type ]; + } + if ( 'link' === $type ) { + // The served root or the WordPress root may be a link (current -> releases/). + if ( 0 === strpos( "$code/$root/", $path . '/' ) ) { + return false; + } + $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); + if ( $inside ) { + if ( null !== $real && 0 === strpos( dirname( $path ) . '/', $real . '/' ) ) { + $found = "$path links to its own ancestor " . $real; + return true; + } + return false; + } + $found = "$path is a link outside the WordPress directory"; + return true; + } + if ( 'dir' === $type ) { + if ( $inside ) { + if ( $path !== $abspath && ( file_exists( "$path/wp-settings.php" ) || is_dir( "$path/wp-includes" ) ) ) { + $found = "$path holds another WordPress install"; + return true; + } + return true; } - ); - foreach ( new \RecursiveIteratorIterator( $tree ) as $item ) { - if ( ++$seen > 20000 || $item->isLink() || ( $item->isFile() && self::php_name( $item->getFilename() ) ) ) { - return $entry . '/' . substr( $item->getPathname(), strlen( $path ) + 1 ); + if ( '.' === $name[0] ) { + return false; } + // Old releases beside the live one, when nginx doesn't serve them. + return ! ( null !== $releases && dirname( $path ) === $releases && 0 !== strpos( $path . '/', $top . '/' ) ); + } + if ( ! $inside && self::php_name( $name ) && ! in_array( $path, $allowed, true ) ) { + $found = "$path is PHP outside the WordPress directory" . ( null === $abspath ? ' (there is no WordPress this check recognises)' : '' ); + return true; + } + return false; + } + ); + if ( null !== $error ) { + return "can't look through the site's files: $error"; + } + + return null === $found ? $user_ini : self::clean( $found ) . '; this check can\'t scan that layout'; + } + + /** + * Walks a directory tree without following links, bounded in time: $visit( $path, $name, file|dir|link|other ) returns + * true to stop, and for a directory whether to go into it. + * + * @param string $top Real directory. + * @param callable $visit See above. + * + * @return string|null Why the walk could not finish, or null. + */ + protected function walk_tree( $top, callable $visit ) { + $todo = [ $top ]; + $deadline = microtime( true ) + self::WALK_SECONDS; + while ( $todo ) { + $dir = array_pop( $todo ); + if ( microtime( true ) > $deadline ) { + return 'it takes more than ' . self::WALK_SECONDS . ' s to list'; + } + $entries = @scandir( $dir ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $entries ) { + return self::clean( $dir ) . ' can\'t be listed'; + } + foreach ( $entries as $name ) { + if ( '.' === $name || '..' === $name ) { + continue; + } + $path = "$dir/$name"; + $stat = @lstat( $path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + $mode = false === $stat ? 0 : $stat['mode'] & 0170000; + $type = 0120000 === $mode ? 'link' : ( 0040000 === $mode ? 'dir' : ( 0100000 === $mode ? 'file' : 'other' ) ); + $go = $visit( $path, $name, $type ); + if ( 'dir' === $type && $go ) { + $todo[] = $path; + } elseif ( 'dir' !== $type && true === $go ) { + return null; } - } catch ( \Exception $e ) { - return $entry; } } @@ -986,32 +1211,194 @@ function ( $item ) use ( $wp ) { /** * @param string $name File name. * - * @return bool Whether PHP code may be in it (the extensions the scanner checks). + * @return bool Whether the scanner reads it as PHP code (its CODE_EXTENSIONS, any case). */ protected static function php_name( $name ) { - return 1 === preg_match( '/\.(php[0-9]?|phtml|inc|module|install|theme)$/i', $name ); + return 1 === preg_match( '/\.(?:php|inc|phtml|module|install|theme|engine|php5|php7)$/iD', $name ); } /** - * A file PHP runs before every request (auto_prepend_file in the served root's .user.ini or the site's php.ini files), - * which can set what WordPress loads before wp-config.php does. + * The PHP settings that load or change code outside the scan, wherever the site's PHP takes them from: the .user.ini + * files found, the site's php.ini, conf.d/*.ini, php-fpm.conf and pool files. Every assignment counts. + * + * @param object $site_data Site record. + * @param string $code Real path of the site's app/. + * @param array $user_ini .user.ini files found ([ path, type ] each). + * @param array|null $layout wp_layout_of() result, or null for a php site. + * + * @return string|null tool_error detail. + */ + protected function prepend_check( $site_data, $code, array $user_ini, $layout ) { + $conf = $site_data->site_fs_path . '/config/php'; + $files = []; + foreach ( array_merge( [ "$conf/php/php.ini" ], (array) glob( "$conf/php/conf.d/*.ini" ) ) as $file ) { + $files[ $file ] = 'ini'; + } + foreach ( array_merge( [ "$conf/php-fpm.conf" ], (array) glob( "$conf/php-fpm.d/*.conf" ) ) as $file ) { + $files[ $file ] = 'fpm'; + } + foreach ( $user_ini as list( $path, $type ) ) { + $files[ $path ] = 'file' === $type ? 'ini' : 'bad'; + } + $app = $site_data->site_fs_path . '/app/'; + foreach ( $files as $file => $kind ) { + if ( ! file_exists( $file ) && ! is_link( $file ) ) { + continue; + } + $shown = self::clean( str_replace( "$code/", $app, $file ) ); + $text = 'bad' === $kind || ! is_file( $file ) || filesize( $file ) > self::CONFIG_MAX ? false : @file_get_contents( $file ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $text ) { + return "can't read $shown, which may set a file PHP runs before WordPress"; + } + foreach ( self::php_settings( $text, $kind ) as list( $key, $value ) ) { + if ( ! $this->php_setting_ok( $code, $key, $value, $layout ) ) { + return "$shown sets $key to " . self::clean( '' === $value ? '""' : $value ) . ', which this check can\'t confirm'; + } + } + } + + return null; + } + + /** + * Every assignment of the settings that load or change code (auto_prepend_file, auto_append_file, opcache.preload, + * include_path, user_ini.filename, zend.multibyte, zend.script_encoding) and FPM's include= and + * security.limit_extensions, in file order. + * + * @param string $text Its text. + * @param string $kind ini or fpm. + * + * @return array[] [ key, value (unquoted) ] each. + */ + public static function php_settings( $text, $kind ) { + $keys = '(auto_prepend_file|auto_append_file|opcache\.preload|include_path|user_ini\.filename|zend\.multibyte|zend\.script_encoding)'; + $pattern = 'fpm' === $kind + ? '/^[ \t]*(?:php(?:_admin)?_(?:value|flag)\[' . $keys . '\]|(include|security\.limit_extensions))[ \t]*=[ \t]*([^\r\n]*)$/mi' + : '/^[ \t]*' . $keys . '()[ \t]*=[ \t]*([^\r\n]*)$/mi'; + $out = []; + preg_match_all( $pattern, $text, $all, PREG_SET_ORDER ); + foreach ( $all as $m ) { + $value = trim( $m[3] ); + if ( preg_match( '/^"([^"]*)"|^\'([^\']*)\'/', $value, $q ) ) { + $value = isset( $q[2] ) ? $q[2] : $q[1]; + } else { + $value = trim( preg_replace( '/[ \t]*;.*$/', '', $value ) ); + } + $out[] = [ strtolower( '' !== $m[1] ? $m[1] : $m[2] ), $value ]; + } + + return $out; + } + + /** + * @param string $code Real path of the site's app/. + * @param string $key Setting. + * @param string $value Its value. + * @param array|null $layout wp_layout_of() result, or null for a php site. + * + * @return bool + */ + protected function php_setting_ok( $code, $key, $value, $layout ) { + $off = in_array( strtolower( $value ), [ '', 'none', 'off', 'no', 'false', 'null', '0' ], true ); + switch ( $key ) { + case 'include': + return 'etc/php-fpm.d/*.conf' === $value; + case 'security.limit_extensions': + return '.php' === $value; + case 'user_ini.filename': + return '' === $value || '.user.ini' === $value; + case 'zend.multibyte': + return $off; + case 'auto_prepend_file': + break; + default: + return $off; + } + if ( $off ) { + return true; + } + $path = Site_PHP_Compat_Layout::normalise( $value ); + if ( '/' !== $value[0] || null === $path || 0 !== strpos( $path, '/var/www/' ) ) { + return false; + } + $file = $this->site_file( $code, substr( $path, strlen( '/var/www/' ) ), self::PHP_SOURCE_MAX ); + if ( 'ok' !== $file['state'] ) { + return false; + } + if ( null === $layout ) { + $htdocs = self::resolve_in( $code, 'htdocs' ); + return null !== $htdocs && 0 === strpos( $file['real'], "$htdocs/" ) && self::php_name( $file['real'] ); + } + + // Any loader the scan reads (Wordfence's wordfence-waf.php, NinjaFirewall's, …). + return self::scanned_by_wp_scan( $file['real'], $layout['abspath'] ); + } + + /** + * nginx and PHP-FPM settings that could run other code than the scan reads: nginx's own files (config/nginx/, conf.d/, + * custom/), and php-fpm.conf's and the pools' include= (in prepend_check()). * * @param object $site_data Site record. - * @param string $code Real path of the site's app/. - * @param string $rel Served root relative to app/. * * @return string|null tool_error detail. */ - protected function prepended( $site_data, $code, $rel ) { - $files = [ "$rel/.user.ini" => $this->read_site_file( $code, "$rel/.user.ini" ) ]; - foreach ( (array) glob( $site_data->site_fs_path . '/config/php/php/conf.d/*.ini' ) as $ini ) { - $files[ $ini ] = is_file( $ini ) && filesize( $ini ) <= self::CONFIG_MAX ? (string) @file_get_contents( $ini ) : ''; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable counts as empty. + protected function server_config_check( $site_data ) { + $dir = $site_data->site_fs_path . '/config/nginx'; + $files = array_merge( (array) glob( "$dir/*" ), (array) glob( "$dir/conf.d/*.conf" ), (array) glob( "$dir/custom/*.conf" ) ); + foreach ( $files as $file ) { + if ( is_dir( $file ) && ! is_link( $file ) || preg_match( '/\.(?:default|types)$|^(?:koi-|win-|uwsgi_params|scgi_params)/', basename( $file ) ) && 'fastcgi_params' !== basename( $file ) ) { + continue; + } + $text = is_file( $file ) && filesize( $file ) <= self::CONFIG_MAX ? @file_get_contents( $file ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $text ) { + return "can't read $file, which may change what nginx runs"; + } + $custom = 'custom' === basename( dirname( $file ) ); + if ( $custom && 'admin-tools.conf' === basename( $file ) && self::ADMIN_TOOLS_CONF === str_replace( "\r\n", "\n", $text ) ) { + continue; + } + $why = self::nginx_refusal( $text, $file === $dir . '/conf.d/main.conf', $custom ); + if ( null !== $why ) { + return "$file $why, which this check can't confirm"; + } } - foreach ( $files as $file => $text ) { - if ( null !== $text && preg_match( '/^[ \t]*auto_prepend_file[ \t]*=[ \t]*([^;\r\n]*)/mi', $text, $m ) && ! in_array( strtolower( trim( $m[1], " \t\"'" ) ), [ '', 'none' ], true ) ) { - return "$file sets auto_prepend_file, which runs before WordPress; this check can't tell what it changes"; + + return null; + } + + /** + * What in an nginx file could make it run other code than the scan reads. + * + * @param string $text File text. + * @param bool $main Whether it is conf.d/main.conf (its single root is read by served_root()). + * @param bool $custom Whether it is in custom/. + * + * @return string|null + */ + public static function nginx_refusal( $text, $main, $custom ) { + $text = preg_replace( '/#[^\r\n]*/', '', $text ); + if ( preg_match( '/\bPHP_(?:ADMIN_)?VALUE\b/i', $text ) ) { + return 'sets PHP_VALUE'; + } + preg_match_all( '/(?:^|[;{}])\s*fastcgi_param\s+(SCRIPT_FILENAME|DOCUMENT_ROOT)\s+([^;]*);/i', $text, $all, PREG_SET_ORDER ); + foreach ( $all as $m ) { + $value = trim( $m[2] ); + if ( ! in_array( $value, 'DOCUMENT_ROOT' === strtoupper( $m[1] ) ? [ '$document_root' ] : [ '$request_filename', '$document_root$fastcgi_script_name' ], true ) ) { + return "sets {$m[1]} to $value"; } } + preg_match_all( '/(?:^|[;{}])\s*include\s+([^;\s]+)\s*;/', $text, $all, PREG_SET_ORDER ); + foreach ( $all as $m ) { + if ( ! in_array( $m[1], [ 'mime.types', 'fastcgi_params', 'fastcgi.conf', '/usr/local/openresty/nginx/conf/conf.d/main.conf', '/usr/local/openresty/nginx/conf/custom/*.conf' ], true ) ) { + return "includes {$m[1]}"; + } + } + if ( ! $main && preg_match( '/(?:^|[;{}])\s*(root|alias)\s/', $text, $m ) ) { + return "sets $m[1]"; + } + if ( $custom && preg_match( '/(?:^|[;{}])\s*fastcgi_pass\s/', $text ) ) { + return 'passes requests to PHP'; + } return null; } @@ -1040,18 +1427,29 @@ protected function extra_mounts( $site_data, $code ) { return "could not read $file; enable the site to check mounted code"; } if ( $mounts ) { - return "$file mounts code below /var/www, which this check can only see while the site runs; enable the site and run it again"; + return "$file may mount code or change how PHP starts, which this check can only see while the site runs; enable the site and run it again"; } } return []; } - $inspect = $this->docker( [ 'docker', 'inspect', '--format', '{{json .Mounts}}', $ids[0] ], 60 ); - $mounts = 0 === $inspect['code'] ? json_decode( trim( $inspect['stdout'] ), true ) : null; - if ( ! is_array( $mounts ) ) { + $inspect = $this->docker( [ 'docker', 'inspect', '--format', '{{json .}}', $ids[0] ], 60 ); + $info = 0 === $inspect['code'] ? json_decode( trim( $inspect['stdout'] ), true ) : null; + $mounts = isset( $info['Mounts'] ) && is_array( $info['Mounts'] ) ? $info['Mounts'] : null; + if ( null === $mounts ) { return 'could not read the mounts of the site\'s php container'; } + $detail = $this->container_config_check( $info ); + if ( null !== $detail ) { + return $detail; + } $admin = realpath( EE_ROOT_DIR . '/admin-tools' ); + // EE's own mounts outside /var/www: PHP's config, its logs and admin-tools' data. + $known = [ + '/usr/local/etc' => realpath( $site_data->site_fs_path . '/config/php' ), + '/var/log/php' => realpath( $site_data->site_fs_path . '/logs/php' ), + '/etc/easyengine/admin-tools' => realpath( $site_data->site_fs_path . '/config/admin-tools' ), + ]; foreach ( $mounts as $mount ) { $dst = isset( $mount['Destination'] ) ? rtrim( (string) $mount['Destination'], '/' ) : ''; $src = isset( $mount['Source'] ) ? (string) $mount['Source'] : ''; @@ -1062,9 +1460,15 @@ protected function extra_mounts( $site_data, $code ) { } continue; } - if ( 0 !== strpos( $dst, '/var/www/' ) ) { + if ( isset( $known[ $dst ] ) ) { + if ( false === $known[ $dst ] || realpath( $src ) !== $known[ $dst ] ) { + return 'the site\'s php container gets ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', not from EE\'s own directory for it'; + } continue; } + if ( 0 !== strpos( $dst, '/var/www/' ) ) { + return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', code this check doesn\'t scan'; + } // EE's own admin tools (ee site admin-tools): not the site's code. if ( '/var/www/htdocs/ee-admin' === $dst && false !== $admin && realpath( $src ) === $admin ) { continue; @@ -1074,7 +1478,7 @@ protected function extra_mounts( $site_data, $code ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', which this check can\'t mount'; } // The WordPress root and its config are read on the host before the scan: only a mount inside wp-content leaves them as read. - if ( $this->wp_layout && ! preg_match( '#/wp-content(/|$)#', $dst ) ) { + if ( $this->wp_layout && 0 !== strpos( $dst . '/', $this->scan_path . '/wp-content/' ) ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' over the WordPress files, which this check reads before it scans'; } EE::debug( "php-compat: also mounting $src at $dst" ); @@ -1084,6 +1488,41 @@ protected function extra_mounts( $site_data, $code ) { return $this->extra_mounts; } + /** + * The php container must run as EE starts it: the image's command and entrypoint, and the image's environment plus + * only EE's own variables (so no PHPRC or PHP_INI_SCAN_DIR loads other PHP settings). + * + * @param array $info docker inspect of the container. + * + * @return string|null tool_error detail. + */ + protected function container_config_check( array $info ) { + $image = isset( $info['Image'] ) ? (string) $info['Image'] : ''; + $run = '' === $image ? null : $this->docker( [ 'docker', 'image', 'inspect', '--format', '{{json .Config}}', $image ], 60 ); + $own = null !== $run && 0 === $run['code'] ? json_decode( trim( $run['stdout'] ), true ) : null; + if ( ! is_array( $own ) || ! isset( $info['Config'] ) || ! is_array( $info['Config'] ) ) { + return 'could not read how the site\'s php container is configured'; + } + $config = $info['Config']; + foreach ( [ 'Cmd', 'Entrypoint' ] as $key ) { + if ( ( isset( $config[ $key ] ) ? $config[ $key ] : null ) !== ( isset( $own[ $key ] ) ? $own[ $key ] : null ) ) { + return "the site's php container runs another " . strtolower( $key ) . ' than its image, which this check can\'t confirm'; + } + } + $image_env = []; + foreach ( isset( $own['Env'] ) ? (array) $own['Env'] : [] as $pair ) { + $image_env[ strtok( $pair, '=' ) ] = $pair; + } + foreach ( isset( $config['Env'] ) ? (array) $config['Env'] : [] as $pair ) { + $name = (string) strtok( $pair, '=' ); + if ( isset( $image_env[ $name ] ) ? $image_env[ $name ] !== $pair : ! preg_match( '/^(?:WORDPRESS_DB_[A-Z_]+|DB_[A-Z_]+|MYSQL_[A-Z_]+|REDIS_HOST|USER_ID|GROUP_ID|VIRTUAL_HOST|NEWRELIC_[A-Z_]+)$/D', $name ) ) { + return 'the site\'s php container sets ' . self::clean( $name ) . ', which this check can\'t confirm'; + } + } + + return null; + } + /** * Whether a compose file may mount anything below /var/www, read without a YAML parser (the release phar has none). * Only lines that can't name such a mount are passed over: short volume entries (`- src:dst[:mode]`) and `target:` @@ -1104,10 +1543,11 @@ protected static function compose_mounts_code( $file ) { if ( '' === $line || '#' === $line[0] ) { continue; } - if ( false !== strpos( $line, '$' ) ) { + // Interpolation, and keys that pull mounts in from elsewhere. + if ( false !== strpos( $line, '$' ) || preg_match( '/^-?\s*(?:extends|include|volumes_from|command|entrypoint)\s*:|PHPRC|PHP_INI_SCAN_DIR/', $line ) ) { return true; } - if ( false === strpos( $line, '/var/www' ) || preg_match( '/^-?\s*source:\s/', $line ) ) { + if ( false === stripos( $line, 'www' ) || preg_match( '/^-?\s*source:\s/', $line ) ) { continue; } $target = null; @@ -1119,7 +1559,8 @@ protected static function compose_mounts_code( $file ) { // An environment entry (`- NAME=value`), not a volume. continue; } - if ( null === $target || 0 === strpos( rtrim( $target, '/' ) . '/', '/var/www/' ) ) { + // A destination spelt another way (`//`, `/./`, `/../`, a backslash) may still be below /var/www. + if ( null === $target || preg_match( '#//|/\.\.?(/|$)|\\\\#', $target ) || 0 === strpos( rtrim( $target, '/' ) . '/', '/var/www/' ) ) { return true; } } @@ -1128,26 +1569,30 @@ protected static function compose_mounts_code( $file ) { } /** - * The root nginx serves (main.conf), or the public directory in EE's record when main.conf can't be read. + * The root nginx serves (main.conf), or the public directory in EE's record when there is no main.conf. * * @param object $site_data Site record. * - * @return string|null Path under /var/www/htdocs; null when main.conf is there but has no single plain root. + * @return string Path under /var/www/htdocs, or `!`. */ protected function served_root( $site_data ) { // `--public-dir=a//b` is stored as given; the scanner refuses `//`. $db = rtrim( preg_replace( '#/+#', '/', (string) $site_data->site_container_fs_path ), '/' ); $db = '' === $db ? '/var/www/htdocs' : $db; $conf = $this->nginx_conf; + if ( ! file_exists( $conf ) && ! is_link( $conf ) ) { + EE::debug( "php-compat: there is no $conf; using the public directory $db" ); + return $db; + } $text = is_file( $conf ) && filesize( $conf ) <= self::CONFIG_MAX ? @file_get_contents( $conf ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. if ( false === $text ) { - EE::debug( "php-compat: $conf can't be read; using the public directory $db" ); - return $db; + return "!can't read $conf, so can't tell which directory nginx serves"; } - // Exactly one root, as EE writes it; anything else is a config this check doesn't guess at. - $root = 1 === preg_match_all( '/^\s*root\s+([^\s;]+)\s*;/m', $text, $m ) ? rtrim( preg_replace( '#/+#', '/', $m[1][0] ), '/' ) : null; - if ( null === $root || ! preg_match( self::ROOT_PATTERN, $root ) ) { - return null; + $text = preg_replace( '/#[^\r\n]*/', '', $text ); + // Exactly one root, as EE writes it, and no alias; anything else is a config this check doesn't guess at. + $root = 1 === preg_match_all( '/(?:^|[;{}])\s*root\s+([^\s;{}]+)\s*;/', $text, $m ) ? rtrim( preg_replace( '#/+#', '/', $m[1][0] ), '/' ) : null; + if ( null === $root || ! preg_match( self::ROOT_PATTERN, $root ) || preg_match( '/(?:^|[;{}])\s*alias\s/', $text ) ) { + return "!can't tell which directory nginx serves: $conf has no single plain root"; } if ( $root !== $db ) { EE::warning( sprintf( "EE's record of %s has %s as its public directory, but nginx serves %s (root in %s). Checking what nginx serves.", $this->site, $db, $root, $conf ) ); @@ -1156,130 +1601,6 @@ protected function served_root( $site_data ) { return $root; } - /** - * WordPress root relative to app/: where the served index.php loads WordPress from, the served root or its current/ (as - * backup finds it), else wp-cli.yml's path. - * - * @param string $code Real path of the site's app/. - * @param string $rel Served root relative to app/. - * - * @return string|null The root, null when none is found, or `!` when the served index.php loads WordPress from - * somewhere this check can't follow. - */ - protected function wp_root( $code, $rel ) { - $loader = $this->index_wp_root( $code, $rel ); - $candidates = \EE\Site\Utils\get_wp_root_candidates( $rel ); - if ( false === $loader ) { - return "!can't resolve where {$rel}/index.php loads WordPress from"; - } - if ( null !== $loader ) { - // What is actually served is the only candidate: a stale copy elsewhere must not stand in for it. - $candidates = [ $loader ]; - } else { - foreach ( array_unique( [ $rel, 'htdocs' ] ) as $dir ) { - $path = $this->wp_cli_path( $code, $dir ); - if ( null !== $path ) { - $candidates[] = $path; - } - } - } - $candidates = array_values( array_unique( $candidates ) ); - // In order; a WordPress directory may have no wp-content when WP_CONTENT_DIR moves it (refused later). - foreach ( $candidates as $candidate ) { - foreach ( [ 'wp-content', 'wp-settings.php' ] as $marker ) { - if ( null !== self::resolve_in( $code, $candidate . '/' . $marker ) ) { - return $candidate; - } - } - } - - return null === $loader ? null : "!{$rel}/index.php loads WordPress from {$loader}, which holds no WordPress"; - } - - /** - * The directory the served index.php loads WordPress (wp-blog-header.php or wp-load.php) from, read without running it. - * - * @param string $code Real path of the site's app/. - * @param string $rel Served root relative to app/. - * - * @return string|false|null Relative to app/; null when index.php doesn't load WordPress (or isn't there), false when it - * may but not in a form this check reads, or can't be read. - */ - protected function index_wp_root( $code, $rel ) { - $index = self::resolve_in( $code, "$rel/index.php" ); - if ( null === $index ) { - return null; - } - $source = $this->read_site_file( $code, "$rel/index.php", self::PHP_SOURCE_MAX ); - $loads = null === $source ? false : self::loaded_from( $source, 'wp-blog-header.php' ); - if ( ! is_array( $loads ) ) { - return $loads; - } - list( $path, $from_dir ) = $loads; - if ( '/' === substr( $path, 0, 1 ) && ! $from_dir ) { - if ( 0 !== strpos( $path, '/var/www/' ) ) { - return false; - } - $path = substr( $path, strlen( '/var/www/' ) ); - } else { - // __DIR__, or a relative path, which PHP-FPM resolves from the script's own directory: the real one. The served - // path stands in for it (keeping a current/ link for the scanner) only when it is that same directory and no `..`. - $real = dirname( substr( $index, strlen( $code ) + 1 ) ); - $base = ! preg_match( '#(^|/)\.\.(/|$)#', $path ) && self::resolve_in( $code, $rel ) === dirname( $index ) ? $rel : $real; - $path = $base . '/' . $path; - } - $path = trim( preg_replace( '#/+#', '/', preg_replace( '#(^|/)\.(?=/|$)#', '$1', $path ) ), '/' ); - - return '' === $path ? false : $path; - } - - /** - * Where a PHP file loads WordPress (wp-blog-header.php or wp-load.php) from, read from its tokens: the string in front of - * the name, with `__DIR__ .` or `dirname( __FILE__ ) .` before it or nothing. - * - * @param string $source PHP source. - * @param string $file Kept for callers; wp-blog-header.php and wp-load.php are both looked for. - * - * @return array|false|null [ directory part, whether it is from the file's own directory ]; false when it loads WordPress - * in another form, or includes something this check can't resolve; null when it doesn't. - */ - public static function loaded_from( $source, $file = 'wp-blog-header.php' ) { - $php = self::analyse_php( $source ); - if ( null !== $php['halt_reason'] ) { - return false; - } - $found = null; - foreach ( $php['includes'] as $include ) { - if ( $include['in_func'] ) { - continue; - } - $names = preg_match( '/wp-(blog-header|load)\b/i', $include['expr'] ); - if ( ! $names && $include['static'] ) { - continue; - } - // Loading WordPress, or something this check can't name: only a plain, unconditional statement is read. - if ( null !== $found || ! $names || ! $include['alone'] || $include['overlong'] - || ! preg_match( '/^\(?(?:(__DIR__|dirname\(__FILE__\))\.)?([\'"])([^\'"$\\\\]*?)wp-(?:blog-header|load)\.php\2\)?$/i', $include['expr'], $m ) ) { - return false; - } - // PHP joins `__DIR__ . 'wp/…'` as written: a sibling, not a child. - if ( '' !== $m[1] && '' !== $m[3] && '/' !== $m[3][0] ) { - return false; - } - $found = [ $m[3], '' !== $m[1] ]; - } - - return $found; - } - - /** - * `path:` of /wp-cli.yml, relative to app/. - * - * @param string $code Real path of the site's app/. - * @param string $dir Directory relative to app/. - * - * @return string|null - */ protected function wp_cli_path( $code, $dir ) { $text = $this->read_site_file( $code, $dir . '/wp-cli.yml' ); $text = null === $text ? null : str_replace( [ "\r\n", "\r" ], "\n", $text ); @@ -1301,109 +1622,9 @@ protected function wp_cli_path( $code, $dir ) { } /** - * Refuses a verdict when the config WordPress loads moves its code where the scanner doesn't look: reads wp-config.php, - * the files it includes (as far as they can be named without running anything) and the served index.php. - * - * @param string $code Real path of the site's app/. - * @param string $root WordPress root relative to app/. - * @param string $app The site's app/ path with a trailing slash, for messages. - * @param string $rel Served root relative to app/. - * - * @return string|null tool_error detail, or null when the scan covers what WordPress loads. - */ - protected function check_wp_dirs( $code, $root, $app, $rel ) { - $abspath = self::resolve_in( $code, $root ); - $content = $root . '/wp-content'; - $queue = []; - foreach ( $this->wp_config_files( $code, $root, $abspath ) as $file ) { - $queue[] = [ $file, false, true ]; - } - // The served index.php runs before WordPress too; its own includes are WordPress', not followed here. - $index = self::resolve_in( $code, "$rel/index.php" ); - if ( null !== $index ) { - $queue[] = [ substr( $index, strlen( $code ) + 1 ), false, false ]; - } - $values = []; - $seen = []; - $included = []; - while ( $queue ) { - list( $file, $conditional, $follow ) = array_shift( $queue ); - if ( isset( $seen[ $file ] ) ) { - continue; - } - $seen[ $file ] = true; - if ( count( $seen ) > 50 ) { - return "the config of WordPress includes more files than this check follows (from $app$file)"; - } - $source = $this->read_site_file( $code, $file, self::PHP_SOURCE_MAX ); - if ( null === $source ) { - return "can't read $app$file, so this check can't tell which plugins and themes WordPress loads"; - } - $php = self::analyse_php( $source ); - if ( null !== $php['unresolved'] ) { - return "can't resolve {$php['unresolved']} in $app$file, so this check can't tell which plugins and themes WordPress loads. It follows only define( 'WP_CONTENT_DIR', <__DIR__, dirname( __FILE__ ), dirname( __DIR__ ), ABSPATH or WP_CONTENT_DIR> . '' ) or a /var/www path, before wp-settings.php is loaded"; - } - foreach ( $php['defines'] as $name => $expr ) { - if ( $conditional ) { - return "can't resolve $name in $app$file: that file is loaded only under a condition"; - } - if ( isset( $values[ $name ] ) ) { - return "can't resolve $name in $app$file: it is defined more than once"; - } - $values[ $name ] = [ $expr, $file ]; - } - foreach ( $follow ? $php['includes'] : [] as $include ) { - if ( $include['in_func'] || $include['after_boot'] || $include['boot'] ) { - continue; - } - $target = $include['overlong'] ? null : $this->dir_value( $code, $include['expr'], $file, $abspath, $content, true ); - if ( null === $target ) { - return "can't follow the include `" . self::clean( substr( $include['expr'], 0, 80 ) ) . "` in $app$file, so this check can't tell which plugins and themes WordPress loads"; - } - $real = self::resolve_in( $code, $target ); - if ( null !== $real && is_file( $real ) ) { - // A missing file only warns (include) or stops the site (require): either way it defines nothing. - $queue[] = [ substr( $real, strlen( $code ) + 1 ), $conditional || ! $include['alone'], true ]; - $included[] = $real; - } - } - } - - // What the config includes is code the site runs: only what the scanner reads (its directory, minus what it skips) is covered. - foreach ( array_unique( $included ) as $real ) { - if ( ! self::scanned_by_wp_scan( $real, $abspath ) ) { - $file = substr( $real, strlen( $code ) + 1 ); - return "WordPress's config loads $app$file, which is outside the scanned directory $app$root (or in a part the scan skips); this check can't scan that layout yet"; - } - } - - foreach ( self::DIR_CONSTANTS as $name ) { - if ( ! isset( $values[ $name ] ) ) { - continue; - } - list( $expr, $file ) = $values[ $name ]; - $dir = $this->dir_value( $code, $expr, $file, $abspath, $content ); - if ( null === $dir ) { - return "can't resolve $name in $app$file"; - } - $real = self::resolve_in( $code, $dir ); - if ( null === $real ) { - return "$name in $app$file points to $app$dir, which doesn't exist"; - } - $default = 'WP_CONTENT_DIR' === $name ? $content : $content . ( 'WP_PLUGIN_DIR' === $name ? '/plugins' : '/mu-plugins' ); - if ( self::resolve_in( $code, $default ) === $real ) { - continue; - } - $what = 'WP_CONTENT_DIR' === $name ? 'plugins and themes' : ( 'WP_PLUGIN_DIR' === $name ? 'plugins' : 'must-use plugins' ); - return "WordPress loads $what from $app$dir ($name in $app$file); this check can't scan that layout yet"; - } - - return null; - } - - /** - * Whether a wp scan of the WordPress directory reads this file: inside it, outside core and the directories the scanner - * skips by name (uploads, cache, upgrade, languages, upgrade-temp-backup at a content root's top; node_modules, .git). + * Whether a wp scan of the WordPress directory reads this file as code: inside it, a code extension, outside core and + * the directories the scanner skips (uploads, cache, upgrade, languages, upgrade-temp-backup at a content root's top; + * node_modules, .git anywhere), as compat-scanner's listFiles() does. * * @param string $real Real host path of the file. * @param string|null $abspath Real WordPress root. @@ -1411,494 +1632,105 @@ protected function check_wp_dirs( $code, $root, $app, $rel ) { * @return bool */ protected static function scanned_by_wp_scan( $real, $abspath ) { - if ( null === $abspath || 0 !== strpos( $real, $abspath . '/' ) ) { + if ( null === $abspath || 0 !== strpos( $real, $abspath . '/' ) || ! self::php_name( basename( $real ) ) ) { return false; } $parts = explode( '/', substr( $real, strlen( $abspath ) + 1 ) ); if ( in_array( $parts[0], [ 'wp-admin', 'wp-includes' ], true ) || array_intersect( $parts, [ 'node_modules', '.git' ] ) ) { return false; } - // A content root's top-level skips: wp-content/uploads/…, and the same under any other directory's first level. - return ! ( count( $parts ) > 2 && in_array( $parts[1], [ 'uploads', 'cache', 'upgrade', 'languages', 'upgrade-temp-backup' ], true ) ); - } - - /** - * Whether a served index.php does nothing but load WordPress: literal defines and one require/include of - * wp-blog-header.php or wp-load.php. - * - * @param string $source PHP source. - * - * @return bool - */ - public static function only_loads_wordpress( $source ) { - $code = ''; - foreach ( @token_get_all( $source ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. - if ( is_array( $token ) && in_array( $token[0], [ T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG ], true ) ) { - continue; - } - if ( is_array( $token ) && in_array( $token[0], [ T_CLOSE_TAG, T_INLINE_HTML ], true ) ) { - // Only trailing whitespace may follow the code. - if ( '' !== trim( $token[1], " \t\r\n?>" ) ) { - return false; - } - continue; - } - $code .= ( '' !== $code && is_array( $token ) && T_STRING === $token[0] && preg_match( '/\w$/', $code ) ) ? ' ' . $token[1] : ( is_array( $token ) ? $token[1] : $token ); + if ( 1 === count( $parts ) && in_array( $parts[0], self::CORE_FILES, true ) ) { + return false; } - $quoted = "(?:'[^'\\\\]*'|\"[^\"\\\\\$]*\")"; - $literal = "(?:true|false|null|-?\\d+|$quoted)"; - $define = "@?\\\\?define\\((?:'[A-Za-z0-9_]+'|\"[A-Za-z0-9_]+\"),$literal\\);"; - $load = "(?:require|include)(?:_once)?\\(?(?:(?:__DIR__|dirname\\(__FILE__\\))\\.)?(?:'[^'\\\\\$]*wp-(?:blog-header|load)\\.php'|\"[^\"\\\\\$]*wp-(?:blog-header|load)\\.php\")\\)?;"; - return 1 === preg_match( "/^(?:$define)*$load(?:$define)*\$/i", $code ); + return ! ( count( $parts ) > 2 && in_array( $parts[1], [ 'uploads', 'cache', 'upgrade', 'languages', 'upgrade-temp-backup' ], true ) ); } /** - * The wp-config.php WordPress loads: in its directory, else the parent without wp-settings.php. Relative to app/. + * The wp-config.php WordPress loads: in its directory, else the parent without wp-settings.php (the real parent, as + * WordPress looks; the served parent too, as the scanner looks). A file there that can't be read counts. * - * @param string $code Real path of the site's app/. - * @param string $root WordPress root relative to app/. - * @param string|null $abspath Real WordPress root. + * @param string $code Real path of the site's app/. + * @param string $root WordPress root relative to app/ (as served). + * @param string $abspath Real WordPress root. * - * @return string[] + * @return string[] Its path relative to app/, or nothing. */ protected function wp_config_files( $code, $root, $abspath ) { - if ( null === $abspath ) { - return []; - } - $real_root = substr( $abspath, strlen( $code ) + 1 ); - $config = null; - if ( null !== self::resolve_in( $code, $real_root . '/wp-config.php' ) ) { - $config = $real_root . '/wp-config.php'; - } else { - // EE's own sites keep it in app/, above htdocs. - foreach ( array_unique( [ dirname( $real_root ), dirname( $root ) ] ) as $parent ) { - $parent = '.' === $parent ? '' : "$parent/"; - if ( null !== self::resolve_in( $code, "{$parent}wp-config.php" ) && null === self::resolve_in( $code, "{$parent}wp-settings.php" ) ) { - $config = "{$parent}wp-config.php"; - break; - } + $real_root = substr( $abspath, strlen( $code ) + 1 ); + $candidates = [ "$real_root/wp-config.php" ]; + foreach ( array_unique( [ dirname( $real_root ), dirname( $root ) ] ) as $parent ) { + $parent = '.' === $parent ? '' : "$parent/"; + if ( null === self::resolve_in( $code, "{$parent}wp-settings.php" ) ) { + $candidates[] = "{$parent}wp-config.php"; } } - if ( null === $config ) { - return []; - } - - return [ substr( self::resolve_in( $code, $config ), strlen( $code ) + 1 ) ]; - } - - /** - * Whether a require or include in the source names a file ending in $suffix (a string in its operand). - * - * @param string $source PHP source. - * @param string $suffix End of the path, e.g. config/application.php (a whole path segment). - * - * @return bool - */ - public static function includes( $source, $suffix ) { - foreach ( self::analyse_php( $source )['includes'] as $include ) { - if ( $include['overlong'] ) { - return true; - } - foreach ( $include['strings'] as $path ) { - if ( $path === $suffix || substr( $path, -strlen( $suffix ) - 1 ) === "/$suffix" ) { - return true; - } + foreach ( $candidates as $candidate ) { + if ( 'absent' !== $this->site_file( $code, $candidate, self::PHP_SOURCE_MAX )['state'] ) { + return [ $candidate ]; } } - return false; - } - - /** - * Plain defines of the directory constants in a PHP file, read without running it. - * - * @param string $source PHP source. - * - * @return array|string Constant => value expression (whitespace and comments removed), or what the file does with a - * directory constant that can't be read this way. - */ - public static function dir_defines( $source ) { - $php = self::analyse_php( $source ); - - return null === $php['unresolved'] ? $php['defines'] : $php['unresolved']; + return []; } /** - * Reads a PHP file's tokens once, without running it: the plain defines of the directory constants, anything else it - * does with them, and its includes. - * - * A define counts only as a statement of its own outside any block (braced or `if (…): … endif;`), or in its own - * `if ( ! defined( 'X' ) )` guard, before wp-settings.php is loaded; after that load nothing changes them any more, so - * the rest is passed over. After a load that may not run, a top-level return/exit or __halt_compiler, a define is - * unresolved. `const X = …`, a computed define name, eval() and any other use of a name are unresolved too. + * A file under app/ as the scanner container sees it, never from outside app/, never more than $max bytes, and only a + * regular file (a FIFO is never opened). * - * @param string $source PHP source. + * @param string $code Real path of the site's app/. + * @param string $rel Path relative to app/. + * @param int $max Size cap. * - * @return array 'defines' (name => value expression), 'unresolved' (string|null), 'halt_reason' (string|null) and - * 'includes' (each: expr, strings, static, alone, in_func, boot, after_boot, overlong). + * @return array [ state => absent ] when nothing is there; [ state => bad, detail ] when something is there that can't + * be read as a regular file inside app/; [ state => ok, real, source ]. */ - public static function analyse_php( $source ) { - $result = [ - 'defines' => [], - 'unresolved' => null, - 'halt_reason' => null, - 'includes' => [], - ]; - // Short open tags depend on the site's php.ini, not this one's: such a file can't be read reliably here. - if ( false === stripos( $source, ' 0 ? $t[ $i - 1 ] : [ T_OPEN_TAG, '' ]; - $start[ $i ] = in_array( $prev[0], $tags, true ) || ( null === $prev[0] && in_array( $prev[1], [ ';', '}', '{' ], true ) ); - if ( in_array( $type, $bodies, true ) ) { - $body = true; - } - if ( in_array( $type, $opens, true ) ) { - $header = $parens; - } elseif ( null === $type && '(' === $text ) { - // Punctuation only: the text of a string piece (T_ENCAPSED_AND_WHITESPACE) can be `)` or `}` too. - $parens++; - } elseif ( null === $type && ')' === $text ) { - $parens--; - if ( $header === $parens ) { - $header = null; - if ( isset( $t[ $i + 1 ] ) && null === $t[ $i + 1 ][0] && ':' === $t[ $i + 1 ][1] ) { - $level++; - $stack[] = 'a'; - } - } - } elseif ( in_array( $type, $ends, true ) ) { - $level--; - array_pop( $stack ); - } elseif ( ( null === $type && '{' === $text ) || in_array( $type, [ T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ], true ) ) { - $level++; - $stack[] = $body && null === $type ? 'f' : 'b'; - $body = false; - } elseif ( null === $type && '}' === $text ) { - $level--; - array_pop( $stack ); - } elseif ( null === $type && ';' === $text ) { - $body = false; - } - } - - // Includes, each operand ending where PHP ends the expression; the wp-settings.php load; top-level return/exit. - $booted = PHP_INT_MAX; - $maybe = PHP_INT_MAX; - $halt = PHP_INT_MAX; - $static = [ T_CONSTANT_ENCAPSED_STRING, T_DIR, T_FILE ]; - for ( $i = 0; $i < $n; $i++ ) { - $type = $t[ $i ][0]; - if ( in_array( $type, [ T_RETURN, T_EXIT, T_HALT_COMPILER ], true ) && 0 === $depth[ $i ] && $i < $halt ) { - $halt = $i; - $result['halt_reason'] = $t[ $i ][1]; - } - if ( T_EVAL === $type && ! $func[ $i ] && null === $result['unresolved'] ) { - $result['unresolved'] = 'eval()'; - } - if ( ! in_array( $type, $includes, true ) ) { - continue; + protected function site_file( $code, $rel, $max = self::CONFIG_MAX ) { + $real = self::resolve_in( $code, $rel ); + if ( null === $real ) { + // Nothing at all, or something (a link on the way) that leaves app/ or can't be resolved. + if ( preg_match( '/[\x00-\x1F\x7F]/', $rel ) ) { + return [ 'state' => 'bad', 'detail' => 'its path has control characters' ]; } - $expr = ''; - $strings = []; - $is_fixed = true; - $nest = 0; - $ternary = 0; - $overlong = false; - for ( $j = $i + 1; $j < $n; $j++ ) { - list( $jt, $jx ) = $t[ $j ]; - $open = ( null === $jt && in_array( $jx, [ '(', '[', '{' ], true ) ) || in_array( $jt, [ T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ], true ); - $close = null === $jt && in_array( $jx, [ ')', ']', '}' ], true ); - if ( ( $close && 0 === $nest ) || ( 0 === $nest && ( in_array( $jt, [ T_CLOSE_TAG, T_INLINE_HTML, T_DOUBLE_ARROW ], true ) || ( null === $jt && in_array( $jx, [ ';', ',' ], true ) ) ) ) ) { - break; - } - if ( 0 === $nest && null === $jt && ':' === $jx ) { - if ( 0 === $ternary ) { - break; - } - $ternary--; - } elseif ( 0 === $nest && null === $jt && '?' === $jx ) { - $ternary++; - } - if ( $j - $i > 256 ) { - $overlong = true; - break; - } - $nest += $open ? 1 : ( $close ? -1 : 0 ); - $expr .= $jx; - if ( T_CONSTANT_ENCAPSED_STRING === $jt ) { - $strings[] = substr( $jx, 1, -1 ); - } - $named = T_STRING === $jt && in_array( strtolower( $jx ), [ 'dirname', 'abspath' ], true ); - $is_fixed = $is_fixed && ( in_array( $jt, $static, true ) || $named || ( null === $jt && in_array( $jx, [ '(', ')', '.' ], true ) ) ); - } - $boot = false; - foreach ( $strings as $string ) { - $boot = $boot || 'wp-settings.php' === basename( $string ); - } - $alone = $start[ $i ] && 0 === $depth[ $i ]; - if ( $boot && ! $func[ $i ] ) { - $maybe = min( $maybe, $i ); - if ( $alone ) { - $booted = min( $booted, $i ); + for ( $path = rtrim( "$code/$rel", '/' ); strlen( $path ) > strlen( $code ); $path = dirname( $path ) ) { + if ( is_link( $path ) ) { + return [ 'state' => 'bad', 'detail' => 'is reached through a link that leaves the site\'s files or goes nowhere' ]; } } - $result['includes'][] = [ - 'index' => $i, - 'expr' => $expr, - 'strings' => $strings, - 'static' => $is_fixed && ! $overlong, - 'alone' => $alone, - 'in_func' => $func[ $i ], - 'boot' => $boot, - 'overlong' => $overlong, - ]; - } - foreach ( $result['includes'] as $k => $include ) { - $result['includes'][ $k ]['after_boot'] = $include['index'] > $booted || $include['index'] > $halt; + return file_exists( "$code/$rel" ) ? [ 'state' => 'bad', 'detail' => 'can\'t be resolved' ] : [ 'state' => 'absent' ]; } - if ( null !== $result['unresolved'] ) { - return $result; + $stat = @lstat( $real ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $stat || 0100000 !== ( $stat['mode'] & 0170000 ) ) { + return [ 'state' => 'bad', 'detail' => 'is not a regular file' ]; } - - // Defines, defined() checks and every other mention of a directory constant, up to where WordPress has booted. - $names = self::DIR_CONSTANTS; - $covered = []; - $at = []; - $stop = min( $maybe, $halt ); - $end = min( $n, $booted ); - $sig = function ( $k ) use ( $t ) { - return isset( $t[ $k ] ) ? $t[ $k ] : [ null, '' ]; - }; - for ( $i = 0; $i < $end; $i++ ) { - list( $type, $text ) = $t[ $i ]; - if ( T_CONST === $type && T_STRING === $sig( $i + 1 )[0] && in_array( $sig( $i + 1 )[1], $names, true ) ) { - $result['unresolved'] = $sig( $i + 1 )[1]; - return $result; - } - $before = $sig( $i - 1 ); - $method = in_array( $before[0], [ T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_FUNCTION, T_NEW ], true ) || ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) && T_NULLSAFE_OBJECT_OPERATOR === $before[0] ); - // PHP 8 reads `\define` as one name token. - $global = defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $type; - if ( ( T_STRING !== $type && ! $global ) || $method || '(' !== $sig( $i + 1 )[1] ) { - continue; - } - $call = ltrim( strtolower( $text ), '\\' ); - if ( 'defined' === $call && T_CONSTANT_ENCAPSED_STRING === $sig( $i + 2 )[0] ) { - $covered[ $i + 2 ] = true; - continue; - } - if ( 'define' !== $call ) { - continue; - } - $arg = $sig( $i + 2 ); - if ( T_CONSTANT_ENCAPSED_STRING !== $arg[0] || ! in_array( $sig( $i + 3 )[1], [ ',' ], true ) ) { - // define( $name, … ), define( 'A' . 'B', … ): the name can't be read here. - $result['unresolved'] = 'a define() whose name is not a plain string'; - return $result; - } - $name = substr( $arg[1], 1, -1 ); - if ( ! in_array( $name, $names, true ) ) { - continue; - } - $covered[ $i + 2 ] = true; - // The value runs to the `)` that closes the call; a trailing comma is allowed. - $nest = 0; - $value = ''; - for ( $j = $i + 4; $j < $n; $j++ ) { - list( $jt, $jx ) = $t[ $j ]; - if ( null === $jt && ')' === $jx && 0 === $nest ) { - break; - } - $nest += ( null === $jt && '(' === $jx ) ? 1 : ( ( null === $jt && ')' === $jx ) ? -1 : 0 ); - $covered[ $j ] = true; - $value .= $jx; - } - $value = rtrim( $value, ',' ); - $after = $sig( $j + 1 ); - // The statement starts at the define, or at an `@` or `\` in front of it. - $s = in_array( $before[1], [ '@', '\\' ], true ) ? $i - 1 : $i; - $guard = self::guarded( $t, $depth, $start, $s, $name, $j + 1 ); - $plain = $start[ $s ] && 0 === $depth[ $s ]; - if ( ( ! $plain && ! $guard ) || $s > $stop || isset( $result['defines'][ $name ] ) || ! ( ( null === $after[0] && ';' === $after[1] ) || T_CLOSE_TAG === $after[0] ) ) { - $result['unresolved'] = $name; - return $result; - } - $result['defines'][ $name ] = $value; - $at[ $name ] = $i; - } - for ( $i = 0; $i < $end; $i++ ) { - list( $type, $text ) = $t[ $i ]; - if ( isset( $covered[ $i ] ) ) { - continue; - } - $before = $sig( $i - 1 ); - $member = in_array( $before[0], [ T_OBJECT_OPERATOR, T_DOUBLE_COLON ], true ) || ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) && T_NULLSAFE_OBJECT_OPERATOR === $before[0] ); - $name = T_STRING === $type && ! $member ? $text : ( T_CONSTANT_ENCAPSED_STRING === $type ? substr( $text, 1, -1 ) : null ); - if ( null === $name || ! in_array( $name, $names, true ) ) { - continue; - } - // A use after the file's own plain define of that constant reads what it set. - if ( T_STRING === $type && isset( $at[ $name ] ) && $i > $at[ $name ] ) { - continue; - } - $result['unresolved'] = $name; - return $result; - } - - return $result; - } - - /** - * Whether the define at $s sits in its own `if ( ! defined( 'X' ) )` guard: unbraced, or braced around it alone. - * - * @param array $t Tokens. - * @param int[] $depth Block depth per token. - * @param bool[] $start Statement start per token. - * @param int $s First token of the define statement. - * @param string $name Constant name. - * @param int $after Token after the define's `)`. - * - * @return bool - */ - protected static function guarded( array $t, array $depth, array $start, $s, $name, $after ) { - $braced = $s > 0 && null === $t[ $s - 1 ][0] && '{' === $t[ $s - 1 ][1]; - $g = $s - ( $braced ? 1 : 0 ) - 8; - $want = [ [ T_IF ], '(', '!', [ T_STRING, 'defined' ], '(', [ T_CONSTANT_ENCAPSED_STRING ], ')', ')' ]; - if ( $g < 0 ) { - return false; - } - foreach ( $want as $k => $w ) { - $tok = $t[ $g + $k ]; - $ok = is_array( $w ) ? $tok[0] === $w[0] && ( ! isset( $w[1] ) || strtolower( $tok[1] ) === $w[1] ) : ( null === $tok[0] && $tok[1] === $w ); - if ( ! $ok ) { - return false; - } + $handle = @fopen( $real, 'rb' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $handle ) { + return [ 'state' => 'bad', 'detail' => 'can\'t be opened' ]; } - if ( substr( $t[ $g + 5 ][1], 1, -1 ) !== $name || ! $start[ $g ] || 0 !== $depth[ $g ] ) { - return false; + $fstat = fstat( $handle ); + $text = $fstat && 0100000 === ( $fstat['mode'] & 0170000 ) && $fstat['ino'] === $stat['ino'] ? stream_get_contents( $handle, $max + 1 ) : false; + fclose( $handle ); + if ( false === $text ) { + return [ 'state' => 'bad', 'detail' => 'changed while it was read' ]; } - // Braced: the block holds this define alone. - return ! $braced || ( isset( $t[ $after + 1 ] ) && null === $t[ $after + 1 ][0] && '}' === $t[ $after + 1 ][1] ); - } - - /** - * A directory constant's (or include's) value relative to app/, from the plain forms dir_defines() returns. - * - * @param string $code Real path of the site's app/. - * @param string $expr Value expression. - * @param string $file File it is in, relative to app/ (real). - * @param string|null $abspath Real WordPress root. - * @param string $content WP_CONTENT_DIR relative to app/. - * @param bool $relative Whether a relative string counts from the file's directory (an include path). - * - * @return string|null - */ - protected function dir_value( $code, $expr, $file, $abspath, $content, $relative = false ) { - $string = '\'[^\'\\\\]*\'|"[^"\\\\$]*"'; - $expr = preg_match( '/^\((.*)\)$/s', $expr, $outer ) ? $outer[1] : $expr; - if ( preg_match( "/^($string)$/", $expr, $m ) ) { - $path = substr( $m[1], 1, -1 ); - if ( $relative && '' !== $path && '/' !== $path[0] ) { - $base = dirname( $file ); - $base = '.' === $base ? '' : $base; - } elseif ( 0 !== strpos( $path . '/', '/var/www/' ) ) { - return null; - } else { - $base = ''; - $path = substr( $path, strlen( '/var/www/' ) ); - } - } elseif ( preg_match( "/^(__DIR__|dirname\\(__FILE__\\)|dirname\\(__DIR__\\)|dirname\\(dirname\\(__FILE__\\)\\)|ABSPATH|WP_CONTENT_DIR)\\.($string)$/i", $expr, $m ) ) { - $dir = dirname( $file ); - // dirname() of app/ itself is outside the site. - if ( '.' === $dir && 0 === stripos( $m[1], 'dirname(' ) && 0 !== strcasecmp( $m[1], 'dirname(__FILE__)' ) ) { - return null; - } - $base = [ - '__dir__' => $dir, - 'dirname(__file__)' => $dir, - 'dirname(__dir__)' => dirname( $dir ), - 'dirname(dirname(__file__))' => dirname( $dir ), - 'abspath' => null === $abspath ? null : substr( $abspath, strlen( $code ) + 1 ), - 'wp_content_dir' => $content, - ][ strtolower( $m[1] ) ]; - if ( null === $base ) { - return null; - } - $base = '.' === $base ? '' : $base; - $path = substr( $m[2], 1, -1 ); - // PHP joins the strings as they are: only ABSPATH ends in `/`, so `__DIR__ . '-x'` is a sibling, not a child. - if ( 'abspath' !== strtolower( $m[1] ) && '' !== $path && '/' !== $path[0] ) { - return null; - } - } else { - return null; + if ( strlen( $text ) > $max ) { + return [ 'state' => 'bad', 'detail' => 'is larger than ' . self::size( $max ) . ', more than this check reads' ]; } - // `..` stays for resolve_in(), which takes it after the links before it, as the kernel does. - $parts = array_filter( - explode( '/', $base . '/' . $path ), - function ( $part ) { - return '' !== $part && '.' !== $part; - } - ); - return $parts ? implode( '/', $parts ) : null; + return [ 'state' => 'ok', 'real' => $real, 'source' => $text ]; } /** - * A file under app/, read the way the scanner container sees it, never from outside app/, never more than $max bytes. - * * @param string $code Real path of the site's app/. * @param string $rel Path relative to app/. * @param int $max Size cap. * - * @return string|null + * @return string|null The file's text; null when it isn't there or can't be read. */ protected function read_site_file( $code, $rel, $max = self::CONFIG_MAX ) { - $path = self::resolve_in( $code, $rel ); - if ( null === $path ) { - return null; - } - $handle = @fopen( $path, 'rb' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- null when unreadable. - if ( false === $handle ) { - return null; - } - $stat = fstat( $handle ); - $text = $stat && 0100000 === ( $stat['mode'] & 0170000 ) ? stream_get_contents( $handle, $max + 1 ) : false; - fclose( $handle ); + $file = $this->site_file( $code, $rel, $max ); - return false === $text || strlen( $text ) > $max ? null : $text; + return 'ok' === $file['state'] ? $file['source'] : null; } /** diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php new file mode 100644 index 00000000..efd7e466 --- /dev/null +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -0,0 +1,824 @@ + 'wp-content', + 'WP_PLUGIN_DIR' => 'wp-content/plugins', + 'WPMU_PLUGIN_DIR' => 'wp-content/mu-plugins', + ]; + + /** Constants a config may never set: each moves core or theme code WordPress loads. */ + const NEVER_DEFINED = [ 'WPINC', 'TEMPLATEPATH', 'STYLESHEETPATH', 'WP_LANG_DIR', 'PLUGINDIR', 'MUPLUGINDIR' ]; + + /** The only variables a config may assign (table prefix, multisite, EE's --cache and memcached object caches). */ + const VARIABLES = [ 'table_prefix', 'base', 'redis_server', 'memcached_servers' ]; + + /** The only $_SERVER keys a config may set: what proxy and HTTPS snippets set, never where the script is. */ + const SERVER_KEYS = [ 'HTTPS', 'SERVER_PORT', 'REMOTE_ADDR', 'HTTP_HOST', 'SERVER_NAME', 'REQUEST_SCHEME', 'HTTP_X_FORWARDED_PROTO', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_PORT', 'HTTP_X_FORWARDED_SSL', 'HTTP_X_REAL_IP' ]; + + /** The only settings ini_set() may change in a config. */ + const INI_KEYS = [ 'display_errors', 'display_startup_errors', 'log_errors', 'error_log', 'error_reporting', 'memory_limit', 'max_execution_time', 'max_input_time', 'max_input_vars', 'upload_max_filesize', 'post_max_size', 'default_socket_timeout', 'date.timezone', 'session.gc_maxlifetime' ]; + + /** The only functions an expression may call: none has a side effect or loads code. */ + const PURE_FUNCTIONS = [ 'defined', 'dirname', 'getenv', 'strpos', 'stripos', 'strtolower', 'strtoupper', 'in_array', 'explode', 'trim', 'file_exists', 'isset', 'empty', 'array' ]; + + /** Statements (besides define/assignment/include) a config may make, each with any allowed expressions as arguments. */ + const PURE_STATEMENTS = [ 'ini_set', 'error_reporting' ]; + + /** Files below the WordPress root that EE's own --vip config loads, and how each is checked. */ + const VIP_FILES = [ + 'wp-content/mu-plugins/000-pre-vip-config/requires.php' => 'requires', + 'wp-content/vip-config/vip-config.php' => 'vip-config', + ]; + + /** + * The significant tokens of a PHP file: comments and whitespace dropped, `\name` read as `name`, a closing `?>` read as + * `;`. Refuses whatever the host's tokenizer and the site's PHP could read differently or that is not plain code. + * + * @param string $source PHP source. + * + * @return array|string List of [ id, text, line ] (id is the T_* constant or the character), or the reason it is refused. + */ + public static function tokens( $source ) { + $raw = @token_get_all( $source ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a broken file still tokenises. + if ( ! $raw || ! is_array( $raw[0] ) || T_OPEN_TAG !== $raw[0][0] || 0 !== strncasecmp( $raw[0][1], '"; + } + } + $last = $out ? end( $out )[0] : null; + if ( ';' !== $last && '}' !== $last && null !== $last ) { + $out[] = [ ';', '?>', $line ]; + } + break; + } + if ( in_array( $t[0], [ T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_INLINE_HTML, T_START_HEREDOC, T_HALT_COMPILER ], true ) ) { + return "line $line has " . ( T_START_HEREDOC === $t[0] ? 'a heredoc' : ( T_HALT_COMPILER === $t[0] ? '__halt_compiler' : 'another PHP tag or text outside PHP' ) ); + } + if ( $fq === $t[0] ) { + $name = substr( $t[1], 1 ); + if ( false !== strpos( $name, '\\' ) ) { + return "line $line names $t[1], in a namespace"; + } + $out[] = [ T_STRING, $name, $line ]; + continue; + } + if ( T_NS_SEPARATOR === $t[0] ) { + // PHP 7: `\define` is a separator and a name; a separator after a name is a namespace path. + $prev = $out ? end( $out )[0] : null; + if ( T_STRING === $prev || ! isset( $raw[ $i + 1 ] ) || ! is_array( $raw[ $i + 1 ] ) || T_STRING !== $raw[ $i + 1 ][0] ) { + return "line $line has a namespaced name"; + } + continue; + } + $out[] = [ $t[0], $t[1], $line ]; + } + + return $out; + } + + /** + * Recognises WordPress's own index.php: an optional `define( 'WP_USE_THEMES', true|false );` and one require/include of + * `__DIR__ . '

/wp-blog-header.php'` (or `dirname( __FILE__ ) . …`), as every WordPress version since 4.9 ships it, with + *

empty or a plain path below the file's directory. + * + * @param string $source PHP source. + * + * @return array|string [ 'sub' =>

without its leading slash ] or the reason it isn't recognised. + */ + public static function index_loader( $source ) { + $t = self::tokens( $source ); + if ( is_string( $t ) ) { + return $t; + } + $i = 0; + if ( self::is_word( $t, 0, 'define' ) ) { + $end = self::statement_end( $t, 0 ); + $args = null === $end ? null : self::call_args( $t, 0, $end ); + if ( ! $args || 2 !== count( $args ) || 'WP_USE_THEMES' !== self::name_literal( $t, $args[0] ) + || 1 !== count( $args[1] ) || ! self::is_word( $t, $args[1][0], [ 'true', 'false' ] ) ) { + return 'line ' . $t[0][2] . ' is not define( \'WP_USE_THEMES\', true );'; + } + $i = $end + 1; + } + $end = isset( $t[ $i ] ) ? self::statement_end( $t, $i ) : null; + $inc = null === $end ? null : self::include_target( $t, $i, $end ); + if ( null === $inc || 'blog-header' !== $inc['kind'] ) { + return isset( $t[ $i ] ) ? 'line ' . $t[ $i ][2] . ' is not require __DIR__ . \'/wp-blog-header.php\';' : 'it does not load wp-blog-header.php'; + } + if ( count( $t ) !== $end + 1 ) { + return 'line ' . $t[ $end + 1 ][2] . ' comes after WordPress is loaded'; + } + + return [ 'sub' => trim( dirname( $inc['path'] ), '/.' ) ]; + } + + /** + * Checks a wp-config.php (or a file it loads) statement by statement against the config grammar. + * + * $env: 'root' (real WordPress root), 'dir' (real directory of this file: __DIR__), 'file' (for messages), 'boot' + * (whether this file must end with the wp-settings.php load), 'resolve' (callable( $abs_path ) returning + * [ 'state' => 'absent'|'bad'|'ok', 'real' => …, 'source' => …, 'scanned' => bool, 'detail' => … ] for a file this one + * loads; 'bad' is a file that is there but can't be read as the scanner would). + * + * @param string $source PHP source. + * @param array $env See above. + * @param int $depth Nesting of loaded files. + * + * @return string|null Why it is refused, or null. + */ + public static function check_config( $source, array $env, $depth = 0 ) { + $t = self::tokens( $source ); + if ( is_string( $t ) ) { + return "{$env['file']}: $t"; + } + $state = [ 'booted' => false, 'content' => null, 'guard' => null ]; + $error = self::statements( $t, 0, count( $t ), $env, $depth, $state, true ); + if ( null !== $error ) { + return $error; + } + if ( $env['boot'] && ! $state['booted'] ) { + return "{$env['file']} does not end with require_once ABSPATH . 'wp-settings.php';"; + } + + return null; + } + + /** + * @return string|null + */ + private static function statements( array $t, $i, $to, array $env, $depth, array &$state, $top ) { + while ( $i < $to ) { + if ( $state['booted'] ) { + return self::unknown( $t, $i, $env, 'comes after wp-settings.php is loaded' ); + } + if ( ';' === $t[ $i ][0] ) { + $i++; + continue; + } + if ( T_IF === $t[ $i ][0] ) { + $next = self::if_block( $t, $i, $to, $env, $depth, $state ); + if ( is_string( $next ) ) { + return $next; + } + $i = $next; + continue; + } + $end = self::statement_end( $t, $i, $to ); + if ( null === $end ) { + return self::unknown( $t, $i, $env ); + } + $error = self::simple( $t, $i, $end, $env, $depth, $state, $top ); + if ( null !== $error ) { + return $error; + } + $i = $end + 1; + } + + return null; + } + + /** + * `if ( expr ) { … } elseif ( expr ) { … } else { … }`, braced or one statement each; the alternative syntax is refused. + * + * @return int|string Index after the block, or the reason it is refused. + */ + private static function if_block( array $t, $i, $to, array $env, $depth, array &$state ) { + while ( true ) { + $kw = $t[ $i ][0]; + if ( T_ELSE !== $kw ) { + $close = isset( $t[ $i + 1 ] ) && '(' === $t[ $i + 1 ][0] ? self::matching( $t, $i + 1, $to ) : null; + if ( null === $close ) { + return self::unknown( $t, $i, $env ); + } + $error = self::expr( $t, $i + 2, $close, $env, 'condition' ); + if ( null !== $error ) { + return $error; + } + $body = $close + 1; + $guard = $close === $i + 7 && '!' === $t[ $i + 2 ][0] && self::is_word( $t, $i + 3, 'defined' ) && '(' === $t[ $i + 4 ][0] && ')' === $t[ $i + 6 ][0] ? self::name_literal( $t, [ $i + 5 ] ) : null; + } else { + $body = $i + 1; + $guard = null; + } + $outer = $state['guard']; + $state['guard'] = T_IF === $kw ? $guard : null; + if ( ! isset( $t[ $body ] ) ) { + return self::unknown( $t, $i, $env ); + } + if ( '{' === $t[ $body ][0] ) { + $end = self::matching( $t, $body, $to ); + if ( null === $end ) { + return self::unknown( $t, $i, $env ); + } + $error = self::statements( $t, $body + 1, $end, $env, $depth, $state, false ); + $after = $end + 1; + } elseif ( ':' === $t[ $body ][0] || T_IF === $t[ $body ][0] && T_ELSE !== $kw ) { + return self::unknown( $t, $i, $env ); + } elseif ( T_IF === $t[ $body ][0] ) { + // `else if`. + $after = self::if_block( $t, $body, $to, $env, $depth, $state ); + return $after; + } else { + $end = self::statement_end( $t, $body, $to ); + if ( null === $end ) { + return self::unknown( $t, $body, $env ); + } + $error = self::simple( $t, $body, $end, $env, $depth, $state, false ); + $after = $end + 1; + } + $state['guard'] = $outer; + if ( null !== $error ) { + return $error; + } + if ( $after < $to && in_array( $t[ $after ][0], [ T_ELSEIF, T_ELSE ], true ) && T_ELSE !== $kw ) { + $i = $after; + continue; + } + + return $after; + } + } + + /** + * One statement without a block: define, a `defined() || define()` guard, an assignment, ini_set/error_reporting, or a + * require/include this check can name. + * + * @return string|null + */ + private static function simple( array $t, $i, $end, array $env, $depth, array &$state, $top ) { + $s = '@' === $t[ $i ][0] ? $i + 1 : $i; + // define( 'NAME', expr ); + if ( self::is_word( $t, $s, 'define' ) ) { + $args = self::call_args( $t, $s, $end ); + if ( null === $args || 2 !== count( $args ) ) { + return self::unknown( $t, $i, $env ); + } + return self::define( $t, $args, $env, $state, $i ); + } + // defined( 'NAME' ) || define( 'NAME', expr ); + if ( self::is_word( $t, $s, 'defined' ) && isset( $t[ $s + 1 ] ) && '(' === $t[ $s + 1 ][0] ) { + $close = self::matching( $t, $s + 1, $end ); + $or = null === $close ? null : $close + 1; + $args = null === $or || ! in_array( $t[ $or ][0], [ T_BOOLEAN_OR, T_LOGICAL_OR ], true ) || ! self::is_word( $t, $or + 1, 'define' ) ? null : self::call_args( $t, $or + 1, $end ); + $name = null === $close || $close !== $s + 3 ? null : self::name_literal( $t, [ $s + 2 ] ); + if ( null === $args || 2 !== count( $args ) || null === $name || self::name_literal( $t, $args[0] ) !== $name ) { + return self::unknown( $t, $i, $env ); + } + $outer = $state['guard']; + $state['guard'] = $name; + $error = self::define( $t, $args, $env, $state, $i ); + $state['guard'] = $outer; + return $error; + } + // $var = expr; $_SERVER['KEY'] = expr; + if ( T_VARIABLE === $t[ $i ][0] ) { + $name = substr( $t[ $i ][1], 1 ); + $eq = $i + 1; + if ( '_SERVER' === $name && isset( $t[ $i + 3 ] ) && '[' === $t[ $i + 1 ][0] && ']' === $t[ $i + 3 ][0] ) { + $key = self::name_literal( $t, [ $i + 2 ] ); + if ( ! in_array( $key, self::SERVER_KEYS, true ) ) { + return self::unknown( $t, $i, $env, 'sets a $_SERVER key this check doesn\'t accept' ); + } + $eq = $i + 4; + } elseif ( ! in_array( $name, self::VARIABLES, true ) ) { + return self::unknown( $t, $i, $env, "assigns \${$name}, which this check doesn't accept" ); + } + if ( ! isset( $t[ $eq ] ) || '=' !== $t[ $eq ][0] || $eq + 1 >= $end ) { + return self::unknown( $t, $i, $env ); + } + return self::expr( $t, $eq + 1, $end, $env, 'value' ); + } + // ini_set( … ); error_reporting( … ); + if ( self::is_word( $t, $s, self::PURE_STATEMENTS ) ) { + $args = self::call_args( $t, $s, $end ); + if ( null === $args || self::is_word( $t, $s, 'ini_set' ) && ( 2 !== count( $args ) || ! in_array( strtolower( (string) self::literal_arg( $t, $args[0] ) ), self::INI_KEYS, true ) ) ) { + return self::unknown( $t, $i, $env ); + } + foreach ( $args as $arg ) { + $error = $arg ? self::expr( $t, $arg[0], end( $arg ) + 1, $env, 'argument' ) : null; + if ( null !== $error ) { + return $error; + } + } + return null; + } + if ( in_array( $t[ $i ][0], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { + return self::include_statement( $t, $i, $end, $env, $depth, $state, $top ); + } + + return self::unknown( $t, $i, $env ); + } + + /** + * @return string|null + */ + private static function define( array $t, array $args, array $env, array &$state, $at ) { + $name = self::name_literal( $t, $args[0] ); + if ( null === $name ) { + return self::unknown( $t, $at, $env, 'defines a constant whose name is not a plain string' ); + } + $upper = strtoupper( $name ); + if ( in_array( $upper, self::NEVER_DEFINED, true ) ) { + return "{$env['file']} line {$t[ $at ][2]} defines $name, which changes where WordPress loads code from"; + } + if ( ! $args[1] ) { + return self::unknown( $t, $at, $env ); + } + if ( 'ABSPATH' === $upper ) { + // Only WordPress's own guard: wp-load.php has set it already, but a direct request for wp-config.php hasn't. + $value = self::signature( $t, $args[1] ); + if ( ! $env['boot'] || 'ABSPATH' !== $state['guard'] || ! in_array( $value, [ "T_DIR . '/'", 'T_DIR . "/"', "T_STRING:dirname ( T_FILE ) . '/'", 'T_STRING:dirname ( T_FILE ) . "/"' ], true ) ) { + return self::unknown( $t, $at, $env, 'defines ABSPATH other than in WordPress\'s own guard' ); + } + return null; + } + if ( isset( self::DIR_DEFAULTS[ $upper ] ) ) { + $name = $upper; + $path = self::path_value( $t, $args[1][0], end( $args[1] ) + 1, $env, $state['content'] ); + $default = $env['root'] . '/' . self::DIR_DEFAULTS[ $name ]; + if ( null === $path ) { + return "can't resolve $name in {$env['file']} (line {$t[ $at ][2]}); this check only accepts its default, $default"; + } + if ( $path !== $default ) { + return "{$env['file']} sets $name to $path (line {$t[ $at ][2]}); this check only accepts its default, $default"; + } + if ( 'WP_CONTENT_DIR' === $name ) { + $state['content'] = $path; + } + return null; + } + + return self::expr( $t, $args[1][0], end( $args[1] ) + 1, $env, 'value' ); + } + + /** + * @return string|null + */ + private static function include_statement( array $t, $i, $end, array $env, $depth, array &$state, $top ) { + $inc = self::include_target( $t, $i, $end ); + if ( null === $inc ) { + return self::unknown( $t, $i, $env, 'loads a file this check can\'t name' ); + } + if ( 'settings' === $inc['kind'] ) { + if ( ! $env['boot'] || ! $top ) { + return self::unknown( $t, $i, $env, 'loads wp-settings.php somewhere other than at the end of wp-config.php' ); + } + $state['booted'] = true; + return null; + } + if ( 'blog-header' === $inc['kind'] ) { + return self::unknown( $t, $i, $env ); + } + $base = [ + 'ABSPATH' => $env['root'], + '__DIR__' => $env['dir'], + '__FILE__' => $env['dir'], + 'dirname-2' => dirname( $env['dir'] ), + ][ $inc['base'] ]; + $path = self::normalise( $base . '/' . ltrim( $inc['path'], '/' ) ); + // PHP joins `__DIR__ . 'x.php'` without a slash: a sibling of the directory, never what's meant here. + if ( null === $path || '' === $inc['path'] || '/' !== $inc['path'][0] && 'ABSPATH' !== $inc['base'] || '.php' !== substr( $path, -4 ) ) { + return self::unknown( $t, $i, $env, 'loads a file this check can\'t name' ); + } + $file = call_user_func( $env['resolve'], $path ); + if ( 'absent' === $file['state'] ) { + return null; + } + if ( 'ok' !== $file['state'] ) { + return "{$env['file']} line {$t[ $i ][2]} loads $path, which " . $file['detail']; + } + $rel = 0 === strpos( $file['real'], $env['root'] . '/' ) ? substr( $file['real'], strlen( $env['root'] ) + 1 ) : null; + if ( null === $rel || ! $file['scanned'] ) { + return "{$env['file']} line {$t[ $i ][2]} loads {$file['real']}, outside what the scan of {$env['root']} checks"; + } + if ( isset( self::VIP_FILES[ $rel ] ) ) { + $error = self::vip_file( $file['source'], self::VIP_FILES[ $rel ] ); + return null === $error ? null : "{$file['real']} (loaded by {$env['file']}): $error"; + } + if ( $depth >= 2 ) { + return "{$env['file']} line {$t[ $i ][2]} loads {$file['real']}, a config file nested too deep for this check"; + } + + return self::check_config( $file['source'], [ 'dir' => dirname( $file['real'] ), 'file' => $file['real'], 'boot' => false ] + $env, $depth + 1 ); + } + + /** + * EE's --vip files, which the scan checks as code: they may not touch the directory constants or hooks, run code from a + * string, or (requires.php) load anything but `$mu_plugins_base . $file` below its own mu-plugins/lib. + * + * @param string $source PHP source. + * @param string $kind 'requires' or 'vip-config'. + * + * @return string|null + */ + public static function vip_file( $source, $kind ) { + $t = self::tokens( $source ); + if ( is_string( $t ) ) { + return $t; + } + $names = array_merge( array_keys( self::DIR_DEFAULTS ), self::NEVER_DEFINED ); + $n = count( $t ); + for ( $i = 0; $i < $n; $i++ ) { + list( $id, $text, $line ) = $t[ $i ]; + $word = T_CONSTANT_ENCAPSED_STRING === $id ? substr( $text, 1, -1 ) : $text; + if ( ( T_STRING === $id || T_CONSTANT_ENCAPSED_STRING === $id ) && in_array( strtoupper( $word ), $names, true ) ) { + return "line $line names $word"; + } + if ( T_VARIABLE === $id && in_array( substr( $text, 1 ), [ 'GLOBALS', 'wp_filter', 'wp_theme_directories' ], true ) ) { + return "line $line uses $text"; + } + if ( in_array( $id, [ T_EVAL, '`', '$' ], true ) || T_VARIABLE === $id && isset( $t[ $i + 1 ] ) && '(' === $t[ $i + 1 ][0] ) { + return "line $line runs code this check can't read"; + } + if ( in_array( $id, [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { + $ok = 'requires' === $kind && isset( $t[ $i + 4 ] ) && '$mu_plugins_base' === $t[ $i + 1 ][1] && '.' === $t[ $i + 2 ][0] && '$file' === $t[ $i + 3 ][1] && ';' === $t[ $i + 4 ][0]; + if ( ! $ok ) { + return "line $line loads a file this check can't name"; + } + } + if ( 'requires' === $kind && T_VARIABLE === $id && '$mu_plugins_base' === $text && isset( $t[ $i + 1 ] ) && '=' === $t[ $i + 1 ][0] ) { + $want = [ '=', 'dirname', '(', '__DIR__', ')', ';' ]; + $got = array_map( + function ( $tok ) { + return $tok[1]; + }, + array_slice( $t, $i + 1, 6 ) + ); + if ( $want !== $got ) { + return "line $line sets \$mu_plugins_base to something other than dirname( __DIR__ )"; + } + } + if ( 'requires' === $kind && T_CONSTANT_ENCAPSED_STRING === $id && '.php' === substr( $word, -4 ) && ! preg_match( '#^/lib/(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*\.php$#D', $word ) ) { + return "line $line names $word, outside mu-plugins/lib"; + } + } + + return null; + } + + /** + * Checks an expression: literals, constants, $variables and $array[…] reads, the operators, casts, array literals and the + * pure functions; no other call, no `new`, eval, include, backticks, `$$`, `::`, `->`, closures or assignment. + * + * @return string|null + */ + private static function expr( array $t, $from, $to, array $env, $what ) { + static $ops = null; + if ( null === $ops ) { + $ops = [ '.', '?', ':', '!', ',', '-', '+', '*', '/', '%', '|', '&', '^', '~', '<', '>', '@', ')', ']', '(', '[', + T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL, + T_BOOLEAN_AND, T_BOOLEAN_OR, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR, T_COALESCE, T_DOUBLE_ARROW, T_SL, T_SR, + T_INT_CAST, T_BOOL_CAST, T_STRING_CAST, T_DOUBLE_CAST, T_SPACESHIP, T_POW ]; + // PHP 8.1 tokenises `&` by what follows it. + foreach ( [ 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG' ] as $name ) { + if ( defined( $name ) ) { + $ops[] = constant( $name ); + } + } + } + if ( $from >= $to ) { + return self::unknown( $t, max( 0, $from - 1 ), $env ); + } + $after_value = [ T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER, T_VARIABLE, T_DIR, T_FILE, T_LINE, ')', ']', T_STRING ]; + for ( $i = $from; $i < $to; $i++ ) { + list( $id, $text, $line ) = $t[ $i ]; + $call = isset( $t[ $i + 1 ] ) && $i + 1 < $to && '(' === $t[ $i + 1 ][0]; + if ( in_array( $id, [ T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER, T_DIR, T_FILE, T_LINE ], true ) ) { + if ( $call ) { + return "{$env['file']} line $line calls a string as a function"; + } + continue; + } + if ( T_VARIABLE === $id ) { + if ( $call ) { + return "{$env['file']} line $line calls a variable as a function"; + } + continue; + } + if ( in_array( $id, [ T_STRING, T_ISSET, T_EMPTY, T_ARRAY ], true ) ) { + $word = strtolower( $text ); + if ( $call && ! in_array( $word, self::PURE_FUNCTIONS, true ) ) { + return "{$env['file']} line $line calls $text(), which this check doesn't accept in a config"; + } + if ( ! $call && T_STRING !== $id ) { + return self::unknown( $t, $i, $env ); + } + continue; + } + if ( '(' === $id && $i > $from && in_array( $t[ $i - 1 ][0], $after_value, true ) && ! in_array( $t[ $i - 1 ][0], [ T_STRING ], true ) ) { + return "{$env['file']} line $line calls the result of an expression"; + } + if ( ! in_array( $id, $ops, true ) ) { + return "{$env['file']} line $line has " . self::clean( $text ) . " in a $what, which this check doesn't accept in a config"; + } + } + + return null; + } + + /** + * The host path an expression of ABSPATH, __DIR__, dirname( __FILE__ ), WP_CONTENT_DIR and string literals joined by `.` + * gives, or null when it is anything else. + * + * @return string|null + */ + private static function path_value( array $t, $from, $to, array $env, $content ) { + $path = ''; + $i = $from; + while ( $i < $to ) { + list( $id, $text ) = $t[ $i ]; + if ( '(' === $id && ')' === $t[ $to - 1 ][0] && $i === $from && self::matching( $t, $i, $to ) === $to - 1 ) { + $to--; + $i++; + continue; + } + $part = null; + $next = $i + 1; + if ( T_DIR === $id ) { + $part = $env['dir']; + } elseif ( self::is_word( $t, $i, 'abspath' ) && 'ABSPATH' === $text ) { + $part = $env['root'] . '/'; + } elseif ( 'WP_CONTENT_DIR' === $text && T_STRING === $id ) { + $part = null === $content ? $env['root'] . '/wp-content' : $content; + } elseif ( T_CONSTANT_ENCAPSED_STRING === $id ) { + $part = self::literal( $text ); + } elseif ( self::is_word( $t, $i, 'dirname' ) && isset( $t[ $i + 3 ] ) && '(' === $t[ $i + 1 ][0] && ')' === $t[ $i + 3 ][0] && in_array( $t[ $i + 2 ][0], [ T_FILE, T_DIR ], true ) ) { + $part = T_FILE === $t[ $i + 2 ][0] ? $env['dir'] : dirname( $env['dir'] ); + $next = $i + 4; + } + if ( null === $part ) { + return null; + } + $path .= $part; + $i = $next; + if ( $i < $to ) { + if ( '.' !== $t[ $i ][0] ) { + return null; + } + $i++; + } + } + + return self::normalise( $path ); + } + + /** + * What a require/include statement loads: wp-settings.php from ABSPATH, wp-blog-header.php from the file's directory, or a + * file named by `ABSPATH|__DIR__|dirname( __FILE__ )|dirname( __DIR__ ) . 'literal'`. + * + * @return array|null [ 'kind' => settings|blog-header|file, 'base' => ABSPATH|__DIR__|__FILE__|dirname-2, 'path' => literal ]. + */ + private static function include_target( array $t, $i, $end ) { + if ( ! in_array( $t[ $i ][0], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { + return null; + } + $from = $i + 1; + $to = $end; + if ( $from < $to && '(' === $t[ $from ][0] && self::matching( $t, $from, $to ) === $to - 1 ) { + $from++; + $to--; + } + $ops = array_slice( $t, $from, $to - $from ); + $sig = implode( + ' ', + array_map( + function ( $tok ) { + return is_int( $tok[0] ) ? token_name( $tok[0] ) . ':' . strtolower( $tok[1] ) : $tok[0]; + }, + $ops + ) + ); + $bases = [ + 'T_STRING:abspath .' => 'ABSPATH', + 'T_DIR:__dir__ .' => '__DIR__', + 'T_STRING:dirname ( T_FILE:__file__ ) .' => '__FILE__', + 'T_STRING:dirname ( T_DIR:__dir__ ) .' => 'dirname-2', + ]; + foreach ( $bases as $prefix => $base ) { + if ( 0 !== strpos( $sig, $prefix . ' ' ) || 'ABSPATH' === $base && 'ABSPATH' !== $ops[0][1] ) { + continue; + } + $last = end( $ops ); + if ( substr_count( $sig, ' ' ) !== substr_count( $prefix, ' ' ) + 1 || T_CONSTANT_ENCAPSED_STRING !== $last[0] ) { + return null; + } + $path = self::literal( $last[1] ); + if ( null === $path || preg_match( '#(^|/)\.\.?(/|$)#', $path ) || preg_match( '/[\x00-\x1F\x7F]/', $path ) ) { + return null; + } + if ( 'ABSPATH' === $base && in_array( $path, [ 'wp-settings.php', '/wp-settings.php' ], true ) ) { + return [ 'kind' => 'settings', 'base' => $base, 'path' => $path ]; + } + if ( in_array( $base, [ '__DIR__', '__FILE__' ], true ) && preg_match( '#^(?:/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*/wp-blog-header\.php$#D', $path ) ) { + return [ 'kind' => 'blog-header', 'base' => $base, 'path' => $path ]; + } + return [ 'kind' => 'file', 'base' => $base, 'path' => $path ]; + } + + return null; + } + + /** + * Index of the `;` ending the statement at $i (brackets balanced, no braces), or null. + */ + private static function statement_end( array $t, $i, $to = null ) { + $to = null === $to ? count( $t ) : $to; + $depth = 0; + for ( ; $i < $to; $i++ ) { + $id = $t[ $i ][0]; + if ( '(' === $id || '[' === $id ) { + $depth++; + } elseif ( ')' === $id || ']' === $id ) { + if ( --$depth < 0 ) { + return null; + } + } elseif ( '{' === $id || '}' === $id || T_CURLY_OPEN === $id || T_DOLLAR_OPEN_CURLY_BRACES === $id ) { + return null; + } elseif ( ';' === $id && 0 === $depth ) { + return $i; + } + } + + return null; + } + + /** + * Index of the bracket closing the one at $i, or null. + */ + private static function matching( array $t, $i, $to ) { + $pairs = [ '(' => ')', '[' => ']', '{' => '}' ]; + $stack = []; + for ( ; $i < $to; $i++ ) { + $id = $t[ $i ][0]; + if ( T_CURLY_OPEN === $id || T_DOLLAR_OPEN_CURLY_BRACES === $id ) { + return null; + } + if ( is_string( $id ) && isset( $pairs[ $id ] ) ) { + $stack[] = $pairs[ $id ]; + } elseif ( is_string( $id ) && in_array( $id, $pairs, true ) ) { + if ( array_pop( $stack ) !== $id ) { + return null; + } + if ( ! $stack ) { + return $i; + } + } + } + + return null; + } + + /** + * Arguments of `name( … )` spanning exactly $s..$end-1 ($end is the `;`): lists of token indexes, a trailing comma dropped. + * + * @return array[]|null + */ + private static function call_args( array $t, $s, $end ) { + if ( ! isset( $t[ $s + 1 ] ) || '(' !== $t[ $s + 1 ][0] || self::matching( $t, $s + 1, $end ) !== $end - 1 ) { + return null; + } + $args = [ [] ]; + $depth = 0; + for ( $i = $s + 2; $i < $end - 1; $i++ ) { + $id = $t[ $i ][0]; + if ( ',' === $id && 0 === $depth ) { + $args[] = []; + continue; + } + $depth += in_array( $id, [ '(', '[' ], true ) ? 1 : ( in_array( $id, [ ')', ']' ], true ) ? -1 : 0 ); + $args[ count( $args ) - 1 ][] = $i; + } + if ( count( $args ) > 1 && ! end( $args ) ) { + array_pop( $args ); + } + + return in_array( [], $args, true ) && [ [] ] !== $args ? null : ( [ [] ] === $args ? [] : $args ); + } + + /** + * The constant name in a single string-literal argument, when it has no escapes or interpolation. + * + * @param array $t Tokens. + * @param int[] $arg Token indexes of the argument. + * + * @return string|null + */ + private static function name_literal( array $t, array $arg ) { + if ( 1 !== count( $arg ) || T_CONSTANT_ENCAPSED_STRING !== $t[ $arg[0] ][0] ) { + return null; + } + $name = substr( $t[ $arg[0] ][1], 1, -1 ); + + return preg_match( '/^[A-Za-z_][A-Za-z0-9_]*$/D', $name ) ? $name : null; + } + + /** + * A string literal's value, when it has no escape PHP would read differently in single and double quotes. + * + * @return string|null + */ + private static function literal( $text ) { + $body = substr( $text, 1, -1 ); + if ( false !== strpos( $body, '\\' ) || '"' === $text[0] && false !== strpos( $body, '$' ) ) { + return null; + } + + return $body; + } + + /** + * Collapses `//`, `/./` and `x/../` in an absolute path; null when `..` would go above /. + */ + public static function normalise( $path ) { + $out = []; + foreach ( explode( '/', $path ) as $part ) { + if ( '' === $part || '.' === $part ) { + continue; + } + if ( '..' === $part ) { + if ( ! $out ) { + return null; + } + array_pop( $out ); + continue; + } + $out[] = $part; + } + + return '/' . implode( '/', $out ); + } + + /** + * Tokens of an argument as `T_NAME:text` (names lower-cased) or the character, joined by spaces. + */ + private static function signature( array $t, array $arg ) { + return implode( + ' ', + array_map( + function ( $i ) use ( $t ) { + return is_int( $t[ $i ][0] ) ? ( T_CONSTANT_ENCAPSED_STRING === $t[ $i ][0] ? $t[ $i ][1] : token_name( $t[ $i ][0] ) . ( T_STRING === $t[ $i ][0] ? ':' . strtolower( $t[ $i ][1] ) : '' ) ) : $t[ $i ][0]; + }, + $arg + ) + ); + } + + /** + * A single string-literal argument's value. + */ + private static function literal_arg( array $t, array $arg ) { + return 1 === count( $arg ) && T_CONSTANT_ENCAPSED_STRING === $t[ $arg[0] ][0] ? self::literal( $t[ $arg[0] ][1] ) : null; + } + + private static function is_word( array $t, $i, $words ) { + return isset( $t[ $i ] ) && T_STRING === $t[ $i ][0] && in_array( strtolower( $t[ $i ][1] ), (array) $words, true ); + } + + private static function unknown( array $t, $i, array $env, $why = null ) { + $text = ''; + for ( $j = $i, $n = count( $t ); $j < $n && strlen( $text ) < 60 && ';' !== $t[ $j ][0]; $j++ ) { + $text .= ( '' !== $text && preg_match( '/^\w/', $t[ $j ][1] ) && preg_match( '/\w$/', $text ) ? ' ' : '' ) . $t[ $j ][1]; + } + $text = self::clean( trim( substr( $text, 0, 60 ) ) ); + + return isset( $t[ $i ] ) + ? "{$env['file']} line {$t[ $i ][2]} " . ( null === $why ? "isn't a statement this check recognises" : $why ) . ": $text" + : "{$env['file']} ends early"; + } + + private static function clean( $text ) { + return class_exists( __NAMESPACE__ . '\\Site_PHP_Compat', false ) ? Site_PHP_Compat::clean( $text ) : preg_replace( '/[\x00-\x1F\x7F]/', '?', $text ); + } +} diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index fbbf2cc0..1e71d732 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3309,7 +3309,7 @@ public function sync( $args, $assoc_args ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core) with wp-config.php and the files it includes; for PHP sites, everything under htdocs. A layout it can't read with certainty (a moved wp-content, code mounted or included from elsewhere) gets no verdict. It ends with a verdict: safe to upgrade (every file checked, no errors), not safe (at least one error), or can't confirm (some files couldn't be checked). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, everything under htdocs. A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: safe to upgrade (every file checked, no errors), not safe (at least one error), or can't confirm (some files couldn't be checked). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * From 00f5680534af69a785cd01baf80be489e6e43f56 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 13:37:39 +0530 Subject: [PATCH 23/53] fix(site): read php-compat's layout under the lock and never let it block a delete - A scan reads the layout after the image pull, under the site lock; an estimate reads it after taking its lock, and doesn't run when the site was deleted or changed during the pull. - `ee site delete` of a site never checked takes the site lock without asking docker. Once a check's container is gone, a lock holder that doesn't answer no longer refuses the delete; it warns and goes on. A running restore still refuses it. - A signal while delete stops php-compat ends it with "nothing was deleted" instead of the rollback messages. php-compat handles SIGQUIT too. - Restore retries the site lock for three seconds, so a --cancel or an estimate's probe doesn't refuse it, and its message names a check, --cancel or delete. - Behat: /dev/null is checked with stat() and recreated by rename; the own-directory scenario keeps wp-config.php where WordPress looks; the delete scenario no longer depends on timing. --- features/bootstrap/FeatureContext.php | 16 ++++-- features/php-compat.feature | 4 +- src/helper/Site_Backup_Restore.php | 15 +++++- src/helper/Site_PHP_Compat.php | 72 +++++++++++++++++---------- src/helper/class-ee-site.php | 32 ++++++++++-- 5 files changed, 102 insertions(+), 37 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 7eb8c6b6..65ccfb4e 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -490,7 +490,7 @@ public function cleanupScenario(AfterScenarioScope $scope) { // A failed --output check could have replaced /dev/null with a file; never leave the runner without it. clearstatcache( true, '/dev/null' ); - self::repairDevNull( @lstat( '/dev/null' ) ); + self::repairDevNull( @stat( '/dev/null' ) ); $this->commands = []; chdir($this->ee_path); @@ -998,7 +998,7 @@ public function devNullShouldStillBeTheNullDevice() if ( $stat && 0020000 === ( $stat['mode'] & 0170000 ) && ( 'Linux' !== PHP_OS_FAMILY || 259 === $stat['rdev'] ) ) { return; } - self::repairDevNull( $stat ); + self::repairDevNull( @stat( '/dev/null' ) ); throw new Exception( '/dev/null was replaced: ' . var_export( $stat, true ) ); } @@ -1006,15 +1006,21 @@ public function devNullShouldStillBeTheNullDevice() * Recreate /dev/null only on Linux and only when it is no character device at all (e.g. replaced by a file), so a * healthy one is never removed. * - * @param array|false $stat lstat() of /dev/null. + * @param array|false $stat stat() of /dev/null (a link to a character device counts as healthy). */ private static function repairDevNull( $stat ) { if ( 'Linux' !== PHP_OS_FAMILY || ( $stat && 0020000 === ( $stat['mode'] & 0170000 ) ) ) { return; } - @unlink( '/dev/null' ); - exec( 'mknod -m 666 /dev/null c 1 3' ); + // Made beside it and renamed over it, so there is never a moment without /dev/null. + $tmp = '/dev/.null-' . getmypid(); + @unlink( $tmp ); + exec( 'mknod -m 666 ' . escapeshellarg( $tmp ) . ' c 1 3', $out, $code ); + if ( 0 !== $code || ! rename( $tmp, '/dev/null' ) ) { + @unlink( $tmp ); + throw new Exception( 'could not recreate /dev/null' ); + } } /** diff --git a/features/php-compat.feature b/features/php-compat.feature index 7ac2e195..38c9cf56 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -230,7 +230,6 @@ Feature: Check the PHP compatibility of a site's code And the directory "{SITES_DIR}/bh-site-command-191.test/app/htdocs/bulk" holds 5000 generated PHP files When I run 'bin/ee site php-compat bh-site-command-191.test --php=8.4 --estimate --format=json' Then the command should succeed - And the file "{EE_ROOT_DIR}/tmp/php-compat/.estimate-lock/bh-site-command-191.test" should exist When I start 'bin/ee site php-compat bh-site-command-191.test --php=8.4 --format=json' in the background And I wait up to 120 seconds until the command "docker inspect -f '{{.State.Running}}' ee-php-compat-bh-site-command-191.test | grep -qx true" succeeds And I run 'bin/ee site delete bh-site-command-191.test --yes' @@ -242,7 +241,8 @@ Feature: Check the PHP compatibility of a site's code And the file "{EE_ROOT_DIR}/tmp/php-compat/.cancel-lock/bh-site-command-191.test" should not exist And the file "{EE_ROOT_DIR}/tmp/php-compat/.cancel/bh-site-command-191.test" should not exist When I wait up to 120 seconds for the background command to finish - Then the JSON field "status" in STDOUT should be "cancelled" + # Stopped by the delete, or done just before it. + Then STDOUT should match "/"status":"(cancelled|ok)"/" Scenario: A hangup doesn't stop a running check Given the compat-scanner image is available diff --git a/src/helper/Site_Backup_Restore.php b/src/helper/Site_Backup_Restore.php index 8c2ace2d..31e2db2d 100644 --- a/src/helper/Site_Backup_Restore.php +++ b/src/helper/Site_Backup_Restore.php @@ -2588,9 +2588,20 @@ private function check_and_install( $command, $name ) { * replaces app/; the lock goes with the process. Shared: php-compat holds it exclusive, so it can tell a restore from a check. */ private function hold_scan_lock() { - $message = sprintf( 'A php-compat check of %1$s is running and reads the files a restore replaces. Wait for it to finish or stop it with `ee site php-compat %1$s --cancel`, then run the restore again.', $this->site_data['site_url'] ); + $message = sprintf( 'A php-compat check, `ee site php-compat %1$s --cancel` or `ee site delete %1$s` holds the site\'s lock (a check reads the files a restore replaces). Wait for it to finish or stop a check with `ee site php-compat %1$s --cancel`, then run the restore again.', $this->site_data['site_url'] ); $handle = @fopen( $this->site_data['site_fs_path'], 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. - if ( false !== $handle && flock( $handle, LOCK_SH | LOCK_NB, $would_block ) ) { + // A --cancel or an estimate's probe holds it only for a moment: try for a few seconds before refusing. + $locked = false; + for ( $try = 0; false !== $handle && $try < 30; $try++ ) { + if ( $try ) { + usleep( 100000 ); + } + $locked = flock( $handle, LOCK_SH | LOCK_NB, $would_block ); + if ( $locked || ! $would_block ) { + break; + } + } + if ( $locked ) { $this->scan_lock = $handle; // After taking the lock: an estimate takes its own first, then looks for a restore. if ( Site_PHP_Compat::estimate_running( $this->site_data['site_url'] ) ) { diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 462c233c..6319b2f4 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -359,10 +359,6 @@ protected function run_scan( $site_data, $timeout, $output ) { if ( false === $code ) { return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); } - $layout = $this->resolve_layout( $site_data, $code ); - if ( null !== $layout ) { - return $layout; - } if ( false !== strpbrk( $code, ',"' ) ) { return $this->doc( 'tool_error', 'the site code path has a comma or a quote' ); } @@ -397,6 +393,11 @@ protected function run_scan( $site_data, $timeout, $output ) { if ( null !== $pull ) { return $this->doc( 'tool_error', $pull ); } + // Read under the site lock and after the pull, so the layout checked is the one scanned. + $layout = $this->resolve_layout( $site_data, $code ); + if ( null !== $layout ) { + return $layout; + } $mounts = $this->extra_mounts( $site_data, $code ); if ( is_string( $mounts ) ) { return $this->doc( 'tool_error', $mounts ); @@ -501,10 +502,6 @@ protected function run_estimate( $site_data ) { if ( false === $code ) { return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); } - $layout = $this->resolve_layout( $site_data, $code ); - if ( null !== $layout ) { - return $layout; - } if ( false !== strpbrk( $code, ',"' ) ) { return $this->doc( 'tool_error', 'the site code path has a comma or a quote' ); } @@ -526,6 +523,14 @@ protected function run_estimate( $site_data ) { if ( $this->restore_running( $site_data->site_fs_path ) ) { return $this->doc( 'tool_error', 'a restore of the site is running' ); } + // The pull ran unlocked: a delete may have gone through meanwhile, and the layout is read only now. + if ( ! is_dir( $site_data->site_fs_path ) || $this->code_dir( $site_data->site_fs_path ) !== $code ) { + return $this->doc( 'tool_error', 'the site was deleted or changed while the scanner image was pulled' ); + } + $layout = $this->resolve_layout( $site_data, $code ); + if ( null !== $layout ) { + return $layout; + } $mounts = $this->extra_mounts( $site_data, $code ); if ( is_string( $mounts ) ) { return $this->doc( 'tool_error', $mounts ); @@ -3099,9 +3104,9 @@ public function stop_for_delete( $site_data, $dispatch = null ) { $this->dispatch = $dispatch; $parent = rtrim( $this->temp_base(), '/' ) . '/' . self::TEMP_DIR; $name = 'ee-php-compat-' . $this->site; - // Nothing to do, and no temp directory created, for a site never checked. - if ( ! file_exists( $parent ) && ! is_link( $parent ) && false === $this->container_status( $name ) ) { - return null; + // Never checked on this host: no check runs without the temporary directory, and docker isn't asked. + if ( ! file_exists( $parent ) && ! is_link( $parent ) ) { + return $this->hold_for_delete( $site_data ); } $usable = $this->temp_parent(); if ( null === $usable || null === $this->cancel_path( $usable ) ) { @@ -3110,20 +3115,9 @@ public function stop_for_delete( $site_data, $dispatch = null ) { if ( false !== $this->container_status( $name ) && ! $this->container_gone( $name ) ) { return "could not remove the container $name"; } - // A scan whose container was just removed lets go of the site lock as it ends; kept as below. - if ( ! $this->lock_site( $site_data->site_fs_path ) ) { - if ( $this->restore_running( $site_data->site_fs_path ) ) { - return 'a restore of the site is running'; - } - if ( ! $this->wait_for_site_lock( $site_data->site_fs_path, $this->cancel_wait() ) ) { - return 'the running check did not stop within ' . $this->cancel_wait() . ' s'; - } - } - $this->delete_lock = $this->lock; - $this->lock = null; - - return null; + return $this->hold_for_delete( $site_data ); } + $kept = null; try { $result = $this->run_cancel( $site_data ); if ( 'tool_error' !== $result['doc']['status'] ) { @@ -3135,7 +3129,11 @@ public function stop_for_delete( $site_data, $dispatch = null ) { $this->cleanup(); } if ( 'tool_error' === $result['doc']['status'] ) { - return $result['doc']['detail']; + // Once its container is gone the check reads nothing more: a process that doesn't let go of the lock doesn't stop the delete. + if ( $this->restore_running( $site_data->site_fs_path ) || false !== $this->container_status( $name ) && ! $this->container_gone( $name ) ) { + return $result['doc']['detail']; + } + EE::warning( "The php-compat check of {$this->site} didn't stop cleanly ({$result['doc']['detail']}); its container is gone, so the delete goes on." ); } $this->delete_lock = $kept; $parent = $this->temp_parent(); @@ -3157,6 +3155,30 @@ public function stop_for_delete( $site_data, $dispatch = null ) { return null; } + /** + * Takes the site lock for the rest of a delete, so no check starts meanwhile. Refused only while a restore runs; a lock + * another php-compat process keeps past CANCEL_WAIT gives a warning, not a refusal. + * + * @param object $site_data Site record. + * + * @return string|null Why the delete can't go on, or null. + */ + protected function hold_for_delete( $site_data ) { + if ( ! $this->lock_site( $site_data->site_fs_path ) ) { + if ( $this->restore_running( $site_data->site_fs_path ) ) { + return 'a restore of the site is running'; + } + if ( ! $this->wait_for_site_lock( $site_data->site_fs_path, $this->cancel_wait() ) ) { + EE::warning( "Another php-compat process of {$this->site} still holds the site's lock after " . $this->cancel_wait() . ' s; the delete goes on.' ); + return null; + } + } + $this->delete_lock = $this->lock; + $this->lock = null; + + return null; + } + /** * Wait for a running estimate of the site to end (it holds its lock file), so its file isn't removed under it. * diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 1e71d732..1c6f7178 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -248,13 +248,29 @@ public function delete( $args, $assoc_args ) { // A running php-compat check mounts the site's code: stop it first, and drop what php-compat keeps for the site. // Kept on $this: the site lock it holds must last until this process ends. $this->php_compat_check = new Site_PHP_Compat(); - $compat = $this->php_compat_check->stop_for_delete( + // Nothing is deleted yet: a signal while php-compat is stopped ends the delete without the rollback messages. + $previous = []; + if ( function_exists( 'pcntl_signal' ) ) { + $site = $this->site_data['site_url']; + foreach ( [ SIGTERM, SIGINT, SIGQUIT, SIGUSR1, SIGHUP ] as $signal ) { + $previous[ $signal ] = pcntl_signal_get_handler( $signal ); + pcntl_signal( + $signal, + function () use ( $site ) { + $this->delete_stopped( $site ); + } + ); + } + } + $compat = $this->php_compat_check->stop_for_delete( (object) $this->site_data, - // Dispatched in this class's scope, where the protected rollback() handlers can be called. function () { pcntl_signal_dispatch(); } ); + foreach ( $previous as $signal => $handler ) { + pcntl_signal( $signal, $handler ); + } if ( null !== $compat ) { \EE::error( sprintf( 'Could not stop the php-compat check of %s (%s). Nothing was deleted.', $this->site_data['site_url'], $compat ) ); } @@ -3306,6 +3322,16 @@ public function sync( $args, $assoc_args ) { } } + /** + * A signal while `ee site delete` stops php-compat: nothing is deleted yet, so there is nothing to roll back. + * + * @param string $site Site name. + */ + protected function delete_stopped( $site ) { + \EE::warning( "Delete of $site stopped: nothing was deleted." ); + exit( 1 ); + } + /** * Checks a site's PHP code for compatibility with a PHP version. * @@ -3383,7 +3409,7 @@ public function php_compat( $args, $assoc_args ) { \EE::warning( 'Stopping the check: removing its container and temporary files.' ); exit( 1 ); }; - foreach ( [ SIGTERM, SIGINT, SIGUSR1 ] as $signal ) { + foreach ( [ SIGTERM, SIGINT, SIGQUIT, SIGUSR1 ] as $signal ) { pcntl_signal( $signal, $stop ); } // A lost terminal doesn't stop a check; it ends and cleans up on its own, or with --cancel. Ignored rather than From 50adf0adb74de63a5cae6c2abdd2bd7be7e044e9 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 13:40:03 +0530 Subject: [PATCH 24/53] fix(site): accept every stock EE PHP and nginx config in php-compat - FPM's include= is accepted in both forms EE's php images ship: relative before PHP 8.6, absolute from 8.6. - An nginx include is refused only when it points at the site's files (/var/www), uses `..` or a variable, or is quoted, so the includes of old main.conf and nginx.conf versions pass. - macOS's custom.ini mount counts as EE's own. - A refused layout is answered at once again, before the site lock and the image pull; the layout read under the lock stays the one that counts. - Listing the site's files answers signals and --cancel between directories. --- src/helper/Site_PHP_Compat.php | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 6319b2f4..4d647c84 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -359,6 +359,11 @@ protected function run_scan( $site_data, $timeout, $output ) { if ( false === $code ) { return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); } + // Read first so a layout this check refuses is answered at once, without a lock or a pull; read again under the lock. + $layout = $this->resolve_layout( $site_data, $code ); + if ( null !== $layout ) { + return $layout; + } if ( false !== strpbrk( $code, ',"' ) ) { return $this->doc( 'tool_error', 'the site code path has a comma or a quote' ); } @@ -502,6 +507,11 @@ protected function run_estimate( $site_data ) { if ( false === $code ) { return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); } + // Read first so a layout this check refuses is answered at once, without a lock or a pull; read again under the lock. + $layout = $this->resolve_layout( $site_data, $code ); + if ( null !== $layout ) { + return $layout; + } if ( false !== strpbrk( $code, ',"' ) ) { return $this->doc( 'tool_error', 'the site code path has a comma or a quote' ); } @@ -1189,6 +1199,13 @@ protected function walk_tree( $top, callable $visit ) { if ( microtime( true ) > $deadline ) { return 'it takes more than ' . self::WALK_SECONDS . ' s to list'; } + // A long walk still answers a signal or a --cancel (run() reports cancelled then). + if ( function_exists( 'pcntl_signal_dispatch' ) ) { + null === $this->dispatch ? pcntl_signal_dispatch() : call_user_func( $this->dispatch ); + } + if ( $this->cancel_requested() ) { + return 'a cancel was requested'; + } $entries = @scandir( $dir ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. if ( false === $entries ) { return self::clean( $dir ) . ' can\'t be listed'; @@ -1307,7 +1324,8 @@ protected function php_setting_ok( $code, $key, $value, $layout ) { $off = in_array( strtolower( $value ), [ '', 'none', 'off', 'no', 'false', 'null', '0' ], true ); switch ( $key ) { case 'include': - return 'etc/php-fpm.d/*.conf' === $value; + // php-fpm.conf of EE's images: relative before PHP 8.6, absolute from 8.6. + return in_array( $value, [ 'etc/php-fpm.d/*.conf', '/usr/local/etc/php-fpm.d/*.conf' ], true ); case 'security.limit_extensions': return '.php' === $value; case 'user_ini.filename': @@ -1392,9 +1410,10 @@ public static function nginx_refusal( $text, $main, $custom ) { return "sets {$m[1]} to $value"; } } + // nginx's own config directory (old images used /etc/nginx) is EE's; anything the site's code can write is not. preg_match_all( '/(?:^|[;{}])\s*include\s+([^;\s]+)\s*;/', $text, $all, PREG_SET_ORDER ); foreach ( $all as $m ) { - if ( ! in_array( $m[1], [ 'mime.types', 'fastcgi_params', 'fastcgi.conf', '/usr/local/openresty/nginx/conf/conf.d/main.conf', '/usr/local/openresty/nginx/conf/custom/*.conf' ], true ) ) { + if ( preg_match( '#/var/www|\.\.|\$|^["\']#', $m[1] ) ) { return "includes {$m[1]}"; } } @@ -1454,6 +1473,8 @@ protected function extra_mounts( $site_data, $code ) { '/usr/local/etc' => realpath( $site_data->site_fs_path . '/config/php' ), '/var/log/php' => realpath( $site_data->site_fs_path . '/logs/php' ), '/etc/easyengine/admin-tools' => realpath( $site_data->site_fs_path . '/config/admin-tools' ), + // macOS mounts only custom.ini instead of all of config/php. + '/usr/local/etc/php/php/conf.d/custom.ini' => realpath( $site_data->site_fs_path . '/config/php/php/conf.d/custom.ini' ), ]; foreach ( $mounts as $mount ) { $dst = isset( $mount['Destination'] ) ? rtrim( (string) $mount['Destination'], '/' ) : ''; From 075970cd9f95bfb6abee345d4e1811fb529cd47e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 13:51:04 +0530 Subject: [PATCH 25/53] feat(site): scope php-compat's verdict to what it checked and gate WordPress core by version - Never print "Safe to upgrade". The positive line says what was checked: "No PHP 8.4 problems found in the 412 files checked in (plugins, themes, mu-plugins, drop-ins and config in

). WordPress 6.8 supports PHP 8.4.", followed by "Not checked: WordPress core files (only its version is checked)." - JSON keeps safe_to_upgrade (true only then) and adds checked, not_checked (the scanner's entries plus core) and wordpress. - WordPress's version is read from wp-includes/version.php (one literal $wp_version, else tool_error) and compared with WordPress's own table of supported PHP versions (WP_PHP_SUPPORT, from make.wordpress.org, 2026-11-04). A core too old or too new for the target is not safe; a target WordPress hasn't declared support for is can't confirm. - Any file the scanner reports as not checked gives can't confirm, whatever its reason. - Accept EE's own New Relic socket volume at /run/newrelic on the php container. --- features/php-compat.feature | 36 ++++- src/helper/Site_PHP_Compat.php | 188 ++++++++++++++++++++++++-- src/helper/Site_PHP_Compat_Layout.php | 28 ++++ src/helper/class-ee-site.php | 2 +- 4 files changed, 242 insertions(+), 12 deletions(-) diff --git a/features/php-compat.feature b/features/php-compat.feature index 38c9cf56..c4679ef2 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -44,6 +44,36 @@ Feature: Check the PHP compatibility of a site's code And STDOUT should match "/\nThis is static analysis with PHPCompatibility [^\n]+\. Its coverage isn't complete and it can't see breakage that only shows at runtime\.\n$/" And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-180.test" should not exist + @wp + Scenario: A WordPress site's verdict covers what was checked, and core by its version + Given the compat-scanner image is available + And the site "bh-site-command-193.test" exists, created with "--type=wp" + When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4 --format=json' + Then the command should succeed + And the JSON field "status" in STDOUT should be "ok" + And the JSON field "wordpress.supports" in STDOUT should be "true" + And the JSON field "checked.dir" in STDOUT should contain "bh-site-command-193.test/app/htdocs" + And STDOUT should contain "only its version is checked" + When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4' + Then the command should succeed + And STDOUT should not contain "Safe to upgrade" + And STDOUT should contain "WordPress core files (only its version is checked)" + # A WordPress too old for the target is never fine, whatever the scan finds. + When I run 'sed -i "s#^.wp_version = .*#\$wp_version = \"6.1.1\";#" {SITES_DIR}/bh-site-command-193.test/app/htdocs/wp-includes/version.php' + Then the command should succeed + When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4 --format=json' + Then the command should succeed + And the JSON field "safe_to_upgrade" in STDOUT should be "false" + And the JSON field "wordpress.version" in STDOUT should be "6.1.1" + When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4' + Then the command should succeed + And STDOUT should contain "WordPress 6.1 doesn't support PHP 8.4; update WordPress to at least 6.7 first" + # A PHP version WordPress hasn't declared support for can't be confirmed. + When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.6' + Then the command should succeed + And STDOUT should contain "WordPress hasn't declared support for PHP 8.6 yet" + And STDOUT should not contain "Safe to upgrade" + Scenario: The JSON summary of a php site Given the compat-scanner image is available And the site "bh-site-command-181.test" exists, created with "--type=php" @@ -64,14 +94,16 @@ Feature: Check the PHP compatibility of a site's code And the directory "{EE_ROOT_DIR}/tmp/php-compat/bh-site-command-181.test" should not exist And the docker container "ee-php-compat-bh-site-command-181.test" should not exist - Scenario: The table of a php site without errors says it is safe + Scenario: The table of a php site without errors says what was checked, never "safe" Given the compat-scanner image is available And the site "bh-site-command-184.test" exists, created with "--type=php" And I write "/wp-content. + /** + * PHP versions each WordPress branch supports, [ lowest, highest ], from WordPress's own "PHP Compatibility and WordPress + * Versions" page (https://make.wordpress.org/core/handbook/references/php-compatibility-and-wordpress-versions/, last + * updated 2026-11-04). A target newer than every row is one WordPress hasn't declared support for yet. + */ + const WP_PHP_SUPPORT = [ + '7.1' => [ '7.4', '8.5' ], + '7.0' => [ '7.4', '8.5' ], + '6.9' => [ '7.2', '8.5' ], + '6.8' => [ '7.2', '8.4' ], + '6.7' => [ '7.2', '8.4' ], + '6.6' => [ '7.2', '8.3' ], + '6.5' => [ '7.0', '8.3' ], + '6.4' => [ '7.0', '8.3' ], + '6.3' => [ '7.0', '8.2' ], + '6.2' => [ '5.6', '8.2' ], + '6.1' => [ '5.6', '8.2' ], + '6.0' => [ '5.6', '8.1' ], + '5.9' => [ '5.6', '8.1' ], + '5.8' => [ '5.6', '8.0' ], + '5.7' => [ '5.6', '8.0' ], + '5.6' => [ '5.6', '8.0' ], + '5.5' => [ '5.6', '7.4' ], + '5.4' => [ '5.6', '7.4' ], + '5.3' => [ '5.6', '7.4' ], + '5.2' => [ '5.6', '7.3' ], + '5.1' => [ '5.2', '7.3' ], + '5.0' => [ '5.2', '7.3' ], + '4.9' => [ '5.2', '7.2' ], + '4.8' => [ '5.2', '7.1' ], + '4.7' => [ '5.2', '7.1' ], + ]; + /** Longest php-compat lists the site's files for (PHP outside WordPress, links, .user.ini files). */ const WALK_SECONDS = 120; @@ -110,6 +143,9 @@ class Site_PHP_Compat { /** @var bool Whether this is a WordPress scan (its WordPress directory, core left out) rather than all of htdocs. */ protected $wp_layout = false; + /** @var array|null WordPress's version ( version, branch ) read from the scanned root's wp-includes/version.php. */ + protected $wp_version; + /** @var string|null Cancel request file a scan watches once it holds the site lock. */ protected $cancel_marker; @@ -473,7 +509,7 @@ protected function run_scan( $site_data, $timeout, $output ) { return $this->cancelled(); } - $summary = $this->summary( $doc ); + $summary = $this->summary( $this->scoped( $doc, $report ) ); if ( null !== $output ) { if ( ! $this->write_report( $output, $raw ) ) { return $this->doc( 'tool_error', "could not write the report to $output" ); @@ -960,8 +996,16 @@ function ( $path, $name, $type ) use ( &$user_ini ) { if ( null !== $index ) { $allowed[] = $index; } + $this->wp_version = null; if ( null !== $layout['abspath'] ) { - $config = $this->check_wp_config( $code, $root, $layout['abspath'], $app ); + // Core isn't scanned: its version decides whether it supports the target PHP. + $file = $this->site_file( $code, substr( $layout['abspath'], strlen( $code ) + 1 ) . '/wp-includes/version.php', self::PHP_SOURCE_MAX ); + $version = 'ok' === $file['state'] ? Site_PHP_Compat_Layout::wp_version( $file['source'] ) : 'it ' . ( 'bad' === $file['state'] ? $file['detail'] : 'is missing' ); + if ( is_string( $version ) ) { + return $this->doc( 'tool_error', "can't read WordPress's version from $app$root/wp-includes/version.php: " . self::clean( $version ) ); + } + $this->wp_version = $version; + $config = $this->check_wp_config( $code, $root, $layout['abspath'], $app ); if ( is_string( $config ) ) { return $this->doc( 'tool_error', $config ); } @@ -1486,6 +1530,10 @@ protected function extra_mounts( $site_data, $code ) { } continue; } + // The New Relic daemon's socket: EE's global volume, never code. + if ( '/run/newrelic' === $dst && isset( $mount['Type'], $mount['Name'] ) && 'volume' === $mount['Type'] && ( defined( 'GLOBAL_NEWRELIC_DAEMON' ) ? GLOBAL_NEWRELIC_DAEMON : 'global-newrelic-daemon' ) . '_newrelic_sock' === $mount['Name'] ) { + continue; + } if ( isset( $known[ $dst ] ) ) { if ( false === $known[ $dst ] || realpath( $src ) !== $known[ $dst ] ) { return 'the site\'s php container gets ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', not from EE\'s own directory for it'; @@ -2602,6 +2650,99 @@ protected function output_dir_unchanged( $path ) { return $real === $this->output_dir['path'] && $stat && $stat['dev'] === $this->output_dir['dev'] && $stat['ino'] === $this->output_dir['ino'] && $this->trusted_dir( $real ); } + /** + * The verdict this check gives from the scanner's result: what was checked, what wasn't, and for WordPress whether its + * core supports the target. Safe only with no error, nothing the scanner left unchecked, and core supporting the target. + * + * @param array $doc Validated scanner summary. + * @param array $report Validated report. + * + * @return array $doc with safe_to_upgrade, checked, not_checked and (WordPress) wordpress set. + */ + protected function scoped( array $doc, array $report ) { + $doc['checked'] = [ + 'dir' => self::clean( (string) $this->looked_in ), + 'components' => $doc['components_checked'], + 'files' => $doc['files_checked'], + ]; + $doc['not_checked'] = array_map( + function ( $entry ) { + return [ + 'type' => self::clean( $entry['type'] ), + 'slug' => self::clean( $entry['slug'] ), + 'branch' => null === $entry['branch'] ? null : self::clean( $entry['branch'] ), + 'file' => self::clean( $entry['file'] ), + 'reason' => self::clean( $entry['reason'] ), + ]; + }, + $report['not_checked'] + ); + $core = null; + if ( $this->wp_layout && null !== $this->wp_version ) { + $doc['not_checked'][] = [ + 'type' => 'core', + 'slug' => 'wordpress', + 'branch' => null, + 'file' => 'wp-admin, wp-includes and the core files beside them', + 'reason' => 'only its version is checked', + ]; + $core = self::wp_supports( $this->wp_version['branch'], $this->target ); + $doc['wordpress'] = [ + 'version' => self::clean( $this->wp_version['version'] ), + 'supports' => $core['supports'], + 'minimum' => $core['minimum'], + ]; + } + if ( $doc['errors'] > 0 || ( null !== $core && false === $core['supports'] ) ) { + $doc['safe_to_upgrade'] = false; + } elseif ( $doc['files_not_checked'] > 0 || ( null !== $core && null === $core['supports'] ) ) { + $doc['safe_to_upgrade'] = null; + } else { + $doc['safe_to_upgrade'] = true; + } + + return $doc; + } + + /** + * Whether a WordPress branch supports a PHP version, by WP_PHP_SUPPORT. + * + * @param string $branch WordPress major.minor. + * @param string $target PHP major.minor. + * + * @return array supports (true, false, or null when WordPress hasn't said), minimum (lowest WordPress branch supporting + * the target, or null) and why (the verdict's reason, null when supported). + */ + public static function wp_supports( $branch, $target ) { + $minimum = null; + $highest = '0'; + foreach ( self::WP_PHP_SUPPORT as $wp => list( $low, $high ) ) { + if ( version_compare( $target, $low, '>=' ) && version_compare( $target, $high, '<=' ) ) { + $minimum = (string) $wp; + } + $highest = version_compare( $high, $highest, '>' ) ? $high : $highest; + } + if ( version_compare( $target, $highest, '>' ) ) { + return [ 'supports' => null, 'minimum' => null, 'why' => "WordPress hasn't declared support for PHP $target yet" ]; + } + $newest = (string) array_keys( self::WP_PHP_SUPPORT )[0]; + if ( version_compare( $branch, $newest, '>' ) ) { + return [ 'supports' => null, 'minimum' => $minimum, 'why' => "this check doesn't know which PHP versions WordPress $branch supports" ]; + } + if ( isset( self::WP_PHP_SUPPORT[ $branch ] ) ) { + list( $low, $high ) = self::WP_PHP_SUPPORT[ $branch ]; + if ( version_compare( $target, $low, '>=' ) && version_compare( $target, $high, '<=' ) ) { + return [ 'supports' => true, 'minimum' => $minimum, 'why' => null ]; + } + if ( version_compare( $target, $low, '<' ) ) { + return [ 'supports' => false, 'minimum' => $minimum, 'why' => "WordPress $branch doesn't support PHP $target; it needs PHP $low or newer" ]; + } + } + $why = "WordPress $branch doesn't support PHP $target"; + + return [ 'supports' => false, 'minimum' => $minimum, 'why' => null === $minimum ? $why : "$why; update WordPress to at least $minimum first" ]; + } + /** * Container scan summary to print: findings never, `site` always. * @@ -2775,13 +2916,36 @@ protected function table_lines( array $doc, $report ) { } $tail = sprintf( '%s. %s checked.', self::count_of( $doc['warnings'], 'warning' ), self::count_of( $doc['files_checked'], 'file' ) ); + $core = isset( $doc['wordpress'] ) && null !== $this->wp_version ? self::wp_supports( $this->wp_version['branch'], $target ) : null; + $why = null === $core || true === $core['supports'] ? null : $core['why']; if ( false === $doc['safe_to_upgrade'] ) { - yield sprintf( 'Not safe to upgrade %s to PHP %s: %s in %s. %s', $site, $target, self::count_of( $doc['errors'], 'error' ), self::count_of( $doc['components_with_errors'], 'component' ), $tail ); + if ( $doc['errors'] > 0 ) { + yield sprintf( 'Not safe to upgrade %s to PHP %s: %s in %s. %s', $site, $target, self::count_of( $doc['errors'], 'error' ), self::count_of( $doc['components_with_errors'], 'component' ), $tail ); + if ( null !== $why && false === $core['supports'] ) { + yield ucfirst( $why ) . '.'; + } + } else { + yield sprintf( 'Not safe to upgrade %s to PHP %s: %s. %s', $site, $target, $why, $tail ); + } } elseif ( true === $doc['safe_to_upgrade'] ) { - yield sprintf( 'Safe to upgrade %s to PHP %s: 0 errors. %s', $site, $target, $tail ); + // Only what was checked: never "safe" for the whole site. + $what = $this->wp_layout ? 'plugins, themes, mu-plugins, drop-ins and config' : 'all PHP'; + $found = 0 === $doc['warnings'] ? 'problems' : 'errors'; + $line = sprintf( 'No PHP %s %s found in the %s checked in %s (%s in %s).', $target, $found, self::count_of( $doc['files_checked'], 'file' ), $site, $what, self::clean( (string) $this->looked_in ) ); + if ( null !== $core ) { + $line .= sprintf( ' WordPress %s supports PHP %s.', $this->wp_version['branch'], $target ); + } + yield $line . ( $doc['warnings'] > 0 ? ' ' . self::count_of( $doc['warnings'], 'warning' ) . '.' : '' ); } else { - $could = 1 === $doc['files_not_checked'] ? 'file couldn\'t' : 'files couldn\'t'; - yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %d %s be checked. %s', $site, $target, $doc['files_not_checked'], $could, $tail ); + if ( $doc['files_not_checked'] > 0 ) { + $could = 1 === $doc['files_not_checked'] ? 'file couldn\'t' : 'files couldn\'t'; + yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %d %s be checked. %s', $site, $target, $doc['files_not_checked'], $could, $tail ); + if ( null !== $why ) { + yield ucfirst( $why ) . '.'; + } + } else { + yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %s. %s', $site, $target, $why, $tail ); + } } yield ''; @@ -2812,6 +2976,12 @@ protected function table_lines( array $doc, $report ) { foreach ( $report['not_checked'] as $entry ) { yield ' ' . self::place( $entry ) . ': ' . self::clean( $entry['file'] ) . ' (' . self::clean( $entry['reason'] ) . ')'; } + if ( null !== $this->wp_version ) { + yield ' WordPress core files (only its version is checked)'; + } + yield ''; + } elseif ( null !== $this->wp_version ) { + yield 'Not checked: WordPress core files (only its version is checked).'; yield ''; } @@ -2821,8 +2991,8 @@ protected function table_lines( array $doc, $report ) { } $tool = isset( $doc['tool']['phpcompatibility'] ) && is_string( $doc['tool']['phpcompatibility'] ) ? ' ' . self::clean( $doc['tool']['phpcompatibility'] ) : ''; - // WordPress core is never checked: its own release notes say which PHP versions it supports. - $scope = $this->wp_layout ? ' WordPress core is not checked: make sure your WordPress version supports this PHP version.' : ''; + // Core's files are never scanned; its version is compared with the PHP versions WordPress says it supports. + $scope = $this->wp_layout ? ' WordPress core is checked only by its version, against the PHP versions WordPress lists as supported.' : ''; yield "This is static analysis with PHPCompatibility$tool.$scope Its coverage isn't complete and it can't see breakage that only shows at runtime."; } diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index efd7e466..95e1269f 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -144,6 +144,34 @@ public static function index_loader( $source ) { return [ 'sub' => trim( dirname( $inc['path'] ), '/.' ) ]; } + /** + * WordPress's version from wp-includes/version.php: exactly one `$wp_version = '';` statement. + * + * @param string $source PHP source. + * + * @return array|string [ 'version' => …, 'branch' => major.minor ], or why it can't be read. + */ + public static function wp_version( $source ) { + $t = self::tokens( $source ); + if ( is_string( $t ) ) { + return $t; + } + $found = null; + foreach ( $t as $i => $token ) { + if ( T_VARIABLE !== $token[0] || '$wp_version' !== $token[1] ) { + continue; + } + $ok = null === $found && isset( $t[ $i + 3 ] ) && '=' === $t[ $i + 1 ][0] && T_CONSTANT_ENCAPSED_STRING === $t[ $i + 2 ][0] && ';' === $t[ $i + 3 ][0] && ( 0 === $i || ';' === $t[ $i - 1 ][0] ); + $value = $ok ? self::literal( $t[ $i + 2 ][1] ) : null; + if ( null === $value || ! preg_match( '/^(\d+)\.(\d+)(?:\.\d+)*(?:-[A-Za-z0-9.]+)?$/D', $value, $m ) ) { + return 'line ' . $token[2] . ' is not a single $wp_version = \'\'; statement'; + } + $found = [ 'version' => $value, 'branch' => (int) $m[1] . '.' . (int) $m[2] ]; + } + + return null === $found ? 'it does not set $wp_version' : $found; + } + /** * Checks a wp-config.php (or a file it loads) statement by statement against the config grammar. * diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 1c6f7178..25310ac2 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3335,7 +3335,7 @@ protected function delete_stopped( $site ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, everything under htdocs. A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: safe to upgrade (every file checked, no errors), not safe (at least one error), or can't confirm (some files couldn't be checked). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, everything under htdocs. A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked, or WordPress hasn't declared support for the target). It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions. Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * From 8c8d906d8ec4f3be309266d6072ea03647875e53 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 13:56:07 +0530 Subject: [PATCH 26/53] fix(site): make php-compat's report match its verdict and accept CI/CD release layouts - The --output report carries stdout's gated verdict and fields (checked, not_checked, wordpress), with the full not_checked list and every component. stdout stays fixed-size: at most 10 not_checked entries of 256 characters each, plus not_checked_more. - not_checked lists only what the scanner reported; core's note is wordpress.core_files_checked. - A WordPress newer than the support table counts as supporting what the newest listed version supports, and says so (wordpress.table_newest). An unknown branch inside the table is can't confirm. A target below a branch's lowest PHP names that PHP instead of a WordPress to update to. The core reason is printed with errors too. - Nightly, dev and RC version strings (7.3-alpha-65762-src, 7.2-RC3-65000) are read. - A link to a config file already read and validated (releases/wp-config.php -> ../wp-config.php) is not code outside WordPress. Old releases are out of scope when nginx serves current/; when nginx serves the directory holding releases/, they are refused with a hint to use --public-dir=current. - Directory constants written as container paths (/var/www/htdocs/wp-content) compare equal to their defaults. - The site-files walk stops at the first finding in a directory too, so a nested install or a served old release is never reported as something else. - The New Relic socket mount must be EE's local volume with no options. checked and wordpress can't come from the scanner. --- features/COVERAGE.md | 5 +- features/php-compat.feature | 14 +- src/helper/Site_PHP_Compat.php | 176 ++++++++++++++++++++------ src/helper/Site_PHP_Compat_Layout.php | 8 +- src/helper/class-ee-site.php | 6 +- 5 files changed, 159 insertions(+), 50 deletions(-) diff --git a/features/COVERAGE.md b/features/COVERAGE.md index 977151cc..1498b5d0 100644 --- a/features/COVERAGE.md +++ b/features/COVERAGE.md @@ -225,8 +225,9 @@ Every scan scenario needs core's `img-versions.json` to pin `easyengine/compat-s | Item | Status | Scenarios | |---|---|---| | `--format=json` on a wp and a php site: one-line summary, exit 0, no findings | covered (wp part @wp) | compat: The JSON summary of a WordPress site; The JSON summary of a php site | -| Table: verdict line first ("Not safe", "Safe"), every error with file, line and sniff, static-analysis line last | covered ("Not safe" part @wp) | compat: The table starts with the verdict line...; The table of a php site without errors says it is safe | -| "Can't confirm" verdict line | not covered | needs a file uid 33 can't read; the scanner side is in the dockerfiles fixture test | +| Table: verdict line first ("Not safe", or "No PHP problems found in …" scoped to what was checked; never "Safe to upgrade"), every error with file, line and sniff, static-analysis line last | covered ("Not safe" part @wp) | compat: The table starts with the verdict line...; The table of a php site without errors says what was checked, never "safe" | +| WordPress core gate: version.php read, too-old core is "Not safe", undeclared PHP (8.6) is "Can't confirm", JSON `wordpress` object | covered @wp | compat: A WordPress site's verdict covers what was checked, and core by its version | +| "Can't confirm" verdict line from unchecked files | not covered | needs a file uid 33 can't read; the scanner side is in the dockerfiles fixture test | | `--output`: root-owned 0600, replaces an existing file, same fields as the summary, `report`/`report_bytes` | covered | compat: --output writes a root-owned 0600 report... | | No finding text in ee.log | covered | compat: ee.log holds no finding text after a check with findings | | html site refused, bad or missing `--php` (dispatcher and command checks), flags `--cancel` doesn't take | covered | compat: An html site is refused; A bad --php value, a missing one, or a flag --cancel does not take is rejected (outline) | diff --git a/features/php-compat.feature b/features/php-compat.feature index c4679ef2..7e54f3a2 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -48,12 +48,16 @@ Feature: Check the PHP compatibility of a site's code Scenario: A WordPress site's verdict covers what was checked, and core by its version Given the compat-scanner image is available And the site "bh-site-command-193.test" exists, created with "--type=wp" + # Pinned to a branch in the check's table, whatever WordPress the site got. + When I run 'sed -i "s#^.wp_version = .*#\$wp_version = \"6.8.3\";#" {SITES_DIR}/bh-site-command-193.test/app/htdocs/wp-includes/version.php' + Then the command should succeed When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4 --format=json' Then the command should succeed And the JSON field "status" in STDOUT should be "ok" And the JSON field "wordpress.supports" in STDOUT should be "true" And the JSON field "checked.dir" in STDOUT should contain "bh-site-command-193.test/app/htdocs" - And STDOUT should contain "only its version is checked" + And the JSON field "wordpress.core_files_checked" in STDOUT should be "false" + And STDOUT should not contain "only its version is checked" When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4' Then the command should succeed And STDOUT should not contain "Safe to upgrade" @@ -61,14 +65,20 @@ Feature: Check the PHP compatibility of a site's code # A WordPress too old for the target is never fine, whatever the scan finds. When I run 'sed -i "s#^.wp_version = .*#\$wp_version = \"6.1.1\";#" {SITES_DIR}/bh-site-command-193.test/app/htdocs/wp-includes/version.php' Then the command should succeed - When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4 --format=json' + When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4 --format=json --output={TMP}/report-193.json' Then the command should succeed And the JSON field "safe_to_upgrade" in STDOUT should be "false" And the JSON field "wordpress.version" in STDOUT should be "6.1.1" + And the JSON file "{TMP}/report-193.json" should hold every field of the STDOUT JSON except "report,report_bytes" When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.4' Then the command should succeed And STDOUT should contain "WordPress 6.1 doesn't support PHP 8.4; update WordPress to at least 6.7 first" # A PHP version WordPress hasn't declared support for can't be confirmed. + When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.6 --format=json --output={TMP}/report-193.json' + Then the command should succeed + And the JSON field "wordpress.supports" in STDOUT should be null + And the JSON field "safe_to_upgrade" in STDOUT should be null + And the JSON file "{TMP}/report-193.json" should hold every field of the STDOUT JSON except "report,report_bytes" When I run 'bin/ee site php-compat bh-site-command-193.test --php=8.6' Then the command should succeed And STDOUT should contain "WordPress hasn't declared support for PHP 8.6 yet" diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index e68b64a4..ce70b057 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -45,7 +45,11 @@ class Site_PHP_Compat { const SUMMARY_INTS = [ 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'duration_s' ]; const ESTIMATE_INTS = [ 'php_files', 'php_bytes', 'components', 'estimated_seconds', 'estimated_seconds_low', 'estimated_seconds_high' ]; // --format=json prints only the documented keys (INTERFACE.md), in this order. - const SUMMARY_KEYS = [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'checked', 'not_checked', 'wordpress', 'duration_s', 'tool' ]; + const SUMMARY_KEYS = [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'checked', 'not_checked', 'not_checked_more', 'wordpress', 'duration_s', 'tool' ]; + + // stdout stays fixed-size: at most this many not_checked entries, each string at most NOT_CHECKED_CHARS characters. + const NOT_CHECKED_STDOUT = 10; + const NOT_CHECKED_CHARS = 256; const TOOL_KEYS = [ 'phpcs', 'phpcompatibility', 'phpcompatibility_wp', 'image' ]; const ESTIMATE_KEYS = [ 'v', 'status', 'estimate', 'site', 'target', 'php_files', 'php_bytes', 'components', 'estimated_seconds', 'estimated_seconds_low', 'estimated_seconds_high', 'inputs' ]; const INPUT_KEYS = [ 'calibration_bytes', 'calibration_seconds', 'startup_seconds', 'bytes_per_second', 'batches', 'seconds_per_batch', 'cpus', 'load_average_1m', 'low_factor', 'high_factor' ]; @@ -61,7 +65,6 @@ class Site_PHP_Compat { const CONFIG_MAX = 1048576; // Size cap for PHP files read on the host (wp-config.php and what it includes, index.php): tokens take ~500x the bytes. const PHP_SOURCE_MAX = 262144; - // Constants that move the code WordPress loads away from /wp-content. /** * PHP versions each WordPress branch supports, [ lowest, highest ], from WordPress's own "PHP Compatibility and WordPress * Versions" page (https://make.wordpress.org/core/handbook/references/php-compatibility-and-wordpress-versions/, last @@ -509,8 +512,11 @@ protected function run_scan( $site_data, $timeout, $output ) { return $this->cancelled(); } - $summary = $this->summary( $this->scoped( $doc, $report ) ); + $full = $this->summary( $this->scoped( $doc, $report ) ); + $summary = self::capped( $full ); if ( null !== $output ) { + // The report says what stdout says (gated verdict, scoped fields), with the full not_checked list and the components. + $raw = self::encode( $full + [ 'components' => $report['components'] ] ); if ( ! $this->write_report( $output, $raw ) ) { return $this->doc( 'tool_error', "could not write the report to $output" ); } @@ -1140,6 +1146,14 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { 'file' => $file['real'], 'boot' => true, 'resolve' => $resolve, + // Container (/var/www/…) and host paths, links resolved, so a default written either way compares equal. + 'canon' => function ( $path ) use ( $code ) { + if ( 0 === strpos( $path . '/', '/var/www/' ) ) { + $path = $code . substr( $path, strlen( '/var/www' ) ); + } + $real = 0 === strpos( $path . '/', $code . '/' ) ? self::resolve_in( $code, ltrim( substr( $path, strlen( $code ) ), '/' ) ) : null; + return null === $real ? $path : $real; + }, ] ); if ( null !== $error ) { @@ -1167,9 +1181,11 @@ protected function app_walk( $code, $rel, $root, $abspath, array $allowed ) { $top = (string) self::resolve_in( $code, $rel ); // The live release: the WordPress root or its ancestor directly in a releases/ directory. $releases = null; + $live = null; for ( $dir = $abspath; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { if ( 'releases' === basename( dirname( $dir ) ) ) { $releases = dirname( $dir ); + $live = $dir; break; } } @@ -1177,7 +1193,7 @@ protected function app_walk( $code, $rel, $root, $abspath, array $allowed ) { $found = null; $error = $this->walk_tree( $code, - function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $releases, &$user_ini, &$found ) { + function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $releases, $live, &$user_ini, &$found ) { $inside = null !== $abspath && 0 === strpos( $path . '/', $abspath . '/' ); if ( '.user.ini' === $name ) { $user_ini[] = [ $path, $type ]; @@ -1188,33 +1204,44 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ return false; } $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); + // A link to a file already read and validated (releases/wp-config.php -> ../wp-config.php): no other code. + if ( null !== $real && in_array( $real, $allowed, true ) ) { + return false; + } if ( $inside ) { if ( null !== $real && 0 === strpos( dirname( $path ) . '/', $real . '/' ) ) { $found = "$path links to its own ancestor " . $real; - return true; + return 'stop'; } return false; } $found = "$path is a link outside the WordPress directory"; - return true; + return 'stop'; } if ( 'dir' === $type ) { if ( $inside ) { if ( $path !== $abspath && ( file_exists( "$path/wp-settings.php" ) || is_dir( "$path/wp-includes" ) ) ) { $found = "$path holds another WordPress install"; - return true; + return 'stop'; } return true; } if ( '.' === $name[0] ) { return false; } - // Old releases beside the live one, when nginx doesn't serve them. - return ! ( null !== $releases && dirname( $path ) === $releases && 0 !== strpos( $path . '/', $top . '/' ) ); + // Old releases beside the live one are out of scope only when nginx doesn't serve them (root at current/ or deeper). + if ( null !== $releases && dirname( $path ) === $releases && $path !== $live ) { + if ( 0 === strpos( $path . '/', $top . '/' ) ) { + $found = "!nginx serves $top, which also exposes old releases (" . substr( $path, strlen( $top ) + 1 ) . "); set the site's public dir to current (`--public-dir=current`) or remove old releases"; + return 'stop'; + } + return false; + } + return true; } if ( ! $inside && self::php_name( $name ) && ! in_array( $path, $allowed, true ) ) { $found = "$path is PHP outside the WordPress directory" . ( null === $abspath ? ' (there is no WordPress this check recognises)' : '' ); - return true; + return 'stop'; } return false; } @@ -1223,12 +1250,16 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ return "can't look through the site's files: $error"; } - return null === $found ? $user_ini : self::clean( $found ) . '; this check can\'t scan that layout'; + if ( null === $found ) { + return $user_ini; + } + + return '!' === $found[0] ? self::clean( substr( $found, 1 ) ) : self::clean( $found ) . '; this check can\'t scan that layout'; } /** * Walks a directory tree without following links, bounded in time: $visit( $path, $name, file|dir|link|other ) returns - * true to stop, and for a directory whether to go into it. + * 'stop' to stop (true also stops for a non-directory), and for a directory whether to go into it. * * @param string $top Real directory. * @param callable $visit See above. @@ -1263,10 +1294,11 @@ protected function walk_tree( $top, callable $visit ) { $mode = false === $stat ? 0 : $stat['mode'] & 0170000; $type = 0120000 === $mode ? 'link' : ( 0040000 === $mode ? 'dir' : ( 0100000 === $mode ? 'file' : 'other' ) ); $go = $visit( $path, $name, $type ); + if ( 'stop' === $go || ( 'dir' !== $type && true === $go ) ) { + return null; + } if ( 'dir' === $type && $go ) { $todo[] = $path; - } elseif ( 'dir' !== $type && true === $go ) { - return null; } } } @@ -1531,7 +1563,7 @@ protected function extra_mounts( $site_data, $code ) { continue; } // The New Relic daemon's socket: EE's global volume, never code. - if ( '/run/newrelic' === $dst && isset( $mount['Type'], $mount['Name'] ) && 'volume' === $mount['Type'] && ( defined( 'GLOBAL_NEWRELIC_DAEMON' ) ? GLOBAL_NEWRELIC_DAEMON : 'global-newrelic-daemon' ) . '_newrelic_sock' === $mount['Name'] ) { + if ( '/run/newrelic' === $dst && isset( $mount['Type'], $mount['Name'] ) && 'volume' === $mount['Type'] && ( defined( 'GLOBAL_NEWRELIC_DAEMON' ) ? GLOBAL_NEWRELIC_DAEMON : 'global-newrelic-daemon' ) . '_newrelic_sock' === $mount['Name'] && $this->ee_plain_volume( $mount['Name'] ) ) { continue; } if ( isset( $known[ $dst ] ) ) { @@ -1562,6 +1594,22 @@ protected function extra_mounts( $site_data, $code ) { return $this->extra_mounts; } + /** + * Whether a named volume is a plain local volume EE made: its EasyEngine label, and no options (a bind or a remote + * filesystem under the same name would have them). + * + * @param string $name Volume name. + * + * @return bool + */ + protected function ee_plain_volume( $name ) { + $run = $this->docker( [ 'docker', 'volume', 'inspect', '--format', '{{json .}}', $name ], 60 ); + $info = 0 === $run['code'] ? json_decode( trim( $run['stdout'] ), true ) : null; + + return is_array( $info ) && isset( $info['Labels']['org.label-schema.vendor'] ) && 'EasyEngine' === $info['Labels']['org.label-schema.vendor'] + && ( ! isset( $info['Driver'] ) || 'local' === $info['Driver'] ) && empty( $info['Options'] ); + } + /** * The php container must run as EE starts it: the image's command and entrypoint, and the image's environment plus * only EE's own variables (so no PHPRC or PHP_INI_SCAN_DIR loads other PHP settings). @@ -2657,9 +2705,11 @@ protected function output_dir_unchanged( $path ) { * @param array $doc Validated scanner summary. * @param array $report Validated report. * - * @return array $doc with safe_to_upgrade, checked, not_checked and (WordPress) wordpress set. + * @return array $doc with safe_to_upgrade, checked, not_checked (the scanner's entries) and (WordPress) wordpress set. */ protected function scoped( array $doc, array $report ) { + // Only EE sets these; the scanner can't. + unset( $doc['checked'], $doc['not_checked'], $doc['wordpress'] ); $doc['checked'] = [ 'dir' => self::clean( (string) $this->looked_in ), 'components' => $doc['components_checked'], @@ -2677,20 +2727,17 @@ function ( $entry ) { }, $report['not_checked'] ); - $core = null; + $doc['not_checked_more'] = 0; + $core = null; if ( $this->wp_layout && null !== $this->wp_version ) { - $doc['not_checked'][] = [ - 'type' => 'core', - 'slug' => 'wordpress', - 'branch' => null, - 'file' => 'wp-admin, wp-includes and the core files beside them', - 'reason' => 'only its version is checked', - ]; + // Core's files are never scanned; not_checked stays the scanner's own list (its type and reason values are a fixed set). $core = self::wp_supports( $this->wp_version['branch'], $this->target ); $doc['wordpress'] = [ - 'version' => self::clean( $this->wp_version['version'] ), - 'supports' => $core['supports'], - 'minimum' => $core['minimum'], + 'version' => self::clean( $this->wp_version['version'] ), + 'supports' => $core['supports'], + 'minimum' => $core['minimum'], + 'table_newest' => $core['table_newest'], + 'core_files_checked' => false, ]; } if ( $doc['errors'] > 0 || ( null !== $core && false === $core['supports'] ) ) { @@ -2704,6 +2751,35 @@ function ( $entry ) { return $doc; } + /** + * The summary as stdout prints it: fixed-size, so not_checked keeps its first NOT_CHECKED_STDOUT entries, each string + * cut to NOT_CHECKED_CHARS characters, and not_checked_more counts the rest (the --output report has them all). + * + * @param array $summary Full summary. + * + * @return array + */ + public static function capped( array $summary ) { + if ( ! isset( $summary['not_checked'] ) ) { + return $summary; + } + $all = $summary['not_checked']; + $summary['not_checked'] = array_map( + function ( $entry ) { + foreach ( $entry as $key => $value ) { + if ( is_string( $value ) && preg_match( '/^.{' . self::NOT_CHECKED_CHARS . '}/us', $value, $m ) && $m[0] !== $value ) { + $entry[ $key ] = $m[0]; + } + } + return $entry; + }, + array_slice( $all, 0, self::NOT_CHECKED_STDOUT ) + ); + $summary['not_checked_more'] = max( 0, count( $all ) - self::NOT_CHECKED_STDOUT ); + + return $summary; + } + /** * Whether a WordPress branch supports a PHP version, by WP_PHP_SUPPORT. * @@ -2711,7 +2787,8 @@ function ( $entry ) { * @param string $target PHP major.minor. * * @return array supports (true, false, or null when WordPress hasn't said), minimum (lowest WordPress branch supporting - * the target, or null) and why (the verdict's reason, null when supported). + * the target, or null), table_newest (the newest row, when the branch is newer than the table) and why + * (the reason to print, or null). */ public static function wp_supports( $branch, $target ) { $minimum = null; @@ -2722,27 +2799,44 @@ public static function wp_supports( $branch, $target ) { } $highest = version_compare( $high, $highest, '>' ) ? $high : $highest; } + $result = function ( $supports, $why, $min = null, $newest = null ) { + return [ 'supports' => $supports, 'minimum' => $min, 'table_newest' => $newest, 'why' => $why ]; + }; if ( version_compare( $target, $highest, '>' ) ) { - return [ 'supports' => null, 'minimum' => null, 'why' => "WordPress hasn't declared support for PHP $target yet" ]; + return $result( null, "WordPress hasn't declared support for PHP $target yet" ); } - $newest = (string) array_keys( self::WP_PHP_SUPPORT )[0]; + $branches = array_map( 'strval', array_keys( self::WP_PHP_SUPPORT ) ); + $newest = $branches[0]; + $oldest = end( $branches ); if ( version_compare( $branch, $newest, '>' ) ) { - return [ 'supports' => null, 'minimum' => $minimum, 'why' => "this check doesn't know which PHP versions WordPress $branch supports" ]; - } - if ( isset( self::WP_PHP_SUPPORT[ $branch ] ) ) { - list( $low, $high ) = self::WP_PHP_SUPPORT[ $branch ]; + // WordPress doesn't drop a newer PHP within its support window: a newer branch supports what the newest row does. + list( $low, $high ) = self::WP_PHP_SUPPORT[ $newest ]; if ( version_compare( $target, $low, '>=' ) && version_compare( $target, $high, '<=' ) ) { - return [ 'supports' => true, 'minimum' => $minimum, 'why' => null ]; + return $result( true, "WordPress $branch is newer than this check's table; WordPress $newest supports PHP $target", $minimum, $newest ); } - if ( version_compare( $target, $low, '<' ) ) { - return [ 'supports' => false, 'minimum' => $minimum, 'why' => "WordPress $branch doesn't support PHP $target; it needs PHP $low or newer" ]; + return $result( null, "WordPress $branch is newer than this check's table, and WordPress $newest doesn't support PHP $target", $minimum, $newest ); + } + if ( ! isset( self::WP_PHP_SUPPORT[ $branch ] ) ) { + // Older than every row: it can't support a PHP newer than the oldest row does. + if ( version_compare( $branch, $oldest, '<' ) && version_compare( $target, self::WP_PHP_SUPPORT[ $oldest ][1], '>' ) ) { + $why = "WordPress $branch doesn't support PHP $target"; + return $result( false, null === $minimum ? $why : "$why; update WordPress to at least $minimum first", $minimum ); } + return $result( null, "this check doesn't know which PHP versions WordPress $branch supports", $minimum ); + } + list( $low, $high ) = self::WP_PHP_SUPPORT[ $branch ]; + if ( version_compare( $target, $low, '<' ) ) { + return $result( false, "WordPress $branch needs PHP $low or newer, so it doesn't support PHP $target" ); + } + if ( version_compare( $target, $high, '<=' ) ) { + return $result( true, null, $minimum ); } $why = "WordPress $branch doesn't support PHP $target"; - return [ 'supports' => false, 'minimum' => $minimum, 'why' => null === $minimum ? $why : "$why; update WordPress to at least $minimum first" ]; + return $result( false, null === $minimum ? $why : "$why; update WordPress to at least $minimum first", $minimum ); } + /** * Container scan summary to print: findings never, `site` always. * @@ -2917,11 +3011,11 @@ protected function table_lines( array $doc, $report ) { $tail = sprintf( '%s. %s checked.', self::count_of( $doc['warnings'], 'warning' ), self::count_of( $doc['files_checked'], 'file' ) ); $core = isset( $doc['wordpress'] ) && null !== $this->wp_version ? self::wp_supports( $this->wp_version['branch'], $target ) : null; - $why = null === $core || true === $core['supports'] ? null : $core['why']; + $why = null === $core ? null : $core['why']; if ( false === $doc['safe_to_upgrade'] ) { if ( $doc['errors'] > 0 ) { yield sprintf( 'Not safe to upgrade %s to PHP %s: %s in %s. %s', $site, $target, self::count_of( $doc['errors'], 'error' ), self::count_of( $doc['components_with_errors'], 'component' ), $tail ); - if ( null !== $why && false === $core['supports'] ) { + if ( null !== $why ) { yield ucfirst( $why ) . '.'; } } else { @@ -2933,7 +3027,7 @@ protected function table_lines( array $doc, $report ) { $found = 0 === $doc['warnings'] ? 'problems' : 'errors'; $line = sprintf( 'No PHP %s %s found in the %s checked in %s (%s in %s).', $target, $found, self::count_of( $doc['files_checked'], 'file' ), $site, $what, self::clean( (string) $this->looked_in ) ); if ( null !== $core ) { - $line .= sprintf( ' WordPress %s supports PHP %s.', $this->wp_version['branch'], $target ); + $line .= ' ' . ( null === $why ? sprintf( 'WordPress %s supports PHP %s', $this->wp_version['branch'], $target ) : ucfirst( $why ) ) . '.'; } yield $line . ( $doc['warnings'] > 0 ? ' ' . self::count_of( $doc['warnings'], 'warning' ) . '.' : '' ); } else { diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index 95e1269f..1ba901ea 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -163,7 +163,8 @@ public static function wp_version( $source ) { } $ok = null === $found && isset( $t[ $i + 3 ] ) && '=' === $t[ $i + 1 ][0] && T_CONSTANT_ENCAPSED_STRING === $t[ $i + 2 ][0] && ';' === $t[ $i + 3 ][0] && ( 0 === $i || ';' === $t[ $i - 1 ][0] ); $value = $ok ? self::literal( $t[ $i + 2 ][1] ) : null; - if ( null === $value || ! preg_match( '/^(\d+)\.(\d+)(?:\.\d+)*(?:-[A-Za-z0-9.]+)?$/D', $value, $m ) ) { + // Releases, RCs, betas, nightlies and dev builds: 7.2-RC3-65000, 7.3-alpha-65762-src. + if ( null === $value || strlen( $value ) > 64 || ! preg_match( '/^(\d+)\.(\d+)(?:\.\d+)*(?:-[A-Za-z0-9.]+)*$/D', $value, $m ) ) { return 'line ' . $token[2] . ' is not a single $wp_version = \'\'; statement'; } $found = [ 'version' => $value, 'branch' => (int) $m[1] . '.' . (int) $m[2] ]; @@ -399,7 +400,10 @@ private static function define( array $t, array $args, array $env, array &$state if ( null === $path ) { return "can't resolve $name in {$env['file']} (line {$t[ $at ][2]}); this check only accepts its default, $default"; } - if ( $path !== $default ) { + $canon = isset( $env['canon'] ) ? $env['canon'] : function ( $value ) { + return $value; + }; + if ( call_user_func( $canon, $path ) !== call_user_func( $canon, $default ) ) { return "{$env['file']} sets $name to $path (line {$t[ $at ][2]}); this check only accepts its default, $default"; } if ( 'WP_CONTENT_DIR' === $name ) { diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 25310ac2..43cd46df 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3335,7 +3335,7 @@ protected function delete_stopped( $site ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, everything under htdocs. A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked, or WordPress hasn't declared support for the target). It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions. Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, everything under htdocs. A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked, or WordPress hasn't declared support for the target). It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * @@ -3366,7 +3366,7 @@ protected function delete_stopped( $site ) { * : Print how long a check of this site should take on this server, without checking anything. * * [--format=] - * : Render output in a particular format. json prints the verdict and the counts, never the findings. + * : Render output in a particular format. json prints the verdict, the counts, what was checked and what wasn't (and for WordPress its version and whether it supports the target), never the findings. * --- * default: table * options: @@ -3375,7 +3375,7 @@ protected function delete_stopped( $site ) { * --- * * [--output=] - * : Also write the full report, with every error and warning, as JSON to this absolute path. The file is owned by root with mode 0600 and replaces an existing one. It is written only when the check finishes with a result (status ok); otherwise an existing file is left as it was. Its directory and every parent must be owned by root and not writable by other users (a sticky directory such as /tmp is fine). Not with --estimate. + * : Also write the full report, with every error and warning, as JSON to this absolute path: the JSON summary's fields (the same verdict) plus every component and its findings. The file is owned by root with mode 0600 and replaces an existing one. It is written only when the check finishes with a result (status ok); otherwise an existing file is left as it was. Its directory and every parent must be owned by root and not writable by other users (a sticky directory such as /tmp is fine). Not with --estimate. * * [--timeout=] * : Time limit for the scan itself, in seconds. A scan that hits it reports tool_error and no verdict. Pulling the scanner image on first use isn't counted. Default: 7200. Not with --estimate. From 19b012d3a3a23705c49d09857b086b19b873bcd1 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:08:06 +0530 Subject: [PATCH 27/53] fix(site): close php-compat's second-review gaps in paths, links and the support table - A directory constant with a `..` segment is refused in every spelling: PHP follows each link before `..`, so a textual collapse could call another directory the default. A container path whose tail doesn't exist yet (mu-plugins) is compared through its longest existing prefix. - A link inside the WordPress root to another install (releases/2/old -> ../1) is refused, and a WordPress root's own index.php that links into another directory says so. - A report json_encode() can't write is tool_error, and an existing --output file is left as it was. - A WordPress newer than the support table counts as supporting a target only within the newest row's range and in the upgrade direction (at or above the PHP the site runs now); otherwise it is can't confirm, with no minimum below the newest row's floor. - The served-old-releases hint says to recreate (or clone) the site with --public-dir=current. --- src/helper/Site_PHP_Compat.php | 58 ++++++++++++++++++++++----- src/helper/Site_PHP_Compat_Layout.php | 9 ++++- 2 files changed, 55 insertions(+), 12 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index ce70b057..d2c05795 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -149,6 +149,9 @@ class Site_PHP_Compat { /** @var array|null WordPress's version ( version, branch ) read from the scanned root's wp-includes/version.php. */ protected $wp_version; + /** @var string|null The PHP version the site runs now (its record), major.minor; null when unknown. */ + protected $current_php; + /** @var string|null Cancel request file a scan watches once it holds the site lock. */ protected $cancel_marker; @@ -517,6 +520,10 @@ protected function run_scan( $site_data, $timeout, $output ) { if ( null !== $output ) { // The report says what stdout says (gated verdict, scoped fields), with the full not_checked list and the components. $raw = self::encode( $full + [ 'components' => $report['components'] ] ); + // A value json_encode() refuses (INF in a key EE doesn't know): no report rather than an empty one. + if ( '' === $raw ) { + return $this->doc( 'tool_error', 'could not encode the report' ); + } if ( ! $this->write_report( $output, $raw ) ) { return $this->doc( 'tool_error', "could not write the report to $output" ); } @@ -1002,7 +1009,8 @@ function ( $path, $name, $type ) use ( &$user_ini ) { if ( null !== $index ) { $allowed[] = $index; } - $this->wp_version = null; + $this->wp_version = null; + $this->current_php = isset( $site_data->php_version ) && preg_match( '/^\d+\.\d+$/D', (string) $site_data->php_version ) ? (string) $site_data->php_version : null; if ( null !== $layout['abspath'] ) { // Core isn't scanned: its version decides whether it supports the target PHP. $file = $this->site_file( $code, substr( $layout['abspath'], strlen( $code ) + 1 ) . '/wp-includes/version.php', self::PHP_SOURCE_MAX ); @@ -1085,7 +1093,11 @@ protected function wp_layout_of( $code, $rel, $app ) { return "WordPress in $app$root resolves to " . self::clean( str_replace( "$code/", $app, $abspath ) ) . ", outside the directory nginx serves ($app$rel)"; } if ( $root !== $rel ) { + // Rule (b) for the WordPress root's own index.php too (a2, a3); in a1 it is the served one, checked above. $own = $this->site_file( $code, "$root/index.php", self::PHP_SOURCE_MAX ); + if ( 'ok' === $own['state'] && dirname( $own['real'] ) !== $abspath ) { + return "$app$root/index.php is a link to " . self::clean( str_replace( "$code/", $app, $own['real'] ) ) . ', so it loads WordPress from another directory'; + } $own = 'ok' === $own['state'] ? Site_PHP_Compat_Layout::index_loader( $own['source'] ) : 'it ' . ( 'bad' === $own['state'] ? $own['detail'] : 'is missing' ); if ( is_string( $own ) || '' !== $own['sub'] ) { return "$app$root/index.php isn't WordPress's own index.php (" . self::clean( is_string( $own ) ? $own : 'it loads WordPress from elsewhere' ) . ')'; @@ -1151,8 +1163,19 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { if ( 0 === strpos( $path . '/', '/var/www/' ) ) { $path = $code . substr( $path, strlen( '/var/www' ) ); } - $real = 0 === strpos( $path . '/', $code . '/' ) ? self::resolve_in( $code, ltrim( substr( $path, strlen( $code ) ), '/' ) ) : null; - return null === $real ? $path : $real; + if ( 0 !== strpos( $path . '/', $code . '/' ) ) { + return $path; + } + // The longest prefix that exists, resolved, then the rest (mu-plugins may not exist yet). + $rest = ''; + for ( $prefix = $path; strlen( $prefix ) > strlen( $code ); $prefix = dirname( $prefix ) ) { + $real = self::resolve_in( $code, ltrim( substr( $prefix, strlen( $code ) ), '/' ) ); + if ( null !== $real ) { + return $real . $rest; + } + $rest = '/' . basename( $prefix ) . $rest; + } + return $path; }, ] ); @@ -1213,6 +1236,10 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ $found = "$path links to its own ancestor " . $real; return 'stop'; } + if ( null !== $real && is_dir( $real ) && ( file_exists( "$real/wp-settings.php" ) || is_dir( "$real/wp-includes" ) ) ) { + $found = "$path links to another WordPress install ($real)"; + return 'stop'; + } return false; } $found = "$path is a link outside the WordPress directory"; @@ -1232,7 +1259,7 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ // Old releases beside the live one are out of scope only when nginx doesn't serve them (root at current/ or deeper). if ( null !== $releases && dirname( $path ) === $releases && $path !== $live ) { if ( 0 === strpos( $path . '/', $top . '/' ) ) { - $found = "!nginx serves $top, which also exposes old releases (" . substr( $path, strlen( $top ) + 1 ) . "); set the site's public dir to current (`--public-dir=current`) or remove old releases"; + $found = "!nginx serves $top, which also exposes old releases (" . substr( $path, strlen( $top ) + 1 ) . "); recreate (or clone) the site with `--public-dir=current`, or remove old releases"; return 'stop'; } return false; @@ -2731,7 +2758,7 @@ function ( $entry ) { $core = null; if ( $this->wp_layout && null !== $this->wp_version ) { // Core's files are never scanned; not_checked stays the scanner's own list (its type and reason values are a fixed set). - $core = self::wp_supports( $this->wp_version['branch'], $this->target ); + $core = self::wp_supports( $this->wp_version['branch'], $this->target, $this->current_php ); $doc['wordpress'] = [ 'version' => self::clean( $this->wp_version['version'] ), 'supports' => $core['supports'], @@ -2784,13 +2811,14 @@ function ( $entry ) { * Whether a WordPress branch supports a PHP version, by WP_PHP_SUPPORT. * * @param string $branch WordPress major.minor. - * @param string $target PHP major.minor. + * @param string $target PHP major.minor. + * @param string|null $current PHP the site runs now, major.minor (only used for a branch newer than the table). * * @return array supports (true, false, or null when WordPress hasn't said), minimum (lowest WordPress branch supporting * the target, or null), table_newest (the newest row, when the branch is newer than the table) and why * (the reason to print, or null). */ - public static function wp_supports( $branch, $target ) { + public static function wp_supports( $branch, $target, $current = null ) { $minimum = null; $highest = '0'; foreach ( self::WP_PHP_SUPPORT as $wp => list( $low, $high ) ) { @@ -2809,12 +2837,17 @@ public static function wp_supports( $branch, $target ) { $newest = $branches[0]; $oldest = end( $branches ); if ( version_compare( $branch, $newest, '>' ) ) { - // WordPress doesn't drop a newer PHP within its support window: a newer branch supports what the newest row does. + // WordPress doesn't drop a newer PHP within its support window, but may raise its floor: a newer branch supports + // what the newest row does only when moving up from the PHP the site runs now. list( $low, $high ) = self::WP_PHP_SUPPORT[ $newest ]; if ( version_compare( $target, $low, '>=' ) && version_compare( $target, $high, '<=' ) ) { - return $result( true, "WordPress $branch is newer than this check's table; WordPress $newest supports PHP $target", $minimum, $newest ); + if ( null !== $current && version_compare( $target, $current, '>=' ) ) { + return $result( true, "WordPress $branch is newer than this check's table; WordPress $newest supports PHP $target", $minimum, $newest ); + } + return $result( null, "WordPress $branch is newer than this check's table, which can't tell whether it still supports PHP $target" . ( null === $current ? '' : ", below the PHP $current the site runs now" ), $minimum, $newest ); } - return $result( null, "WordPress $branch is newer than this check's table, and WordPress $newest doesn't support PHP $target", $minimum, $newest ); + // Below the newest row's floor nothing says a newer WordPress still runs it: no minimum to name. + return $result( null, "WordPress $branch is newer than this check's table, and WordPress $newest doesn't support PHP $target", version_compare( $target, $low, '<' ) ? null : $minimum, $newest ); } if ( ! isset( self::WP_PHP_SUPPORT[ $branch ] ) ) { // Older than every row: it can't support a PHP newer than the oldest row does. @@ -3010,7 +3043,7 @@ protected function table_lines( array $doc, $report ) { } $tail = sprintf( '%s. %s checked.', self::count_of( $doc['warnings'], 'warning' ), self::count_of( $doc['files_checked'], 'file' ) ); - $core = isset( $doc['wordpress'] ) && null !== $this->wp_version ? self::wp_supports( $this->wp_version['branch'], $target ) : null; + $core = isset( $doc['wordpress'] ) && null !== $this->wp_version ? self::wp_supports( $this->wp_version['branch'], $target, $this->current_php ) : null; $why = null === $core ? null : $core['why']; if ( false === $doc['safe_to_upgrade'] ) { if ( $doc['errors'] > 0 ) { @@ -3262,6 +3295,9 @@ public static function clean( $text ) { */ public static function encode( array $doc ) { $json = json_encode( $doc, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | self::JSON_UTF8 ); + if ( false === $json ) { + return ''; + } return preg_replace_callback( '/[' . self::UNSAFE_CHARS . ']/u', diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index 1ba901ea..4c97a4f5 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -397,6 +397,9 @@ private static function define( array $t, array $args, array $env, array &$state $name = $upper; $path = self::path_value( $t, $args[1][0], end( $args[1] ) + 1, $env, $state['content'] ); $default = $env['root'] . '/' . self::DIR_DEFAULTS[ $name ]; + if ( false === $path ) { + return "{$env['file']} sets $name with `..` (line {$t[ $at ][2]}); this check only accepts its default, $default, written without `..`"; + } if ( null === $path ) { return "can't resolve $name in {$env['file']} (line {$t[ $at ][2]}); this check only accepts its default, $default"; } @@ -582,7 +585,7 @@ private static function expr( array $t, $from, $to, array $env, $what ) { /** * The host path an expression of ABSPATH, __DIR__, dirname( __FILE__ ), WP_CONTENT_DIR and string literals joined by `.` - * gives, or null when it is anything else. + * gives, null when it is anything else, or false when a literal has a `..` segment. * * @return string|null */ @@ -613,6 +616,10 @@ private static function path_value( array $t, $from, $to, array $env, $content ) if ( null === $part ) { return null; } + // PHP follows each link before `..`; a textual collapse could call another directory the default. + if ( preg_match( '#(^|/)\.\.(/|$)#', $part ) ) { + return false; + } $path .= $part; $i = $next; if ( $i < $to ) { From d5fd4acf115671fef9d56438cb7db602c57287c8 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:11:17 +0530 Subject: [PATCH 28/53] fix(site): close the third review's php-compat gaps in settings, walks and delete - PHP settings are read the way PHP reads them: CRLF and CR-only files, a leading BOM, FPM keys with spaces or quotes, php-fpm-fcgi.ini and conf.d dot-files. Only bare none/off/no/false/null mean "no file"; a quoted value with more after it is never matched. - A php site's prepend must be a file its scan reads (not node_modules, .git or an old release). - On a stopped site, any custom compose definition for the php service gives tool_error; files for other services are fine. - Dot-directories are walked like any other, so PHP in htdocs/.well-known is refused; only the www-data home's tool directories in /var/www are skipped. - nginx includes are an allowlist again: what EE's nginx files include in every version it shipped. - PHP in a directory the WordPress root links to (Deployer's shared uploads) counts as inside it, and an unused app/wp-config.php beside an imported tree's own config is not refused. - `ee site delete` stops a running estimate after 10 s and goes on. - The public-directory mismatch warning is printed once. --- features/php-compat.feature | 2 +- src/helper/Site_PHP_Compat.php | 185 ++++++++++++++++++++++----------- 2 files changed, 127 insertions(+), 60 deletions(-) diff --git a/features/php-compat.feature b/features/php-compat.feature index 7e54f3a2..51910cd2 100644 --- a/features/php-compat.feature +++ b/features/php-compat.feature @@ -321,7 +321,7 @@ Feature: Check the PHP compatibility of a site's code And I run 'bin/ee site php-compat bh-site-command-190.test --php=8.4 --format=json' Then the command should succeed And the JSON field "status" in STDOUT should be "tool_error" - And the JSON field "detail" in STDOUT should contain "user-docker-compose/mount.yml may mount code or change how PHP starts, which this check can only see while the site runs" + And the JSON field "detail" in STDOUT should contain "user-docker-compose/mount.yml may change the site's php service, which this check can only see while the site runs" @wp Scenario: WordPress in its own directory is found through the index.php nginx serves diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index d2c05795..222ba3e1 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -98,6 +98,12 @@ class Site_PHP_Compat { '4.7' => [ '5.2', '7.1' ], ]; + /** Dot-directories of the www-data home in /var/www (app/): tool caches, never site code. */ + const HOME_DOTDIRS = [ '.wp-cli', '.composer', '.cache', '.config', '.local', '.npm', '.ssh' ]; + + /** The include targets of EE's nginx.conf, main.conf and admin-tools.conf, current and historical (dockerfiles nginx, site-type templates). */ + const NGINX_INCLUDES = [ 'mime.types', 'fastcgi_params', 'fastcgi.conf', '/usr/local/openresty/nginx/conf/conf.d/main.conf', '/usr/local/openresty/nginx/conf/custom/*.conf', 'custom/*.conf', 'user/*.conf', '/etc/nginx/custom/*.conf', '/etc/nginx/conf.d/*.conf', '/etc/nginx/main.conf', '/etc/nginx/default.conf', '/etc/nginx/sites-enabled/*', '/version.conf' ]; + /** Longest php-compat lists the site's files for (PHP outside WordPress, links, .user.ini files). */ const WALK_SECONDS = 120; @@ -149,6 +155,9 @@ class Site_PHP_Compat { /** @var array|null WordPress's version ( version, branch ) read from the scanned root's wp-includes/version.php. */ protected $wp_version; + /** @var bool Whether the record/nginx root mismatch was already reported. */ + protected $warned_root = false; + /** @var string|null The PHP version the site runs now (its record), major.minor; null when unknown. */ protected $current_php; @@ -900,7 +909,8 @@ public function docker_run_args( $mode, $image, $site_data, $code, $out = null, '--mount', "type=bind,src=$code,dst=/var/www,readonly" ); if ( 'estimate' === $mode && null !== $this->estimate_label ) { - array_push( $args, '--label', 'ee-php-compat-estimate=' . $this->estimate_label ); + // The site label lets `ee site delete` stop a running estimate. + array_push( $args, '--label', 'ee-php-compat-estimate=' . $this->estimate_label, '--label', 'ee-php-compat-estimate-site=' . $this->site ); } if ( 'estimate' === $mode ) { // The byte model misses PHPCS's per-file cost on dense many-file trees (2x short seen): more per batch, wider top end. @@ -1184,6 +1194,15 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { return self::clean( str_replace( "$code/", $app, $error ) ); } + // WordPress takes ABSPATH's wp-config.php first: one in the parent (EE's app/wp-config.php beside an imported tree) + // is never loaded, so it is no code outside WordPress either. + if ( dirname( $file['real'] ) === $abspath ) { + $parent = $this->site_file( $code, ltrim( substr( dirname( $abspath ), strlen( $code ) ), '/' ) . '/wp-config.php', self::PHP_SOURCE_MAX ); + if ( 'ok' === $parent['state'] ) { + $read[] = $parent['real']; + } + } + return $read; } @@ -1214,9 +1233,11 @@ protected function app_walk( $code, $rel, $root, $abspath, array $allowed ) { } $user_ini = []; $found = null; + $outside = []; + $linked = []; $error = $this->walk_tree( $code, - function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $releases, $live, &$user_ini, &$found ) { + function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $releases, $live, &$user_ini, &$found, &$outside, &$linked ) { $inside = null !== $abspath && 0 === strpos( $path . '/', $abspath . '/' ); if ( '.user.ini' === $name ) { $user_ini[] = [ $path, $type ]; @@ -1240,6 +1261,10 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ $found = "$path links to another WordPress install ($real)"; return 'stop'; } + // The scanner follows it: what lies there counts as inside (e.g. shared uploads of a Deployer release). + if ( null !== $real && is_dir( $real ) && 0 !== strpos( $real . '/', $abspath . '/' ) ) { + $linked[] = $real; + } return false; } $found = "$path is a link outside the WordPress directory"; @@ -1253,7 +1278,9 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ } return true; } - if ( '.' === $name[0] ) { + // The www-data home in /var/www (wp-cli packages, composer cache) is not site code; other dot-directories are + // walked like any other (nginx serves e.g. .well-known). + if ( dirname( $path ) === $code && in_array( $name, self::HOME_DOTDIRS, true ) ) { return false; } // Old releases beside the live one are out of scope only when nginx doesn't serve them (root at current/ or deeper). @@ -1267,8 +1294,9 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ return true; } if ( ! $inside && self::php_name( $name ) && ! in_array( $path, $allowed, true ) ) { - $found = "$path is PHP outside the WordPress directory" . ( null === $abspath ? ' (there is no WordPress this check recognises)' : '' ); - return 'stop'; + // Decided after the walk: a link from inside WordPress to its directory may still turn up. + $outside[] = $path; + return count( $outside ) >= 1000 ? 'stop' : false; } return false; } @@ -1276,6 +1304,18 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ if ( null !== $error ) { return "can't look through the site's files: $error"; } + if ( null === $found ) { + foreach ( $outside as $path ) { + $covered = false; + foreach ( $linked as $target ) { + $covered = $covered || 0 === strpos( $path, $target . '/' ); + } + if ( ! $covered ) { + $found = "$path is PHP outside the WordPress directory" . ( null === $abspath ? ' (there is no WordPress this check recognises)' : '' ); + break; + } + } + } if ( null === $found ) { return $user_ini; @@ -1356,7 +1396,14 @@ protected static function php_name( $name ) { protected function prepend_check( $site_data, $code, array $user_ini, $layout ) { $conf = $site_data->site_fs_path . '/config/php'; $files = []; - foreach ( array_merge( [ "$conf/php/php.ini" ], (array) glob( "$conf/php/conf.d/*.ini" ) ) as $file ) { + // php-fpm-fcgi.ini replaces php.ini for FPM when it exists; PHP's conf.d scan loads dot-files too. + $scanned = array_map( + function ( $name ) use ( $conf ) { + return "$conf/php/conf.d/$name"; + }, + preg_grep( '/\.ini$/', (array) @scandir( "$conf/php/conf.d" ) ) // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- missing is fine. + ); + foreach ( array_merge( [ "$conf/php/php.ini", "$conf/php/php-fpm-fcgi.ini" ], $scanned ) as $file ) { $files[ $file ] = 'ini'; } foreach ( array_merge( [ "$conf/php-fpm.conf" ], (array) glob( "$conf/php-fpm.d/*.conf" ) ) as $file ) { @@ -1375,8 +1422,8 @@ protected function prepend_check( $site_data, $code, array $user_ini, $layout ) if ( false === $text ) { return "can't read $shown, which may set a file PHP runs before WordPress"; } - foreach ( self::php_settings( $text, $kind ) as list( $key, $value ) ) { - if ( ! $this->php_setting_ok( $code, $key, $value, $layout ) ) { + foreach ( self::php_settings( $text, $kind ) as list( $key, $value, $quoted ) ) { + if ( ! $this->php_setting_ok( $code, $key, $value, $layout, $quoted ) ) { return "$shown sets $key to " . self::clean( '' === $value ? '""' : $value ) . ', which this check can\'t confirm'; } } @@ -1393,38 +1440,47 @@ protected function prepend_check( $site_data, $code, array $user_ini, $layout ) * @param string $text Its text. * @param string $kind ini or fpm. * - * @return array[] [ key, value (unquoted) ] each. + * @return array[] [ key, value (unquoted), whether it was quoted ] each. */ public static function php_settings( $text, $kind ) { + // PHP's ini scanner ends a line at \r\n, \n or a bare \r; a UTF-8 BOM before the first key is skipped. + $text = str_replace( [ "\r\n", "\r" ], "\n", preg_replace( '/^\xEF\xBB\xBF/', '', $text ) ); $keys = '(auto_prepend_file|auto_append_file|opcache\.preload|include_path|user_ini\.filename|zend\.multibyte|zend\.script_encoding)'; $pattern = 'fpm' === $kind - ? '/^[ \t]*(?:php(?:_admin)?_(?:value|flag)\[' . $keys . '\]|(include|security\.limit_extensions))[ \t]*=[ \t]*([^\r\n]*)$/mi' - : '/^[ \t]*' . $keys . '()[ \t]*=[ \t]*([^\r\n]*)$/mi'; + ? '/^[ \t]*(?:php(?:_admin)?_(?:value|flag)[ \t]*\[[ \t]*["\']?' . $keys . '["\']?[ \t]*\]|(include|security\.limit_extensions))[ \t]*=[ \t]*([^\n]*)$/mi' + : '/^[ \t]*' . $keys . '()[ \t]*=[ \t]*([^\n]*)$/mi'; $out = []; preg_match_all( $pattern, $text, $all, PREG_SET_ORDER ); foreach ( $all as $m ) { - $value = trim( $m[3] ); - if ( preg_match( '/^"([^"]*)"|^\'([^\']*)\'/', $value, $q ) ) { - $value = isset( $q[2] ) ? $q[2] : $q[1]; + $value = trim( $m[3] ); + $quoted = false; + if ( preg_match( '/^(["\'])(.*?)\1(.*)$/', $value, $q ) ) { + $rest = trim( $q[3] ); + // PHP joins adjacent parts ("/a".php): anything but a comment after the quote keeps the raw text, never matched. + $value = '' === $rest || ';' === $rest[0] ? $q[2] : $value; + $quoted = true; } else { $value = trim( preg_replace( '/[ \t]*;.*$/', '', $value ) ); } - $out[] = [ strtolower( '' !== $m[1] ? $m[1] : $m[2] ), $value ]; + $out[] = [ strtolower( '' !== $m[1] ? $m[1] : $m[2] ), $value, $quoted ]; } return $out; } + /** * @param string $code Real path of the site's app/. * @param string $key Setting. * @param string $value Its value. * @param array|null $layout wp_layout_of() result, or null for a php site. + * @param bool $quoted Whether the value was quoted. * * @return bool */ - protected function php_setting_ok( $code, $key, $value, $layout ) { - $off = in_array( strtolower( $value ), [ '', 'none', 'off', 'no', 'false', 'null', '0' ], true ); + protected function php_setting_ok( $code, $key, $value, $layout, $quoted = false ) { + // Only the bare keywords mean "nothing" to PHP; a quoted "none", or 0, is a file name. + $off = '' === $value || ! $quoted && in_array( strtolower( $value ), [ 'none', 'off', 'no', 'false', 'null' ], true ); switch ( $key ) { case 'include': // php-fpm.conf of EE's images: relative before PHP 8.6, absolute from 8.6. @@ -1452,8 +1508,7 @@ protected function php_setting_ok( $code, $key, $value, $layout ) { return false; } if ( null === $layout ) { - $htdocs = self::resolve_in( $code, 'htdocs' ); - return null !== $htdocs && 0 === strpos( $file['real'], "$htdocs/" ) && self::php_name( $file['real'] ); + return $this->scanned_by_php_scan( $code, $file['real'] ); } // Any loader the scan reads (Wordfence's wordfence-waf.php, NinjaFirewall's, …). @@ -1472,7 +1527,7 @@ protected function server_config_check( $site_data ) { $dir = $site_data->site_fs_path . '/config/nginx'; $files = array_merge( (array) glob( "$dir/*" ), (array) glob( "$dir/conf.d/*.conf" ), (array) glob( "$dir/custom/*.conf" ) ); foreach ( $files as $file ) { - if ( is_dir( $file ) && ! is_link( $file ) || preg_match( '/\.(?:default|types)$|^(?:koi-|win-|uwsgi_params|scgi_params)/', basename( $file ) ) && 'fastcgi_params' !== basename( $file ) ) { + if ( is_dir( $file ) && ! is_link( $file ) || dirname( $file ) === $dir && preg_match( '/\.(?:default|types)$|^(?:koi-|win-|uwsgi_params|scgi_params)/', basename( $file ) ) ) { continue; } $text = is_file( $file ) && filesize( $file ) <= self::CONFIG_MAX ? @file_get_contents( $file ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. @@ -1513,10 +1568,10 @@ public static function nginx_refusal( $text, $main, $custom ) { return "sets {$m[1]} to $value"; } } - // nginx's own config directory (old images used /etc/nginx) is EE's; anything the site's code can write is not. - preg_match_all( '/(?:^|[;{}])\s*include\s+([^;\s]+)\s*;/', $text, $all, PREG_SET_ORDER ); + // Only what EE's own nginx files include, in every version EE has shipped. + preg_match_all( '/(?:^|[;{}])\s*include\s+([^;]+?)\s*;/', $text, $all, PREG_SET_ORDER ); foreach ( $all as $m ) { - if ( preg_match( '#/var/www|\.\.|\$|^["\']#', $m[1] ) ) { + if ( ! in_array( $m[1], self::NGINX_INCLUDES, true ) ) { return "includes {$m[1]}"; } } @@ -1554,7 +1609,7 @@ protected function extra_mounts( $site_data, $code ) { return "could not read $file; enable the site to check mounted code"; } if ( $mounts ) { - return "$file may mount code or change how PHP starts, which this check can only see while the site runs; enable the site and run it again"; + return "$file may change the site's php service, which this check can only see while the site runs; enable the site and run it again"; } } @@ -1673,10 +1728,10 @@ protected function container_config_check( array $info ) { } /** - * Whether a compose file may mount anything below /var/www, read without a YAML parser (the release phar has none). - * Only lines that can't name such a mount are passed over: short volume entries (`- src:dst[:mode]`) and `target:` - * keys are judged by their destination, `source:` lines are fine; any other line that mentions /var/www, and any `$` - * (interpolation), counts as one. + * Whether a compose file may change the php service of a stopped site, read without a YAML parser (the release phar has + * none): any `php` key (block or flow style, quoted or not), any merge key or anchor use, any `extends` or `include`, and + * any interpolation count. Only a running container shows what PHP really gets, so this never tries to tell harmless + * php settings from others. * * @param string $file Compose file. * @@ -1687,36 +1742,12 @@ protected static function compose_mounts_code( $file ) { if ( false === $text ) { return null; } - foreach ( preg_split( '/\r\n|\r|\n/', $text ) as $line ) { - $line = trim( $line ); - if ( '' === $line || '#' === $line[0] ) { - continue; - } - // Interpolation, and keys that pull mounts in from elsewhere. - if ( false !== strpos( $line, '$' ) || preg_match( '/^-?\s*(?:extends|include|volumes_from|command|entrypoint)\s*:|PHPRC|PHP_INI_SCAN_DIR/', $line ) ) { - return true; - } - if ( false === stripos( $line, 'www' ) || preg_match( '/^-?\s*source:\s/', $line ) ) { - continue; - } - $target = null; - if ( preg_match( '/^-?\s*target:\s*([\'"]?)([^\'"#\s]+)\1\s*$/', $line, $m ) ) { - $target = $m[2]; - } elseif ( preg_match( '/^-\s*([\'"]?)([^\'"#\s:]+):([^\'"#\s:]+)(?::(?:ro|rw|z|Z|cached|delegated|consistent)(?:,[a-z]+)*)?\1\s*$/', $line, $m ) ) { - $target = $m[3]; - } elseif ( preg_match( '/^-\s*[A-Za-z_][A-Za-z0-9_]*=/', $line ) ) { - // An environment entry (`- NAME=value`), not a volume. - continue; - } - // A destination spelt another way (`//`, `/./`, `/../`, a backslash) may still be below /var/www. - if ( null === $target || preg_match( '#//|/\.\.?(/|$)|\\\\#', $target ) || 0 === strpos( rtrim( $target, '/' ) . '/', '/var/www/' ) ) { - return true; - } - } + $text = preg_replace( '/(^|\s)#[^\r\n]*/', '$1', $text ); - return false; + return 1 === preg_match( '/(?:^|[\s{,])["\']?php["\']?\s*:|<<\s*:|\*[A-Za-z0-9_-]|\b(?:extends|include)\s*:|\$/m', $text ); } + /** * The root nginx serves (main.conf), or the public directory in EE's record when there is no main.conf. * @@ -1743,7 +1774,9 @@ protected function served_root( $site_data ) { if ( null === $root || ! preg_match( self::ROOT_PATTERN, $root ) || preg_match( '/(?:^|[;{}])\s*alias\s/', $text ) ) { return "!can't tell which directory nginx serves: $conf has no single plain root"; } - if ( $root !== $db ) { + if ( $root !== $db && ! $this->warned_root ) { + // resolve_layout() runs twice (early, then under the lock): say it once. + $this->warned_root = true; EE::warning( sprintf( "EE's record of %s has %s as its public directory, but nginx serves %s (root in %s). Checking what nginx serves.", $this->site, $db, $root, $conf ) ); } @@ -1823,6 +1856,35 @@ protected function wp_config_files( $code, $root, $abspath ) { return []; } + /** + * Whether a php site's scan reads this file as code: in htdocs, a code extension, outside node_modules and .git, and + * not in an old release beside the live one behind a `current` link (the scanner's oldReleases()). + * + * @param string $code Real path of the site's app/. + * @param string $real Real host path of the file. + * + * @return bool + */ + protected function scanned_by_php_scan( $code, $real ) { + $htdocs = self::resolve_in( $code, 'htdocs' ); + if ( null === $htdocs || 0 !== strpos( $real, "$htdocs/" ) || ! self::php_name( basename( $real ) ) ) { + return false; + } + $parts = explode( '/', substr( $real, strlen( $htdocs ) + 1 ) ); + if ( array_intersect( $parts, [ 'node_modules', '.git' ] ) ) { + return false; + } + $served = null === $this->scan_path ? null : self::resolve_in( $code, ltrim( substr( $this->scan_path, strlen( '/var/www' ) ), '/' ) ); + if ( null !== $served && 'releases' === basename( dirname( $served ) ) ) { + $releases = dirname( $served ); + if ( 0 === strpos( $real, "$releases/" ) && 0 !== strpos( $real, "$served/" ) ) { + return false; + } + } + + return true; + } + /** * A file under app/ as the scanner container sees it, never from outside app/, never more than $max bytes, and only a * regular file (a FIFO is never opened). @@ -3459,7 +3521,12 @@ public function stop_for_delete( $site_data, $dispatch = null ) { $this->delete_lock = $kept; $parent = $this->temp_parent(); if ( null !== $parent && ! $this->wait_for_estimate( $parent ) ) { - return 'an estimate of the site is still running'; + // An estimate only reads the site: stop its container and go on, never refuse the delete. + $ps = $this->docker( [ 'docker', 'ps', '-aq', '--no-trunc', '--filter', 'label=ee-php-compat-estimate-site=' . $this->site ], 60 ); + foreach ( 0 === $ps['code'] ? preg_split( '/\s+/', trim( $ps['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ) : [] as $id ) { + $this->docker( [ 'docker', 'rm', '-f', $id ], 60 ); + } + EE::warning( "Stopped the php-compat estimate of {$this->site}; the delete goes on." ); } if ( null !== $parent ) { $files = [ "$parent/.cancel/{$this->site}", "$parent/.cancel-lock/{$this->site}", "$parent/.estimate-lock/{$this->site}" ]; @@ -3536,10 +3603,10 @@ protected function wait_for_estimate( $parent ) { } /** - * @return int Seconds `ee site delete` waits for a running estimate: its whole time limit. + * @return int Seconds `ee site delete` waits for a running estimate to end on its own before it stops it. */ protected function estimate_wait() { - return self::ESTIMATE_TIMEOUT + self::PROCESS_MARGIN; + return 10; } /** From b306e55d1c92fe4a04a7b4024d591dc789d9c499 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:16:47 +0530 Subject: [PATCH 29/53] fix(site): tighten php-compat's .. rule, install links and current-PHP source - A `..` in a directory constant is tested on the joined value, so splitting it across literals ('/L/.' . './wp-content') no longer passes. - A link inside WordPress is refused when its target, any ancestor of the target or a direct child of it holds another WordPress install, not only when it points at an install's root. - For a WordPress newer than the support table, the PHP the site runs now counts only when its record and its running php container's image agree. - A report encoding that isn't a non-empty string is tool_error. --- src/helper/Site_PHP_Compat.php | 58 ++++++++++++++++++++++++--- src/helper/Site_PHP_Compat_Layout.php | 10 +++-- 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 222ba3e1..3ef09ebb 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -158,9 +158,12 @@ class Site_PHP_Compat { /** @var bool Whether the record/nginx root mismatch was already reported. */ protected $warned_root = false; - /** @var string|null The PHP version the site runs now (its record), major.minor; null when unknown. */ + /** @var string|null The PHP version the site's record says, major.minor; null when unknown. */ protected $current_php; + /** @var string|null The PHP version of the running php container's image (easyengine/phpX.Y), null when unknown. */ + protected $container_php; + /** @var string|null Cancel request file a scan watches once it holds the site lock. */ protected $cancel_marker; @@ -530,7 +533,7 @@ protected function run_scan( $site_data, $timeout, $output ) { // The report says what stdout says (gated verdict, scoped fields), with the full not_checked list and the components. $raw = self::encode( $full + [ 'components' => $report['components'] ] ); // A value json_encode() refuses (INF in a key EE doesn't know): no report rather than an empty one. - if ( '' === $raw ) { + if ( ! is_string( $raw ) || '' === $raw ) { return $this->doc( 'tool_error', 'could not encode the report' ); } if ( ! $this->write_report( $output, $raw ) ) { @@ -1257,8 +1260,8 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ $found = "$path links to its own ancestor " . $real; return 'stop'; } - if ( null !== $real && is_dir( $real ) && ( file_exists( "$real/wp-settings.php" ) || is_dir( "$real/wp-includes" ) ) ) { - $found = "$path links to another WordPress install ($real)"; + if ( null !== $real && self::reaches_install( $code, $real, $abspath ) ) { + $found = "$path links into another WordPress install ($real)"; return 'stop'; } // The scanner follows it: what lies there counts as inside (e.g. shared uploads of a Deployer release). @@ -1324,6 +1327,39 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ return '!' === $found[0] ? self::clean( substr( $found, 1 ) ) : self::clean( $found ) . '; this check can\'t scan that layout'; } + /** + * Whether a link target is (in) another WordPress install: the target, any of its ancestors up to app/, or (for a + * directory) any direct child holds wp-settings.php or wp-includes/. The live WordPress root doesn't count. + * + * @param string $code Real path of the site's app/. + * @param string $real Real link target. + * @param string $abspath Real WordPress root. + * + * @return bool + */ + protected static function reaches_install( $code, $real, $abspath ) { + $install = function ( $dir ) use ( $abspath ) { + return $dir !== $abspath && is_dir( $dir ) && ( is_file( "$dir/wp-settings.php" ) || is_dir( "$dir/wp-includes" ) ); + }; + for ( $dir = $real; strlen( $dir ) >= strlen( $code ); $dir = dirname( $dir ) ) { + if ( $install( $dir ) ) { + return true; + } + if ( $dir === $code ) { + break; + } + } + if ( is_dir( $real ) && ! is_link( $real ) ) { + foreach ( (array) @scandir( $real ) as $name ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable lists nothing. + if ( '.' !== $name && '..' !== $name && ! is_link( "$real/$name" ) && $install( "$real/$name" ) ) { + return true; + } + } + } + + return false; + } + /** * Walks a directory tree without following links, bounded in time: $visit( $path, $name, file|dir|link|other ) returns * 'stop' to stop (true also stops for a non-directory), and for a directory whether to go into it. @@ -1708,6 +1744,8 @@ protected function container_config_check( array $info ) { return 'could not read how the site\'s php container is configured'; } $config = $info['Config']; + // The PHP it runs: easyengine/php8.4:; easyengine/php (latest) or any other image tells nothing. + $this->container_php = isset( $config['Image'] ) && preg_match( '#^easyengine/php(\d+\.\d+):#', (string) $config['Image'], $m ) ? $m[1] : null; foreach ( [ 'Cmd', 'Entrypoint' ] as $key ) { if ( ( isset( $config[ $key ] ) ? $config[ $key ] : null ) !== ( isset( $own[ $key ] ) ? $own[ $key ] : null ) ) { return "the site's php container runs another " . strtolower( $key ) . ' than its image, which this check can\'t confirm'; @@ -2820,7 +2858,7 @@ function ( $entry ) { $core = null; if ( $this->wp_layout && null !== $this->wp_version ) { // Core's files are never scanned; not_checked stays the scanner's own list (its type and reason values are a fixed set). - $core = self::wp_supports( $this->wp_version['branch'], $this->target, $this->current_php ); + $core = self::wp_supports( $this->wp_version['branch'], $this->target, $this->current_php() ); $doc['wordpress'] = [ 'version' => self::clean( $this->wp_version['version'] ), 'supports' => $core['supports'], @@ -2840,6 +2878,13 @@ function ( $entry ) { return $doc; } + /** + * @return string|null The PHP version the site runs now: only when its record and its running container agree. + */ + protected function current_php() { + return null !== $this->current_php && $this->current_php === $this->container_php ? $this->current_php : null; + } + /** * The summary as stdout prints it: fixed-size, so not_checked keeps its first NOT_CHECKED_STDOUT entries, each string * cut to NOT_CHECKED_CHARS characters, and not_checked_more counts the rest (the --output report has them all). @@ -2881,6 +2926,7 @@ function ( $entry ) { * (the reason to print, or null). */ public static function wp_supports( $branch, $target, $current = null ) { + $current = null !== $current && preg_match( '/^\d+\.\d+$/D', (string) $current ) ? (string) $current : null; $minimum = null; $highest = '0'; foreach ( self::WP_PHP_SUPPORT as $wp => list( $low, $high ) ) { @@ -3105,7 +3151,7 @@ protected function table_lines( array $doc, $report ) { } $tail = sprintf( '%s. %s checked.', self::count_of( $doc['warnings'], 'warning' ), self::count_of( $doc['files_checked'], 'file' ) ); - $core = isset( $doc['wordpress'] ) && null !== $this->wp_version ? self::wp_supports( $this->wp_version['branch'], $target, $this->current_php ) : null; + $core = isset( $doc['wordpress'] ) && null !== $this->wp_version ? self::wp_supports( $this->wp_version['branch'], $target, $this->current_php() ) : null; $why = null === $core ? null : $core['why']; if ( false === $doc['safe_to_upgrade'] ) { if ( $doc['errors'] > 0 ) { diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index 4c97a4f5..c47678ec 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -616,10 +616,6 @@ private static function path_value( array $t, $from, $to, array $env, $content ) if ( null === $part ) { return null; } - // PHP follows each link before `..`; a textual collapse could call another directory the default. - if ( preg_match( '#(^|/)\.\.(/|$)#', $part ) ) { - return false; - } $path .= $part; $i = $next; if ( $i < $to ) { @@ -630,6 +626,12 @@ private static function path_value( array $t, $from, $to, array $env, $content ) } } + // PHP follows each link before `..`; a textual collapse could call another directory the default. The joined + // string is tested, so `'/L/.' . './x'` counts too. + if ( preg_match( '#(^|/)\.\.(/|$)#', $path ) ) { + return false; + } + return self::normalise( $path ); } From a8a8a112e538b4f6bdd0f2a2ded662104d5aa650 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:19:28 +0530 Subject: [PATCH 30/53] fix(site): accept the wp-config lines plugins and WordPress's handbook write php-compat refused common real sites: Really Simple Security's session cookie block, the "increase upload size" ini_set snippet, WP Offload Media's serialize()d settings, the handbook's FS_CHMOD_DIR umask() form, the WP-CLI php_sapi_name() guard and the reverse-proxy snippets' local variables. - ini_set() takes the session cookie, pcre, zlib, output and error settings too; keys that name a file, path, handler or callback PHP loads (include_path, auto_prepend_file, opcache.*, session.save_handler, unserialize_callback_func) stay out. - Values may call more pure functions (string, array, hash and version helpers, serialize, json_encode); umask() only without arguments and filter_var() only with a VALIDATE/SANITIZE filter. constant(), preg_replace(), unserialize() and anything taking a callback stay out. - set_time_limit(), date_default_timezone_set(), umask(), header() and mb_internal_encoding() are accepted as statements. - $forwarded_ips, $http_x_headers, $xffaddrs and $batcache may be assigned. --- src/helper/Site_PHP_Compat_Layout.php | 42 ++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index 4c97a4f5..e953c3fa 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -20,19 +20,39 @@ class Site_PHP_Compat_Layout { const NEVER_DEFINED = [ 'WPINC', 'TEMPLATEPATH', 'STYLESHEETPATH', 'WP_LANG_DIR', 'PLUGINDIR', 'MUPLUGINDIR' ]; /** The only variables a config may assign (table prefix, multisite, EE's --cache and memcached object caches). */ - const VARIABLES = [ 'table_prefix', 'base', 'redis_server', 'memcached_servers' ]; + const VARIABLES = [ 'table_prefix', 'base', 'redis_server', 'memcached_servers', 'forwarded_ips', 'http_x_headers', 'xffaddrs', 'batcache' ]; /** The only $_SERVER keys a config may set: what proxy and HTTPS snippets set, never where the script is. */ const SERVER_KEYS = [ 'HTTPS', 'SERVER_PORT', 'REMOTE_ADDR', 'HTTP_HOST', 'SERVER_NAME', 'REQUEST_SCHEME', 'HTTP_X_FORWARDED_PROTO', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_PORT', 'HTTP_X_FORWARDED_SSL', 'HTTP_X_REAL_IP' ]; - /** The only settings ini_set() may change in a config. */ - const INI_KEYS = [ 'display_errors', 'display_startup_errors', 'log_errors', 'error_log', 'error_reporting', 'memory_limit', 'max_execution_time', 'max_input_time', 'max_input_vars', 'upload_max_filesize', 'post_max_size', 'default_socket_timeout', 'date.timezone', 'session.gc_maxlifetime' ]; + /** + * The only settings ini_set() may change in a config: none names a file, path, handler or callback PHP loads or runs + * (so never include_path, auto_prepend_file, opcache.*, session.save_handler or unserialize_callback_func). + * upload_max_size isn't a PHP setting, but a widely copied snippet sets it (ini_set() then just fails). + */ + const INI_KEYS = [ 'display_errors', 'display_startup_errors', 'log_errors', 'error_log', 'error_reporting', 'memory_limit', 'max_execution_time', 'max_input_time', 'max_input_vars', 'max_input_nesting_level', 'upload_max_filesize', 'upload_max_size', 'post_max_size', 'default_socket_timeout', 'date.timezone', 'html_errors', 'log_errors_max_len', 'ignore_repeated_errors', 'ignore_repeated_source', 'default_charset', 'output_buffering', 'zlib.output_compression', 'zlib.output_compression_level', 'pcre.backtrack_limit', 'pcre.recursion_limit', 'pcre.jit', 'session.gc_maxlifetime', 'session.gc_probability', 'session.gc_divisor', 'session.cookie_httponly', 'session.cookie_secure', 'session.cookie_samesite', 'session.cookie_lifetime', 'session.cookie_domain', 'session.cookie_path', 'session.use_only_cookies', 'session.use_strict_mode', 'session.use_trans_sid', 'session.name' ]; + + /** + * The only functions an expression may call: none loads code, takes a callback or can autoload a class (so never + * constant(), filter_var() with FILTER_CALLBACK, preg_replace(), unserialize() or class_exists()), and each exists with + * the same signature on every PHP version php-compat checks. umask() and filter_var() are checked further in expr(). + */ + const PURE_FUNCTIONS = [ 'defined', 'dirname', 'basename', 'getenv', 'strpos', 'stripos', 'strrpos', 'strstr', 'stristr', 'strtolower', 'strtoupper', 'ucfirst', 'lcfirst', 'ucwords', 'in_array', 'explode', 'implode', 'join', 'trim', 'rtrim', 'ltrim', 'substr', 'strlen', 'str_replace', 'str_ireplace', 'str_pad', 'sprintf', 'md5', 'sha1', 'crc32', 'base64_encode', 'serialize', 'json_encode', 'urlencode', 'rawurlencode', 'parse_url', 'intval', 'floatval', 'strval', 'boolval', 'abs', 'round', 'floor', 'ceil', 'is_numeric', 'is_string', 'is_array', 'is_bool', 'array_merge', 'array_keys', 'array_values', 'array_key_exists', 'array_search', 'array_unique', 'array_slice', 'file_exists', 'is_file', 'is_dir', 'is_readable', 'php_sapi_name', 'phpversion', 'php_uname', 'gethostname', 'version_compare', 'extension_loaded', 'function_exists', 'umask', 'filter_var', 'isset', 'empty', 'array' ]; - /** The only functions an expression may call: none has a side effect or loads code. */ - const PURE_FUNCTIONS = [ 'defined', 'dirname', 'getenv', 'strpos', 'stripos', 'strtolower', 'strtoupper', 'in_array', 'explode', 'trim', 'file_exists', 'isset', 'empty', 'array' ]; + /** + * Statements (besides define/assignment/include) a config may make, each with any allowed expressions as arguments: + * they change settings of this request, never what PHP loads. + */ + const PURE_STATEMENTS = [ 'ini_set', 'error_reporting', 'set_time_limit', 'date_default_timezone_set', 'umask', 'header', 'mb_internal_encoding' ]; + + /** Significant tokens read per file; real configs have a few thousand. */ + const MAX_TOKENS = 50000; - /** Statements (besides define/assignment/include) a config may make, each with any allowed expressions as arguments. */ - const PURE_STATEMENTS = [ 'ini_set', 'error_reporting' ]; + /** How deep `if` blocks may nest: deeper ones cost quadratic time to match. */ + const MAX_NEST = 16; + + /** Files one config check may follow, counting each once. */ + const MAX_FILES = 32; /** Files below the WordPress root that EE's own --vip config loads, and how each is checked. */ const VIP_FILES = [ @@ -567,6 +587,14 @@ private static function expr( array $t, $from, $to, array $env, $what ) { if ( $call && ! in_array( $word, self::PURE_FUNCTIONS, true ) ) { return "{$env['file']} line $line calls $text(), which this check doesn't accept in a config"; } + $close = $call && in_array( $word, [ 'umask', 'filter_var' ], true ) ? self::matching( $t, $i + 1, $to ) : null; + $args = null === $close ? null : self::call_args( $t, $i, $close + 1 ); + // umask() only reads the mask; filter_var() only validates or sanitises (FILTER_CALLBACK runs code). + if ( 'umask' === $word && $call && [] !== $args || 'filter_var' === $word && ( null === $args || count( $args ) < 2 || count( $args ) > 3 + || 1 !== count( $args[1] ) || T_STRING !== $t[ $args[1][0] ][0] || ! preg_match( '/^FILTER_(?:VALIDATE|SANITIZE|DEFAULT|UNSAFE_RAW)/', $t[ $args[1][0] ][1] ) + || isset( $args[2] ) && ( 1 !== count( $args[2] ) || T_STRING !== $t[ $args[2][0] ][0] || ! preg_match( '/^FILTER_(?:FLAG_|NULL_ON_FAILURE$)/', $t[ $args[2][0] ][1] ) ) ) ) { + return "{$env['file']} line $line calls $text() in a form this check doesn't accept in a config"; + } if ( ! $call && T_STRING !== $id ) { return self::unknown( $t, $i, $env ); } From 467e7e675908623ea75e9dc569f08a9c4f13eb19 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:21:40 +0530 Subject: [PATCH 31/53] fix(site): refuse what php-compat's tokens can't read the way the site's PHP does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A b-prefixed string (b'…') is one token whose text starts with the prefix, so every literal read shifted by a character: `include ABSPATH . b'wp-content/uploads/x.php'` resolved to a missing file and was accepted while PHP loads it. - A comment that is never closed runs on PHP 7 and is a parse error on PHP 8. - PHP 8.5's pipe `|>` is `|` `>` to an older host's tokenizer, so `'id' |> 'system'` passed there; `%>` ends PHP code on a 5.6 site with asp_tags on. - A host without the tokenizer extension gets a reason instead of a fatal error, files over 50000 tokens are refused, and a UTF-8 BOM before self::MAX_TOKENS ) { + return 'it has more than ' . self::MAX_TOKENS . ' tokens'; + } if ( ! is_array( $t ) ) { + // Hosts before PHP 8.5 read the pipe `|>` as `|` `>`; `%>` ends PHP code on a 5.6 site with asp_tags on. + if ( ( '|' === $t || '%' === $t ) && isset( $raw[ $i + 1 ] ) && '>' === $raw[ $i + 1 ] ) { + return "line $line has $t>, which some PHP versions read differently"; + } $out[] = [ $t, $t, $line ]; continue; } @@ -88,6 +103,17 @@ public static function tokens( $source ) { if ( T_COMMENT === $t[0] && 0 === strpos( $t[1], '#[' ) || defined( 'T_ATTRIBUTE' ) && T_ATTRIBUTE === $t[0] ) { return "line $line has an attribute, which PHP 7 reads as a comment"; } + // PHP 7 runs a file whose last comment is never closed; PHP 8 refuses to parse it. + if ( in_array( $t[0], [ T_COMMENT, T_DOC_COMMENT ], true ) && 0 === strncmp( $t[1], '/*', 2 ) && ( strlen( $t[1] ) < 4 || '*/' !== substr( $t[1], -2 ) ) ) { + return "line $line has a comment that is never closed"; + } + if ( $pipe === $t[0] ) { + return "line $line has |>, which some PHP versions read differently"; + } + // `b'…'` is one token: the prefix would shift every literal read below. + if ( T_CONSTANT_ENCAPSED_STRING === $t[0] && '\'' !== $t[1][0] && '"' !== $t[1][0] ) { + return "line $line has a string with a b prefix"; + } if ( in_array( $t[0], $skip, true ) ) { continue; } @@ -372,7 +398,7 @@ private static function simple( array $t, $i, $end, array $env, $depth, array &$ // ini_set( … ); error_reporting( … ); if ( self::is_word( $t, $s, self::PURE_STATEMENTS ) ) { $args = self::call_args( $t, $s, $end ); - if ( null === $args || self::is_word( $t, $s, 'ini_set' ) && ( 2 !== count( $args ) || ! in_array( strtolower( (string) self::literal_arg( $t, $args[0] ) ), self::INI_KEYS, true ) ) ) { + if ( null === $args || self::is_word( $t, $s, 'ini_set' ) && ( 2 !== count( $args ) || ! in_array( self::lower( (string) self::literal_arg( $t, $args[0] ) ), self::INI_KEYS, true ) ) ) { return self::unknown( $t, $i, $env ); } foreach ( $args as $arg ) { @@ -398,7 +424,7 @@ private static function define( array $t, array $args, array $env, array &$state if ( null === $name ) { return self::unknown( $t, $at, $env, 'defines a constant whose name is not a plain string' ); } - $upper = strtoupper( $name ); + $upper = self::upper( $name ); if ( in_array( $upper, self::NEVER_DEFINED, true ) ) { return "{$env['file']} line {$t[ $at ][2]} defines $name, which changes where WordPress loads code from"; } @@ -508,7 +534,7 @@ public static function vip_file( $source, $kind ) { for ( $i = 0; $i < $n; $i++ ) { list( $id, $text, $line ) = $t[ $i ]; $word = T_CONSTANT_ENCAPSED_STRING === $id ? substr( $text, 1, -1 ) : $text; - if ( ( T_STRING === $id || T_CONSTANT_ENCAPSED_STRING === $id ) && in_array( strtoupper( $word ), $names, true ) ) { + if ( ( T_STRING === $id || T_CONSTANT_ENCAPSED_STRING === $id ) && in_array( self::upper( $word ), $names, true ) ) { return "line $line names $word"; } if ( T_VARIABLE === $id && in_array( substr( $text, 1 ), [ 'GLOBALS', 'wp_filter', 'wp_theme_directories' ], true ) ) { @@ -583,7 +609,7 @@ private static function expr( array $t, $from, $to, array $env, $what ) { continue; } if ( in_array( $id, [ T_STRING, T_ISSET, T_EMPTY, T_ARRAY ], true ) ) { - $word = strtolower( $text ); + $word = self::lower( $text ); if ( $call && ! in_array( $word, self::PURE_FUNCTIONS, true ) ) { return "{$env['file']} line $line calls $text(), which this check doesn't accept in a config"; } @@ -682,7 +708,7 @@ private static function include_target( array $t, $i, $end ) { ' ', array_map( function ( $tok ) { - return is_int( $tok[0] ) ? token_name( $tok[0] ) . ':' . strtolower( $tok[1] ) : $tok[0]; + return is_int( $tok[0] ) ? token_name( $tok[0] ) . ':' . self::lower( $tok[1] ) : $tok[0]; }, $ops ) @@ -855,7 +881,7 @@ private static function signature( array $t, array $arg ) { ' ', array_map( function ( $i ) use ( $t ) { - return is_int( $t[ $i ][0] ) ? ( T_CONSTANT_ENCAPSED_STRING === $t[ $i ][0] ? $t[ $i ][1] : token_name( $t[ $i ][0] ) . ( T_STRING === $t[ $i ][0] ? ':' . strtolower( $t[ $i ][1] ) : '' ) ) : $t[ $i ][0]; + return is_int( $t[ $i ][0] ) ? ( T_CONSTANT_ENCAPSED_STRING === $t[ $i ][0] ? $t[ $i ][1] : token_name( $t[ $i ][0] ) . ( T_STRING === $t[ $i ][0] ? ':' . self::lower( $t[ $i ][1] ) : '' ) ) : $t[ $i ][0]; }, $arg ) @@ -869,8 +895,19 @@ private static function literal_arg( array $t, array $arg ) { return 1 === count( $arg ) && T_CONSTANT_ENCAPSED_STRING === $t[ $arg[0] ][0] ? self::literal( $t[ $arg[0] ][1] ) : null; } + /** + * ASCII case mapping: before PHP 8.2 strtolower() follows the locale, and a Turkish one keeps `I`. + */ + public static function lower( $text ) { + return strtr( $text, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz' ); + } + + public static function upper( $text ) { + return strtr( $text, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ); + } + private static function is_word( array $t, $i, $words ) { - return isset( $t[ $i ] ) && T_STRING === $t[ $i ][0] && in_array( strtolower( $t[ $i ][1] ), (array) $words, true ); + return isset( $t[ $i ] ) && T_STRING === $t[ $i ][0] && in_array( self::lower( $t[ $i ][1] ), (array) $words, true ); } private static function unknown( array $t, $i, array $env, $why = null ) { From 96223842c1d4227799cda4227fb1009a20decb06 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:23:48 +0530 Subject: [PATCH 32/53] fix(site): close php-compat's reference and include-base holes in wp-config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `&` is accepted only as bitwise and. `$base = &$wp_filter;` bound an allowed variable to any global and wrote through it. - BLOCKS_PATH, GETID3_INCLUDEPATH, LANGDIR and AKISMET__PLUGIN_DIR may not be defined: core 4.9–7.1 and Akismet require from them, and an earlier define wins. WPCACHEHOME must point inside the WordPress root (or outside the site, as a path left from another host), and WPLANG, FS_METHOD and WP_DEFAULT_THEME, which core puts into a file name, must be plain names. - `! defined( 'X' ) && define( 'X', … )`, an (array) cast, define()'s third argument when false, `declare( strict_types = 1 );` and a constant name with trailing spaces (the handbook's own FTP_PLUGIN_DIR line) are accepted; a third argument of true is refused, since PHP 8 has no case-insensitive constants. --- src/helper/Site_PHP_Compat_Layout.php | 63 ++++++++++++++++++++++++--- 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index f6ff1768..c379f032 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -16,8 +16,18 @@ class Site_PHP_Compat_Layout { 'WPMU_PLUGIN_DIR' => 'wp-content/mu-plugins', ]; - /** Constants a config may never set: each moves core or theme code WordPress loads. */ - const NEVER_DEFINED = [ 'WPINC', 'TEMPLATEPATH', 'STYLESHEETPATH', 'WP_LANG_DIR', 'PLUGINDIR', 'MUPLUGINDIR' ]; + /** + * Constants a config may never set: each moves core or theme code WordPress loads. Core (4.9–7.1) requires from + * BLOCKS_PATH and GETID3_INCLUDEPATH with a guard or after its own define, so an earlier define wins; Akismet ships + * with core. + */ + const NEVER_DEFINED = [ 'WPINC', 'TEMPLATEPATH', 'STYLESHEETPATH', 'WP_LANG_DIR', 'PLUGINDIR', 'MUPLUGINDIR', 'LANGDIR', 'BLOCKS_PATH', 'GETID3_INCLUDEPATH', 'AKISMET__PLUGIN_DIR' ]; + + /** Constants code is loaded from that a config may set only to a path inside the WordPress root (WP Super Cache's drop-in). */ + const INSIDE_ROOT = [ 'WPCACHEHOME' ]; + + /** Constants core puts into the name of a file it loads (locale file, filesystem class, theme): a plain name only. */ + const NAME_VALUES = [ 'WPLANG', 'FS_METHOD', 'WP_DEFAULT_THEME' ]; /** The only variables a config may assign (table prefix, multisite, EE's --cache and memcached object caches). */ const VARIABLES = [ 'table_prefix', 'base', 'redis_server', 'memcached_servers', 'forwarded_ips', 'http_x_headers', 'xffaddrs', 'batcache' ]; @@ -357,16 +367,30 @@ private static function simple( array $t, $i, $end, array $env, $depth, array &$ // define( 'NAME', expr ); if ( self::is_word( $t, $s, 'define' ) ) { $args = self::call_args( $t, $s, $end ); + if ( null !== $args && 3 === count( $args ) && 1 === count( $args[2] ) && self::is_word( $t, $args[2][0], 'true' ) ) { + return self::unknown( $t, $i, $env, 'defines a case-insensitive constant, which PHP 8 no longer has' ); + } + // A third argument of false is the default, ignored on every version. + if ( null !== $args && 3 === count( $args ) && 1 === count( $args[2] ) && self::is_word( $t, $args[2][0], 'false' ) ) { + array_pop( $args ); + } if ( null === $args || 2 !== count( $args ) ) { return self::unknown( $t, $i, $env ); } return self::define( $t, $args, $env, $state, $i ); } - // defined( 'NAME' ) || define( 'NAME', expr ); - if ( self::is_word( $t, $s, 'defined' ) && isset( $t[ $s + 1 ] ) && '(' === $t[ $s + 1 ][0] ) { + // declare( strict_types = 0|1 ); + if ( T_DECLARE === $t[ $i ][0] && $end === $i + 6 && self::is_word( $t, $i + 2, 'strict_types' ) && '(' === $t[ $i + 1 ][0] && '=' === $t[ $i + 3 ][0] && in_array( $t[ $i + 4 ][1], [ '0', '1' ], true ) && ')' === $t[ $i + 5 ][0] ) { + return null; + } + // defined( 'NAME' ) || define( 'NAME', expr ); ! defined( 'NAME' ) && define( 'NAME', expr ); + $not = '!' === $t[ $s ][0] ? 1 : 0; + if ( self::is_word( $t, $s + $not, 'defined' ) && isset( $t[ $s + $not + 1 ] ) && '(' === $t[ $s + $not + 1 ][0] ) { + $s += $not; $close = self::matching( $t, $s + 1, $end ); $or = null === $close ? null : $close + 1; - $args = null === $or || ! in_array( $t[ $or ][0], [ T_BOOLEAN_OR, T_LOGICAL_OR ], true ) || ! self::is_word( $t, $or + 1, 'define' ) ? null : self::call_args( $t, $or + 1, $end ); + $ops = $not ? [ T_BOOLEAN_AND, T_LOGICAL_AND ] : [ T_BOOLEAN_OR, T_LOGICAL_OR ]; + $args = null === $or || ! in_array( $t[ $or ][0], $ops, true ) || ! self::is_word( $t, $or + 1, 'define' ) ? null : self::call_args( $t, $or + 1, $end ); $name = null === $close || $close !== $s + 3 ? null : self::name_literal( $t, [ $s + 2 ] ); if ( null === $args || 2 !== count( $args ) || null === $name || self::name_literal( $t, $args[0] ) !== $name ) { return self::unknown( $t, $i, $env ); @@ -439,6 +463,26 @@ private static function define( array $t, array $args, array $env, array &$state } return null; } + if ( in_array( $upper, self::NAME_VALUES, true ) ) { + $value = self::literal_arg( $t, $args[1] ); + if ( null === $value || ! preg_match( '/^[A-Za-z0-9_.@-]*$/D', $value ) ) { + return "{$env['file']} line {$t[ $at ][2]} sets $name to something other than a plain name, which WordPress puts into the name of a file it loads"; + } + return null; + } + if ( in_array( $upper, self::INSIDE_ROOT, true ) ) { + $raw = self::path_value( $t, $args[1][0], end( $args[1] ) + 1, $env, $state['content'] ); + $path = is_string( $raw ) && isset( $env['canon'] ) ? call_user_func( $env['canon'], $raw ) : $raw; + $site = false; + foreach ( [ '/var/www', $env['dir'], $env['root'] ] as $prefix ) { + $site = $site || is_string( $raw ) && 0 === strpos( $raw . '/', $prefix . '/' ); + } + // Inside the WordPress root the scan reads it; a path outside the site (left from another host) isn't there. + if ( ! is_string( $path ) || $site && 0 !== strpos( $path . '/', $env['root'] . '/' ) ) { + return "{$env['file']} line {$t[ $at ][2]} sets $name, which code is loaded from, to a path outside {$env['root']}"; + } + return null; + } if ( isset( self::DIR_DEFAULTS[ $upper ] ) ) { $name = $upper; $path = self::path_value( $t, $args[1][0], end( $args[1] ) + 1, $env, $state['content'] ); @@ -581,7 +625,7 @@ private static function expr( array $t, $from, $to, array $env, $what ) { $ops = [ '.', '?', ':', '!', ',', '-', '+', '*', '/', '%', '|', '&', '^', '~', '<', '>', '@', ')', ']', '(', '[', T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL, T_BOOLEAN_AND, T_BOOLEAN_OR, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR, T_COALESCE, T_DOUBLE_ARROW, T_SL, T_SR, - T_INT_CAST, T_BOOL_CAST, T_STRING_CAST, T_DOUBLE_CAST, T_SPACESHIP, T_POW ]; + T_INT_CAST, T_BOOL_CAST, T_STRING_CAST, T_DOUBLE_CAST, T_ARRAY_CAST, T_SPACESHIP, T_POW ]; // PHP 8.1 tokenises `&` by what follows it. foreach ( [ 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG' ] as $name ) { if ( defined( $name ) ) { @@ -596,6 +640,10 @@ private static function expr( array $t, $from, $to, array $env, $what ) { for ( $i = $from; $i < $to; $i++ ) { list( $id, $text, $line ) = $t[ $i ]; $call = isset( $t[ $i + 1 ] ) && $i + 1 < $to && '(' === $t[ $i + 1 ][0]; + // `&` only as bitwise and: after `=`, `(`, `,` or `=>` it takes a reference, which writes through to any global. + if ( '&' === $text && ( $i === $from || ! in_array( $t[ $i - 1 ][0], $after_value, true ) ) ) { + return "{$env['file']} line $line takes a reference with &, which this check doesn't accept in a config"; + } if ( in_array( $id, [ T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER, T_DIR, T_FILE, T_LINE ], true ) ) { if ( $call ) { return "{$env['file']} line $line calls a string as a function"; @@ -834,7 +882,8 @@ private static function name_literal( array $t, array $arg ) { } $name = substr( $t[ $arg[0] ][1], 1, -1 ); - return preg_match( '/^[A-Za-z_][A-Za-z0-9_]*$/D', $name ) ? $name : null; + // Trailing spaces: the handbook's own `'FTP_PLUGIN_DIR '` (a different constant, so harmless). + return preg_match( '/^[A-Za-z_][A-Za-z0-9_]* *$/D', $name ) ? $name : null; } /** From ca001b1044809a4c9c5542c80807b33f3a758006 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:26:00 +0530 Subject: [PATCH 33/53] fix(site): read the files wp-config.php loads as scanned code, within bounds A file wp-config.php loads from inside the scanned WordPress root had to fit the config grammar, so Really Simple Security's advanced-headers.php refused the site. Such a file is scanned anyway; when it doesn't fit the grammar it is now screened: it may not name the constants or globals WordPress loads code from, define a constant by a computed name or ABSPATH, run code from a string, call extract(), constant() and the like, or load a file other than one this check accepts. Files outside the scan are still refused. - An absolute include path is the container's (/var/www is app/), and `@include` is read like `include`, so the plugin's static rule and its `@` forms are named. - At most 32 distinct files are followed per check and each is read once; `if` blocks may nest 16 deep. Both were unbounded and quadratic. - index.php's loader path may not end a directory with a dot, which pointed the check at another directory than PHP's. - A --vip file may not define a constant by a computed name. --- src/helper/Site_PHP_Compat_Layout.php | 142 ++++++++++++++++++++++++-- 1 file changed, 136 insertions(+), 6 deletions(-) diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index c379f032..3cea23a7 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -197,7 +197,7 @@ public static function index_loader( $source ) { return 'line ' . $t[ $end + 1 ][2] . ' comes after WordPress is loaded'; } - return [ 'sub' => trim( dirname( $inc['path'] ), '/.' ) ]; + return [ 'sub' => trim( dirname( $inc['path'] ), '/' ) ]; } /** @@ -248,7 +248,10 @@ public static function check_config( $source, array $env, $depth = 0 ) { if ( is_string( $t ) ) { return "{$env['file']}: $t"; } - $state = [ 'booted' => false, 'content' => null, 'guard' => null ]; + if ( ! isset( $env['followed'] ) ) { + $env['followed'] = new \ArrayObject(); + } + $state = [ 'booted' => false, 'content' => null, 'guard' => null, 'nest' => 0 ]; $error = self::statements( $t, 0, count( $t ), $env, $depth, $state, true ); if ( null !== $error ) { return $error; @@ -300,6 +303,20 @@ private static function statements( array $t, $i, $to, array $env, $depth, array * @return int|string Index after the block, or the reason it is refused. */ private static function if_block( array $t, $i, $to, array $env, $depth, array &$state ) { + if ( $state['nest'] >= self::MAX_NEST ) { + return self::unknown( $t, $i, $env, 'nests `if` blocks deeper than this check reads' ); + } + $state['nest']++; + $after = self::if_chain( $t, $i, $to, $env, $depth, $state ); + $state['nest']--; + + return $after; + } + + /** + * @return int|string + */ + private static function if_chain( array $t, $i, $to, array $env, $depth, array &$state ) { while ( true ) { $kw = $t[ $i ][0]; if ( T_ELSE !== $kw ) { @@ -433,8 +450,8 @@ private static function simple( array $t, $i, $end, array $env, $depth, array &$ } return null; } - if ( in_array( $t[ $i ][0], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { - return self::include_statement( $t, $i, $end, $env, $depth, $state, $top ); + if ( in_array( $t[ $s ][0], [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { + return self::include_statement( $t, $s, $end, $env, $depth, $state, $top ); } return self::unknown( $t, $i, $env ); @@ -526,17 +543,33 @@ private static function include_statement( array $t, $i, $end, array $env, $dept if ( 'blog-header' === $inc['kind'] ) { return self::unknown( $t, $i, $env ); } + + return self::follow( $t, $i, $inc, $env, $depth ); + } + + /** + * A file a config (or a file it loads) names: absent is fine; inside the scanned WordPress root it must pass the config + * grammar, or else be code the scan reads that touches nothing WordPress loads code from (screen()). + * + * @return string|null + */ + private static function follow( array $t, $i, array $inc, array $env, $depth ) { $base = [ 'ABSPATH' => $env['root'], '__DIR__' => $env['dir'], '__FILE__' => $env['dir'], 'dirname-2' => dirname( $env['dir'] ), + '/' => '', ][ $inc['base'] ]; $path = self::normalise( $base . '/' . ltrim( $inc['path'], '/' ) ); // PHP joins `__DIR__ . 'x.php'` without a slash: a sibling of the directory, never what's meant here. if ( null === $path || '' === $inc['path'] || '/' !== $inc['path'][0] && 'ABSPATH' !== $inc['base'] || '.php' !== substr( $path, -4 ) ) { return self::unknown( $t, $i, $env, 'loads a file this check can\'t name' ); } + // An absolute path is the container's: /var/www is the site's app/. + if ( '/' === $inc['base'] && isset( $env['canon'] ) ) { + $path = call_user_func( $env['canon'], $path ); + } $file = call_user_func( $env['resolve'], $path ); if ( 'absent' === $file['state'] ) { return null; @@ -555,8 +588,91 @@ private static function include_statement( array $t, $i, $end, array $env, $dept if ( $depth >= 2 ) { return "{$env['file']} line {$t[ $i ][2]} loads {$file['real']}, a config file nested too deep for this check"; } + $key = $depth . ':' . $file['real']; + if ( $env['followed']->offsetExists( $key ) ) { + return $env['followed'][ $key ]; + } + if ( count( $env['followed'] ) >= self::MAX_FILES ) { + return "{$env['file']} line {$t[ $i ][2]} loads {$file['real']}, more files than this check follows"; + } + $sub = [ 'dir' => dirname( $file['real'] ), 'file' => $file['real'], 'boot' => false ] + $env; + $error = self::check_config( $file['source'], $sub, $depth + 1 ); + if ( null !== $error ) { + $error = self::screen( $file['source'], $sub, $depth + 1 ); + } + $env['followed'][ $key ] = $error; + + return $error; + } + + /** + * A file below the WordPress root that the scan reads as code but that doesn't fit the config grammar (a plugin's + * generated headers file, say). PHP loads it before wp-settings.php, so it may not name the constants or globals + * WordPress loads code from, run code from a string, or load a file other than one follow() accepts. Like the --vip + * files, it is a token screen, not a proof: deliberate evasion is left to the coverage of app/. + * + * @return string|null + */ + private static function screen( $source, array $env, $depth ) { + $t = self::tokens( $source ); + if ( is_string( $t ) ) { + return "{$env['file']}: $t"; + } + $names = array_merge( array_keys( self::DIR_DEFAULTS ), self::NEVER_DEFINED, self::INSIDE_ROOT, self::NAME_VALUES ); + $deny = [ 'extract', 'parse_str', 'call_user_func', 'call_user_func_array', 'create_function', 'set_include_path', 'spl_autoload', 'ini_alter', 'assert', 'preg_replace', 'unserialize', 'constant' ]; + $n = count( $t ); + for ( $i = 0; $i < $n; $i++ ) { + list( $id, $text, $line ) = $t[ $i ]; + $at = "{$env['file']} line $line"; + $word = T_CONSTANT_ENCAPSED_STRING === $id ? substr( $text, 1, -1 ) : $text; + $call = isset( $t[ $i + 1 ] ) && '(' === $t[ $i + 1 ][0]; + if ( ( T_STRING === $id || T_CONSTANT_ENCAPSED_STRING === $id ) && in_array( self::upper( $word ), $names, true ) ) { + return "$at names $word, which changes where WordPress loads code from"; + } + if ( T_VARIABLE === $id && in_array( substr( $text, 1 ), [ 'GLOBALS', 'wp_filter', 'wp_theme_directories', 'wp_plugin_paths', 'wp_local_package', 'locale' ], true ) ) { + return "$at uses $text, which WordPress reads to find code"; + } + if ( in_array( $id, [ T_EVAL, '`', '$' ], true ) || $call && in_array( $id, [ T_VARIABLE, T_CONSTANT_ENCAPSED_STRING ], true ) ) { + return "$at runs code this check can't read"; + } + if ( T_STRING === $id && $call && in_array( self::lower( $text ), $deny, true ) ) { + return "$at calls $text(), which can load code or set what this check can't see"; + } + if ( T_STRING === $id && $call && 'ini_set' === self::lower( $text ) ) { + $close = self::matching( $t, $i + 1, $n ); + $args = null === $close ? null : self::call_args( $t, $i, $close + 1 ); + if ( ! $args || ! in_array( self::lower( (string) self::literal_arg( $t, $args[0] ) ), self::INI_KEYS, true ) ) { + return "$at calls ini_set() for a setting this check doesn't accept"; + } + } + if ( ( T_STRING === $id && $call && 'define' === self::lower( $text ) || T_CONST === $id ) ) { + $close = T_CONST === $id ? null : self::matching( $t, $i + 1, $n ); + $args = null === $close ? null : self::call_args( $t, $i, $close + 1 ); + $name = T_CONST === $id ? ( isset( $t[ $i + 1 ] ) && T_STRING === $t[ $i + 1 ][0] ? $t[ $i + 1 ][1] : null ) : ( $args ? self::name_literal( $t, $args[0] ) : null ); + if ( null === $name ) { + return "$at defines a constant whose name is not a plain string"; + } + if ( 'ABSPATH' === self::upper( $name ) ) { + return "$at defines ABSPATH, which only WordPress's own guard in wp-config.php may"; + } + } + if ( in_array( $id, [ T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE ], true ) ) { + $end = self::statement_end( $t, $i ); + $inc = null === $end ? null : self::include_target( $t, $i, $end ); + if ( null === $inc || 'blog-header' === $inc['kind'] ) { + return "$at loads a file this check can't name"; + } + if ( 'settings' === $inc['kind'] ) { + return "$at loads wp-settings.php somewhere other than at the end of wp-config.php"; + } + $error = self::follow( $t, $i, $inc, $env, $depth ); + if ( null !== $error ) { + return $error; + } + } + } - return self::check_config( $file['source'], [ 'dir' => dirname( $file['real'] ), 'file' => $file['real'], 'boot' => false ] + $env, $depth + 1 ); + return null; } /** @@ -584,6 +700,14 @@ public static function vip_file( $source, $kind ) { if ( T_VARIABLE === $id && in_array( substr( $text, 1 ), [ 'GLOBALS', 'wp_filter', 'wp_theme_directories' ], true ) ) { return "line $line uses $text"; } + // A name built at run time (`'WP_' . 'CONTENT_DIR'`) would get past the name check above. + if ( T_STRING === $id && 'define' === self::lower( $text ) && isset( $t[ $i + 1 ] ) && '(' === $t[ $i + 1 ][0] ) { + $close = self::matching( $t, $i + 1, $n ); + $args = null === $close ? null : self::call_args( $t, $i, $close + 1 ); + if ( ! $args || null === self::name_literal( $t, $args[0] ) ) { + return "line $line defines a constant whose name is not a plain string"; + } + } if ( in_array( $id, [ T_EVAL, '`', '$' ], true ) || T_VARIABLE === $id && isset( $t[ $i + 1 ] ) && '(' === $t[ $i + 1 ][0] ) { return "line $line runs code this check can't read"; } @@ -767,6 +891,12 @@ function ( $tok ) { 'T_STRING:dirname ( T_FILE:__file__ ) .' => '__FILE__', 'T_STRING:dirname ( T_DIR:__dir__ ) .' => 'dirname-2', ]; + // An absolute literal: `require '/var/www/htdocs/wp-content/x.php';`. + if ( 1 === count( $ops ) && T_CONSTANT_ENCAPSED_STRING === $ops[0][0] ) { + $path = self::literal( $ops[0][1] ); + + return null === $path || '/' !== substr( $path, 0, 1 ) || preg_match( '#(^|/)\.\.?(/|$)#', $path ) || preg_match( '/[\x00-\x1F\x7F]/', $path ) ? null : [ 'kind' => 'file', 'base' => '/', 'path' => $path ]; + } foreach ( $bases as $prefix => $base ) { if ( 0 !== strpos( $sig, $prefix . ' ' ) || 'ABSPATH' === $base && 'ABSPATH' !== $ops[0][1] ) { continue; @@ -782,7 +912,7 @@ function ( $tok ) { if ( 'ABSPATH' === $base && in_array( $path, [ 'wp-settings.php', '/wp-settings.php' ], true ) ) { return [ 'kind' => 'settings', 'base' => $base, 'path' => $path ]; } - if ( in_array( $base, [ '__DIR__', '__FILE__' ], true ) && preg_match( '#^(?:/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*/wp-blog-header\.php$#D', $path ) ) { + if ( in_array( $base, [ '__DIR__', '__FILE__' ], true ) && preg_match( '#^(?:/[A-Za-z0-9_-](?:[A-Za-z0-9_.-]*[A-Za-z0-9_-])?)*/wp-blog-header\.php$#D', $path ) ) { return [ 'kind' => 'blog-header', 'base' => $base, 'path' => $path ]; } return [ 'kind' => 'file', 'base' => $base, 'path' => $path ]; From 435260a6a237fdad88c10d39b50aef91c526c315 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:28:31 +0530 Subject: [PATCH 34/53] fix(site): accept WP Engine's $wpe_* leftovers in wp-config.php Sites moved from WP Engine keep its `$wpe_cdn_uris=array ( );` family in wp-config.php. Only WP Engine's own plugin reads them, so php-compat no longer refuses the site for them. --- src/helper/Site_PHP_Compat_Layout.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index 3cea23a7..95cf6438 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -29,7 +29,10 @@ class Site_PHP_Compat_Layout { /** Constants core puts into the name of a file it loads (locale file, filesystem class, theme): a plain name only. */ const NAME_VALUES = [ 'WPLANG', 'FS_METHOD', 'WP_DEFAULT_THEME' ]; - /** The only variables a config may assign (table prefix, multisite, EE's --cache and memcached object caches). */ + /** + * The only variables a config may assign (table prefix, multisite, EE's --cache and memcached object caches, the locals of + * reverse-proxy snippets), besides WP Engine's `$wpe_*` leftovers, which only its own plugin reads. + */ const VARIABLES = [ 'table_prefix', 'base', 'redis_server', 'memcached_servers', 'forwarded_ips', 'http_x_headers', 'xffaddrs', 'batcache' ]; /** The only $_SERVER keys a config may set: what proxy and HTTPS snippets set, never where the script is. */ @@ -428,7 +431,7 @@ private static function simple( array $t, $i, $end, array $env, $depth, array &$ return self::unknown( $t, $i, $env, 'sets a $_SERVER key this check doesn\'t accept' ); } $eq = $i + 4; - } elseif ( ! in_array( $name, self::VARIABLES, true ) ) { + } elseif ( ! in_array( $name, self::VARIABLES, true ) && 0 !== strpos( $name, 'wpe_' ) ) { return self::unknown( $t, $i, $env, "assigns \${$name}, which this check doesn't accept" ); } if ( ! isset( $t[ $eq ] ) || '=' !== $t[ $eq ][0] || $eq + 1 >= $end ) { From a7a1b29ab85aa9bb0261289670d6232f25fcc2f0 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:41:33 +0530 Subject: [PATCH 35/53] feat(site): give php-compat's positive verdict only when the scanner read every code file - After the scan, every code file in app/ (by the manifest's extensions and content sniff, all directories, links resolved) must be one the scanner lists in its manifest as checked or not checked, or an exact exempt shape: old releases when nginx serves current/, the live WordPress root's core files, EE's unused app/wp-config.php beside the root's own, and the served index.php of WordPress-in-a-subdirectory. Anything else, or no manifest, is can't confirm, with up to 10 of the files named. The JSON summary and report carry cross_check. - Paths a site writes are never collapsed as text on an accept path: directory constants, includes and prepend values are resolved the way the container resolves them; a wp-cli.yml path: with a `.` or `..` segment or `//` isn't used. --- src/helper/Site_PHP_Compat.php | 241 +++++++++++++++++++++++++- src/helper/Site_PHP_Compat_Layout.php | 8 +- 2 files changed, 237 insertions(+), 12 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 3ef09ebb..31776b70 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -45,7 +45,7 @@ class Site_PHP_Compat { const SUMMARY_INTS = [ 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'duration_s' ]; const ESTIMATE_INTS = [ 'php_files', 'php_bytes', 'components', 'estimated_seconds', 'estimated_seconds_low', 'estimated_seconds_high' ]; // --format=json prints only the documented keys (INTERFACE.md), in this order. - const SUMMARY_KEYS = [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'checked', 'not_checked', 'not_checked_more', 'wordpress', 'duration_s', 'tool' ]; + const SUMMARY_KEYS = [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'checked', 'not_checked', 'not_checked_more', 'wordpress', 'cross_check', 'duration_s', 'tool' ]; // stdout stays fixed-size: at most this many not_checked entries, each string at most NOT_CHECKED_CHARS characters. const NOT_CHECKED_STDOUT = 10; @@ -155,6 +155,12 @@ class Site_PHP_Compat { /** @var array|null WordPress's version ( version, branch ) read from the scanned root's wp-includes/version.php. */ protected $wp_version; + /** @var array|null What resolve_layout() found, for the cross-check: top, abspath, a2 index (real host paths). */ + protected $cross_layout; + + /** @var array|null The cross-check of the scanner's manifest (cross_check()). */ + protected $cross; + /** @var bool Whether the record/nginx root mismatch was already reported. */ protected $warned_root = false; @@ -522,6 +528,9 @@ protected function run_scan( $site_data, $timeout, $output ) { return $this->doc( 'tool_error', self::exit_detail( $run, 'without a valid report' ) ); } + // The final gate: every code file in app/ is one the scanner read or reported, or an exact exempt shape. + $this->cross = $this->cross_check( $code, $out ); + // Last point a cancel wins: after it, the result stands and --output is written. if ( $this->cancel_requested() ) { return $this->cancelled(); @@ -1003,7 +1012,8 @@ function ( $path, $name, $type ) use ( &$user_ini ) { return 'dir' === $type; } ); - $detail = null !== $error ? "can't look through {$app}htdocs for .user.ini files: $error" : $this->prepend_check( $site_data, $code, $user_ini, null ); + $this->cross_layout = [ 'top' => self::resolve_in( $code, $rel ), 'abspath' => null, 'index' => null ]; + $detail = null !== $error ? "can't look through {$app}htdocs for .user.ini files: $error" : $this->prepend_check( $site_data, $code, $user_ini, null ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); } @@ -1038,6 +1048,12 @@ function ( $path, $name, $type ) use ( &$user_ini ) { } $allowed = array_merge( $allowed, $config ); } + $this->cross_layout = [ + 'top' => self::resolve_in( $code, $rel ), + 'abspath' => $layout['abspath'], + // (d): the served index.php of layout a2, which passed WordPress's own loader recogniser above. + 'index' => $root !== $rel ? $index : null, + ]; $walk = $this->app_walk( $code, $rel, $root, $layout['abspath'], $allowed ); if ( is_string( $walk ) ) { return $this->doc( 'tool_error', str_replace( "$code/", $app, $walk ) ); @@ -1327,6 +1343,199 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ return '!' === $found[0] ? self::clean( substr( $found, 1 ) ) : self::clean( $found ) . '; this check can\'t scan that layout'; } + /** + * Compares every code file in app/ with the scanner's manifest (/out/manifest.json): each must be in `checked`, in or + * under `not_checked`, or one of the exact exempt shapes (INTERFACE.md "Cross-check"): (a) old releases when nginx serves + * current/ or deeper, (b) the live WordPress root's core files, (c) EE's unused app/wp-config.php beside the root's own, + * (d) the served index.php of layout a2. Code is what the manifest says: its extensions, and its content sniff. + * + * @param string $code Real path of the site's app/. + * @param string $out The scan's /out directory on the host. + * + * @return array manifest (bool), unlisted (up to 10 container paths), unlisted_more (int), error (string|null). + */ + protected function cross_check( $code, $out ) { + $result = [ 'manifest' => false, 'unlisted' => [], 'unlisted_more' => 0, 'error' => null ]; + $file = $out . '/manifest.json'; + clearstatcache( true, $file ); + $raw = is_file( $file ) && ! is_link( $file ) && filesize( $file ) <= self::REPORT_MAX ? @file_get_contents( $file ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + $m = false === $raw ? null : json_decode( $raw, true ); + $ok = is_array( $m ) && isset( $m['v'], $m['code_extensions'], $m['checked'], $m['not_checked'] ) && 1 === $m['v'] && array_key_exists( 'sniff', $m ) + && is_array( $m['code_extensions'] ) && is_array( $m['checked'] ) && is_array( $m['not_checked'] ); + foreach ( $ok ? array_merge( $m['code_extensions'], $m['checked'], $m['not_checked'] ) : [] as $value ) { + $ok = $ok && is_string( $value ) && '' !== $value; + } + $sniff = $ok ? self::manifest_sniff( $m['sniff'] ) : false; + if ( ! $ok || false === $sniff ) { + return $result; + } + $result['manifest'] = true; + $insensitive = ! empty( $m['extensions_case_insensitive'] ); + $extensions = array_map( + function ( $ext ) { + return preg_quote( $ext, '/' ); + }, + $m['code_extensions'] + ); + $code_name = '/\.(?:' . implode( '|', $extensions ) . ')$/D' . ( $insensitive ? 'i' : '' ); + $checked = array_flip( $m['checked'] ); + $not_checked = $m['not_checked']; + $exempt = $this->cross_exempt( $code ); + $unlisted = []; + $count = 0; + $result['error'] = $this->walk_tree( + $code, + function ( $path, $name, $type ) use ( $code, $code_name, $sniff, $checked, $not_checked, $exempt, &$unlisted, &$count ) { + if ( 'dir' === $type ) { + return true; + } + if ( 'file' !== $type || ! ( preg_match( $code_name, $name ) || self::sniffed( $path, $name, $sniff ) ) ) { + return false; + } + $container = '/var/www' . substr( $path, strlen( $code ) ); + if ( isset( $checked[ $container ] ) || call_user_func( $exempt, $path ) ) { + return false; + } + foreach ( $not_checked as $entry ) { + if ( $entry === $container || '/' === substr( $entry, -1 ) && 0 === strpos( $container, $entry ) ) { + return false; + } + } + if ( ++$count <= self::NOT_CHECKED_STDOUT ) { + $unlisted[] = self::clean( $container ); + } + return false; + } + ); + $result['unlisted'] = $unlisted; + $result['unlisted_more'] = max( 0, $count - self::NOT_CHECKED_STDOUT ); + + return $result; + } + + /** + * The manifest's content sniff, validated: null (extensions only), [ bytes, regex, exclude, scope ], or false when it + * is something this check can't apply exactly. + * + * @param mixed $sniff Manifest value. + * + * @return array|null|false + */ + protected static function manifest_sniff( $sniff ) { + if ( null === $sniff ) { + return null; + } + if ( ! is_array( $sniff ) || ! isset( $sniff['bytes'], $sniff['regex'] ) || ! is_int( $sniff['bytes'] ) || $sniff['bytes'] < 1 || ! is_string( $sniff['regex'] ) || false === @preg_match( $sniff['regex'], '' ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- an invalid pattern is false. + return false; + } + $exclude = isset( $sniff['exclude_extensions'] ) ? $sniff['exclude_extensions'] : []; + $scope = isset( $sniff['scope'] ) ? $sniff['scope'] : 'all'; + if ( ! is_array( $exclude ) || 'all' !== $scope ) { + // Only the scope this check knows how to reproduce; anything else fails closed (no positive verdict). + return false; + } + foreach ( $exclude as $ext ) { + if ( ! is_string( $ext ) ) { + return false; + } + } + + return [ min( $sniff['bytes'], 1048576 ), $sniff['regex'], array_map( 'strtolower', $exclude ) ]; + } + + /** + * Whether a regular file without a code extension is code by the manifest's sniff. + * + * @param string $path Real host path. + * @param string $name File name. + * @param array|null $sniff manifest_sniff(). + * + * @return bool + */ + protected static function sniffed( $path, $name, $sniff ) { + if ( null === $sniff ) { + return false; + } + list( $bytes, $regex, $exclude ) = $sniff; + $dot = strrpos( $name, '.' ); + if ( false !== $dot && in_array( strtolower( substr( $name, $dot + 1 ) ), $exclude, true ) ) { + return false; + } + $handle = @fopen( $path, 'rb' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable is sniffed as nothing. + if ( false === $handle ) { + return true; + } + $head = (string) fread( $handle, $bytes ); + fclose( $handle ); + + return 1 === preg_match( $regex, $head ); + } + + /** + * The exact exempt shapes of the cross-check (INTERFACE.md "Cross-check", each approved by the user). + * + * @param string $code Real path of the site's app/. + * + * @return callable( $real_host_path ) bool + */ + protected function cross_exempt( $code ) { + $layout = null === $this->cross_layout ? [ 'top' => null, 'abspath' => null, 'index' => null ] : $this->cross_layout; + $abspath = $layout['abspath']; + $top = $layout['top']; + // (a) The live release: the WordPress root's (or the served root's) ancestor directly in releases/. + $live = null; + for ( $dir = null !== $abspath ? $abspath : $top; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { + if ( 'releases' === basename( dirname( $dir ) ) ) { + $live = $dir; + break; + } + } + $old_releases = null !== $live && null !== $top && 0 === strpos( $top . '/', $live . '/' ) ? dirname( $live ) : null; + // (c) EE's app/wp-config.php when the WordPress root has its own, which WordPress loads first. + $unused_config = null !== $abspath && $abspath !== $code && is_file( "$abspath/wp-config.php" ) ? "$code/wp-config.php" : null; + $index = $layout['index']; + + return function ( $path ) use ( $abspath, $old_releases, $live, $unused_config, $index ) { + if ( null !== $old_releases && 0 === strpos( $path, $old_releases . '/' ) && 0 !== strpos( $path, $live . '/' ) ) { + return true; + } + if ( null !== $abspath && 0 === strpos( $path, $abspath . '/' ) ) { + $rel = substr( $path, strlen( $abspath ) + 1 ); + if ( 0 === strpos( $rel, 'wp-admin/' ) || 0 === strpos( $rel, 'wp-includes/' ) || in_array( $rel, self::CORE_FILES, true ) ) { + return true; + } + } + + return $path === $unused_config || $path === $index; + }; + } + + /** + * @param array|null $cross cross_check() result. + * + * @return bool Whether the cross-check allows a positive verdict. + */ + protected static function cross_ok( $cross ) { + return null !== $cross && $cross['manifest'] && null === $cross['error'] && ! $cross['unlisted'] && 0 === $cross['unlisted_more']; + } + + /** + * @param array|null $cross cross_check() result. + * + * @return string Why the cross-check refuses a positive verdict. + */ + protected static function cross_text( $cross ) { + if ( null === $cross || ! $cross['manifest'] ) { + return "the scanner gave no list of the files it read (an older scanner image), so this check can't tell that it read all the site's code"; + } + if ( null !== $cross['error'] ) { + return "can't list the site's files to compare with what the scanner read: {$cross['error']}"; + } + $count = count( $cross['unlisted'] ) + $cross['unlisted_more']; + + return sprintf( '%s the scanner didn\'t read: %s%s', self::count_of( $count, 'code file' ), implode( ', ', $cross['unlisted'] ), $cross['unlisted_more'] > 0 ? ", and {$cross['unlisted_more']} more" : '' ); + } + /** * Whether a link target is (in) another WordPress install: the target, any of its ancestors up to app/, or (for a * directory) any direct child holds wp-settings.php or wp-includes/. The live WordPress root doesn't count. @@ -1535,11 +1744,11 @@ protected function php_setting_ok( $code, $key, $value, $layout, $quoted = false if ( $off ) { return true; } - $path = Site_PHP_Compat_Layout::normalise( $value ); - if ( '/' !== $value[0] || null === $path || 0 !== strpos( $path, '/var/www/' ) ) { + // Resolved like the container resolves it (links first, then `..`), never collapsed as text. + if ( 0 !== strpos( $value, '/var/www/' ) ) { return false; } - $file = $this->site_file( $code, substr( $path, strlen( '/var/www/' ) ), self::PHP_SOURCE_MAX ); + $file = $this->site_file( $code, substr( $value, strlen( '/var/www/' ) ), self::PHP_SOURCE_MAX ); if ( 'ok' !== $file['state'] ) { return false; } @@ -1836,7 +2045,11 @@ protected function wp_cli_path( $code, $dir ) { } else { $path = $dir . '/' . $path; } - $path = trim( preg_replace( '#/+#', '/', preg_replace( '#(^|/)\.(?=/|$)#', '$1', $path ) ), '/' ); + // Never collapsed as text: a `.` or `..` segment, or `//`, isn't a path this check names. + if ( preg_match( '#(^|/)\.\.?(/|$)|//#', $path ) ) { + return null; + } + $path = trim( $path, '/' ); return preg_match( '#^htdocs(?:/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*$#D', $path ) ? $path : null; } @@ -2836,7 +3049,7 @@ protected function output_dir_unchanged( $path ) { */ protected function scoped( array $doc, array $report ) { // Only EE sets these; the scanner can't. - unset( $doc['checked'], $doc['not_checked'], $doc['wordpress'] ); + unset( $doc['checked'], $doc['not_checked'], $doc['wordpress'], $doc['cross_check'] ); $doc['checked'] = [ 'dir' => self::clean( (string) $this->looked_in ), 'components' => $doc['components_checked'], @@ -2867,9 +3080,14 @@ function ( $entry ) { 'core_files_checked' => false, ]; } + $doc['cross_check'] = null === $this->cross ? null : [ + 'manifest' => $this->cross['manifest'], + 'unlisted' => $this->cross['unlisted'], + 'unlisted_more' => $this->cross['unlisted_more'], + ]; if ( $doc['errors'] > 0 || ( null !== $core && false === $core['supports'] ) ) { $doc['safe_to_upgrade'] = false; - } elseif ( $doc['files_not_checked'] > 0 || ( null !== $core && null === $core['supports'] ) ) { + } elseif ( $doc['files_not_checked'] > 0 || ( null !== $core && null === $core['supports'] ) || ! self::cross_ok( $this->cross ) ) { $doc['safe_to_upgrade'] = null; } else { $doc['safe_to_upgrade'] = true; @@ -3178,8 +3396,13 @@ protected function table_lines( array $doc, $report ) { if ( null !== $why ) { yield ucfirst( $why ) . '.'; } - } else { + } elseif ( null !== $why ) { yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %s. %s', $site, $target, $why, $tail ); + } else { + yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %s. %s', $site, $target, self::cross_text( $this->cross ), $tail ); + } + if ( ( $doc['files_not_checked'] > 0 || null !== $why ) && ! self::cross_ok( $this->cross ) ) { + yield ucfirst( self::cross_text( $this->cross ) ) . '.'; } } yield ''; diff --git a/src/helper/Site_PHP_Compat_Layout.php b/src/helper/Site_PHP_Compat_Layout.php index 08592ae0..b1de65b3 100644 --- a/src/helper/Site_PHP_Compat_Layout.php +++ b/src/helper/Site_PHP_Compat_Layout.php @@ -564,9 +564,10 @@ private static function follow( array $t, $i, array $inc, array $env, $depth ) { 'dirname-2' => dirname( $env['dir'] ), '/' => '', ][ $inc['base'] ]; - $path = self::normalise( $base . '/' . ltrim( $inc['path'], '/' ) ); + // No textual normalising: the literal has no `.` or `..` segment, and resolve() follows links like PHP. + $path = $base . '/' . ltrim( $inc['path'], '/' ); // PHP joins `__DIR__ . 'x.php'` without a slash: a sibling of the directory, never what's meant here. - if ( null === $path || '' === $inc['path'] || '/' !== $inc['path'][0] && 'ABSPATH' !== $inc['base'] || '.php' !== substr( $path, -4 ) ) { + if ( '' === $inc['path'] || '/' !== $inc['path'][0] && 'ABSPATH' !== $inc['base'] || '.php' !== substr( $path, -4 ) ) { return self::unknown( $t, $i, $env, 'loads a file this check can\'t name' ); } // An absolute path is the container's: /var/www is the site's app/. @@ -861,7 +862,8 @@ private static function path_value( array $t, $from, $to, array $env, $content ) return false; } - return self::normalise( $path ); + // Returned as joined: canon() resolves it the way PHP does (links first); never collapsed as text. + return $path; } /** From 7f793b0d348cc2ae0f41cd53f7eb6aa282eaf167 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:46:30 +0530 Subject: [PATCH 36/53] fix(site): read the scanner's real file manifest in php-compat's cross-check - Reads the manifest the scanner writes: phar_regex (a phar is code and must be not checked), the content sniff with scope except_skipped_dirs (no sniff below the skipped dirs it lists, by name), roots, old_releases and core, and b64: paths in every path field. Any other scope, an unknown version or a malformed manifest gives no positive verdict. - Compares files by inode on the host, mapping /var/www to app/ only when no link is on the way; a not checked directory covers what is below it by real path. - A file uid 33 can't read is not sniffed, judged from its mode bits and its directories' (only a certain no counts); a code-named file is code either way. - The manifest's exemptions count only where EE's own shape check agrees: old releases only when nginx serves the live release (php: also listed by the scanner; wp: never listed), core only for the live WordPress root and only what both call core, so index.php must be read. When roots, core or old releases disagree, nothing is positive. excluded exempts nothing. --- src/helper/Site_PHP_Compat.php | 446 ++++++++++++++++++++++++++------- 1 file changed, 351 insertions(+), 95 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 31776b70..bd6383c5 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -107,6 +107,9 @@ class Site_PHP_Compat { /** Longest php-compat lists the site's files for (PHP outside WordPress, links, .user.ini files). */ const WALK_SECONDS = 120; + // Directory names the scanner searches by name only (its manifest's sniff.skipped_dirs); the sniff doesn't apply below them. + const SCANNER_SKIP_NAMES = [ 'uploads', 'cache', 'upgrade', 'upgrade-temp-backup', 'node_modules', '.git' ]; + /** EE's own config/nginx/custom/admin-tools.conf (site-type-wp templates/config/nginx/admin-tools.conf.mustache). */ const ADMIN_TOOLS_CONF = "# ee-admin pages\nlocation ^~ /ee-admin/ {\n\troot /var/www/htdocs ;\n\tlocation ~ \\.php$ {\n\t\ttry_files \$uri =404;\n\t\tinclude fastcgi_params;\n\t\tfastcgi_pass php;\n\t}\n}\n"; @@ -155,7 +158,7 @@ class Site_PHP_Compat { /** @var array|null WordPress's version ( version, branch ) read from the scanned root's wp-includes/version.php. */ protected $wp_version; - /** @var array|null What resolve_layout() found, for the cross-check: top, abspath, a2 index (real host paths). */ + /** @var array|null What resolve_layout() found, for the cross-check: wp, and as real host paths scan (the scanner's root), top, abspath, a2 index. */ protected $cross_layout; /** @var array|null The cross-check of the scanner's manifest (cross_check()). */ @@ -1012,7 +1015,7 @@ function ( $path, $name, $type ) use ( &$user_ini ) { return 'dir' === $type; } ); - $this->cross_layout = [ 'top' => self::resolve_in( $code, $rel ), 'abspath' => null, 'index' => null ]; + $this->cross_layout = [ 'wp' => false, 'scan' => $code, 'top' => self::resolve_in( $code, $rel ), 'abspath' => null, 'index' => null ]; $detail = null !== $error ? "can't look through {$app}htdocs for .user.ini files: $error" : $this->prepend_check( $site_data, $code, $user_ini, null ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); } @@ -1049,6 +1052,8 @@ function ( $path, $name, $type ) use ( &$user_ini ) { $allowed = array_merge( $allowed, $config ); } $this->cross_layout = [ + 'wp' => true, + 'scan' => self::resolve_in( $code, $root ), 'top' => self::resolve_in( $code, $rel ), 'abspath' => $layout['abspath'], // (d): the served index.php of layout a2, which passed WordPress's own loader recogniser above. @@ -1344,10 +1349,10 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ } /** - * Compares every code file in app/ with the scanner's manifest (/out/manifest.json): each must be in `checked`, in or - * under `not_checked`, or one of the exact exempt shapes (INTERFACE.md "Cross-check"): (a) old releases when nginx serves - * current/ or deeper, (b) the live WordPress root's core files, (c) EE's unused app/wp-config.php beside the root's own, - * (d) the served index.php of layout a2. Code is what the manifest says: its extensions, and its content sniff. + * Compares every code file in app/ with the scanner's manifest (/out/manifest.json, INTERFACE.md "File manifest"): + * each must be in `checked` or `not_checked` (by inode, or under a not_checked directory), or one of the exact exempt + * shapes of "Cross-check". Code is what the manifest says it is; the manifest's own exemptions count only where EE's + * shape check agrees. * * @param string $code Real path of the site's app/. * @param string $out The scan's /out directory on the host. @@ -1356,57 +1361,70 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ */ protected function cross_check( $code, $out ) { $result = [ 'manifest' => false, 'unlisted' => [], 'unlisted_more' => 0, 'error' => null ]; - $file = $out . '/manifest.json'; - clearstatcache( true, $file ); - $raw = is_file( $file ) && ! is_link( $file ) && filesize( $file ) <= self::REPORT_MAX ? @file_get_contents( $file ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. - $m = false === $raw ? null : json_decode( $raw, true ); - $ok = is_array( $m ) && isset( $m['v'], $m['code_extensions'], $m['checked'], $m['not_checked'] ) && 1 === $m['v'] && array_key_exists( 'sniff', $m ) - && is_array( $m['code_extensions'] ) && is_array( $m['checked'] ) && is_array( $m['not_checked'] ); - foreach ( $ok ? array_merge( $m['code_extensions'], $m['checked'], $m['not_checked'] ) : [] as $value ) { - $ok = $ok && is_string( $value ) && '' !== $value; - } - $sniff = $ok ? self::manifest_sniff( $m['sniff'] ) : false; - if ( ! $ok || false === $sniff ) { + $m = $this->read_manifest( $out ); + if ( ! is_array( $m ) ) { + $result['error'] = $m; + return $result; + } + $rules = $this->manifest_rules( $code, $m ); + if ( is_string( $rules ) ) { + $result['error'] = $rules; return $result; } $result['manifest'] = true; - $insensitive = ! empty( $m['extensions_case_insensitive'] ); - $extensions = array_map( - function ( $ext ) { - return preg_quote( $ext, '/' ); - }, - $m['code_extensions'] - ); - $code_name = '/\.(?:' . implode( '|', $extensions ) . ')$/D' . ( $insensitive ? 'i' : '' ); - $checked = array_flip( $m['checked'] ); - $not_checked = $m['not_checked']; - $exempt = $this->cross_exempt( $code ); $unlisted = []; $count = 0; - $result['error'] = $this->walk_tree( + $seen = []; + $searchable = [ $code => self::uid33_may( @lstat( $code ), 0100 ) ]; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + $covered = function ( $path, array $stat, $phar ) use ( $code, $rules ) { + $ino = $stat['dev'] . ':' . $stat['ino']; + if ( ( ! $phar && isset( $rules['checked'][ $ino ] ) ) || isset( $rules['nc_files'][ $ino ] ) || null !== self::under_any( $path, $code, $rules['nc_dirs'] ) ) { + return true; + } + return call_user_func( $rules['exempt'], $path ); + }; + $walk = $this->walk_tree( $code, - function ( $path, $name, $type ) use ( $code, $code_name, $sniff, $checked, $not_checked, $exempt, &$unlisted, &$count ) { + function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $covered, &$searchable, &$seen, &$unlisted, &$count ) { if ( 'dir' === $type ) { + $searchable[ $path ] = $searchable[ dirname( $path ) ] && self::uid33_may( $stat, 0100 ); return true; } - if ( 'file' !== $type || ! ( preg_match( $code_name, $name ) || self::sniffed( $path, $name, $sniff ) ) ) { - return false; - } - $container = '/var/www' . substr( $path, strlen( $code ) ); - if ( isset( $checked[ $container ] ) || call_user_func( $exempt, $path ) ) { + if ( 'link' === $type ) { + // A code-named link runs its target as code, whatever the target is called. + if ( ! preg_match( $rules['code_name'], $name ) && ! preg_match( $rules['phar'], $name ) ) { + return false; + } + $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); + $stat = null === $target ? false : @lstat( $target ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $stat || 0100000 !== ( $stat['mode'] & 0170000 ) ) { + return false; + } + $phar = 1 === preg_match( $rules['phar'], $name ) || 1 === preg_match( $rules['phar'], basename( $target ) ); + $path = $target; + } elseif ( 'file' !== $type ) { return false; - } - foreach ( $not_checked as $entry ) { - if ( $entry === $container || '/' === substr( $entry, -1 ) && 0 === strpos( $container, $entry ) ) { + } else { + $phar = 1 === preg_match( $rules['phar'], $name ); + if ( ! $phar && ! preg_match( $rules['code_name'], $name ) && ! $this->manifest_sniffs( $path, $name, $stat, $searchable[ dirname( $path ) ], $rules ) ) { return false; } } + // A file reached again (through a link, or a hard link) counts once. + $ino = $stat['dev'] . ':' . $stat['ino']; + if ( isset( $seen[ $ino ] ) || $covered( $path, $stat, $phar ) ) { + return false; + } + $seen[ $ino ] = true; if ( ++$count <= self::NOT_CHECKED_STDOUT ) { - $unlisted[] = self::clean( $container ); + $unlisted[] = self::clean( '/var/www' . substr( $path, strlen( $code ) ) ); } return false; } ); + if ( null !== $walk ) { + $result['error'] = "can't list the site's files to compare with what the scanner read: $walk"; + } $result['unlisted'] = $unlisted; $result['unlisted_more'] = max( 0, $count - self::NOT_CHECKED_STDOUT ); @@ -1414,75 +1432,175 @@ function ( $path, $name, $type ) use ( $code, $code_name, $sniff, $checked, $not } /** - * The manifest's content sniff, validated: null (extensions only), [ bytes, regex, exclude, scope ], or false when it - * is something this check can't apply exactly. + * Reads and validates /out/manifest.json; paths written `b64:` are decoded. * - * @param mixed $sniff Manifest value. + * @param string $out The scan's /out directory on the host. * - * @return array|null|false + * @return array|string|null The manifest; null when there is none; why it can't be used. */ - protected static function manifest_sniff( $sniff ) { - if ( null === $sniff ) { + protected function read_manifest( $out ) { + $file = $out . '/manifest.json'; + clearstatcache( true, $file ); + if ( false === @lstat( $file ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- none is an older scanner. return null; } - if ( ! is_array( $sniff ) || ! isset( $sniff['bytes'], $sniff['regex'] ) || ! is_int( $sniff['bytes'] ) || $sniff['bytes'] < 1 || ! is_string( $sniff['regex'] ) || false === @preg_match( $sniff['regex'], '' ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- an invalid pattern is false. - return false; + $bad = "the scanner's list of the files it read can't be used"; + try { + self::raise_memory_limit(); + $raw = \EE\Site\Utils\get_container_file_contents( $file, $out, self::REPORT_MAX ); + if ( ! $this->make_room( self::decode_cost( $raw ) ) ) { + return "$bad: it needs more memory to read than is available"; + } + $m = json_decode( $raw, true ); + } catch ( \Exception $e ) { + return "$bad: " . self::clean( $e->getMessage() ); } - $exclude = isset( $sniff['exclude_extensions'] ) ? $sniff['exclude_extensions'] : []; - $scope = isset( $sniff['scope'] ) ? $sniff['scope'] : 'all'; - if ( ! is_array( $exclude ) || 'all' !== $scope ) { - // Only the scope this check knows how to reproduce; anything else fails closed (no positive verdict). - return false; + if ( ! is_array( $m ) || ! array_key_exists( 'v', $m ) ) { + return "$bad: it isn't valid"; } - foreach ( $exclude as $ext ) { - if ( ! is_string( $ext ) ) { + if ( 1 !== $m['v'] ) { + return "$bad: its version isn't one this check knows"; + } + $strings = function ( $list ) { + if ( ! is_array( $list ) || array_values( $list ) !== $list ) { return false; } + foreach ( $list as $item ) { + if ( ! is_string( $item ) || '' === $item ) { + return false; + } + } + return true; + }; + $regex = function ( $value ) { + return is_string( $value ) && false !== @preg_match( $value, '' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- an invalid pattern is false. + }; + $sniff = isset( $m['sniff'] ) ? $m['sniff'] : null; + $core = isset( $m['core'] ) ? $m['core'] : null; + $valid = isset( $m['code_extensions'], $m['phar_regex'], $m['roots'], $m['excluded'], $m['old_releases'], $m['checked'], $m['not_checked'] ) + && $strings( $m['code_extensions'] ) && $m['code_extensions'] && isset( $m['extensions_case_insensitive'] ) && is_bool( $m['extensions_case_insensitive'] ) && $regex( $m['phar_regex'] ) + // No sniff (null) would switch content sniffing off: the scanner always writes one. + && is_array( $sniff ) && isset( $sniff['bytes'], $sniff['regex'], $sniff['exclude_extensions'], $sniff['scope'] ) && is_int( $sniff['bytes'] ) && $sniff['bytes'] > 0 + && $regex( $sniff['regex'] ) && is_array( $sniff['exclude_extensions'] ) && ( ! $sniff['exclude_extensions'] || $strings( $sniff['exclude_extensions'] ) ) + && is_array( $core ) && array_key_exists( 'root', $core ) && ( null === $core['root'] || ( is_string( $core['root'] ) && '' !== $core['root'] ) ) && isset( $core['dirs'], $core['files'] ) && $strings( $core['dirs'] ) && $strings( $core['files'] ); + foreach ( [ 'roots', 'excluded', 'old_releases', 'checked', 'not_checked' ] as $key ) { + $valid = $valid && ( [] === $m[ $key ] || $strings( $m[ $key ] ) ); + } + if ( ! $valid ) { + return "$bad: it isn't valid"; + } + // Only scopes this check reproduces exactly; any other fails closed. + if ( 'except_skipped_dirs' === $sniff['scope'] ) { + if ( ! isset( $sniff['skipped_dirs'] ) || ! ( [] === $sniff['skipped_dirs'] || $strings( $sniff['skipped_dirs'] ) ) ) { + return "$bad: it isn't valid"; + } + } elseif ( 'all' === $sniff['scope'] ) { + $m['sniff']['skipped_dirs'] = []; + } else { + return "$bad: its content sniff scope isn't one this check knows"; + } + $m['sniff']['exclude_extensions'] = array_map( 'strtolower', $sniff['exclude_extensions'] ); + // Every path is a container path under /var/www; one that isn't valid UTF-8 comes as `b64:` + base64 of its bytes. + $decode = function ( $path ) { + if ( 0 === strpos( $path, 'b64:' ) ) { + $path = base64_decode( substr( $path, 4 ), true ); + } + return is_string( $path ) && 0 === strpos( $path, '/var/www/' ) && false === strpos( $path, "\0" ) ? $path : null; + }; + $lists = [ [ 'roots' ], [ 'excluded' ], [ 'old_releases' ], [ 'checked' ], [ 'not_checked' ], [ 'sniff', 'skipped_dirs' ] ]; + foreach ( $lists as $keys ) { + $list = 1 === count( $keys ) ? $m[ $keys[0] ] : $m['sniff']['skipped_dirs']; + foreach ( $list as $i => $path ) { + $list[ $i ] = $decode( $path ); + if ( null === $list[ $i ] ) { + return "$bad: it names a path outside the site"; + } + } + if ( 1 === count( $keys ) ) { + $m[ $keys[0] ] = $list; + } else { + $m['sniff']['skipped_dirs'] = $list; + } + } + if ( null !== $core['root'] ) { + $m['core']['root'] = $decode( $core['root'] ); + if ( null === $m['core']['root'] ) { + return "$bad: it names a path outside the site"; + } } - return [ min( $sniff['bytes'], 1048576 ), $sniff['regex'], array_map( 'strtolower', $exclude ) ]; + return $m; } /** - * Whether a regular file without a code extension is code by the manifest's sniff. + * The manifest turned into host lookups, after checking its scope against the layout EE resolved. A manifest exemption + * (old_releases, core) counts only where EE's exact shape check agrees; when they disagree, nothing is positive. * - * @param string $path Real host path. - * @param string $name File name. - * @param array|null $sniff manifest_sniff(). + * @param string $code Real path of the site's app/. + * @param array $m read_manifest(). * - * @return bool + * @return array|string Lookups, or why the manifest and this check disagree. */ - protected static function sniffed( $path, $name, $sniff ) { - if ( null === $sniff ) { - return false; - } - list( $bytes, $regex, $exclude ) = $sniff; - $dot = strrpos( $name, '.' ); - if ( false !== $dot && in_array( strtolower( substr( $name, $dot + 1 ) ), $exclude, true ) ) { - return false; + protected function manifest_rules( $code, array $m ) { + $layout = null !== $this->cross_layout ? $this->cross_layout : [ + 'wp' => false, + 'scan' => null, + 'top' => null, + 'abspath' => null, + 'index' => null, + ]; + $disagree = "the scanner's list of the files it read disagrees with this check about the site's %s, so this check can't tell that it read all the site's code"; + $checked = []; + $nc_files = []; + $nc_dirs = []; + foreach ( $m['checked'] as $path ) { + $stat = self::manifest_stat( $code, $path ); + if ( false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { + $checked[ $stat['dev'] . ':' . $stat['ino'] ] = true; + } + } + foreach ( $m['not_checked'] as $path ) { + $host = self::manifest_dir( $code, $path ); + if ( null !== $host ) { + $nc_dirs[ $host ] = true; + continue; + } + $stat = '/' === substr( $path, -1 ) ? false : self::manifest_stat( $code, $path ); + if ( false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { + $nc_files[ $stat['dev'] . ':' . $stat['ino'] ] = true; + } } - $handle = @fopen( $path, 'rb' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable is sniffed as nothing. - if ( false === $handle ) { - return true; + // The sniff isn't applied below the directories the scanner searched by name only (accepted residual R-SNIFF). + $skipped = []; + foreach ( $m['sniff']['skipped_dirs'] as $path ) { + $host = self::manifest_dir( $code, $path ); + if ( null !== $host && in_array( basename( $host ), self::SCANNER_SKIP_NAMES, true ) ) { + $skipped[ $host ] = true; + } } - $head = (string) fread( $handle, $bytes ); - fclose( $handle ); - return 1 === preg_match( $regex, $head ); - } + // roots: the WordPress root EE passed (wp), or all of /var/www (php). + $roots = []; + foreach ( $m['roots'] as $path ) { + $roots[] = self::manifest_dir( $code, $path ); + } + $expected = $layout['wp'] ? $layout['scan'] : $code; + // No root on either side covers nothing, so any code file in app/ is still unlisted. + if ( ( null === $expected ? [] : [ $expected ] ) !== $roots ) { + return sprintf( $disagree, 'scanned directory' ); + } - /** - * The exact exempt shapes of the cross-check (INTERFACE.md "Cross-check", each approved by the user). - * - * @param string $code Real path of the site's app/. - * - * @return callable( $real_host_path ) bool - */ - protected function cross_exempt( $code ) { - $layout = null === $this->cross_layout ? [ 'top' => null, 'abspath' => null, 'index' => null ] : $this->cross_layout; + // (b) core: only the live WordPress root EE resolved, and only what both lists call core (index.php is scanned). $abspath = $layout['abspath']; - $top = $layout['top']; - // (a) The live release: the WordPress root's (or the served root's) ancestor directly in releases/. + $core = null === $m['core']['root'] ? null : self::manifest_dir( $code, $m['core']['root'] ); + if ( ( null === $m['core']['root'] ) !== ( null === $abspath ) || ( null !== $abspath && $core !== $abspath ) ) { + return sprintf( $disagree, 'WordPress core' ); + } + $core_dirs = array_values( array_intersect( $m['core']['dirs'], [ 'wp-admin', 'wp-includes' ] ) ); + $core_files = array_values( array_intersect( $m['core']['files'], self::CORE_FILES ) ); + + // (a) old releases: siblings of the live release in releases/, only when nginx's root is the live release or below. + $top = $layout['top']; $live = null; for ( $dir = null !== $abspath ? $abspath : $top; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { if ( 'releases' === basename( dirname( $dir ) ) ) { @@ -1490,24 +1608,162 @@ protected function cross_exempt( $code ) { break; } } - $old_releases = null !== $live && null !== $top && 0 === strpos( $top . '/', $live . '/' ) ? dirname( $live ) : null; + $old = []; + if ( null !== $live && null !== $top && 0 === strpos( $top . '/', $live . '/' ) ) { + foreach ( (array) @scandir( dirname( $live ) ) as $name ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable lists nothing. + $dir = dirname( $live ) . '/' . $name; + if ( '.' !== $name && '..' !== $name && $dir !== $live && ! is_link( $dir ) && is_dir( $dir ) ) { + $old[ $dir ] = true; + } + } + } + // The scanner names old releases only for php sites, which it walks whole; a wp scan never leaves the live root. + $listed = []; + foreach ( $m['old_releases'] as $path ) { + $host = self::manifest_dir( $code, $path ); + if ( $layout['wp'] || null === $host || ! isset( $old[ $host ] ) ) { + return sprintf( $disagree, 'old releases' ); + } + $listed[ $host ] = true; + } + if ( ! $layout['wp'] ) { + $old = $listed; + } + // (c) EE's app/wp-config.php when the WordPress root has its own, which WordPress loads first. $unused_config = null !== $abspath && $abspath !== $code && is_file( "$abspath/wp-config.php" ) ? "$code/wp-config.php" : null; $index = $layout['index']; - - return function ( $path ) use ( $abspath, $old_releases, $live, $unused_config, $index ) { - if ( null !== $old_releases && 0 === strpos( $path, $old_releases . '/' ) && 0 !== strpos( $path, $live . '/' ) ) { + $exempt = function ( $path ) use ( $code, $old, $abspath, $core_dirs, $core_files, $unused_config, $index ) { + if ( $old && null !== self::under_any( $path, $code, $old ) ) { return true; } if ( null !== $abspath && 0 === strpos( $path, $abspath . '/' ) ) { $rel = substr( $path, strlen( $abspath ) + 1 ); - if ( 0 === strpos( $rel, 'wp-admin/' ) || 0 === strpos( $rel, 'wp-includes/' ) || in_array( $rel, self::CORE_FILES, true ) ) { + $top = strstr( $rel, '/', true ); + if ( false === $top ? in_array( $rel, $core_files, true ) : in_array( $top, $core_dirs, true ) ) { return true; } } return $path === $unused_config || $path === $index; }; + $names = array_map( + function ( $ext ) { + return preg_quote( $ext, '/' ); + }, + $m['code_extensions'] + ); + + return [ + 'code' => $code, + 'checked' => $checked, + 'nc_files' => $nc_files, + 'nc_dirs' => $nc_dirs, + 'skipped' => $skipped, + 'code_name' => '/\.(?:' . implode( '|', $names ) . ')\z/' . ( $m['extensions_case_insensitive'] ? 'i' : '' ), + 'phar' => $m['phar_regex'], + 'sniff' => $m['sniff'], + 'exempt' => $exempt, + ]; + } + + /** + * lstat() of a manifest path on the host, only when it names the same file there: the container path maps to app/ with + * no link on the way (a host lookup would resolve an absolute link against the host). + * + * @param string $code Real path of the site's app/. + * @param string $path Container path under /var/www/. + * + * @return array|false + */ + protected static function manifest_stat( $code, $path ) { + $host = $code . substr( rtrim( $path, '/' ), strlen( '/var/www' ) ); + $real = @realpath( $host ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + + return $real === $host ? @lstat( $host ) : false; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + } + + /** + * @param string $code Real path of the site's app/. + * @param string $path Container path; a directory ends with `/`. + * + * @return string|null Real host directory it names, or null when it isn't one (then it covers nothing). + */ + protected static function manifest_dir( $code, $path ) { + if ( '/' !== substr( $path, -1 ) ) { + return null; + } + $stat = self::manifest_stat( $code, $path ); + + return false !== $stat && 0040000 === ( $stat['mode'] & 0170000 ) ? rtrim( $code . substr( $path, strlen( '/var/www' ) ), '/' ) : null; + } + + /** + * @param string $path Real host path. + * @param string $code Real path of the site's app/. + * @param array $dirs Real host directories as keys. + * + * @return string|null The directory of $dirs that $path is in (any depth), or null. + */ + protected static function under_any( $path, $code, array $dirs ) { + for ( $dir = dirname( $path ); strlen( $dir ) >= strlen( $code ); $dir = dirname( $dir ) ) { + if ( isset( $dirs[ $dir ] ) ) { + return $dir; + } + if ( $dir === $code ) { + break; + } + } + + return null; + } + + /** + * Whether uid 33 (PHP-FPM's www-data, the scanner's user) may have a permission. Only the bits are read, and only "no" + * is certain: the owner class counts when uid 33 owns it, and group or other bits (which bound every ACL entry) say maybe. + * + * @param array|false $stat lstat(). + * @param int $bit 0400 read or 0100 search, in owner position. + * + * @return bool + */ + protected static function uid33_may( $stat, $bit ) { + if ( false === $stat ) { + return true; + } + $mode = $stat['mode']; + + return 0 !== ( $mode & ( ( $bit >> 3 ) | ( $bit >> 6 ) ) ) || ( 33 === $stat['uid'] && 0 !== ( $mode & $bit ) ); + } + + /** + * Whether a regular file without a code name is code by the manifest's content sniff (rule 3 of "File manifest"). + * + * @param string $path Real host path. + * @param string $name File name. + * @param array|false $stat Its lstat(). + * @param bool $searchable Whether uid 33 may reach its directory. + * @param array $rules manifest_rules(). + * + * @return bool + */ + protected function manifest_sniffs( $path, $name, $stat, $searchable, array $rules ) { + $sniff = $rules['sniff']; + if ( in_array( strtolower( (string) pathinfo( $name, PATHINFO_EXTENSION ) ), $sniff['exclude_extensions'], true ) || null !== self::under_any( $path, $rules['code'], $rules['skipped'] ) ) { + return false; + } + // A file uid 33 can't read can't run under PHP-FPM, and the scanner doesn't sniff it either. + if ( ! $searchable || ! self::uid33_may( $stat, 0400 ) ) { + return false; + } + $handle = @fopen( $path, 'rb' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable fails closed. + if ( false === $handle ) { + return true; + } + $head = (string) fread( $handle, min( $sniff['bytes'], 1048576 ) ); + fclose( $handle ); + + return 1 === preg_match( $sniff['regex'], $head ); } /** @@ -1525,11 +1781,11 @@ protected static function cross_ok( $cross ) { * @return string Why the cross-check refuses a positive verdict. */ protected static function cross_text( $cross ) { - if ( null === $cross || ! $cross['manifest'] ) { + if ( null === $cross || ( ! $cross['manifest'] && null === $cross['error'] ) ) { return "the scanner gave no list of the files it read (an older scanner image), so this check can't tell that it read all the site's code"; } if ( null !== $cross['error'] ) { - return "can't list the site's files to compare with what the scanner read: {$cross['error']}"; + return $cross['error']; } $count = count( $cross['unlisted'] ) + $cross['unlisted_more']; @@ -1570,7 +1826,7 @@ protected static function reaches_install( $code, $real, $abspath ) { } /** - * Walks a directory tree without following links, bounded in time: $visit( $path, $name, file|dir|link|other ) returns + * Walks a directory tree without following links, bounded in time: $visit( $path, $name, file|dir|link|other, lstat ) returns * 'stop' to stop (true also stops for a non-directory), and for a directory whether to go into it. * * @param string $top Real directory. @@ -1605,7 +1861,7 @@ protected function walk_tree( $top, callable $visit ) { $stat = @lstat( $path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. $mode = false === $stat ? 0 : $stat['mode'] & 0170000; $type = 0120000 === $mode ? 'link' : ( 0040000 === $mode ? 'dir' : ( 0100000 === $mode ? 'file' : 'other' ) ); - $go = $visit( $path, $name, $type ); + $go = $visit( $path, $name, $type, $stat ); if ( 'stop' === $go || ( 'dir' !== $type && true === $go ) ) { return null; } From f8973411748a3754c923c2d74c26d6f610db1fec Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:54:50 +0530 Subject: [PATCH 37/53] fix(site): say when php-compat's file walk fails, and scan mounted code only where the scanner looks - cross_check in the JSON gains walk (ok, failed, or null when no manifest was usable) and walk_error, so a failed walk of app/ after the scan is visible beside the null verdict; unlisted entries and walk_error are cut to 256 characters. - Code the php container gets from an extra mount is read only by the scanner, so the mount's destination is now resolved through the volume's links first: on wp sites it must be inside the WordPress root's wp-content, on php sites it must not be a dot entry of /var/www, an old release or /var/www itself. Anything else is a tool_error. --- src/helper/Site_PHP_Compat.php | 97 +++++++++++++++++++++++++--------- 1 file changed, 73 insertions(+), 24 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index bd6383c5..907fddff 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -1357,10 +1357,11 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ * @param string $code Real path of the site's app/. * @param string $out The scan's /out directory on the host. * - * @return array manifest (bool), unlisted (up to 10 container paths), unlisted_more (int), error (string|null). + * @return array manifest (bool), unlisted (up to 10 container paths), unlisted_more (int), walk (ok|failed, null when + * no walk ran), walk_error (string|null), error (string|null: why there is no positive verdict besides unlisted). */ protected function cross_check( $code, $out ) { - $result = [ 'manifest' => false, 'unlisted' => [], 'unlisted_more' => 0, 'error' => null ]; + $result = [ 'manifest' => false, 'unlisted' => [], 'unlisted_more' => 0, 'walk' => null, 'walk_error' => null, 'error' => null ]; $m = $this->read_manifest( $out ); if ( ! is_array( $m ) ) { $result['error'] = $m; @@ -1417,13 +1418,15 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $covered, & } $seen[ $ino ] = true; if ( ++$count <= self::NOT_CHECKED_STDOUT ) { - $unlisted[] = self::clean( '/var/www' . substr( $path, strlen( $code ) ) ); + $unlisted[] = self::cut( self::clean( '/var/www' . substr( $path, strlen( $code ) ) ) ); } return false; } ); + $result['walk'] = null === $walk ? 'ok' : 'failed'; if ( null !== $walk ) { - $result['error'] = "can't list the site's files to compare with what the scanner read: $walk"; + $result['walk_error'] = self::cut( $walk ); + $result['error'] = "can't list the site's files to compare with what the scanner read: $walk"; } $result['unlisted'] = $unlisted; $result['unlisted_more'] = max( 0, $count - self::NOT_CHECKED_STDOUT ); @@ -1599,24 +1602,7 @@ protected function manifest_rules( $code, array $m ) { $core_dirs = array_values( array_intersect( $m['core']['dirs'], [ 'wp-admin', 'wp-includes' ] ) ); $core_files = array_values( array_intersect( $m['core']['files'], self::CORE_FILES ) ); - // (a) old releases: siblings of the live release in releases/, only when nginx's root is the live release or below. - $top = $layout['top']; - $live = null; - for ( $dir = null !== $abspath ? $abspath : $top; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { - if ( 'releases' === basename( dirname( $dir ) ) ) { - $live = $dir; - break; - } - } - $old = []; - if ( null !== $live && null !== $top && 0 === strpos( $top . '/', $live . '/' ) ) { - foreach ( (array) @scandir( dirname( $live ) ) as $name ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable lists nothing. - $dir = dirname( $live ) . '/' . $name; - if ( '.' !== $name && '..' !== $name && $dir !== $live && ! is_link( $dir ) && is_dir( $dir ) ) { - $old[ $dir ] = true; - } - } - } + $old = $this->old_release_dirs( $code ); // The scanner names old releases only for php sites, which it walks whole; a wp scan never leaves the live root. $listed = []; foreach ( $m['old_releases'] as $path ) { @@ -1667,6 +1653,37 @@ function ( $ext ) { ]; } + /** + * Exempt shape (a): the old releases beside the live release in releases/, only when nginx's root is the live release + * or below it (--public-dir=current). + * + * @param string $code Real path of the site's app/. + * + * @return array Real host directories as keys. + */ + protected function old_release_dirs( $code ) { + $top = null === $this->cross_layout ? null : $this->cross_layout['top']; + $abspath = null === $this->cross_layout ? null : $this->cross_layout['abspath']; + $live = null; + for ( $dir = null !== $abspath ? $abspath : $top; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { + if ( 'releases' === basename( dirname( $dir ) ) ) { + $live = $dir; + break; + } + } + $old = []; + if ( null !== $live && null !== $top && 0 === strpos( $top . '/', $live . '/' ) ) { + foreach ( (array) @scandir( dirname( $live ) ) as $name ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable lists nothing. + $dir = dirname( $live ) . '/' . $name; + if ( '.' !== $name && '..' !== $name && $dir !== $live && ! is_link( $dir ) && is_dir( $dir ) ) { + $old[ $dir ] = true; + } + } + } + + return $old; + } + /** * lstat() of a manifest path on the host, only when it names the same file there: the container path maps to app/ with * no link on the way (a host lookup would resolve an absolute link against the host). @@ -1836,11 +1853,12 @@ protected static function reaches_install( $code, $real, $abspath ) { */ protected function walk_tree( $top, callable $visit ) { $todo = [ $top ]; - $deadline = microtime( true ) + self::WALK_SECONDS; + $seconds = $this->walk_seconds(); + $deadline = microtime( true ) + $seconds; while ( $todo ) { $dir = array_pop( $todo ); if ( microtime( true ) > $deadline ) { - return 'it takes more than ' . self::WALK_SECONDS . ' s to list'; + return 'it takes more than ' . $seconds . ' s to list'; } // A long walk still answers a signal or a --cancel (run() reports cancelled then). if ( function_exists( 'pcntl_signal_dispatch' ) ) { @@ -1874,6 +1892,13 @@ protected function walk_tree( $top, callable $visit ) { return null; } + /** + * @return int The time bound of a walk of the site's files. + */ + protected function walk_seconds() { + return self::WALK_SECONDS; + } + /** * @param string $name File name. * @@ -2170,6 +2195,19 @@ protected function extra_mounts( $site_data, $code ) { if ( $this->wp_layout && 0 !== strpos( $dst . '/', $this->scan_path . '/wp-content/' ) ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' over the WordPress files, which this check reads before it scans'; } + // Mounted code is seen only by the scanner, never by EE's app/ walk: it must land, after the kernel follows the + // volume's links, where the scanner walks (wp: the root's wp-content; php: not a /var/www dot entry or an old release). + $at = self::resolve_in( $code, substr( $dst, strlen( '/var/www/' ) ) ); + if ( $this->wp_layout ) { + $content = self::resolve_in( $code, substr( $this->scan_path, strlen( '/var/www/' ) ) . '/wp-content' ); + $outside = null === $content || 0 !== strpos( $at . '/', $content . '/' ); + } else { + $top = (string) substr( $at, strlen( $code ) + 1 ); + $outside = '' === $top || '.' === $top[0] || null !== self::under_any( $at . '/x', $code, $this->old_release_dirs( $code ) ); + } + if ( $outside ) { + return 'the site\'s php container mounts ' . self::clean( $dst ) . ' at ' . self::clean( '/var/www' . substr( $at, strlen( $code ) ) ) . ', where the scanner doesn\'t look'; + } EE::debug( "php-compat: also mounting $src at $dst" ); array_push( $this->extra_mounts, '--mount', "type=bind,src=$src,dst=$dst,readonly" ); } @@ -3340,6 +3378,8 @@ function ( $entry ) { 'manifest' => $this->cross['manifest'], 'unlisted' => $this->cross['unlisted'], 'unlisted_more' => $this->cross['unlisted_more'], + 'walk' => $this->cross['walk'], + 'walk_error' => $this->cross['walk_error'], ]; if ( $doc['errors'] > 0 || ( null !== $core && false === $core['supports'] ) ) { $doc['safe_to_upgrade'] = false; @@ -3359,6 +3399,15 @@ protected function current_php() { return null !== $this->current_php && $this->current_php === $this->container_php ? $this->current_php : null; } + /** + * @param string $text Text. + * + * @return string At most NOT_CHECKED_CHARS characters of it, so stdout stays fixed-size. + */ + protected static function cut( $text ) { + return preg_match( '/^.{' . self::NOT_CHECKED_CHARS . '}/us', $text, $m ) ? $m[0] : $text; + } + /** * The summary as stdout prints it: fixed-size, so not_checked keeps its first NOT_CHECKED_STDOUT entries, each string * cut to NOT_CHECKED_CHARS characters, and not_checked_more counts the rest (the --output report has them all). From 2a7a182e352a3ab6f30c33cb9ac1b791ea462d0e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 14:57:27 +0530 Subject: [PATCH 38/53] fix(site): accept EE's unused app/wp-config.php when WordPress loads its config from the root's parent WordPress in htdocs/wp loaded by a stock htdocs/index.php, with its config copied to htdocs/ (one level above the root, where WordPress finds it), was refused because EE's original app/wp-config.php counted as PHP outside the WordPress directory. That file is never loaded when WordPress's own lookup (its root, else the root's real parent) finds another wp-config.php, so it is now accepted then; the cross-check exempts it only when that loaded config was validated and is in the scanner's checked list. --- src/helper/Site_PHP_Compat.php | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 907fddff..7591804f 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -161,6 +161,9 @@ class Site_PHP_Compat { /** @var array|null What resolve_layout() found, for the cross-check: wp, and as real host paths scan (the scanner's root), top, abspath, a2 index. */ protected $cross_layout; + /** @var string|null Real path of the wp-config.php WordPress loads when that makes EE's app/wp-config.php unused (shape (c)). */ + protected $ee_config_unused_by; + /** @var array|null The cross-check of the scanner's manifest (cross_check()). */ protected $cross; @@ -1035,8 +1038,9 @@ function ( $path, $name, $type ) use ( &$user_ini ) { if ( null !== $index ) { $allowed[] = $index; } - $this->wp_version = null; - $this->current_php = isset( $site_data->php_version ) && preg_match( '/^\d+\.\d+$/D', (string) $site_data->php_version ) ? (string) $site_data->php_version : null; + $this->wp_version = null; + $this->ee_config_unused_by = null; + $this->current_php = isset( $site_data->php_version ) && preg_match( '/^\d+\.\d+$/D', (string) $site_data->php_version ) ? (string) $site_data->php_version : null; if ( null !== $layout['abspath'] ) { // Core isn't scanned: its version decides whether it supports the target PHP. $file = $this->site_file( $code, substr( $layout['abspath'], strlen( $code ) + 1 ) . '/wp-includes/version.php', self::PHP_SOURCE_MAX ); @@ -1058,6 +1062,8 @@ function ( $path, $name, $type ) use ( &$user_ini ) { 'abspath' => $layout['abspath'], // (d): the served index.php of layout a2, which passed WordPress's own loader recogniser above. 'index' => $root !== $rel ? $index : null, + // (c): the config WordPress loads instead of EE's app/wp-config.php. + 'config' => $this->ee_config_unused_by, ]; $walk = $this->app_walk( $code, $rel, $root, $layout['abspath'], $allowed ); if ( is_string( $walk ) ) { @@ -1226,6 +1232,15 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { $read[] = $parent['real']; } } + // (c) EE's app/wp-config.php is unused when WordPress's own lookup (its root, else the real parent) loads another file. + $real_root = substr( $abspath, strlen( $code ) + 1 ); + $parent = dirname( $real_root ); + $ee_config = "$code/wp-config.php"; + $stat = @lstat( $ee_config ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( in_array( $config[0], [ "$real_root/wp-config.php", ( '.' === $parent ? '' : "$parent/" ) . 'wp-config.php' ], true ) && $file['real'] !== $ee_config && false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { + $read[] = $ee_config; + $this->ee_config_unused_by = $file['real']; + } return $read; } @@ -1616,8 +1631,10 @@ protected function manifest_rules( $code, array $m ) { $old = $listed; } - // (c) EE's app/wp-config.php when the WordPress root has its own, which WordPress loads first. - $unused_config = null !== $abspath && $abspath !== $code && is_file( "$abspath/wp-config.php" ) ? "$code/wp-config.php" : null; + // (c) EE's app/wp-config.php when WordPress loads another config, validated before the scan and read by the scanner. + $loaded = isset( $layout['config'] ) ? $layout['config'] : null; + $loaded_stat = null === $loaded ? false : @lstat( $loaded ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + $unused_config = null !== $abspath && $abspath !== $code && false !== $loaded_stat && isset( $checked[ $loaded_stat['dev'] . ':' . $loaded_stat['ino'] ] ) ? "$code/wp-config.php" : null; $index = $layout['index']; $exempt = function ( $path ) use ( $code, $old, $abspath, $core_dirs, $core_files, $unused_config, $index ) { if ( $old && null !== self::under_any( $path, $code, $old ) ) { From b1110ee56b9658e159e3ad5fbaf4a9d0adc1d07e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 15:00:18 +0530 Subject: [PATCH 39/53] fix(site): never report php-compat's no_code_found for a site being deleted ee site delete removes the site's directory before its record, so a check starting in that window found no app/ and reported no_code_found, or couldn't open the directory to lock it and went on unlocked. A missing app/ (scan and estimate) and a site directory that can't be opened for the scan's lock are now a tool_error, "the site is being deleted or its files are missing", and nothing is scanned. Delete's own flow is unchanged. --- src/helper/Site_PHP_Compat.php | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 7591804f..1599fc2f 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -107,6 +107,9 @@ class Site_PHP_Compat { /** Longest php-compat lists the site's files for (PHP outside WordPress, links, .user.ini files). */ const WALK_SECONDS = 120; + // tool_error detail when the site's directory or app/ is missing or its lock can't be opened (a delete in progress). + const SITE_GONE = 'the site is being deleted or its files are missing'; + // Directory names the scanner searches by name only (its manifest's sniff.skipped_dirs); the sniff doesn't apply below them. const SCANNER_SKIP_NAMES = [ 'uploads', 'cache', 'upgrade', 'upgrade-temp-backup', 'node_modules', '.git' ]; @@ -164,6 +167,9 @@ class Site_PHP_Compat { /** @var string|null Real path of the wp-config.php WordPress loads when that makes EE's app/wp-config.php unused (shape (c)). */ protected $ee_config_unused_by; + /** @var bool Whether the last lock_site() couldn't open the site directory (gone during a delete). */ + protected $lock_unopenable = false; + /** @var array|null The cross-check of the scanner's manifest (cross_check()). */ protected $cross; @@ -419,8 +425,8 @@ protected function run_scan( $site_data, $timeout, $output ) { } $code = $this->code_dir( $site_data->site_fs_path ); if ( null === $code ) { - $this->looked_in = $site_data->site_fs_path . '/app'; - return $this->doc( 'no_code_found' ); + // R48: delete removes the site's files before its record, so no app/ is never "no code found". + return $this->doc( 'tool_error', self::SITE_GONE ); } if ( false === $code ) { return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); @@ -438,6 +444,10 @@ protected function run_scan( $site_data, $timeout, $output ) { if ( ! $this->lock_site( $site_data->site_fs_path ) ) { return $this->restore_running( $site_data->site_fs_path ) ? $this->doc( 'tool_error', 'a restore of the site is running' ) : $this->doc( 'busy' ); } + // R48: a site directory that can't be opened is being deleted (delete removes it before the record); never scan unlocked. + if ( $this->lock_unopenable ) { + return $this->doc( 'tool_error', self::SITE_GONE ); + } $parent = $this->temp_parent(); if ( null !== $parent ) { $this->cancel_marker = $this->cancel_path( $parent ); @@ -577,8 +587,8 @@ protected function run_estimate( $site_data ) { } $code = $this->code_dir( $site_data->site_fs_path ); if ( null === $code ) { - $this->looked_in = $site_data->site_fs_path . '/app'; - return $this->doc( 'no_code_found' ); + // R48: delete removes the site's files before its record, so no app/ is never "no code found". + return $this->doc( 'tool_error', self::SITE_GONE ); } if ( false === $code ) { return $this->doc( 'tool_error', "can't resolve {$site_data->site_fs_path}/app, the link to the site's code" ); @@ -2567,7 +2577,8 @@ public static function resolve_in( $code, $rel ) { */ protected function lock_site( $site_fs_path ) { // Close-on-exec: a child (docker pull, rm) must not keep the lock after this process is killed. - $handle = @fopen( $site_fs_path, 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + $handle = @fopen( $site_fs_path, 're' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- handled below. + $this->lock_unopenable = false === $handle; if ( false === $handle ) { EE::debug( "Could not open $site_fs_path to lock it; relying on the container name." ); From d3e13fcc15e623182bc9171292a0d163aec9101e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 15:03:06 +0530 Subject: [PATCH 40/53] fix(site): exempt EE's unused app/wp-config.php only as itself and only when nothing loads it - A link to an unused config (app/wp-config.php, or the parent's beside a root that has its own) is no longer accepted as a link to a validated file, so htdocs/x.php -> ../wp-config.php is refused before the scan. In the cross-check a link never gets an exemption: code reached through a link must be one the scanner read. - The unused app/wp-config.php isn't exempt when app/ is the served-path parent of the WordPress root but not its real parent (htdocs -> releases/2), where `wp --path` loads it. - A site directory that exists but can't be opened for the scan's lock is named as such; the no_code_found text drops branches for a missing app/, which is a tool_error now. --- src/helper/Site_PHP_Compat.php | 45 ++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 1599fc2f..d225d750 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -149,10 +149,10 @@ class Site_PHP_Compat { /** @var bool Whether cleanup() took a --cancel request that arrived after the scan's last check. */ protected $late_cancel = false; - /** @var string|null Host directory the scan looked in, for the no_code_found text; null when app/ is missing. */ + /** @var string|null Host directory the scan looked in, for the no_code_found text (set by resolve_layout(), before any scan). */ protected $looked_in; - /** @var string|null The site's nginx config path, for the no_code_found text; null when app/ is missing. */ + /** @var string|null The site's nginx config path, for the no_code_found text (set by resolve_layout(), before any scan). */ protected $nginx_conf; /** @var bool Whether this is a WordPress scan (its WordPress directory, core left out) rather than all of htdocs. */ @@ -167,6 +167,9 @@ class Site_PHP_Compat { /** @var string|null Real path of the wp-config.php WordPress loads when that makes EE's app/wp-config.php unused (shape (c)). */ protected $ee_config_unused_by; + /** @var string[] Real paths of config files accepted only because nothing loads them: never valid link targets. */ + protected $unused_configs = []; + /** @var bool Whether the last lock_site() couldn't open the site directory (gone during a delete). */ protected $lock_unopenable = false; @@ -446,7 +449,7 @@ protected function run_scan( $site_data, $timeout, $output ) { } // R48: a site directory that can't be opened is being deleted (delete removes it before the record); never scan unlocked. if ( $this->lock_unopenable ) { - return $this->doc( 'tool_error', self::SITE_GONE ); + return $this->doc( 'tool_error', is_dir( $site_data->site_fs_path ) ? "the site's directory {$site_data->site_fs_path} can't be opened for locking" : self::SITE_GONE ); } $parent = $this->temp_parent(); if ( null !== $parent ) { @@ -1050,6 +1053,7 @@ function ( $path, $name, $type ) use ( &$user_ini ) { } $this->wp_version = null; $this->ee_config_unused_by = null; + $this->unused_configs = []; $this->current_php = isset( $site_data->php_version ) && preg_match( '/^\d+\.\d+$/D', (string) $site_data->php_version ) ? (string) $site_data->php_version : null; if ( null !== $layout['abspath'] ) { // Core isn't scanned: its version decides whether it supports the target PHP. @@ -1236,20 +1240,27 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { // WordPress takes ABSPATH's wp-config.php first: one in the parent (EE's app/wp-config.php beside an imported tree) // is never loaded, so it is no code outside WordPress either. + $validated = $read; if ( dirname( $file['real'] ) === $abspath ) { $parent = $this->site_file( $code, ltrim( substr( dirname( $abspath ), strlen( $code ) ), '/' ) . '/wp-config.php', self::PHP_SOURCE_MAX ); - if ( 'ok' === $parent['state'] ) { - $read[] = $parent['real']; + if ( 'ok' === $parent['state'] && ! in_array( $parent['real'], $validated, true ) ) { + $read[] = $parent['real']; + $this->unused_configs[] = $parent['real']; } } // (c) EE's app/wp-config.php is unused when WordPress's own lookup (its root, else the real parent) loads another file. + // Not when app/ is the served-path parent but not the real one (htdocs -> releases/2): `wp --path` there loads it. $real_root = substr( $abspath, strlen( $code ) + 1 ); $parent = dirname( $real_root ); $ee_config = "$code/wp-config.php"; $stat = @lstat( $ee_config ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. - if ( in_array( $config[0], [ "$real_root/wp-config.php", ( '.' === $parent ? '' : "$parent/" ) . 'wp-config.php' ], true ) && $file['real'] !== $ee_config && false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { + $cli_loads = '.' === dirname( $root ) && '.' !== $parent; + if ( ! $cli_loads && in_array( $config[0], [ "$real_root/wp-config.php", ( '.' === $parent ? '' : "$parent/" ) . 'wp-config.php' ], true ) && $file['real'] !== $ee_config && false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { $read[] = $ee_config; $this->ee_config_unused_by = $file['real']; + if ( ! in_array( $ee_config, $validated, true ) ) { + $this->unused_configs[] = $ee_config; + } } return $read; @@ -1297,8 +1308,9 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ return false; } $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); - // A link to a file already read and validated (releases/wp-config.php -> ../wp-config.php): no other code. - if ( null !== $real && in_array( $real, $allowed, true ) ) { + // A link to a file already read and validated (releases/wp-config.php -> ../wp-config.php): no other code. A config + // accepted only because nothing loads it was never validated, and a link would load it. + if ( null !== $real && in_array( $real, $allowed, true ) && ! in_array( $real, $this->unused_configs, true ) ) { return false; } if ( $inside ) { @@ -1402,12 +1414,13 @@ protected function cross_check( $code, $out ) { $count = 0; $seen = []; $searchable = [ $code => self::uid33_may( @lstat( $code ), 0100 ) ]; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. - $covered = function ( $path, array $stat, $phar ) use ( $code, $rules ) { + $covered = function ( $path, array $stat, $phar, $exemptable ) use ( $code, $rules ) { $ino = $stat['dev'] . ':' . $stat['ino']; if ( ( ! $phar && isset( $rules['checked'][ $ino ] ) ) || isset( $rules['nc_files'][ $ino ] ) || null !== self::under_any( $path, $code, $rules['nc_dirs'] ) ) { return true; } - return call_user_func( $rules['exempt'], $path ); + // The exempt shapes are the files themselves: code reaching one through a link is ordinary code. + return $exemptable && call_user_func( $rules['exempt'], $path ); }; $walk = $this->walk_tree( $code, @@ -1428,9 +1441,11 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $covered, & } $phar = 1 === preg_match( $rules['phar'], $name ) || 1 === preg_match( $rules['phar'], basename( $target ) ); $path = $target; + $link = true; } elseif ( 'file' !== $type ) { return false; } else { + $link = false; $phar = 1 === preg_match( $rules['phar'], $name ); if ( ! $phar && ! preg_match( $rules['code_name'], $name ) && ! $this->manifest_sniffs( $path, $name, $stat, $searchable[ dirname( $path ) ], $rules ) ) { return false; @@ -1438,7 +1453,7 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $covered, & } // A file reached again (through a link, or a hard link) counts once. $ino = $stat['dev'] . ':' . $stat['ino']; - if ( isset( $seen[ $ino ] ) || $covered( $path, $stat, $phar ) ) { + if ( isset( $seen[ $ino ] ) || $covered( $path, $stat, $phar, ! $link ) ) { return false; } $seen[ $ino ] = true; @@ -3810,13 +3825,7 @@ protected function cancel_text( array $doc ) { */ protected function no_code_text() { $text = "No PHP code found to check in {$this->site}."; - if ( null === $this->looked_in ) { - return $text; - } - $dir = self::clean( $this->looked_in ); - if ( null === $this->nginx_conf ) { - return "$text $dir doesn't exist."; - } + $dir = self::clean( $this->looked_in ); if ( ! $this->wp_layout ) { return "$text Looked for PHP files in $dir."; } From 565b4e0dba126ea8a79536a57232e142ba71b17e Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 15:05:33 +0530 Subject: [PATCH 41/53] fix(site): refuse EE's app/wp-config.php under htdocs -> releases/N only when the release has no config When the WordPress root has its own wp-config.php (a regular file, or a link that reaches one), both the web and `wp --path` load it first, so EE's app/wp-config.php is unused even when app/ is the served-path parent of the root. Shape (c) is now refused only when app/ is that parent, differs from the real parent, and the root has no config of its own. --- src/helper/Site_PHP_Compat.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index d225d750..dd9504bb 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -1249,12 +1249,14 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { } } // (c) EE's app/wp-config.php is unused when WordPress's own lookup (its root, else the real parent) loads another file. - // Not when app/ is the served-path parent but not the real one (htdocs -> releases/2): `wp --path` there loads it. + // Not when app/ is the served-path parent but not the real one (htdocs -> releases/2) and the root has no config of its + // own: `wp --path` there falls back to app/wp-config.php. A root config that is a link counts if it reaches a regular file. $real_root = substr( $abspath, strlen( $code ) + 1 ); $parent = dirname( $real_root ); $ee_config = "$code/wp-config.php"; $stat = @lstat( $ee_config ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. - $cli_loads = '.' === dirname( $root ) && '.' !== $parent; + $own = self::resolve_in( $code, "$real_root/wp-config.php" ); + $cli_loads = '.' === dirname( $root ) && '.' !== $parent && ! ( null !== $own && is_file( $own ) ); if ( ! $cli_loads && in_array( $config[0], [ "$real_root/wp-config.php", ( '.' === $parent ? '' : "$parent/" ) . 'wp-config.php' ], true ) && $file['real'] !== $ee_config && false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { $read[] = $ee_config; $this->ee_config_unused_by = $file['real']; From 58fa1dad8a6e3539560dc82b5357989b4b2c3125 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 15:08:08 +0530 Subject: [PATCH 42/53] fix(site): refuse links php-compat can't follow like the kernel, links into core and WP-CLI requires MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A code-named link whose target this check can't resolve (/var/www/../www/…, /proc/self/root/…, `..` above app/) counts as code the scanner didn't read unless the scanner reported it; inside WordPress such a link is refused before the scan. A plain dangling link, which the kernel can't follow either, is still accepted. - A link inside WordPress whose target is inside the live root's wp-admin/ or wp-includes/ is refused, so plugin or theme code can't be routed into core, which is judged by its version only. - A wp-cli.yml or wp-cli.local.yml between app/ and the served or WordPress root, or the www-data home's .wp-cli/config.yml, that mentions `require` or `inherit` is refused: WP-CLI would load code this check doesn't follow. --- src/helper/Site_PHP_Compat.php | 88 ++++++++++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 5 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index dd9504bb..7714a8b3 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -1042,6 +1042,10 @@ function ( $path, $name, $type ) use ( &$user_ini ) { return $this->doc( 'tool_error', $layout ); } $root = $layout['root']; + $detail = $this->wp_cli_config_check( $code, [ $rel, $root, null === $layout['abspath'] ? $root : substr( $layout['abspath'], strlen( $code ) + 1 ) ], $app ); + if ( null !== $detail ) { + return $this->doc( 'tool_error', $detail ); + } $this->scan_path = '/var/www/' . $root; $this->looked_in = $app . $root; EE::debug( "php-compat: WordPress root $root (nginx root $served)" ); @@ -1309,13 +1313,24 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ if ( 0 === strpos( "$code/$root/", $path . '/' ) ) { return false; } - $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); + $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); // A link to a file already read and validated (releases/wp-config.php -> ../wp-config.php): no other code. A config // accepted only because nothing loads it was never validated, and a link would load it. if ( null !== $real && in_array( $real, $allowed, true ) && ! in_array( $real, $this->unused_configs, true ) ) { return false; } if ( $inside ) { + // The scanner follows links the way the kernel does; one this check can't follow the same way is refused. + // A plain dangling link (nothing there for the kernel either) is harmless. + if ( null === $real && 'missing' !== $why ) { + $found = "$path is a link this check can't follow the way the container does"; + return 'stop'; + } + // Core is judged by its version, not scanned: code reached through a link into it would go unchecked. + if ( null !== $real && ( 0 === strpos( $real . '/', "$abspath/wp-admin/" ) || 0 === strpos( $real . '/', "$abspath/wp-includes/" ) ) ) { + $found = "$path links into WordPress core ($real), which this check doesn't scan"; + return 'stop'; + } if ( null !== $real && 0 === strpos( dirname( $path ) . '/', $real . '/' ) ) { $found = "$path links to its own ancestor " . $real; return 'stop'; @@ -1437,7 +1452,14 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $covered, & return false; } $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); - $stat = null === $target ? false : @lstat( $target ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( null === $target ) { + // The kernel may follow what resolve_in() can't (/var/www/../www, /proc/self/root): read only if reported. + if ( ! isset( $rules['nc_paths'][ '/var/www' . substr( $path, strlen( $code ) ) ] ) && null === self::under_any( $path, $code, $rules['nc_dirs'] ) && ++$count <= self::NOT_CHECKED_STDOUT ) { + $unlisted[] = self::cut( self::clean( '/var/www' . substr( $path, strlen( $code ) ) ) ); + } + return false; + } + $stat = @lstat( $target ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. if ( false === $stat || 0100000 !== ( $stat['mode'] & 0170000 ) ) { return false; } @@ -1598,6 +1620,7 @@ protected function manifest_rules( $code, array $m ) { $checked = []; $nc_files = []; $nc_dirs = []; + $nc_paths = []; foreach ( $m['checked'] as $path ) { $stat = self::manifest_stat( $code, $path ); if ( false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { @@ -1610,6 +1633,10 @@ protected function manifest_rules( $code, array $m ) { $nc_dirs[ $host ] = true; continue; } + if ( '/' !== substr( $path, -1 ) ) { + // As listed: a link that dangles or leaves /var/www is named by its own path. + $nc_paths[ $path ] = true; + } $stat = '/' === substr( $path, -1 ) ? false : self::manifest_stat( $code, $path ); if ( false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { $nc_files[ $stat['dev'] . ':' . $stat['ino'] ] = true; @@ -1689,6 +1716,7 @@ function ( $ext ) { 'checked' => $checked, 'nc_files' => $nc_files, 'nc_dirs' => $nc_dirs, + 'nc_paths' => $nc_paths, 'skipped' => $skipped, 'code_name' => '/\.(?:' . implode( '|', $names ) . ')\z/' . ( $m['extensions_case_insensitive'] ? 'i' : '' ), 'phar' => $m['phar_regex'], @@ -2445,6 +2473,50 @@ protected function wp_config_files( $code, $root, $abspath ) { return []; } + /** + * WP-CLI configs WordPress can be run with: wp-cli.yml and wp-cli.local.yml in each directory from app/ down to the served + * root and the WordPress root (WP-CLI looks upwards from where it runs), and the www-data home's .wp-cli/config.yml. A + * `require:` there loads code (an exempt config, an old release) and `_: inherit:` pulls in another config, so any file + * that mentions either is refused; one that can't be read is refused too (no YAML parser in the phar). + * + * @param string $code Real path of the site's app/. + * @param string[] $dirs Directories relative to app/ (served root, WordPress root as passed and as resolved). + * @param string $app The site's app/ with a trailing slash, for messages. + * + * @return string|null tool_error detail. + */ + protected function wp_cli_config_check( $code, array $dirs, $app ) { + $files = [ '.wp-cli/config.yml' ]; + foreach ( $dirs as $dir ) { + for ( $dir = trim( (string) $dir, '/' ); ; $dir = dirname( $dir ) ) { + $dir = '.' === $dir ? '' : $dir; + $files[] = ltrim( "$dir/wp-cli.yml", '/' ); + $files[] = ltrim( "$dir/wp-cli.local.yml", '/' ); + if ( '' === $dir ) { + break; + } + } + } + foreach ( array_unique( $files ) as $file ) { + // Missing (also below a link such as current/) is no config; a path the container could follow elsewhere is refused. + if ( null === self::resolve_in( $code, $file, $why ) ) { + if ( 'missing' === $why ) { + continue; + } + return "can't read $app$file, a WP-CLI config: it is reached through a link this check can't follow the way the container does"; + } + $found = $this->site_file( $code, $file ); + if ( 'ok' !== $found['state'] ) { + return "can't read $app$file, a WP-CLI config: {$found['detail']}"; + } + if ( preg_match( '/require|inherit/i', $found['source'] ) ) { + return "$app$file can make WP-CLI load more code (`require:` or `inherit`), which this check doesn't follow"; + } + } + + return null; + } + /** * Whether a php site's scan reads this file as code: in htdocs, a code extension, outside node_modules and .git, and * not in an old release beside the live one behind a `current` link (the scanner's oldReleases()). @@ -2536,12 +2608,15 @@ protected function read_site_file( $code, $rel, $max = self::CONFIG_MAX ) { /** * Resolves a path under app/ as the container sees it: a link to /var/www/... points into app/. * - * @param string $code Real path of the site's app/. - * @param string $rel Path relative to app/. + * @param string $code Real path of the site's app/. + * @param string $rel Path relative to app/. + * @param string|null $why Set on null: 'missing' (the kernel can't follow it either) or 'escape' (it leaves app/, or + * this can't tell where the kernel would take it, e.g. /var/www/../www or /proc/self/root). * * @return string|null Real host path inside app/, or null when it doesn't exist or leaves app/. */ - public static function resolve_in( $code, $rel ) { + public static function resolve_in( $code, $rel, &$why = null ) { + $why = 'escape'; // Path text from the site's files: a NUL or another control character is never a real path here. if ( preg_match( '/[\x00-\x1F\x7F]/', $rel ) ) { return null; @@ -2579,11 +2654,14 @@ public static function resolve_in( $code, $rel ) { } // Only a directory can be passed through, as in the kernel. if ( ! file_exists( $path ) || ( $todo && ! is_dir( $path ) ) ) { + $why = 'missing'; return null; } $done[] = $part; } + $why = null; + return rtrim( $code . '/' . implode( '/', $done ), '/' ); } From 1aa2dd917c0e8122ac4c88fcbba71f90c7d88104 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 15:10:27 +0530 Subject: [PATCH 43/53] fix(site): close php-compat's frozen-pair review findings: links into exempt places, files changed during the scan, WP-CLI configs - A link (any name) whose target is or holds an exempt place (an old release, the live root's core, the unused app/wp-config.php, the a2 index.php) counts as code the scanner didn't read unless it reported it; an exempt shape never applies through a link. Outside the scanner's roots a link to a directory, or one this check can't resolve, counts the same. Any link inside the live root's wp-admin/ or wp-includes/ is refused. - Every wp-cli.yml and wp-cli.local.yml in app/ (old releases and the www-data tool dirs aside) and .wp-cli/config.yml may hold only path, url, user, color, quiet and debug as plain values; path must lead to the WordPress root that is scanned (the served root on php sites). Anything else, such as exec, require, inherit or aliases, is refused. - A file whose ctime is at or after the scan's start (the scan starts on the next whole second) counts as unread, except a data-only cache file in a skipped dir by the scanner's own rule; cross_check.changed_during_scan counts them and the table suggests a re-run. - Outside the scanner's roots and the served root only code names count as code (a wp-config.php.bak or shell history in the www-data home no longer blocks a verdict). Exempt and not-checked directories aren't walked or sniffed. - The walk skips a directory or entry removed meanwhile and fails on any other error, a path longer than PATH_MAX included. The sniff opens without blocking, checks it is the file the walk saw, and counts read or PCRE errors as code. Reading the manifest is bounded and answers --cancel. - The php container must run as its image's user with no added groups; a mounted directory holding a .user.ini is refused. Links to /dev/null, /dev/stdout or /dev/stderr and link loops are nothing to read. - The table names old releases left unread on php sites, leads with the cross-check reason when WordPress supports the target, and counts directory entries as such; the help text describes the cross-check and the php scope. --- src/helper/Site_PHP_Compat.php | 515 ++++++++++++++++++++++++++++----- src/helper/class-ee-site.php | 2 +- 2 files changed, 451 insertions(+), 66 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 7714a8b3..793af8fe 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -110,6 +110,16 @@ class Site_PHP_Compat { // tool_error detail when the site's directory or app/ is missing or its lock can't be opened (a delete in progress). const SITE_GONE = 'the site is being deleted or its files are missing'; + // WP-CLI's project configs (any directory) and the www-data user's own, relative to app/. + const WP_CLI_CONFIGS = [ 'wp-cli.yml', 'wp-cli.local.yml' ]; + const WP_CLI_HOME = '.wp-cli/config.yml'; + + // The only keys a WP-CLI config may set: none of them loads code. + const WP_CLI_KEYS = [ 'path', 'url', 'user', 'color', 'quiet', 'debug' ]; + + // Exact link targets that are a sink, never code. + const DEV_SINKS = [ '/dev/null', '/dev/stdout', '/dev/stderr' ]; + // Directory names the scanner searches by name only (its manifest's sniff.skipped_dirs); the sniff doesn't apply below them. const SCANNER_SKIP_NAMES = [ 'uploads', 'cache', 'upgrade', 'upgrade-temp-backup', 'node_modules', '.git' ]; @@ -167,9 +177,15 @@ class Site_PHP_Compat { /** @var string|null Real path of the wp-config.php WordPress loads when that makes EE's app/wp-config.php unused (shape (c)). */ protected $ee_config_unused_by; + /** @var string[] WP-CLI configs found in the site's files, relative to app/. */ + protected $wp_cli_files = []; + /** @var string[] Real paths of config files accepted only because nothing loads them: never valid link targets. */ protected $unused_configs = []; + /** @var int Second the scan started (scan_start_time()); a file with a ctime from then on may not be what the scanner read. */ + protected $scan_start = PHP_INT_MAX; + /** @var bool Whether the last lock_site() couldn't open the site directory (gone during a delete). */ protected $lock_unopenable = false; @@ -501,6 +517,8 @@ protected function run_scan( $site_data, $timeout, $output ) { // From here until cleanup() confirms it is gone, /out may be in use by this container. $this->active_container = $name; + // Files changed from here on may differ from what the scanner read (cross_check() compares ctime). + $this->scan_start = $this->scan_start_time(); $run = $this->docker( $this->docker_run_args( 'scan', $image, $site_data, $code, $out, $timeout ), $timeout + self::PROCESS_MARGIN, true ); if ( $run['timed_out'] ) { return $this->doc( 'tool_error', "timed out after $timeout s" ); @@ -1031,8 +1049,26 @@ function ( $path, $name, $type ) use ( &$user_ini ) { return 'dir' === $type; } ); - $this->cross_layout = [ 'wp' => false, 'scan' => $code, 'top' => self::resolve_in( $code, $rel ), 'abspath' => null, 'index' => null ]; + self::resolve_in( $code, $rel, $why, $hops ); + self::resolve_in( $code, 'htdocs', $why, $more ); + $this->cross_layout = [ 'wp' => false, 'scan' => $code, 'top' => self::resolve_in( $code, $rel ), 'abspath' => null, 'index' => null, 'links' => array_merge( $hops, $more ) ]; $detail = null !== $error ? "can't look through {$app}htdocs for .user.ini files: $error" : $this->prepend_check( $site_data, $code, $user_ini, null ); + if ( null !== $detail ) { + return $this->doc( 'tool_error', $detail ); + } + // WP-CLI configs anywhere in app/ but old releases (not served) and the www-data home's tool dirs. + $old = $this->old_release_dirs( $code ); + $this->wp_cli_files = []; + $error = $this->walk_tree( + $code, + function ( $path, $name, $type ) use ( $code, $old ) { + if ( in_array( $name, self::WP_CLI_CONFIGS, true ) ) { + $this->wp_cli_files[] = substr( $path, strlen( $code ) + 1 ); + } + return 'dir' === $type && ! isset( $old[ $path ] ) && ! ( dirname( $path ) === $code && in_array( $name, self::HOME_DOTDIRS, true ) ); + } + ); + $detail = null !== $error ? "can't look through {$app} for WP-CLI configs: $error" : $this->wp_cli_config_check( $code, $this->cross_layout['top'], $app ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); } @@ -1042,10 +1078,6 @@ function ( $path, $name, $type ) use ( &$user_ini ) { return $this->doc( 'tool_error', $layout ); } $root = $layout['root']; - $detail = $this->wp_cli_config_check( $code, [ $rel, $root, null === $layout['abspath'] ? $root : substr( $layout['abspath'], strlen( $code ) + 1 ) ], $app ); - if ( null !== $detail ) { - return $this->doc( 'tool_error', $detail ); - } $this->scan_path = '/var/www/' . $root; $this->looked_in = $app . $root; EE::debug( "php-compat: WordPress root $root (nginx root $served)" ); @@ -1073,6 +1105,9 @@ function ( $path, $name, $type ) use ( &$user_ini ) { } $allowed = array_merge( $allowed, $config ); } + self::resolve_in( $code, $rel, $why, $hops ); + self::resolve_in( $code, $root, $why, $more ); + $layout_links = array_merge( $hops, $more ); $this->cross_layout = [ 'wp' => true, 'scan' => self::resolve_in( $code, $root ), @@ -1082,11 +1117,17 @@ function ( $path, $name, $type ) use ( &$user_ini ) { 'index' => $root !== $rel ? $index : null, // (c): the config WordPress loads instead of EE's app/wp-config.php. 'config' => $this->ee_config_unused_by, + 'links' => $layout_links, ]; - $walk = $this->app_walk( $code, $rel, $root, $layout['abspath'], $allowed ); + $this->wp_cli_files = []; + $walk = $this->app_walk( $code, $rel, $root, $layout['abspath'], $allowed ); if ( is_string( $walk ) ) { return $this->doc( 'tool_error', str_replace( "$code/", $app, $walk ) ); } + $detail = $this->wp_cli_config_check( $code, $layout['abspath'], $app ); + if ( null !== $detail ) { + return $this->doc( 'tool_error', $detail ); + } $detail = $this->prepend_check( $site_data, $code, $walk, $layout ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); @@ -1308,7 +1349,19 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ if ( '.user.ini' === $name ) { $user_ini[] = [ $path, $type ]; } + if ( in_array( $name, self::WP_CLI_CONFIGS, true ) ) { + $this->wp_cli_files[] = substr( $path, strlen( $code ) + 1 ); + } if ( 'link' === $type ) { + // A log or output file sent to /dev/null, stdout or stderr: exact targets only, never a code name. + if ( ! self::php_name( $name ) && in_array( (string) @readlink( $path ), self::DEV_SINKS, true ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is no sink. + return false; + } + // Core holds no links, and the cross-check doesn't walk core: any link in it is refused. + if ( null !== $abspath && ( 0 === strpos( $path, "$abspath/wp-admin/" ) || 0 === strpos( $path, "$abspath/wp-includes/" ) ) ) { + $found = "$path is a link inside WordPress core, which this check doesn't scan"; + return 'stop'; + } // The served root or the WordPress root may be a link (current -> releases/). if ( 0 === strpos( "$code/$root/", $path . '/' ) ) { return false; @@ -1415,7 +1468,15 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ * no walk ran), walk_error (string|null), error (string|null: why there is no positive verdict besides unlisted). */ protected function cross_check( $code, $out ) { - $result = [ 'manifest' => false, 'unlisted' => [], 'unlisted_more' => 0, 'walk' => null, 'walk_error' => null, 'error' => null ]; + $result = [ + 'manifest' => false, + 'unlisted' => [], + 'unlisted_more' => 0, + 'walk' => null, + 'walk_error' => null, + 'changed' => 0, + 'error' => null, + ]; $m = $this->read_manifest( $out ); if ( ! is_array( $m ) ) { $result['error'] = $m; @@ -1429,71 +1490,134 @@ protected function cross_check( $code, $out ) { $result['manifest'] = true; $unlisted = []; $count = 0; + $changed = 0; $seen = []; + $start = $this->scan_start; $searchable = [ $code => self::uid33_may( @lstat( $code ), 0100 ) ]; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. - $covered = function ( $path, array $stat, $phar, $exemptable ) use ( $code, $rules ) { - $ino = $stat['dev'] . ':' . $stat['ino']; - if ( ( ! $phar && isset( $rules['checked'][ $ino ] ) ) || isset( $rules['nc_files'][ $ino ] ) || null !== self::under_any( $path, $code, $rules['nc_dirs'] ) ) { - return true; + $unread = function ( $path ) use ( $code, &$unlisted, &$count ) { + if ( ++$count <= self::NOT_CHECKED_STDOUT ) { + $unlisted[] = self::cut( self::clean( '/var/www' . substr( $path, strlen( $code ) ) ) ); } - // The exempt shapes are the files themselves: code reaching one through a link is ordinary code. - return $exemptable && call_user_func( $rules['exempt'], $path ); + }; + $reported = function ( $path ) use ( $code, $rules ) { + return isset( $rules['nc_paths'][ '/var/www' . substr( $path, strlen( $code ) ) ] ) || null !== self::under_any( $path, $code, $rules['nc_dirs'] ); }; $walk = $this->walk_tree( $code, - function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $covered, &$searchable, &$seen, &$unlisted, &$count ) { + function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $start, $unread, $reported, &$searchable, &$seen, &$changed ) { if ( 'dir' === $type ) { + // Not read by the scanner and covered as a whole (a not_checked entry, an old release, core): nothing to sniff. + if ( isset( $rules['nc_dirs'][ $path ] ) || isset( $rules['skip_walk'][ $path ] ) ) { + return false; + } $searchable[ $path ] = $searchable[ dirname( $path ) ] && self::uid33_may( $stat, 0100 ); return true; } - if ( 'link' === $type ) { - // A code-named link runs its target as code, whatever the target is called. - if ( ! preg_match( $rules['code_name'], $name ) && ! preg_match( $rules['phar'], $name ) ) { + $link = 'link' === $type; + if ( $link ) { + // The served root's own links (current -> releases/2) are the layout itself. + if ( isset( $rules['layout_links'][ $path ] ) ) { + return false; + } + $named = 1 === preg_match( $rules['code_name'], $name ) || 1 === preg_match( $rules['phar'], $name ); + if ( ! $named && in_array( (string) @readlink( $path ), self::DEV_SINKS, true ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is no sink. + return false; + } + $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); + // Outside the scanner's roots nothing follows a directory link or an unresolvable one for it (the home dirs). + if ( null === self::under_any( $path, $code, $rules['roots'] ) && ( null === $target || is_dir( $target ) ) ) { + if ( ! $reported( $path ) ) { + $unread( $path ); + } return false; } - $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); if ( null === $target ) { // The kernel may follow what resolve_in() can't (/var/www/../www, /proc/self/root): read only if reported. - if ( ! isset( $rules['nc_paths'][ '/var/www' . substr( $path, strlen( $code ) ) ] ) && null === self::under_any( $path, $code, $rules['nc_dirs'] ) && ++$count <= self::NOT_CHECKED_STDOUT ) { - $unlisted[] = self::cut( self::clean( '/var/www' . substr( $path, strlen( $code ) ) ) ); + // A plain dangling link is nothing for the kernel either, unless it has a code name the scanner reports. + if ( ( 'escape' === $why || $named ) && ! $reported( $path ) ) { + $unread( $path ); + } + return false; + } + // A directory link (any name) into or around an exempt place reaches code nobody read: never exempt through a link. + if ( is_dir( $target ) ) { + if ( self::touches( $target, $rules['exempt_places'] ) && ! $reported( $path ) ) { + $unread( $path ); } return false; } - $stat = @lstat( $target ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + $stat = @lstat( $target ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. if ( false === $stat || 0100000 !== ( $stat['mode'] & 0170000 ) ) { return false; } + // A file link runs its target as code when either name is a code name (as the scanner reads it). $phar = 1 === preg_match( $rules['phar'], $name ) || 1 === preg_match( $rules['phar'], basename( $target ) ); + if ( ! $named && ! $phar && ! preg_match( $rules['code_name'], basename( $target ) ) ) { + // Any other file in an exempt place, reached through a link, counts unless the scanner read or reported it. + $tino = $stat['dev'] . ':' . $stat['ino']; + if ( self::touches( $target, $rules['exempt_places'] ) && ! isset( $rules['checked'][ $tino ] ) && ! isset( $rules['nc_files'][ $tino ] ) && ! $reported( $path ) ) { + $unread( $path ); + } + return false; + } $path = $target; - $link = true; } elseif ( 'file' !== $type ) { return false; } else { - $link = false; $phar = 1 === preg_match( $rules['phar'], $name ); - if ( ! $phar && ! preg_match( $rules['code_name'], $name ) && ! $this->manifest_sniffs( $path, $name, $stat, $searchable[ dirname( $path ) ], $rules ) ) { - return false; + if ( ! $phar && ! preg_match( $rules['code_name'], $name ) ) { + // Outside the scanner's roots and the served root only code names count (accepted residual R-SNIFF-OUT). + if ( null === self::under_any( $path, $code, $rules['sniff_roots'] ) || call_user_func( $rules['exempt'], $path ) || $reported( $path ) ) { + return false; + } + if ( ! $this->manifest_sniffs( $path, $name, $stat, $searchable[ dirname( $path ) ], $rules ) ) { + return false; + } } } - // A file reached again (through a link, or a hard link) counts once. + // A file already reported (reached again through a link or a hard link) counts once. Only reported files are + // marked: an exempt file's inode reached through a link must still be judged as the link's code. $ino = $stat['dev'] . ':' . $stat['ino']; - if ( isset( $seen[ $ino ] ) || $covered( $path, $stat, $phar, ! $link ) ) { + if ( isset( $seen[ $ino ] ) ) { return false; } - $seen[ $ino ] = true; - if ( ++$count <= self::NOT_CHECKED_STDOUT ) { - $unlisted[] = self::cut( self::clean( '/var/www' . substr( $path, strlen( $code ) ) ) ); + // Changed since the scan started: not what the scanner read. A cache's data-only file in a skipped dir is fine. + if ( $stat['ctime'] >= $start ) { + if ( ! $phar && null !== self::under_any( $path, $code, $rules['skipped'] ) && self::data_only( $path ) ) { + return false; + } + ++$changed; + $seen[ $ino ] = true; + $unread( $path ); + return false; } + if ( ( ! $phar && isset( $rules['checked'][ $ino ] ) ) || isset( $rules['nc_files'][ $ino ] ) || $reported( $path ) ) { + return false; + } + // The exempt shapes are the files themselves: code reaching one through a link is ordinary code. + if ( ! $link && call_user_func( $rules['exempt'], $path ) ) { + return false; + } + $seen[ $ino ] = true; + $unread( $path ); return false; } ); + $result['changed'] = $changed; $result['walk'] = null === $walk ? 'ok' : 'failed'; if ( null !== $walk ) { - $result['walk_error'] = self::cut( $walk ); + $result['walk_error'] = self::cut( str_replace( "$code/", '/var/www/', $walk ) ); $result['error'] = "can't list the site's files to compare with what the scanner read: $walk"; } $result['unlisted'] = $unlisted; $result['unlisted_more'] = max( 0, $count - self::NOT_CHECKED_STDOUT ); + // Relative to app/, for the positive line (exempt shape (a) leaves them unread). + $result['old_releases'] = array_map( + function ( $dir ) use ( $code ) { + return substr( $dir, strlen( $code ) + 1 ); + }, + array_keys( $rules['old'] ) + ); return $result; } @@ -1621,13 +1745,37 @@ protected function manifest_rules( $code, array $m ) { $nc_files = []; $nc_dirs = []; $nc_paths = []; + // One realpath() and lstat() per entry: bounded, and a signal or --cancel still gets an answer. + $seconds = $this->manifest_seconds(); + $deadline = microtime( true ) + $seconds; + $n = 0; + $tick = function () use ( &$n, $deadline, $seconds ) { + if ( 0 !== ( $n++ % 1000 ) ) { + return null; + } + if ( function_exists( 'pcntl_signal_dispatch' ) ) { + null === $this->dispatch ? pcntl_signal_dispatch() : call_user_func( $this->dispatch ); + } + if ( $this->cancel_requested() ) { + return "the scanner's list of the files it read can't be used: a cancel was requested"; + } + return microtime( true ) > $deadline ? "the scanner's list of the files it read can't be used: it takes more than $seconds s to read" : null; + }; foreach ( $m['checked'] as $path ) { + $stop = $tick(); + if ( null !== $stop ) { + return $stop; + } $stat = self::manifest_stat( $code, $path ); if ( false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { $checked[ $stat['dev'] . ':' . $stat['ino'] ] = true; } } foreach ( $m['not_checked'] as $path ) { + $stop = $tick(); + if ( null !== $stop ) { + return $stop; + } $host = self::manifest_dir( $code, $path ); if ( null !== $host ) { $nc_dirs[ $host ] = true; @@ -1710,6 +1858,37 @@ function ( $ext ) { }, $m['code_extensions'] ); + // Places exempt by shape: a link reaching into one (or holding one) is never exempt. Walked dirs that are covered whole. + $places = []; + $skip_walk = $old; + foreach ( array_keys( $old ) as $dir ) { + $places[ $dir ] = true; + } + if ( null !== $abspath ) { + foreach ( $core_dirs as $dir ) { + $places[ "$abspath/$dir" ] = true; + $skip_walk[ "$abspath/$dir" ] = true; + } + foreach ( $core_files as $file ) { + $places[ "$abspath/$file" ] = false; + } + } + foreach ( [ $unused_config, $index ] as $file ) { + if ( null !== $file ) { + $places[ $file ] = false; + } + } + // Where the content sniff applies: the scanner's roots and the served root (accepted residual R-SNIFF-OUT outside). + $sniff_roots = []; + foreach ( array_merge( $roots, [ $layout['top'] ] ) as $dir ) { + if ( null !== $dir ) { + $sniff_roots[ $dir ] = true; + } + } + $layout_links = []; + foreach ( isset( $layout['links'] ) ? $layout['links'] : [] as $link ) { + $layout_links[ $link ] = true; + } return [ 'code' => $code, @@ -1722,9 +1901,40 @@ function ( $ext ) { 'phar' => $m['phar_regex'], 'sniff' => $m['sniff'], 'exempt' => $exempt, + 'old' => $old, + 'exempt_places' => $places, + 'skip_walk' => $skip_walk, + 'sniff_roots' => $sniff_roots, + 'roots' => array_fill_keys( array_filter( $roots ), true ), + 'layout_links' => $layout_links, ]; } + /** + * Whether a real path is, holds or lies in one of the places: true values are directories, false values files. + * + * @param string $real Real host path. + * @param array $places Real host paths as keys. + * + * @return bool + */ + protected static function touches( $real, array $places ) { + foreach ( $places as $place => $is_dir ) { + if ( $real === $place || ( $is_dir && 0 === strpos( $real, $place . '/' ) ) || 0 === strpos( $place, $real . '/' ) ) { + return true; + } + } + + return false; + } + + /** + * @return int The time bound of reading the scanner's manifest into lookups. + */ + protected function manifest_seconds() { + return self::WALK_SECONDS; + } + /** * Exempt shape (a): the old releases beside the live release in releases/, only when nginx's root is the live release * or below it (--public-dir=current). @@ -1845,14 +2055,21 @@ protected function manifest_sniffs( $path, $name, $stat, $searchable, array $rul if ( ! $searchable || ! self::uid33_may( $stat, 0400 ) ) { return false; } - $handle = @fopen( $path, 'rb' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable fails closed. + // Non-blocking (a FIFO swapped in never hangs) and the same file the walk saw; anything else counts as code. + $handle = @fopen( $path, 'rbn' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable fails closed. if ( false === $handle ) { return true; } - $head = (string) fread( $handle, min( $sniff['bytes'], 1048576 ) ); + $fstat = fstat( $handle ); + if ( false === $fstat || 0100000 !== ( $fstat['mode'] & 0170000 ) || false === $stat || $fstat['dev'] !== $stat['dev'] || $fstat['ino'] !== $stat['ino'] ) { + fclose( $handle ); + return true; + } + $head = fread( $handle, min( $sniff['bytes'], 1048576 ) ); fclose( $handle ); - return 1 === preg_match( $sniff['regex'], $head ); + // A failed read or a PCRE error (false) is no proof the file isn't code. + return false === $head || 0 !== preg_match( $sniff['regex'], $head ); } /** @@ -1877,8 +2094,12 @@ protected static function cross_text( $cross ) { return $cross['error']; } $count = count( $cross['unlisted'] ) + $cross['unlisted_more']; + $text = sprintf( '%s the scanner didn\'t read: %s%s', self::count_of( $count, 'code file' ), implode( ', ', $cross['unlisted'] ), $cross['unlisted_more'] > 0 ? ", and {$cross['unlisted_more']} more" : '' ); + if ( ! empty( $cross['changed'] ) ) { + $text .= sprintf( ' (%s changed while the check ran; run it again when the site is quieter)', self::count_of( $cross['changed'], 'file' ) ); + } - return sprintf( '%s the scanner didn\'t read: %s%s', self::count_of( $count, 'code file' ), implode( ', ', $cross['unlisted'] ), $cross['unlisted_more'] > 0 ? ", and {$cross['unlisted_more']} more" : '' ); + return $text; } /** @@ -1941,6 +2162,10 @@ protected function walk_tree( $top, callable $visit ) { } $entries = @scandir( $dir ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. if ( false === $entries ) { + // Removed after its parent was listed (a cache purge): nothing to walk. Any other failure fails the walk. + if ( $dir !== $top && self::gone( $dir ) ) { + continue; + } return self::clean( $dir ) . ' can\'t be listed'; } foreach ( $entries as $name ) { @@ -1949,7 +2174,14 @@ protected function walk_tree( $top, callable $visit ) { } $path = "$dir/$name"; $stat = @lstat( $path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. - $mode = false === $stat ? 0 : $stat['mode'] & 0170000; + if ( false === $stat ) { + if ( self::gone( $path ) ) { + continue; + } + // E.g. a host path longer than PATH_MAX, which PHP in the container still reaches: fail closed. + return self::clean( $path ) . ' can\'t be read'; + } + $mode = $stat['mode'] & 0170000; $type = 0120000 === $mode ? 'link' : ( 0040000 === $mode ? 'dir' : ( 0100000 === $mode ? 'file' : 'other' ) ); $go = $visit( $path, $name, $type, $stat ); if ( 'stop' === $go || ( 'dir' !== $type && true === $go ) ) { @@ -1964,6 +2196,87 @@ protected function walk_tree( $top, callable $visit ) { return null; } + /** + * Waits for the next whole second and returns it: ctime has whole seconds, so every file with a ctime before it was + * last changed before the scanner started. + * + * @return int + */ + protected function scan_start_time() { + $start = (int) floor( microtime( true ) ) + 1; + while ( microtime( true ) < $start ) { + usleep( 20000 ); + } + + return $start; + } + + /** + * The scanner's data-only rule (compat-scanner dataOnly()), exactly: ``, `die();`, `exit('…'); ?>` forms + * with no later open tag, read to the end up to 8 MiB. + * + * @param string $path Host path. + * + * @return bool + */ + protected static function data_only( $path ) { + $fh = @fopen( $path, 'rbn' ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $fh ) { + return false; + } + $st = fstat( $fh ); + if ( false === $st || 0100000 !== ( $st['mode'] & 0170000 ) ) { + fclose( $fh ); + return false; + } + $head = (string) fread( $fh, 512 ); + $ok = (bool) preg_match( '/\A(?:\xEF\xBB\xBF)?<\?php\s+(?:exit|die)\s*(?:\(\s*(?:\'[^\'\\\\]*\'|"[^"\\\\$]*"|\d+)?\s*\))?\s*;?\s*(__halt_compiler\s*\(\s*\)\s*;?\s*)?\?>/i', $head, $m ); + if ( $ok && empty( $m[1] ) ) { + $rest = substr( $head, strlen( $m[0] ) ); + $read = strlen( $head ); + while ( true ) { + if ( preg_match( '/<\?(?:php(?:\s|\z)|=)/i', $rest ) ) { + $ok = false; + break; + } + $more = fread( $fh, 65536 ); + if ( false === $more || ( '' === $more && ! feof( $fh ) ) ) { + $ok = false; + break; + } + if ( '' === $more ) { + break; + } + $read += strlen( $more ); + if ( $read > 8388608 ) { + $ok = false; + break; + } + $rest = substr( $rest, -5 ) . $more; + } + } + fclose( $fh ); + + return $ok; + } + + /** + * Whether a path that just failed to list or lstat was removed meanwhile (not some other error). + * + * @param string $path Host path. + * + * @return bool + */ + protected static function gone( $path ) { + clearstatcache( true, $path ); + if ( false !== @lstat( $path ) || strlen( $path ) >= 4096 ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + return false; + } + $list = @scandir( dirname( $path ) ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + + return false === $list || ! in_array( basename( $path ), $list, true ); + } + /** * @return int The time bound of a walk of the site's files. */ @@ -2280,6 +2593,21 @@ protected function extra_mounts( $site_data, $code ) { if ( $outside ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' at ' . self::clean( '/var/www' . substr( $at, strlen( $code ) ) ) . ', where the scanner doesn\'t look'; } + // A .user.ini there is seen only inside the container: its prepend/append settings would go unchecked. + $user_ini = null; + $error = is_dir( $src ) ? $this->walk_tree( + realpath( $src ), + function ( $path, $name, $type ) use ( &$user_ini ) { + if ( '.user.ini' === $name ) { + $user_ini = $path; + return 'stop'; + } + return 'dir' === $type; + } + ) : null; + if ( null !== $error || null !== $user_ini ) { + return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ( null !== $user_ini ? ', which holds a .user.ini (' . self::clean( $user_ini ) . ') this check doesn\'t read' : ", which can't be looked through: $error" ); + } EE::debug( "php-compat: also mounting $src at $dst" ); array_push( $this->extra_mounts, '--mount', "type=bind,src=$src,dst=$dst,readonly" ); } @@ -2326,6 +2654,14 @@ protected function container_config_check( array $info ) { return "the site's php container runs another " . strtolower( $key ) . ' than its image, which this check can\'t confirm'; } } + // Both sides read files as PHP-FPM's stock user (uid 33, no other groups): another user or extra groups read others. + $user = isset( $own['User'] ) ? (string) $own['User'] : ''; + if ( ( isset( $config['User'] ) ? (string) $config['User'] : '' ) !== $user ) { + return "the site's php container runs as another user than its image, which this check can't confirm"; + } + if ( ! empty( $info['HostConfig']['GroupAdd'] ) ) { + return "the site's php container adds groups to its user, which this check can't confirm"; + } $image_env = []; foreach ( isset( $own['Env'] ) ? (array) $own['Env'] : [] as $pair ) { $image_env[ strtok( $pair, '=' ) ] = $pair; @@ -2474,31 +2810,20 @@ protected function wp_config_files( $code, $root, $abspath ) { } /** - * WP-CLI configs WordPress can be run with: wp-cli.yml and wp-cli.local.yml in each directory from app/ down to the served - * root and the WordPress root (WP-CLI looks upwards from where it runs), and the www-data home's .wp-cli/config.yml. A - * `require:` there loads code (an exempt config, an old release) and `_: inherit:` pulls in another config, so any file - * that mentions either is refused; one that can't be read is refused too (no YAML parser in the phar). + * WP-CLI configs (every wp-cli.yml and wp-cli.local.yml found in app/, and the www-data user's .wp-cli/config.yml) may + * hold only blank lines, comments and top-level `key: scalar` lines for path, url, user, color, quiet and debug. `path` + * must lead to the WordPress root this check scans (php sites: the served root). Anything else (exec, require, inherit, + * aliases, blocks) can make WP-CLI run code this check doesn't follow; there's no YAML parser in the phar. * - * @param string $code Real path of the site's app/. - * @param string[] $dirs Directories relative to app/ (served root, WordPress root as passed and as resolved). - * @param string $app The site's app/ with a trailing slash, for messages. + * @param string $code Real path of the site's app/. + * @param string|null $live Real path `path:` must lead to. + * @param string $app The site's app/ with a trailing slash, for messages. * * @return string|null tool_error detail. */ - protected function wp_cli_config_check( $code, array $dirs, $app ) { - $files = [ '.wp-cli/config.yml' ]; - foreach ( $dirs as $dir ) { - for ( $dir = trim( (string) $dir, '/' ); ; $dir = dirname( $dir ) ) { - $dir = '.' === $dir ? '' : $dir; - $files[] = ltrim( "$dir/wp-cli.yml", '/' ); - $files[] = ltrim( "$dir/wp-cli.local.yml", '/' ); - if ( '' === $dir ) { - break; - } - } - } - foreach ( array_unique( $files ) as $file ) { - // Missing (also below a link such as current/) is no config; a path the container could follow elsewhere is refused. + protected function wp_cli_config_check( $code, $live, $app ) { + foreach ( array_unique( array_merge( [ self::WP_CLI_HOME ], $this->wp_cli_files ) ) as $file ) { + // Missing (a dangling link included) is no config; one the container could reach elsewhere is refused. if ( null === self::resolve_in( $code, $file, $why ) ) { if ( 'missing' === $why ) { continue; @@ -2509,8 +2834,35 @@ protected function wp_cli_config_check( $code, array $dirs, $app ) { if ( 'ok' !== $found['state'] ) { return "can't read $app$file, a WP-CLI config: {$found['detail']}"; } - if ( preg_match( '/require|inherit/i', $found['source'] ) ) { - return "$app$file can make WP-CLI load more code (`require:` or `inherit`), which this check doesn't follow"; + $text = str_replace( [ "\r\n", "\r" ], "\n", $found['source'] ); + $text = 0 === strpos( $text, "\xEF\xBB\xBF" ) ? substr( $text, 3 ) : $text; + foreach ( explode( "\n", $text ) as $n => $line ) { + if ( '' === trim( $line ) || '#' === substr( ltrim( $line ), 0, 1 ) ) { + continue; + } + // A plain YAML scalar: no flow/anchor/tag/alias start, `:` only when not followed by a blank, ` #` starts a comment. + $scalar = '(?:\'[^\']*\'|"[^"\\\\]*"|[^\s\'"{}\[\],&*!|>%@`#:](?:[^\s#:]|:(?=\S)|[ \t]+(?=[^\s#]))*)'; + if ( ! preg_match( '/^(' . implode( '|', self::WP_CLI_KEYS ) . '):(?:[ \t]+(' . $scalar . '))?[ \t]*(?:[ \t]#.*)?$/D', $line, $m ) ) { + return sprintf( '%s%s line %d isn\'t a WP-CLI setting this check accepts (only %s, as plain values): %s', $app, $file, $n + 1, implode( ', ', self::WP_CLI_KEYS ), self::clean( substr( trim( $line ), 0, 60 ) ) ); + } + if ( 'path' !== $m[1] ) { + continue; + } + $value = isset( $m[2] ) ? trim( $m[2], '\'"' ) : ''; + if ( '' === $value ) { + continue; + } + // Relative to the config's own (real) directory, as WP-CLI reads it; /var/www/… is the site's app/. + $base = substr( dirname( $found['real'] ), strlen( $code ) + 1 ); + if ( '/' === $value[0] ) { + $rel = 0 === strpos( $value . '/', '/var/www/' ) ? substr( $value, strlen( '/var/www/' ) ) : null; + } else { + $rel = ( false === $base || '' === $base ? '' : "$base/" ) . $value; + } + $to = null === $rel ? null : self::resolve_in( $code, $rel ); + if ( null === $live || $to !== $live ) { + return sprintf( '%s%s sets path: %s, which isn\'t the WordPress this check scans', $app, $file, self::clean( $value ) ); + } } } @@ -2612,11 +2964,13 @@ protected function read_site_file( $code, $rel, $max = self::CONFIG_MAX ) { * @param string $rel Path relative to app/. * @param string|null $why Set on null: 'missing' (the kernel can't follow it either) or 'escape' (it leaves app/, or * this can't tell where the kernel would take it, e.g. /var/www/../www or /proc/self/root). + * @param array|null $passed Set to the links passed on the way (their real-location host paths). * * @return string|null Real host path inside app/, or null when it doesn't exist or leaves app/. */ - public static function resolve_in( $code, $rel, &$why = null ) { - $why = 'escape'; + public static function resolve_in( $code, $rel, &$why = null, &$passed = null ) { + $why = 'escape'; + $passed = []; // Path text from the site's files: a NUL or another control character is never a real path here. if ( preg_match( '/[\x00-\x1F\x7F]/', $rel ) ) { return null; @@ -2638,8 +2992,13 @@ public static function resolve_in( $code, $rel, &$why = null ) { } $path = $code . '/' . implode( '/', array_merge( $done, [ $part ] ) ); if ( is_link( $path ) ) { + $passed[] = $path; $target = readlink( $path ); - if ( false === $target || ++$hops > 40 || preg_match( '/[\x00-\x1F\x7F]/', $target ) ) { + if ( ++$hops > 40 ) { + $why = 'missing'; + return null; + } + if ( false === $target || preg_match( '/[\x00-\x1F\x7F]/', $target ) ) { return null; } if ( '/' === substr( $target, 0, 1 ) ) { @@ -3503,6 +3862,7 @@ function ( $entry ) { 'unlisted_more' => $this->cross['unlisted_more'], 'walk' => $this->cross['walk'], 'walk_error' => $this->cross['walk_error'], + 'changed_during_scan' => $this->cross['changed'], ]; if ( $doc['errors'] > 0 || ( null !== $core && false === $core['supports'] ) ) { $doc['safe_to_upgrade'] = false; @@ -3816,20 +4176,45 @@ protected function table_lines( array $doc, $report ) { if ( null !== $core ) { $line .= ' ' . ( null === $why ? sprintf( 'WordPress %s supports PHP %s', $this->wp_version['branch'], $target ) : ucfirst( $why ) ) . '.'; } + // Exempt shape (a): what wasn't read, so the line never claims all of htdocs. + if ( ! $this->wp_layout && null !== $this->cross && ! empty( $this->cross['old_releases'] ) ) { + // looked_in is /app/htdocs on php sites. + $app = dirname( (string) $this->looked_in ) . '/'; + $names = array_map( + function ( $dir ) use ( $app ) { + return self::clean( $app . $dir ); + }, + $this->cross['old_releases'] + ); + $line .= ' Old releases nginx doesn\'t serve aren\'t checked: ' . implode( ', ', $names ) . '.'; + } yield $line . ( $doc['warnings'] > 0 ? ' ' . self::count_of( $doc['warnings'], 'warning' ) . '.' : '' ); } else { + // WordPress's sentence leads only when WordPress itself is the reason (supports null); otherwise it follows. + $core_unknown = null !== $core && null === $core['supports']; if ( $doc['files_not_checked'] > 0 ) { - $could = 1 === $doc['files_not_checked'] ? 'file couldn\'t' : 'files couldn\'t'; + // An entry can be a whole directory (skipped uploads/, a dot dir, a nested install): count entries. + $dirs = (bool) array_filter( + isset( $report['not_checked'] ) ? $report['not_checked'] : [], + function ( $entry ) { + return '/' === substr( (string) $entry['file'], -1 ); + } + ); + $noun = $dirs ? 'file or directory' : 'file'; + $could = 1 === $doc['files_not_checked'] ? "$noun couldn't" : ( $dirs ? 'files or directories' : 'files' ) . " couldn't"; yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %d %s be checked. %s', $site, $target, $doc['files_not_checked'], $could, $tail ); if ( null !== $why ) { yield ucfirst( $why ) . '.'; } - } elseif ( null !== $why ) { + } elseif ( $core_unknown ) { yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %s. %s', $site, $target, $why, $tail ); } else { yield sprintf( 'Can\'t confirm %s is safe for PHP %s: %s. %s', $site, $target, self::cross_text( $this->cross ), $tail ); + if ( null !== $why ) { + yield ucfirst( $why ) . '.'; + } } - if ( ( $doc['files_not_checked'] > 0 || null !== $why ) && ! self::cross_ok( $this->cross ) ) { + if ( ( $doc['files_not_checked'] > 0 || $core_unknown ) && ! self::cross_ok( $this->cross ) ) { yield ucfirst( self::cross_text( $this->cross ) ) . '.'; } } diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 43cd46df..9f137e0d 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3335,7 +3335,7 @@ protected function delete_stopped( $site ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, everything under htdocs. A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked, or WordPress hasn't declared support for the target). It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, the site's PHP in app/ except old releases nginx doesn't serve (a current/ release link) and the www-data user's tool directories (.composer, .wp-cli and the like). A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked; code files the scanner didn't read, such as code in the www-data user's tool directories, a link to code outside what was scanned, or files that changed while the check ran; an older scanner image that lists no files; or WordPress hasn't declared support for the target). After the scan, every code file in the site's files is compared with the list of files the scanner read, and only WordPress core of the live WordPress, old releases nginx doesn't serve, EasyEngine's unused app/wp-config.php and the index.php that loads WordPress from a subdirectory are exempt. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * From 72fd26b663fe4ac7d86201b390dcd40fd79cec70 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Wed, 25 Nov 2026 15:16:25 +0530 Subject: [PATCH 44/53] fix(site): check the WP-CLI configs `wp` reads from the site, served or WordPress root, and accept apache_modules The WP-CLI allowlist now applies to wp-cli.yml and wp-cli.local.yml in each directory from app/ down to the served root and the WordPress root (as written and as resolved), plus the www-data user's .wp-cli/config.yml: the ones `wp` reads when run from those places. A config deeper inside WordPress, such as a plugin's own, applies only when `wp` runs from inside that directory. apache_modules is accepted as a block or flow list of plain module names; aliases and command blocks stay refused. --- src/helper/Site_PHP_Compat.php | 70 ++++++++++++++++++++++++---------- 1 file changed, 49 insertions(+), 21 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 793af8fe..8b83c3d2 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -1056,19 +1056,8 @@ function ( $path, $name, $type ) use ( &$user_ini ) { if ( null !== $detail ) { return $this->doc( 'tool_error', $detail ); } - // WP-CLI configs anywhere in app/ but old releases (not served) and the www-data home's tool dirs. - $old = $this->old_release_dirs( $code ); - $this->wp_cli_files = []; - $error = $this->walk_tree( - $code, - function ( $path, $name, $type ) use ( $code, $old ) { - if ( in_array( $name, self::WP_CLI_CONFIGS, true ) ) { - $this->wp_cli_files[] = substr( $path, strlen( $code ) + 1 ); - } - return 'dir' === $type && ! isset( $old[ $path ] ) && ! ( dirname( $path ) === $code && in_array( $name, self::HOME_DOTDIRS, true ) ); - } - ); - $detail = null !== $error ? "can't look through {$app} for WP-CLI configs: $error" : $this->wp_cli_config_check( $code, $this->cross_layout['top'], $app ); + $this->wp_cli_files = self::wp_cli_chain( $code, [ $rel, $this->cross_layout['top'] ] ); + $detail = $this->wp_cli_config_check( $code, $this->cross_layout['top'], $app ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); } @@ -1119,12 +1108,12 @@ function ( $path, $name, $type ) use ( $code, $old ) { 'config' => $this->ee_config_unused_by, 'links' => $layout_links, ]; - $this->wp_cli_files = []; - $walk = $this->app_walk( $code, $rel, $root, $layout['abspath'], $allowed ); + $walk = $this->app_walk( $code, $rel, $root, $layout['abspath'], $allowed ); if ( is_string( $walk ) ) { return $this->doc( 'tool_error', str_replace( "$code/", $app, $walk ) ); } - $detail = $this->wp_cli_config_check( $code, $layout['abspath'], $app ); + $this->wp_cli_files = self::wp_cli_chain( $code, [ $rel, $root, null === $layout['abspath'] ? null : substr( $layout['abspath'], strlen( $code ) + 1 ), $this->cross_layout['top'] ] ); + $detail = $this->wp_cli_config_check( $code, $layout['abspath'], $app ); if ( null !== $detail ) { return $this->doc( 'tool_error', $detail ); } @@ -1349,9 +1338,6 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ if ( '.user.ini' === $name ) { $user_ini[] = [ $path, $type ]; } - if ( in_array( $name, self::WP_CLI_CONFIGS, true ) ) { - $this->wp_cli_files[] = substr( $path, strlen( $code ) + 1 ); - } if ( 'link' === $type ) { // A log or output file sent to /dev/null, stdout or stderr: exact targets only, never a code name. if ( ! self::php_name( $name ) && in_array( (string) @readlink( $path ), self::DEV_SINKS, true ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is no sink. @@ -2810,7 +2796,38 @@ protected function wp_config_files( $code, $root, $abspath ) { } /** - * WP-CLI configs (every wp-cli.yml and wp-cli.local.yml found in app/, and the www-data user's .wp-cli/config.yml) may + * The WP-CLI configs `wp` reads when run from the site root, the served root or the WordPress root: wp-cli.yml and + * wp-cli.local.yml in each directory from app/ down to each of them (as written and as resolved, since WP-CLI looks + * upwards from the real working directory). Deeper ones apply only to a `wp` run from inside them (residual R-WPCLI-CWD). + * + * @param string $code Real path of the site's app/. + * @param array $dirs Directories, relative to app/ or real host paths; null entries are skipped. + * + * @return string[] Config files relative to app/. + */ + protected static function wp_cli_chain( $code, array $dirs ) { + $files = []; + foreach ( $dirs as $dir ) { + if ( null === $dir ) { + continue; + } + $dir = 0 === strpos( $dir . '/', $code . '/' ) ? substr( $dir, strlen( $code ) + 1 ) : $dir; + for ( $dir = trim( (string) $dir, '/' ); ; $dir = dirname( $dir ) ) { + $dir = '.' === $dir ? '' : $dir; + foreach ( self::WP_CLI_CONFIGS as $name ) { + $files[] = ltrim( "$dir/$name", '/' ); + } + if ( '' === $dir ) { + break; + } + } + } + + return array_values( array_unique( $files ) ); + } + + /** + * WP-CLI configs (wp_cli_chain(), and the www-data user's .wp-cli/config.yml) may * hold only blank lines, comments and top-level `key: scalar` lines for path, url, user, color, quiet and debug. `path` * must lead to the WordPress root this check scans (php sites: the served root). Anything else (exec, require, inherit, * aliases, blocks) can make WP-CLI run code this check doesn't follow; there's no YAML parser in the phar. @@ -2836,14 +2853,25 @@ protected function wp_cli_config_check( $code, $live, $app ) { } $text = str_replace( [ "\r\n", "\r" ], "\n", $found['source'] ); $text = 0 === strpos( $text, "\xEF\xBB\xBF" ) ? substr( $text, 3 ) : $text; + $list = false; foreach ( explode( "\n", $text ) as $n => $line ) { if ( '' === trim( $line ) || '#' === substr( ltrim( $line ), 0, 1 ) ) { continue; } + // apache_modules: a block or flow list of plain module names (mod_rewrite); nothing else may be nested. + $item = '[A-Za-z0-9_.-]+'; + if ( $list && preg_match( '/^[ \t]+-[ \t]+' . $item . '[ \t]*(?:[ \t]#.*)?$/D', $line ) ) { + continue; + } + $list = false; + if ( preg_match( '/^apache_modules:[ \t]*(?:\[[ \t]*(?:' . $item . '[ \t]*(?:,[ \t]*' . $item . '[ \t]*)*)?\])?[ \t]*(?:[ \t]#.*)?$/D', $line, $am ) ) { + $list = false === strpos( $line, '[' ); + continue; + } // A plain YAML scalar: no flow/anchor/tag/alias start, `:` only when not followed by a blank, ` #` starts a comment. $scalar = '(?:\'[^\']*\'|"[^"\\\\]*"|[^\s\'"{}\[\],&*!|>%@`#:](?:[^\s#:]|:(?=\S)|[ \t]+(?=[^\s#]))*)'; if ( ! preg_match( '/^(' . implode( '|', self::WP_CLI_KEYS ) . '):(?:[ \t]+(' . $scalar . '))?[ \t]*(?:[ \t]#.*)?$/D', $line, $m ) ) { - return sprintf( '%s%s line %d isn\'t a WP-CLI setting this check accepts (only %s, as plain values): %s', $app, $file, $n + 1, implode( ', ', self::WP_CLI_KEYS ), self::clean( substr( trim( $line ), 0, 60 ) ) ); + return sprintf( '%s%s line %d isn\'t a WP-CLI setting this check accepts (only %s as plain values, and apache_modules): %s', $app, $file, $n + 1, implode( ', ', self::WP_CLI_KEYS ), self::clean( substr( trim( $line ), 0, 60 ) ) ); } if ( 'path' !== $m[1] ) { continue; From a1b8fb53886ee1dde1481adcd2f2d4b438b579ac Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:01:00 +0530 Subject: [PATCH 45/53] fix(site): ignore nginx-helper's unused bundled Predis and accept release pointers beside current - The ERROR findings of nginx-helper's admin/predis.php are dropped from the verdict only when it is exactly /wp-content/plugins/nginx-helper/admin/predis.php with no link on the way, it and includes/class-nginx-helper.php are the stock files of one released version (2.3.3 to 2.4.1, hashes from wordpress.org), and the running php container has the redis extension: then class_exists( 'Redis' ) keeps Predis from loading. The table says so and the JSON lists it under `ignored`; warnings and every other file are kept. - When nginx serves the live release, a link directly beside current and releases/ whose target is exactly a whole releases/ (previous, Deployer's release) is a release pointer and is ignored, as the scanner does. --- src/helper/Site_PHP_Compat.php | 141 ++++++++++++++++++++++++++++++++- 1 file changed, 138 insertions(+), 3 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 8b83c3d2..be763271 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -45,7 +45,7 @@ class Site_PHP_Compat { const SUMMARY_INTS = [ 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'duration_s' ]; const ESTIMATE_INTS = [ 'php_files', 'php_bytes', 'components', 'estimated_seconds', 'estimated_seconds_low', 'estimated_seconds_high' ]; // --format=json prints only the documented keys (INTERFACE.md), in this order. - const SUMMARY_KEYS = [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'checked', 'not_checked', 'not_checked_more', 'wordpress', 'cross_check', 'duration_s', 'tool' ]; + const SUMMARY_KEYS = [ 'v', 'status', 'site', 'target', 'safe_to_upgrade', 'errors', 'warnings', 'files_checked', 'files_not_checked', 'php_bytes', 'components_checked', 'components_with_errors', 'checked', 'not_checked', 'not_checked_more', 'wordpress', 'cross_check', 'ignored', 'duration_s', 'tool' ]; // stdout stays fixed-size: at most this many not_checked entries, each string at most NOT_CHECKED_CHARS characters. const NOT_CHECKED_STDOUT = 10; @@ -117,6 +117,17 @@ class Site_PHP_Compat { // The only keys a WP-CLI config may set: none of them loads code. const WP_CLI_KEYS = [ 'path', 'url', 'user', 'color', 'quiet', 'debug' ]; + // nginx-helper's bundled Predis (user decision): stock admin/predis.php and includes/class-nginx-helper.php by released + // version, verified from wordpress.org's zips. predis.php loads only via class-predis-purger.php, which the stock + // class-nginx-helper.php requires only when class Redis is missing; EE's php images ship phpredis. + const NGINX_HELPER_PREDIS = [ + '2.4.1' => [ 'c6393c3aeba2358a1ec9b206fda84c54ead3254184be914b08dce886acc6f670', '44fd41fb9275aef9764e1dfb06e47710986894ebafd4de861c2ec684d71aada5' ], + '2.4.0' => [ 'c6393c3aeba2358a1ec9b206fda84c54ead3254184be914b08dce886acc6f670', '2ec2f8579bebdb80024c3bfc2758e21caab7254a563c074cfa9624043c99dfa3' ], + '2.3.5' => [ 'c6393c3aeba2358a1ec9b206fda84c54ead3254184be914b08dce886acc6f670', 'd0f945eedb910007232bc0248e6011883661aa6c47a8f7083e027840d6581ae1' ], + '2.3.4' => [ 'c6393c3aeba2358a1ec9b206fda84c54ead3254184be914b08dce886acc6f670', '4a64a12cc41d0785664ad52fc6a5e71c1a3f46b290822f4982648b282e48c7cb' ], + '2.3.3' => [ 'c6393c3aeba2358a1ec9b206fda84c54ead3254184be914b08dce886acc6f670', '79f77f5c89f5f930e504404ce6efa008a0b260c52b07cb0a588e7894438761d9' ], + ]; + // Exact link targets that are a sink, never code. const DEV_SINKS = [ '/dev/null', '/dev/stdout', '/dev/stderr' ]; @@ -186,6 +197,12 @@ class Site_PHP_Compat { /** @var int Second the scan started (scan_start_time()); a file with a ctime from then on may not be what the scanner read. */ protected $scan_start = PHP_INT_MAX; + /** @var string|null Id of the site's running php container (extra_mounts()); null when it doesn't run. */ + protected $php_container; + + /** @var array[] Findings dropped from the verdict by an exact exemption: [ file, reason, count ]. */ + protected $ignored = []; + /** @var bool Whether the last lock_site() couldn't open the site directory (gone during a delete). */ protected $lock_unopenable = false; @@ -565,6 +582,10 @@ protected function run_scan( $site_data, $timeout, $output ) { return $this->doc( 'tool_error', self::exit_detail( $run, 'without a valid report' ) ); } + // Exact-file exemption (user decision): nginx-helper's bundled Predis isn't loaded when phpredis is. + $this->ignored = []; + $this->ignore_unused_predis( $code, $doc, $report ); + // The final gate: every code file in app/ is one the scanner read or reported, or an exact exempt shape. $this->cross = $this->cross_check( $code, $out ); @@ -1353,6 +1374,10 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ return false; } $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); + // A release pointer beside current (previous -> releases/1) while nginx serves the live release: shape (a). + if ( null !== $releases && null !== $real && 0 === strpos( $top . '/', $live . '/' ) && dirname( $path ) === dirname( $releases ) && dirname( $real ) === $releases ) { + return false; + } // A link to a file already read and validated (releases/wp-config.php -> ../wp-config.php): no other code. A config // accepted only because nothing loads it was never validated, and a link would load it. if ( null !== $real && in_array( $real, $allowed, true ) && ! in_array( $real, $this->unused_configs, true ) ) { @@ -1510,6 +1535,10 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $start, $un return false; } $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); + // A release pointer beside current (previous -> releases/1, Deployer's release -> releases/3): exact shape (a). + if ( null !== $rules['releases_dir'] && null !== $target && dirname( $path ) === dirname( $rules['releases_dir'] ) && dirname( $target ) === $rules['releases_dir'] ) { + return false; + } // Outside the scanner's roots nothing follows a directory link or an unresolvable one for it (the home dirs). if ( null === self::under_any( $path, $code, $rules['roots'] ) && ( null === $target || is_dir( $target ) ) ) { if ( ! $reported( $path ) ) { @@ -1892,6 +1921,7 @@ function ( $ext ) { 'skip_walk' => $skip_walk, 'sniff_roots' => $sniff_roots, 'roots' => array_fill_keys( array_filter( $roots ), true ), + 'releases_dir' => $this->releases_dir( $code ), 'layout_links' => $layout_links, ]; } @@ -1914,6 +1944,24 @@ protected static function touches( $real, array $places ) { return false; } + /** + * @param string $code Real path of the site's app/. + * + * @return string|null The real releases/ directory when exempt shape (a) applies (nginx's root is the live release or + * below it), else null. + */ + protected function releases_dir( $code ) { + $top = null === $this->cross_layout ? null : $this->cross_layout['top']; + $abspath = null === $this->cross_layout ? null : $this->cross_layout['abspath']; + for ( $dir = null !== $abspath ? $abspath : $top; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { + if ( 'releases' === basename( dirname( $dir ) ) ) { + return null !== $top && 0 === strpos( $top . '/', $dir . '/' ) ? dirname( $dir ) : null; + } + } + + return null; + } + /** * @return int The time bound of reading the scanner's manifest into lookups. */ @@ -2182,6 +2230,78 @@ protected function walk_tree( $top, callable $visit ) { return null; } + /** + * Drops the ERROR findings of nginx-helper's bundled Predis (admin/predis.php) from the verdict, only when all hold: + * it is exactly /wp-content/plugins/nginx-helper/admin/predis.php with no link on the way; it and + * includes/class-nginx-helper.php are a stock released pair (NGINX_HELPER_PREDIS), so the class_exists( 'Redis' ) guard + * is intact; and the running php container has the redis extension (a stopped site gets no exemption). Warnings stay. + * + * @param string $code Real path of the site's app/. + * @param array $doc Scanner summary (errors and components_with_errors are adjusted). + * @param array $report Scanner report (the component's findings and counts are adjusted). + */ + protected function ignore_unused_predis( $code, array &$doc, array &$report ) { + $abspath = null === $this->cross_layout ? null : $this->cross_layout['abspath']; + if ( ! $this->wp_layout || null === $abspath || null === $this->php_container ) { + return; + } + $dir = "$abspath/wp-content/plugins/nginx-helper"; + $at = null; + foreach ( $report['components'] as $i => $component ) { + if ( 'plugin' === $component['type'] && 'nginx-helper' === $component['slug'] && null === $component['branch'] ) { + foreach ( $component['findings'] as $finding ) { + if ( 'admin/predis.php' === $finding['file'] && 'ERROR' === $finding['type'] ) { + $at = $i; + break 2; + } + } + } + } + if ( null === $at ) { + return; + } + // Exact files at their own paths: no link anywhere on the way. + $hash = function ( $path ) { + $stat = @lstat( $path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + return false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) && realpath( $path ) === $path ? hash_file( 'sha256', $path ) : null; + }; + $predis = $hash( "$dir/admin/predis.php" ); + $guard = $hash( "$dir/includes/class-nginx-helper.php" ); + $stock = false; + foreach ( self::NGINX_HELPER_PREDIS as $pair ) { + $stock = $stock || ( $predis === $pair[0] && $guard === $pair[1] ); + } + if ( ! $stock ) { + return; + } + $run = $this->docker( [ 'docker', 'exec', $this->php_container, 'php', '-r', 'echo extension_loaded( "redis" ) ? "yes" : "no";' ], 60 ); + if ( 0 !== $run['code'] || 'yes' !== trim( $run['stdout'] ) ) { + return; + } + $component = $report['components'][ $at ]; + $kept = []; + $dropped = 0; + foreach ( $component['findings'] as $finding ) { + if ( 'admin/predis.php' === $finding['file'] && 'ERROR' === $finding['type'] ) { + ++$dropped; + continue; + } + $kept[] = $finding; + } + $component['findings'] = $kept; + $component['errors'] -= $dropped; + $report['components'][ $at ] = $component; + $doc['errors'] -= $dropped; + if ( 0 === $component['errors'] ) { + --$doc['components_with_errors']; + } + $this->ignored[] = [ + 'file' => '/var/www' . substr( "$dir/admin/predis.php", strlen( $code ) ), + 'reason' => "nginx-helper's bundled Predis isn't loaded: the redis extension is installed", + 'count' => $dropped, + ]; + } + /** * Waits for the next whole second and returns it: ctime has whole seconds, so every file with a ctime before it was * last changed before the scanner started. @@ -2492,12 +2612,14 @@ public static function nginx_refusal( $text, $main, $custom ) { * @return array|string --mount arguments, or a tool_error detail. */ protected function extra_mounts( $site_data, $code ) { - $this->extra_mounts = []; + $this->extra_mounts = []; + $this->php_container = null; $ps = $this->docker( [ 'docker', 'ps', '-q', '--no-trunc', '--filter', 'label=io.easyengine.site=' . $this->site, '--filter', 'label=com.docker.compose.service=php' ], 60 ); if ( 0 !== $ps['code'] ) { return 'could not list the site\'s php container: ' . self::first_line( $ps['stderr'] ); } $ids = preg_split( '/\s+/', trim( $ps['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ); + $this->php_container = $ids ? $ids[0] : null; if ( ! $ids ) { // Not running (a disabled site): only its compose files say what it mounts. foreach ( array_merge( [ $site_data->site_fs_path . '/docker-compose-custom.yml' ], (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yml' ), (array) glob( $site_data->site_fs_path . '/user-docker-compose/*.yaml' ) ) as $file ) { @@ -3853,7 +3975,7 @@ protected function output_dir_unchanged( $path ) { */ protected function scoped( array $doc, array $report ) { // Only EE sets these; the scanner can't. - unset( $doc['checked'], $doc['not_checked'], $doc['wordpress'], $doc['cross_check'] ); + unset( $doc['checked'], $doc['not_checked'], $doc['wordpress'], $doc['cross_check'], $doc['ignored'] ); $doc['checked'] = [ 'dir' => self::clean( (string) $this->looked_in ), 'components' => $doc['components_checked'], @@ -3884,6 +4006,15 @@ function ( $entry ) { 'core_files_checked' => false, ]; } + $doc['ignored'] = array_map( + function ( $entry ) { + return [ + 'file' => $entry['file'], + 'reason' => $entry['reason'], + ]; + }, + $this->ignored + ); $doc['cross_check'] = null === $this->cross ? null : [ 'manifest' => $this->cross['manifest'], 'unlisted' => $this->cross['unlisted'], @@ -4204,6 +4335,7 @@ protected function table_lines( array $doc, $report ) { if ( null !== $core ) { $line .= ' ' . ( null === $why ? sprintf( 'WordPress %s supports PHP %s', $this->wp_version['branch'], $target ) : ucfirst( $why ) ) . '.'; } + // Exempt shape (a): what wasn't read, so the line never claims all of htdocs. if ( ! $this->wp_layout && null !== $this->cross && ! empty( $this->cross['old_releases'] ) ) { // looked_in is /app/htdocs on php sites. @@ -4246,6 +4378,9 @@ function ( $entry ) { yield ucfirst( self::cross_text( $this->cross ) ) . '.'; } } + foreach ( $this->ignored as $entry ) { + yield sprintf( 'Ignored %s in nginx-helper\'s bundled Predis (admin/predis.php), which isn\'t loaded because the redis extension is installed.', self::count_of( $entry['count'], 'finding' ) ); + } yield ''; $warnings_only = []; From 0f0081c153238ae38951e8c31eaf88ac08929f11 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:03:33 +0530 Subject: [PATCH 46/53] fix(site): narrow php-compat's newest accept rules to exact shapes - Release pointers: only a link named previous or release, beside releases/, to a release directory, while nginx serves the live release; anything else falls through to the other link rules. - nginx-helper's bundled Predis: also requires no mount over the plugin, a single name for predis.php and its guard, the whole plugin directory matching a stock release (2.2.0 to 2.4.1, from wordpress.org's zips), and no other scanned code naming predis at a word start; the ignored finding stays in the --output report, marked. - WP-CLI configs: no links; only `key: value` lines with plain values, comments in column 0 and an apache_modules block list; path must be one of the texts EE writes for the root, resolve to it from the file's directory, and lead WP-CLI to the wp-config.php this check validated. - A data-only file rewritten during the scan is fine anywhere in the scanner's roots; the scan's start is taken before the layout is read under the lock. - A link in a tree WordPress links to gets the inside-WordPress checks instead of a refusal; on php sites a non-code-named link in a home dot dir that leaves the site is nothing. - More than one php container is refused; a directory link the scanner reports with a trailing slash is matched; JSON names the old releases left unread (checked.excluded_old_releases); the help text names ignored findings and what isn't compared. --- src/helper/Site_PHP_Compat.php | 332 +++++++++++++++++++++++++-------- src/helper/class-ee-site.php | 4 +- 2 files changed, 254 insertions(+), 82 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index be763271..38574f9d 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -120,6 +120,24 @@ class Site_PHP_Compat { // nginx-helper's bundled Predis (user decision): stock admin/predis.php and includes/class-nginx-helper.php by released // version, verified from wordpress.org's zips. predis.php loads only via class-predis-purger.php, which the stock // class-nginx-helper.php requires only when class Redis is missing; EE's php images ship phpredis. + const NGINX_HELPER_RELEASES = [ + '2.2.0' => '3cb381a86e62310b821d4fe50e42de9180215ec95c8d95b6e39dd613016d7aac', + '2.2.1' => '172333813af04fda5019ef6b50b79ffc55eb9862a982b07208daf1394cc695e9', + '2.2.2' => '2f1cfa30d246412de08a34b256c3ee7e80a0d0f57d568406d861b81976d15cb8', + '2.2.3' => '31a12a66a28a2d4dbc67b8d9482faa1abfe1d17af5398a19f6a01dcfeae7dfa5', + '2.2.4' => '2807ff4a45f94e90bc357fbb75749127d34d566b15809b0bb948d6d53c9003cd', + '2.2.5' => '782a16ba3180b6278141e341d9592f0f8bcf6083faeca6d8b13402f041fe6df4', + '2.3.0' => 'aba8a708987030eb8fa2ddddaeddacd6164a62368414155dd009a42d7f382d2a', + '2.3.1' => 'b5508c8ff4f12c865f31fcbd456b01b20970f7e0bd24a4471accce0f2abaa9b4', + '2.3.2' => '33ebef47d56421dbb4c521fc4dda5cd53dde6137dae232061d81879cbdbc0733', + '2.3.3' => 'aa886e16bd93a406e361922323107ba251e1142e533f066b0bfad20d1da32aa3', + '2.3.4' => '0a9e1c709fe4534b68a36991b3f3890e7f3f17aad51081d017f25ab212dfc181', + '2.3.5' => '94ed9a06114e3d92f4d221d5dc146148aa84ee3a8f79304215966c14f606b512', + '2.4.0' => '7420855acc37c6c9da189a2e48759d95940ec07852b9f3f4b7719297da181024', + '2.4.1' => '4812f913cdd19ac9803e3782e6d32f8c51f01057a566c5c083b410a99528f412', + ]; + + // The stock predis.php / class-nginx-helper.php pairs (documentation; NGINX_HELPER_RELEASES pins whole releases). const NGINX_HELPER_PREDIS = [ '2.4.1' => [ 'c6393c3aeba2358a1ec9b206fda84c54ead3254184be914b08dce886acc6f670', '44fd41fb9275aef9764e1dfb06e47710986894ebafd4de861c2ec684d71aada5' ], '2.4.0' => [ 'c6393c3aeba2358a1ec9b206fda84c54ead3254184be914b08dce886acc6f670', '2ec2f8579bebdb80024c3bfc2758e21caab7254a563c074cfa9624043c99dfa3' ], @@ -188,6 +206,18 @@ class Site_PHP_Compat { /** @var string|null Real path of the wp-config.php WordPress loads when that makes EE's app/wp-config.php unused (shape (c)). */ protected $ee_config_unused_by; + /** @var string The site's app/ with a trailing slash (resolve_layout()), for paths named in output. */ + protected $app_path = ''; + + /** @var string[] Resolved host paths of the accepted extra mounts (extra_mounts()). */ + protected $mount_points = []; + + /** @var string[] The manifest's `checked` container paths, decoded (cross_check()). */ + protected $manifest_checked = []; + + /** @var string|null Real path of the wp-config.php WordPress loads, validated by check_wp_config(). */ + protected $loaded_config; + /** @var string[] WP-CLI configs found in the site's files, relative to app/. */ protected $wp_cli_files = []; @@ -510,6 +540,8 @@ protected function run_scan( $site_data, $timeout, $output ) { if ( null !== $pull ) { return $this->doc( 'tool_error', $pull ); } + // From here on a changed file may not be what was validated or scanned (cross_check() compares ctime). + $this->scan_start = $this->scan_start_time(); // Read under the site lock and after the pull, so the layout checked is the one scanned. $layout = $this->resolve_layout( $site_data, $code ); if ( null !== $layout ) { @@ -534,8 +566,6 @@ protected function run_scan( $site_data, $timeout, $output ) { // From here until cleanup() confirms it is gone, /out may be in use by this container. $this->active_container = $name; - // Files changed from here on may differ from what the scanner read (cross_check() compares ctime). - $this->scan_start = $this->scan_start_time(); $run = $this->docker( $this->docker_run_args( 'scan', $image, $site_data, $code, $out, $timeout ), $timeout + self::PROCESS_MARGIN, true ); if ( $run['timed_out'] ) { return $this->doc( 'tool_error', "timed out after $timeout s" ); @@ -582,13 +612,13 @@ protected function run_scan( $site_data, $timeout, $output ) { return $this->doc( 'tool_error', self::exit_detail( $run, 'without a valid report' ) ); } - // Exact-file exemption (user decision): nginx-helper's bundled Predis isn't loaded when phpredis is. - $this->ignored = []; - $this->ignore_unused_predis( $code, $doc, $report ); - // The final gate: every code file in app/ is one the scanner read or reported, or an exact exempt shape. $this->cross = $this->cross_check( $code, $out ); + // Exact exemption (user decision): nginx-helper's bundled Predis isn't loaded when phpredis is. + $this->ignored = []; + $this->ignore_unused_predis( $code, $doc, $report ); + // Last point a cancel wins: after it, the result stands and --output is written. if ( $this->cancel_requested() ) { return $this->cancelled(); @@ -1050,6 +1080,8 @@ protected function resolve_layout( $site_data, $code ) { } $rel = ltrim( substr( $served, strlen( '/var/www' ) ), '/' ); $app = $site_data->site_fs_path . '/app/'; + // For messages and JSON paths named from the site's app/. + $this->app_path = $app; $this->scan_path = $served; $detail = $this->server_config_check( $site_data ); @@ -1078,7 +1110,7 @@ function ( $path, $name, $type ) use ( &$user_ini ) { return $this->doc( 'tool_error', $detail ); } $this->wp_cli_files = self::wp_cli_chain( $code, [ $rel, $this->cross_layout['top'] ] ); - $detail = $this->wp_cli_config_check( $code, $this->cross_layout['top'], $app ); + $detail = $this->wp_cli_config_check( $code, $this->cross_layout['top'], $app, $rel ); return null === $detail ? null : $this->doc( 'tool_error', $detail ); } @@ -1098,6 +1130,7 @@ function ( $path, $name, $type ) use ( &$user_ini ) { $allowed[] = $index; } $this->wp_version = null; + $this->loaded_config = null; $this->ee_config_unused_by = null; $this->unused_configs = []; $this->current_php = isset( $site_data->php_version ) && preg_match( '/^\d+\.\d+$/D', (string) $site_data->php_version ) ? (string) $site_data->php_version : null; @@ -1134,7 +1167,7 @@ function ( $path, $name, $type ) use ( &$user_ini ) { return $this->doc( 'tool_error', str_replace( "$code/", $app, $walk ) ); } $this->wp_cli_files = self::wp_cli_chain( $code, [ $rel, $root, null === $layout['abspath'] ? null : substr( $layout['abspath'], strlen( $code ) + 1 ), $this->cross_layout['top'] ] ); - $detail = $this->wp_cli_config_check( $code, $layout['abspath'], $app ); + $detail = $this->wp_cli_config_check( $code, $layout['abspath'], $app, $root ); if ( null !== $detail ) { return $this->doc( 'tool_error', $detail ); } @@ -1247,8 +1280,9 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { if ( 'ok' !== $file['state'] ) { return "can't read $app{$config[0]}: " . ( 'bad' === $file['state'] ? $file['detail'] : 'it is gone' ); } - $read = [ $file['real'] ]; - $resolve = function ( $path ) use ( $code, $abspath, &$read ) { + $read = [ $file['real'] ]; + $this->loaded_config = $file['real']; + $resolve = function ( $path ) use ( $code, $abspath, &$read ) { if ( 0 !== strpos( $path, "$code/" ) ) { return [ 'state' => 'bad', 'detail' => 'is outside the site\'s files' ]; } @@ -1352,9 +1386,10 @@ protected function app_walk( $code, $rel, $root, $abspath, array $allowed ) { $found = null; $outside = []; $linked = []; + $deferred = []; $error = $this->walk_tree( $code, - function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $releases, $live, &$user_ini, &$found, &$outside, &$linked ) { + function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $releases, $live, &$user_ini, &$found, &$outside, &$linked, &$deferred ) { $inside = null !== $abspath && 0 === strpos( $path . '/', $abspath . '/' ); if ( '.user.ini' === $name ) { $user_ini[] = [ $path, $type ]; @@ -1375,7 +1410,7 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ } $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); // A release pointer beside current (previous -> releases/1) while nginx serves the live release: shape (a). - if ( null !== $releases && null !== $real && 0 === strpos( $top . '/', $live . '/' ) && dirname( $path ) === dirname( $releases ) && dirname( $real ) === $releases ) { + if ( null !== $releases && null !== $real && self::release_pointer( $path, $real, $releases ) && 0 === strpos( $top . '/', $live . '/' ) ) { return false; } // A link to a file already read and validated (releases/wp-config.php -> ../wp-config.php): no other code. A config @@ -1409,8 +1444,9 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ } return false; } - $found = "$path is a link outside the WordPress directory"; - return 'stop'; + // Decided after the walk: it may lie in a directory WordPress reaches through a link (shared wp-content). + $deferred[] = [ $path, $real, $why ]; + return false; } if ( 'dir' === $type ) { if ( $inside ) { @@ -1446,6 +1482,30 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ if ( null !== $error ) { return "can't look through the site's files: $error"; } + // A link in a tree WordPress links to is judged as inside it (the scanner follows it there); any other is refused. + foreach ( null === $found ? $deferred : [] as list( $path, $real, $why ) ) { + $within = false; + foreach ( $linked as $target ) { + $within = $within || 0 === strpos( $path, $target . '/' ); + } + if ( ! $within ) { + $found = "$path is a link outside the WordPress directory"; + } elseif ( null === $real && 'missing' !== $why ) { + $found = "$path is a link this check can't follow the way the container does"; + } elseif ( null !== $real && ( 0 === strpos( $real . '/', "$abspath/wp-admin/" ) || 0 === strpos( $real . '/', "$abspath/wp-includes/" ) ) ) { + $found = "$path links into WordPress core ($real), which this check doesn't scan"; + } elseif ( null !== $real && 0 === strpos( dirname( $path ) . '/', $real . '/' ) ) { + $found = "$path links to its own ancestor " . $real; + } elseif ( null !== $real && self::reaches_install( $code, $real, $abspath ) ) { + $found = "$path links into another WordPress install ($real)"; + } elseif ( null !== $real && is_dir( $real ) && 0 !== strpos( $real . '/', $abspath . '/' ) ) { + // A further directory outside WordPress: its own contents weren't checked as reachable code here. + $found = "$path is a link outside the WordPress directory"; + } + if ( null !== $found ) { + break; + } + } if ( null === $found ) { foreach ( $outside as $path ) { $covered = false; @@ -1479,7 +1539,8 @@ function ( $path, $name, $type ) use ( $code, $top, $root, $abspath, $allowed, $ * no walk ran), walk_error (string|null), error (string|null: why there is no positive verdict besides unlisted). */ protected function cross_check( $code, $out ) { - $result = [ + $this->manifest_checked = []; + $result = [ 'manifest' => false, 'unlisted' => [], 'unlisted_more' => 0, @@ -1493,7 +1554,8 @@ protected function cross_check( $code, $out ) { $result['error'] = $m; return $result; } - $rules = $this->manifest_rules( $code, $m ); + $this->manifest_checked = $m['checked']; + $rules = $this->manifest_rules( $code, $m ); if ( is_string( $rules ) ) { $result['error'] = $rules; return $result; @@ -1536,7 +1598,12 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $start, $un } $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); // A release pointer beside current (previous -> releases/1, Deployer's release -> releases/3): exact shape (a). - if ( null !== $rules['releases_dir'] && null !== $target && dirname( $path ) === dirname( $rules['releases_dir'] ) && dirname( $target ) === $rules['releases_dir'] ) { + if ( null !== $rules['releases_dir'] && null !== $target && self::release_pointer( $path, $target, $rules['releases_dir'] ) ) { + return false; + } + // php sites: a non-code-named link in a www-data home dot dir that leaves the site (.venv/bin/python) is nothing, + // as for the scanner (U13). + if ( ! $named && null === $target && 'escape' === $why && ! $rules['wp'] && '.' === substr( strtok( substr( $path, strlen( $code ) + 1 ), '/' ), 0, 1 ) ) { return false; } // Outside the scanner's roots nothing follows a directory link or an unresolvable one for it (the home dirs). @@ -1596,9 +1663,10 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $start, $un if ( isset( $seen[ $ino ] ) ) { return false; } - // Changed since the scan started: not what the scanner read. A cache's data-only file in a skipped dir is fine. + // Changed since the scan started: not what the scanner read. A data-only file (a cache, Wordfence's wflogs) is fine + // anywhere the scanner walks: it can't run code past its exit. if ( $stat['ctime'] >= $start ) { - if ( ! $phar && null !== self::under_any( $path, $code, $rules['skipped'] ) && self::data_only( $path ) ) { + if ( ! $phar && null !== self::under_any( $path, $code, $rules['roots'] ) && self::data_only( $path ) ) { return false; } ++$changed; @@ -1796,10 +1864,9 @@ protected function manifest_rules( $code, array $m ) { $nc_dirs[ $host ] = true; continue; } - if ( '/' !== substr( $path, -1 ) ) { - // As listed: a link that dangles or leaves /var/www is named by its own path. - $nc_paths[ $path ] = true; - } + // As listed: a link that dangles, leaves /var/www or leads into an exempt place is named by its own path (a directory + // link with a trailing slash). + $nc_paths[ rtrim( $path, '/' ) ] = true; $stat = '/' === substr( $path, -1 ) ? false : self::manifest_stat( $code, $path ); if ( false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) ) { $nc_files[ $stat['dev'] . ':' . $stat['ino'] ] = true; @@ -1922,6 +1989,7 @@ function ( $ext ) { 'sniff_roots' => $sniff_roots, 'roots' => array_fill_keys( array_filter( $roots ), true ), 'releases_dir' => $this->releases_dir( $code ), + 'wp' => $layout['wp'], 'layout_links' => $layout_links, ]; } @@ -1944,6 +2012,27 @@ protected static function touches( $real, array $places ) { return false; } + /** + * @return string The site's app/ with a trailing slash. + */ + protected function app_dir() { + return $this->app_path; + } + + /** + * A release pointer beside current: a link named exactly `previous` or `release`, directly in the directory that holds + * releases/, whose real target is a directory directly in releases/. + * + * @param string $path Link path (its real location). + * @param string $real Its resolved target. + * @param string $releases Real releases/ directory. + * + * @return bool + */ + protected static function release_pointer( $path, $real, $releases ) { + return in_array( basename( $path ), [ 'previous', 'release' ], true ) && dirname( $path ) === dirname( $releases ) && dirname( $real ) === $releases && is_dir( $real ) && ! is_link( $real ); + } + /** * @param string $code Real path of the site's app/. * @@ -2260,35 +2349,53 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( null === $at ) { return; } - // Exact files at their own paths: no link anywhere on the way. - $hash = function ( $path ) { + // Nothing mounted over the plugin: the files hashed on the host must be the ones PHP runs. + $plugin = []; + $plugin[ $dir ] = true; + foreach ( $this->mount_points as $mount ) { + if ( self::touches( $mount, $plugin ) ) { + return; + } + } + // Exact files at their own paths (no link on the way), each with one name only (no second name elsewhere). + foreach ( [ "$dir/admin/predis.php", "$dir/includes/class-nginx-helper.php" ] as $path ) { $stat = @lstat( $path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. - return false !== $stat && 0100000 === ( $stat['mode'] & 0170000 ) && realpath( $path ) === $path ? hash_file( 'sha256', $path ) : null; - }; - $predis = $hash( "$dir/admin/predis.php" ); - $guard = $hash( "$dir/includes/class-nginx-helper.php" ); - $stock = false; - foreach ( self::NGINX_HELPER_PREDIS as $pair ) { - $stock = $stock || ( $predis === $pair[0] && $guard === $pair[1] ); + if ( false === $stat || 0100000 !== ( $stat['mode'] & 0170000 ) || 1 !== $stat['nlink'] || realpath( $path ) !== $path ) { + return; + } } - if ( ! $stock ) { + // The whole plugin is a stock release: same file list, same contents (no other file of it loads predis.php). + if ( ! in_array( self::dir_manifest( $dir ), self::NGINX_HELPER_RELEASES, true ) ) { return; } + // No other code the scanner read mentions predis (another plugin requiring it), matched at a word start so that + // "PhpRedis" (wp-redis, EE's object cache drop-in) doesn't count. + foreach ( $this->manifest_checked as $checked ) { + if ( 0 === strpos( $checked, 'b64:' ) ) { + return; + } + $host = $code . substr( $checked, strlen( '/var/www' ) ); + if ( 0 === strpos( $host, "$dir/" ) ) { + continue; + } + $text = @file_get_contents( $host ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable refuses. + if ( false === $text || 0 !== preg_match( '/(?docker( [ 'docker', 'exec', $this->php_container, 'php', '-r', 'echo extension_loaded( "redis" ) ? "yes" : "no";' ], 60 ); if ( 0 !== $run['code'] || 'yes' !== trim( $run['stdout'] ) ) { return; } $component = $report['components'][ $at ]; - $kept = []; $dropped = 0; - foreach ( $component['findings'] as $finding ) { + foreach ( $component['findings'] as $i => $finding ) { + // Kept in the report, marked: the --output file still shows what was ignored. if ( 'admin/predis.php' === $finding['file'] && 'ERROR' === $finding['type'] ) { ++$dropped; - continue; + $component['findings'][ $i ]['ignored'] = true; } - $kept[] = $finding; } - $component['findings'] = $kept; $component['errors'] -= $dropped; $report['components'][ $at ] = $component; $doc['errors'] -= $dropped; @@ -2296,12 +2403,50 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { --$doc['components_with_errors']; } $this->ignored[] = [ - 'file' => '/var/www' . substr( "$dir/admin/predis.php", strlen( $code ) ), + 'file' => self::cut( self::clean( '/var/www' . substr( "$dir/admin/predis.php", strlen( $code ) ) ) ), 'reason' => "nginx-helper's bundled Predis isn't loaded: the redis extension is installed", 'count' => $dropped, ]; } + /** + * sha256 of a directory's file list: sorted "relative pathsha256" lines, newline-terminated. Anything other than + * regular files and directories (a link, a FIFO) gives null. + * + * @param string $dir Real directory. + * + * @return string|null + */ + protected static function dir_manifest( $dir ) { + $lines = []; + $todo = [ '' ]; + while ( $todo ) { + $rel = array_pop( $todo ); + $entries = @scandir( '' === $rel ? $dir : "$dir/$rel" ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $entries ) { + return null; + } + foreach ( $entries as $name ) { + if ( '.' === $name || '..' === $name ) { + continue; + } + $path = '' === $rel ? $name : "$rel/$name"; + $stat = @lstat( "$dir/$path" ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + $mode = false === $stat ? 0 : $stat['mode'] & 0170000; + if ( 0040000 === $mode ) { + $todo[] = $path; + } elseif ( 0100000 === $mode ) { + $lines[] = $path . "\t" . hash_file( 'sha256', "$dir/$path" ); + } else { + return null; + } + } + } + sort( $lines, SORT_STRING ); + + return hash( 'sha256', implode( "\n", $lines ) . "\n" ); + } + /** * Waits for the next whole second and returns it: ctime has whole seconds, so every file with a ctime before it was * last changed before the scanner started. @@ -2613,12 +2758,17 @@ public static function nginx_refusal( $text, $main, $custom ) { */ protected function extra_mounts( $site_data, $code ) { $this->extra_mounts = []; + $this->mount_points = []; $this->php_container = null; $ps = $this->docker( [ 'docker', 'ps', '-q', '--no-trunc', '--filter', 'label=io.easyengine.site=' . $this->site, '--filter', 'label=com.docker.compose.service=php' ], 60 ); if ( 0 !== $ps['code'] ) { return 'could not list the site\'s php container: ' . self::first_line( $ps['stderr'] ); } $ids = preg_split( '/\s+/', trim( $ps['stdout'] ), -1, PREG_SPLIT_NO_EMPTY ); + // EE runs one php container per site; with more, which one serves a request (and what it mounts) is unknown. + if ( count( $ids ) > 1 ) { + return 'the site has more than one php container (' . count( $ids ) . '), which this check can\'t confirm'; + } $this->php_container = $ids ? $ids[0] : null; if ( ! $ids ) { // Not running (a disabled site): only its compose files say what it mounts. @@ -2716,6 +2866,7 @@ function ( $path, $name, $type ) use ( &$user_ini ) { if ( null !== $error || null !== $user_ini ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ( null !== $user_ini ? ', which holds a .user.ini (' . self::clean( $user_ini ) . ') this check doesn\'t read' : ", which can't be looked through: $error" ); } + $this->mount_points[] = $at; EE::debug( "php-compat: also mounting $src at $dst" ); array_push( $this->extra_mounts, '--mount', "type=bind,src=$src,dst=$dst,readonly" ); } @@ -2949,69 +3100,81 @@ protected static function wp_cli_chain( $code, array $dirs ) { } /** - * WP-CLI configs (wp_cli_chain(), and the www-data user's .wp-cli/config.yml) may - * hold only blank lines, comments and top-level `key: scalar` lines for path, url, user, color, quiet and debug. `path` - * must lead to the WordPress root this check scans (php sites: the served root). Anything else (exec, require, inherit, - * aliases, blocks) can make WP-CLI run code this check doesn't follow; there's no YAML parser in the phar. + * WP-CLI configs (wp_cli_chain(), and the www-data user's .wp-cli/config.yml), exact shapes only (review of a1b8fb53): + * each is a regular file, not a link; every line is blank, a comment starting with `#` in column 0, `key: value` with + * key in WP_CLI_KEYS and value matching `[A-Za-z0-9_./:@-]+` (no quotes, anchors, aliases, flow, comments or spaces), or + * an `apache_modules:` block list of module names. `path` must be one of the texts EE writes for this WordPress root + * (``, `/`, `/var/www/htdocs/`, with or without the slash; `/var/www/htdocs[/]` for htdocs), never a + * number Spyc would coerce; relative to the file's directory it must lead to the live root, and the wp-config.php + * WP-CLI then loads must be the one this check validated. * * @param string $code Real path of the site's app/. * @param string|null $live Real path `path:` must lead to. * @param string $app The site's app/ with a trailing slash, for messages. + * @param string $root The WordPress root (php: the served root) relative to app/, as written. * * @return string|null tool_error detail. */ - protected function wp_cli_config_check( $code, $live, $app ) { + protected function wp_cli_config_check( $code, $live, $app, $root ) { + $dir = 'htdocs' === $root ? '' : ( 0 === strpos( $root, 'htdocs/' ) ? substr( $root, strlen( 'htdocs/' ) ) : null ); + $texts = null === $dir ? [] : ( '' === $dir ? [ '/var/www/htdocs', '/var/www/htdocs/' ] : [ $dir, "$dir/", "/var/www/htdocs/$dir", "/var/www/htdocs/$dir/" ] ); foreach ( array_unique( array_merge( [ self::WP_CLI_HOME ], $this->wp_cli_files ) ) as $file ) { - // Missing (a dangling link included) is no config; one the container could reach elsewhere is refused. - if ( null === self::resolve_in( $code, $file, $why ) ) { + // The directory as the container resolves it; the file itself must be a regular file there, never a link. + $base = self::resolve_in( $code, dirname( $file ), $why ); + if ( null === $base ) { if ( 'missing' === $why ) { continue; } return "can't read $app$file, a WP-CLI config: it is reached through a link this check can't follow the way the container does"; } - $found = $this->site_file( $code, $file ); + $path = $base . '/' . basename( $file ); + $stat = @lstat( $path ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $stat ) { + continue; + } + if ( 0100000 !== ( $stat['mode'] & 0170000 ) ) { + return "$app$file, a WP-CLI config, is a link or not a regular file, which this check doesn't accept"; + } + $found = $this->site_file( $code, substr( $path, strlen( $code ) + 1 ) ); if ( 'ok' !== $found['state'] ) { return "can't read $app$file, a WP-CLI config: {$found['detail']}"; } - $text = str_replace( [ "\r\n", "\r" ], "\n", $found['source'] ); - $text = 0 === strpos( $text, "\xEF\xBB\xBF" ) ? substr( $text, 3 ) : $text; $list = false; - foreach ( explode( "\n", $text ) as $n => $line ) { - if ( '' === trim( $line ) || '#' === substr( ltrim( $line ), 0, 1 ) ) { + foreach ( explode( "\n", str_replace( "\r\n", "\n", $found['source'] ) ) as $n => $line ) { + if ( '' === trim( $line, " \t" ) || '#' === substr( $line, 0, 1 ) ) { continue; } - // apache_modules: a block or flow list of plain module names (mod_rewrite); nothing else may be nested. - $item = '[A-Za-z0-9_.-]+'; - if ( $list && preg_match( '/^[ \t]+-[ \t]+' . $item . '[ \t]*(?:[ \t]#.*)?$/D', $line ) ) { + // apache_modules: a block list of module names; nothing else may be nested. + if ( $list && preg_match( '/^ +- [A-Za-z0-9_.-]+$/D', $line ) ) { continue; } - $list = false; - if ( preg_match( '/^apache_modules:[ \t]*(?:\[[ \t]*(?:' . $item . '[ \t]*(?:,[ \t]*' . $item . '[ \t]*)*)?\])?[ \t]*(?:[ \t]#.*)?$/D', $line, $am ) ) { - $list = false === strpos( $line, '[' ); + $list = 'apache_modules:' === $line; + if ( $list ) { continue; } - // A plain YAML scalar: no flow/anchor/tag/alias start, `:` only when not followed by a blank, ` #` starts a comment. - $scalar = '(?:\'[^\']*\'|"[^"\\\\]*"|[^\s\'"{}\[\],&*!|>%@`#:](?:[^\s#:]|:(?=\S)|[ \t]+(?=[^\s#]))*)'; - if ( ! preg_match( '/^(' . implode( '|', self::WP_CLI_KEYS ) . '):(?:[ \t]+(' . $scalar . '))?[ \t]*(?:[ \t]#.*)?$/D', $line, $m ) ) { - return sprintf( '%s%s line %d isn\'t a WP-CLI setting this check accepts (only %s as plain values, and apache_modules): %s', $app, $file, $n + 1, implode( ', ', self::WP_CLI_KEYS ), self::clean( substr( trim( $line ), 0, 60 ) ) ); + if ( ! preg_match( '/^(' . implode( '|', self::WP_CLI_KEYS ) . '): ([A-Za-z0-9_.\/:@-]+)$/D', $line, $m ) ) { + return sprintf( '%s%s line %d isn\'t a WP-CLI setting this check accepts (only %s as plain values, and an apache_modules list): %s', $app, $file, $n + 1, implode( ', ', self::WP_CLI_KEYS ), self::clean( substr( trim( $line ), 0, 60 ) ) ); } if ( 'path' !== $m[1] ) { continue; } - $value = isset( $m[2] ) ? trim( $m[2], '\'"' ) : ''; - if ( '' === $value ) { - continue; + $value = $m[2]; + // Only the texts EE writes; Spyc would turn 1e1, 0x2 and the like into numbers. + $ok = in_array( $value, $texts, true ) && ! is_numeric( $value ) && ! preg_match( '/^0x/i', $value ); + // Relative to the directory the file is in, as WP-CLI reads it; /var/www/… is the site's app/. + $text = '/' === $value[0] ? $value : '/var/www' . substr( $base, strlen( $code ) ) . '/' . $value; + $to = $ok && 0 === strpos( $text . '/', '/var/www/' ) ? self::resolve_in( $code, substr( $text, strlen( '/var/www/' ) ) ) : null; + $ok = $ok && null !== $live && $to === $live; + // The wp-config.php WP-CLI loads for that path (its own, else the textual parent's) must be the validated one. + if ( $ok && $this->wp_layout ) { + $own = self::resolve_in( $code, substr( rtrim( $text, '/' ), strlen( '/var/www/' ) ) . '/wp-config.php' ); + $parent = substr( dirname( rtrim( $text, '/' ) ), strlen( '/var/www' ) ); + $up = self::resolve_in( $code, ltrim( $parent . '/wp-config.php', '/' ) ); + $loads = null !== $own && is_file( $own ) ? $own : ( null !== $up && is_file( $up ) && null === self::resolve_in( $code, ltrim( $parent . '/wp-settings.php', '/' ) ) ? $up : null ); + $ok = null === $loads || $loads === $this->loaded_config; } - // Relative to the config's own (real) directory, as WP-CLI reads it; /var/www/… is the site's app/. - $base = substr( dirname( $found['real'] ), strlen( $code ) + 1 ); - if ( '/' === $value[0] ) { - $rel = 0 === strpos( $value . '/', '/var/www/' ) ? substr( $value, strlen( '/var/www/' ) ) : null; - } else { - $rel = ( false === $base || '' === $base ? '' : "$base/" ) . $value; - } - $to = null === $rel ? null : self::resolve_in( $code, $rel ); - if ( null === $live || $to !== $live ) { - return sprintf( '%s%s sets path: %s, which isn\'t the WordPress this check scans', $app, $file, self::clean( $value ) ); + if ( ! $ok ) { + return sprintf( '%s%s sets path: %s, which isn\'t a path this check accepts for the WordPress it scans', $app, $file, self::clean( $value ) ); } } } @@ -3976,10 +4139,20 @@ protected function output_dir_unchanged( $path ) { protected function scoped( array $doc, array $report ) { // Only EE sets these; the scanner can't. unset( $doc['checked'], $doc['not_checked'], $doc['wordpress'], $doc['cross_check'], $doc['ignored'] ); + $excluded = []; + if ( null !== $this->cross && ! empty( $this->cross['old_releases'] ) ) { + // Exempt shape (a): never read; looked_in is /htdocs (php) or the WordPress root, so name them from app/. + $app = $this->app_dir(); + foreach ( array_slice( $this->cross['old_releases'], 0, self::NOT_CHECKED_STDOUT ) as $dir ) { + $excluded[] = self::cut( self::clean( $app . $dir ) ); + } + } $doc['checked'] = [ - 'dir' => self::clean( (string) $this->looked_in ), - 'components' => $doc['components_checked'], - 'files' => $doc['files_checked'], + 'dir' => self::clean( (string) $this->looked_in ), + 'components' => $doc['components_checked'], + 'files' => $doc['files_checked'], + // Old releases nginx doesn't serve (exempt shape (a)), never read; at most NOT_CHECKED_STDOUT names. + 'excluded_old_releases' => $excluded, ]; $doc['not_checked'] = array_map( function ( $entry ) { @@ -4338,8 +4511,7 @@ protected function table_lines( array $doc, $report ) { // Exempt shape (a): what wasn't read, so the line never claims all of htdocs. if ( ! $this->wp_layout && null !== $this->cross && ! empty( $this->cross['old_releases'] ) ) { - // looked_in is /app/htdocs on php sites. - $app = dirname( (string) $this->looked_in ) . '/'; + $app = $this->app_dir(); $names = array_map( function ( $dir ) use ( $app ) { return self::clean( $app . $dir ); @@ -4388,7 +4560,7 @@ function ( $entry ) { if ( $component['errors'] > 0 ) { yield sprintf( '%s: %s, %s', self::component_heading( $component ), self::count_of( $component['errors'], 'error' ), self::count_of( $component['warnings'], 'warning' ) ); foreach ( $component['findings'] as $finding ) { - if ( 'ERROR' !== $finding['type'] ) { + if ( 'ERROR' !== $finding['type'] || ! empty( $finding['ignored'] ) ) { continue; } yield ' ' . self::clean( $finding['file'] ) . ':' . $finding['line']; diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 9f137e0d..0d962ded 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3335,7 +3335,7 @@ protected function delete_stopped( $site ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, the site's PHP in app/ except old releases nginx doesn't serve (a current/ release link) and the www-data user's tool directories (.composer, .wp-cli and the like). A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked; code files the scanner didn't read, such as code in the www-data user's tool directories, a link to code outside what was scanned, or files that changed while the check ran; an older scanner image that lists no files; or WordPress hasn't declared support for the target). After the scan, every code file in the site's files is compared with the list of files the scanner read, and only WordPress core of the live WordPress, old releases nginx doesn't serve, EasyEngine's unused app/wp-config.php and the index.php that loads WordPress from a subdirectory are exempt. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, the site's PHP in app/ except old releases nginx doesn't serve (a current/ release link) and the www-data user's tool directories (.composer, .wp-cli and the like). A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked; code files the scanner didn't read, such as code in the www-data user's tool directories, a link to code outside what was scanned, or files that changed while the check ran; an older scanner image that lists no files; or WordPress hasn't declared support for the target). After the scan, every code file in the site's files is compared with the list of files the scanner read, and only WordPress core of the live WordPress, old releases nginx doesn't serve, EasyEngine's unused app/wp-config.php and the index.php that loads WordPress from a subdirectory are exempt. Outside the WordPress directory only files named as PHP count as code, so a non-PHP-named file there that holds PHP (a wp-config.php.bak) isn't compared. Errors in nginx-helper's bundled Predis (admin/predis.php) are ignored, and listed under `ignored`, when the whole plugin is a stock release, nothing else loads Predis and the running PHP has the redis extension: the plugin then never loads that file. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * @@ -3375,7 +3375,7 @@ protected function delete_stopped( $site ) { * --- * * [--output=] - * : Also write the full report, with every error and warning, as JSON to this absolute path: the JSON summary's fields (the same verdict) plus every component and its findings. The file is owned by root with mode 0600 and replaces an existing one. It is written only when the check finishes with a result (status ok); otherwise an existing file is left as it was. Its directory and every parent must be owned by root and not writable by other users (a sticky directory such as /tmp is fine). Not with --estimate. + * : Also write the full report, with every error and warning, as JSON to this absolute path: the JSON summary's fields (the same verdict) plus every component and its findings. A finding left out of the verdict stays in its component, marked `"ignored": true`, and its file is listed under `ignored`. The file is owned by root with mode 0600 and replaces an existing one. It is written only when the check finishes with a result (status ok); otherwise an existing file is left as it was. Its directory and every parent must be owned by root and not writable by other users (a sticky directory such as /tmp is fine). Not with --estimate. * * [--timeout=] * : Time limit for the scan itself, in seconds. A scan that hits it reports tool_error and no verdict. Pulling the scanner image on first use isn't counted. Default: 7200. Not with --estimate. From 4094706cbb35a665bee4bd7239980516dbf30a31 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:06:28 +0530 Subject: [PATCH 47/53] fix(site): accept the wp-cli.yml path EE writes for the site's stored public dir site-type-wp writes htdocs/wp-cli.yml with str_replace( '/var/www/htdocs/', '', trailingslashit( site_container_fs_path ) ), so `--public-dir=a//b` gives `path: a//b/`, which php-compat refused. That exact text is now accepted too; the other rules (no link, value grammar, resolves to the live root, the validated wp-config.php) still apply. --- src/helper/Site_PHP_Compat.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 38574f9d..3e3a9ed1 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -215,6 +215,9 @@ class Site_PHP_Compat { /** @var string[] The manifest's `checked` container paths, decoded (cross_check()). */ protected $manifest_checked = []; + /** @var string The `path:` text site-type-wp writes into htdocs/wp-cli.yml for this site ('' when it writes none). */ + protected $ee_wp_cli_path = ''; + /** @var string|null Real path of the wp-config.php WordPress loads, validated by check_wp_config(). */ protected $loaded_config; @@ -1084,7 +1087,9 @@ protected function resolve_layout( $site_data, $code ) { $this->app_path = $app; $this->scan_path = $served; - $detail = $this->server_config_check( $site_data ); + // site-type-wp's own wp-cli.yml text: str_replace( '/var/www/htdocs/', '', trailingslashit( site_container_fs_path ) ). + $this->ee_wp_cli_path = str_replace( '/var/www/htdocs/', '', rtrim( (string) $site_data->site_container_fs_path, '/\\' ) . '/' ); + $detail = $this->server_config_check( $site_data ); if ( null !== $detail ) { return $this->doc( 'tool_error', $detail ); } @@ -3118,6 +3123,10 @@ protected static function wp_cli_chain( $code, array $dirs ) { protected function wp_cli_config_check( $code, $live, $app, $root ) { $dir = 'htdocs' === $root ? '' : ( 0 === strpos( $root, 'htdocs/' ) ? substr( $root, strlen( 'htdocs/' ) ) : null ); $texts = null === $dir ? [] : ( '' === $dir ? [ '/var/www/htdocs', '/var/www/htdocs/' ] : [ $dir, "$dir/", "/var/www/htdocs/$dir", "/var/www/htdocs/$dir/" ] ); + // Exactly what site-type-wp writes for this site's stored public dir (`--public-dir=a//b` gives `a//b/`). + if ( '' !== $this->ee_wp_cli_path ) { + $texts[] = $this->ee_wp_cli_path; + } foreach ( array_unique( array_merge( [ self::WP_CLI_HOME ], $this->wp_cli_files ) ) as $file ) { // The directory as the container resolves it; the file itself must be a regular file there, never a link. $base = self::resolve_in( $code, dirname( $file ), $why ); From 5dd976547477bead70d09efd57e5f2d9c7e90354 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:09:36 +0530 Subject: [PATCH 48/53] fix(site): tighten the Predis exemption, drop two acceptances, and require a current link for old releases - nginx-helper's bundled Predis is ignored only when the php container has no extra mount at all, every plugin file has one name, no other scanned code names nginx-helper or predis, and PHP-FPM's own module list has redis as well as the CLI. - A non-code-named link in a php site's home dot dir that leaves the site counts as unread again, and the wp-cli.yml path text EE writes for a stored public dir like a//b is refused again. - A wp-cli.yml path that YAML reads as a boolean or null is refused. - Old releases are exempt only behind a link named current beside releases/; a releases/ directory that merely holds the WordPress root gives no exemption and no release pointers. --- src/helper/Site_PHP_Compat.php | 103 ++++++++++++++++----------------- 1 file changed, 51 insertions(+), 52 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 3e3a9ed1..393d91ff 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -215,9 +215,6 @@ class Site_PHP_Compat { /** @var string[] The manifest's `checked` container paths, decoded (cross_check()). */ protected $manifest_checked = []; - /** @var string The `path:` text site-type-wp writes into htdocs/wp-cli.yml for this site ('' when it writes none). */ - protected $ee_wp_cli_path = ''; - /** @var string|null Real path of the wp-config.php WordPress loads, validated by check_wp_config(). */ protected $loaded_config; @@ -1087,9 +1084,7 @@ protected function resolve_layout( $site_data, $code ) { $this->app_path = $app; $this->scan_path = $served; - // site-type-wp's own wp-cli.yml text: str_replace( '/var/www/htdocs/', '', trailingslashit( site_container_fs_path ) ). - $this->ee_wp_cli_path = str_replace( '/var/www/htdocs/', '', rtrim( (string) $site_data->site_container_fs_path, '/\\' ) . '/' ); - $detail = $this->server_config_check( $site_data ); + $detail = $this->server_config_check( $site_data ); if ( null !== $detail ) { return $this->doc( 'tool_error', $detail ); } @@ -1377,16 +1372,9 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { */ protected function app_walk( $code, $rel, $root, $abspath, array $allowed ) { $top = (string) self::resolve_in( $code, $rel ); - // The live release: the WordPress root or its ancestor directly in a releases/ directory. - $releases = null; - $live = null; - for ( $dir = $abspath; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { - if ( 'releases' === basename( dirname( $dir ) ) ) { - $releases = dirname( $dir ); - $live = $dir; - break; - } - } + // The live release: only through a `current` link beside releases/ (live_release(), P1). + $live = $this->live_release( $code ); + $releases = null === $live ? null : dirname( $live ); $user_ini = []; $found = null; $outside = []; @@ -1606,11 +1594,6 @@ function ( $path, $name, $type, $stat = false ) use ( $code, $rules, $start, $un if ( null !== $rules['releases_dir'] && null !== $target && self::release_pointer( $path, $target, $rules['releases_dir'] ) ) { return false; } - // php sites: a non-code-named link in a www-data home dot dir that leaves the site (.venv/bin/python) is nothing, - // as for the scanner (U13). - if ( ! $named && null === $target && 'escape' === $why && ! $rules['wp'] && '.' === substr( strtok( substr( $path, strlen( $code ) + 1 ), '/' ), 0, 1 ) ) { - return false; - } // Outside the scanner's roots nothing follows a directory link or an unresolvable one for it (the home dirs). if ( null === self::under_any( $path, $code, $rules['roots'] ) && ( null === $target || is_dir( $target ) ) ) { if ( ! $reported( $path ) ) { @@ -2045,11 +2028,34 @@ protected static function release_pointer( $path, $real, $releases ) { * below it), else null. */ protected function releases_dir( $code ) { - $top = null === $this->cross_layout ? null : $this->cross_layout['top']; - $abspath = null === $this->cross_layout ? null : $this->cross_layout['abspath']; - for ( $dir = null !== $abspath ? $abspath : $top; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { - if ( 'releases' === basename( dirname( $dir ) ) ) { - return null !== $top && 0 === strpos( $top . '/', $dir . '/' ) ? dirname( $dir ) : null; + $top = null === $this->cross_layout ? null : $this->cross_layout['top']; + $live = $this->live_release( $code ); + + return null !== $live && null !== $top && 0 === strpos( $top . '/', $live . '/' ) ? dirname( $live ) : null; + } + + /** + * The live release of a CI/CD layout (P1): reached by a link named `current` on the served or WordPress root's path, + * located directly beside a real releases/ directory, whose target is a real directory directly in it that holds the + * WordPress root (php: the served root). A releases/ directory that merely holds the root makes no release. + * + * @param string $code Real path of the site's app/. + * + * @return string|null Real live release directory. + */ + protected function live_release( $code ) { + if ( null === $this->cross_layout ) { + return null; + } + $inner = null !== $this->cross_layout['abspath'] ? $this->cross_layout['abspath'] : $this->cross_layout['top']; + foreach ( isset( $this->cross_layout['links'] ) ? $this->cross_layout['links'] : [] as $link ) { + if ( 'current' !== basename( $link ) ) { + continue; + } + $live = self::resolve_in( $code, substr( $link, strlen( $code ) + 1 ) ); + $releases = null === $live ? null : dirname( $live ); + if ( null !== $live && null !== $inner && is_dir( $live ) && 'releases' === basename( $releases ) && ! is_link( $releases ) && dirname( $link ) === dirname( $releases ) && 0 === strpos( $inner . '/', $live . '/' ) ) { + return $live; } } @@ -2072,16 +2078,9 @@ protected function manifest_seconds() { * @return array Real host directories as keys. */ protected function old_release_dirs( $code ) { - $top = null === $this->cross_layout ? null : $this->cross_layout['top']; - $abspath = null === $this->cross_layout ? null : $this->cross_layout['abspath']; - $live = null; - for ( $dir = null !== $abspath ? $abspath : $top; null !== $dir && strlen( $dir ) > strlen( $code ); $dir = dirname( $dir ) ) { - if ( 'releases' === basename( dirname( $dir ) ) ) { - $live = $dir; - break; - } - } - $old = []; + $top = null === $this->cross_layout ? null : $this->cross_layout['top']; + $live = $this->live_release( $code ); + $old = []; if ( null !== $live && null !== $top && 0 === strpos( $top . '/', $live . '/' ) ) { foreach ( (array) @scandir( dirname( $live ) ) as $name ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable lists nothing. $dir = dirname( $live ) . '/' . $name; @@ -2354,13 +2353,9 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( null === $at ) { return; } - // Nothing mounted over the plugin: the files hashed on the host must be the ones PHP runs. - $plugin = []; - $plugin[ $dir ] = true; - foreach ( $this->mount_points as $mount ) { - if ( self::touches( $mount, $plugin ) ) { - return; - } + // No extra mount at all: mounted code (anywhere) is read only in the container, where it could load predis.php (F4). + if ( $this->mount_points ) { + return; } // Exact files at their own paths (no link on the way), each with one name only (no second name elsewhere). foreach ( [ "$dir/admin/predis.php", "$dir/includes/class-nginx-helper.php" ] as $path ) { @@ -2373,8 +2368,9 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( ! in_array( self::dir_manifest( $dir ), self::NGINX_HELPER_RELEASES, true ) ) { return; } - // No other code the scanner read mentions predis (another plugin requiring it), matched at a word start so that - // "PhpRedis" (wp-redis, EE's object cache drop-in) doesn't count. + // No other code the scanner read names the plugin or predis (a literal or glob include of predis.php, F5), predis + // matched at a word start so that "PhpRedis" (wp-redis, EE's object cache drop-in) doesn't count. A fully dynamic + // path naming neither is accepted residual R-PREDIS-DYN. foreach ( $this->manifest_checked as $checked ) { if ( 0 === strpos( $checked, 'b64:' ) ) { return; @@ -2384,7 +2380,7 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { continue; } $text = @file_get_contents( $host ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable refuses. - if ( false === $text || 0 !== preg_match( '/(?docker( [ 'docker', 'exec', $this->php_container, 'php-fpm', '-m' ], 60 ); + if ( 0 !== $fpm['code'] || ! preg_match( '/^redis$/mi', $fpm['stdout'] ) ) { + return; + } $component = $report['components'][ $at ]; $dropped = 0; foreach ( $component['findings'] as $i => $finding ) { @@ -2440,7 +2441,8 @@ protected static function dir_manifest( $dir ) { $mode = false === $stat ? 0 : $stat['mode'] & 0170000; if ( 0040000 === $mode ) { $todo[] = $path; - } elseif ( 0100000 === $mode ) { + } elseif ( 0100000 === $mode && 1 === $stat['nlink'] ) { + // One name only: a second name elsewhere could be included without naming this directory. $lines[] = $path . "\t" . hash_file( 'sha256', "$dir/$path" ); } else { return null; @@ -3123,10 +3125,6 @@ protected static function wp_cli_chain( $code, array $dirs ) { protected function wp_cli_config_check( $code, $live, $app, $root ) { $dir = 'htdocs' === $root ? '' : ( 0 === strpos( $root, 'htdocs/' ) ? substr( $root, strlen( 'htdocs/' ) ) : null ); $texts = null === $dir ? [] : ( '' === $dir ? [ '/var/www/htdocs', '/var/www/htdocs/' ] : [ $dir, "$dir/", "/var/www/htdocs/$dir", "/var/www/htdocs/$dir/" ] ); - // Exactly what site-type-wp writes for this site's stored public dir (`--public-dir=a//b` gives `a//b/`). - if ( '' !== $this->ee_wp_cli_path ) { - $texts[] = $this->ee_wp_cli_path; - } foreach ( array_unique( array_merge( [ self::WP_CLI_HOME ], $this->wp_cli_files ) ) as $file ) { // The directory as the container resolves it; the file itself must be a regular file there, never a link. $base = self::resolve_in( $code, dirname( $file ), $why ); @@ -3169,7 +3167,8 @@ protected function wp_cli_config_check( $code, $live, $app, $root ) { } $value = $m[2]; // Only the texts EE writes; Spyc would turn 1e1, 0x2 and the like into numbers. - $ok = in_array( $value, $texts, true ) && ! is_numeric( $value ) && ! preg_match( '/^0x/i', $value ); + // Spyc turns 1e1, 0x2 and the YAML booleans and null into other values. + $ok = in_array( $value, $texts, true ) && ! is_numeric( $value ) && ! preg_match( '/^0x/i', $value ) && ! preg_match( '/^(true|on|yes|y|false|off|no|n|null|~)$/iD', $value ); // Relative to the directory the file is in, as WP-CLI reads it; /var/www/… is the site's app/. $text = '/' === $value[0] ? $value : '/var/www' . substr( $base, strlen( $code ) ) . '/' . $value; $to = $ok && 0 === strpos( $text . '/', '/var/www/' ) ? self::resolve_in( $code, substr( $text, strlen( '/var/www/' ) ) ) : null; From 33baf3921d4d314ff0e7ce75a7e79c313f90d1a5 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:11:55 +0530 Subject: [PATCH 49/53] fix(site): close the Predis exemption's link and FPM gaps, and align php-compat's prepend check with old releases - nginx-helper's bundled Predis is ignored only when the cross-check allows a positive verdict, no link anywhere in app/ leads to the plugin or into it, and the running PHP-FPM master has phpredis mapped and started after its PHP and FPM config last changed. - WordPress's own language packs of the plugin (wp-content/languages/plugins/nginx-helper-.l10n.php holding only a literal array) no longer count as code that names it. - The php-site prepend check treats exactly shape (a)'s old releases as unread: a release behind a current link stays unread when nginx serves below the live release, and with no current link every release is read. --- src/helper/Site_PHP_Compat.php | 209 +++++++++++++++++++++++++++++++-- src/helper/class-ee-site.php | 2 +- 2 files changed, 198 insertions(+), 13 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 393d91ff..8ea8f3db 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -149,6 +149,35 @@ class Site_PHP_Compat { // Exact link targets that are a sink, never code. const DEV_SINKS = [ '/dev/null', '/dev/stdout', '/dev/stderr' ]; + // Run by the php container's PHP (5.6 and later): what its PHP-FPM master (pid 1) is and loaded, and the newest change + // below /usr/local/etc (PHP's and FPM's config). Unreadable gives null. + const FPM_PROBE = <<<'PHP' +$r = array( 'exe' => @readlink( '/proc/1/exe' ), 'cmdline' => base64_encode( (string) @file_get_contents( '/proc/1/cmdline' ) ), 'stat' => (string) @file_get_contents( '/proc/1/stat' ), 'btime' => preg_match( '/^btime (\d+)$/m', (string) @file_get_contents( '/proc/stat' ), $m ) ? (int) $m[1] : null, 'maps' => 1 === preg_match( '#\s/usr/local/lib/php/extensions/[^/\s]+/redis\.so$#m', (string) @file_get_contents( '/proc/1/maps' ) ), 'newest' => 0 ); +$todo = array( '/usr/local/etc' ); +while ( $todo ) { + $p = array_pop( $todo ); + $s = @lstat( $p ); + $e = false !== $s && 040000 === ( $s['mode'] & 0170000 ) ? @scandir( $p ) : array(); + if ( false === $s || false === $e ) { + $r['newest'] = null; + break; + } + $r['newest'] = max( $r['newest'], $s['mtime'], $s['ctime'] ); + foreach ( $e as $n ) { + if ( '.' !== $n && '..' !== $n ) { + $todo[] = "$p/$n"; + } + } +} +echo json_encode( $r ); +PHP; + + // php-fpm's process title for the image's stock command. It hides -c, -d and -n: container_config_check() pins those. + const FPM_MASTER_TITLE = "php-fpm: master process (/usr/local/etc/php-fpm.conf)\0"; + + // Largest WordPress language pack (.l10n.php) of nginx-helper this check reads as data. + const L10N_MAX = 1048576; + // Directory names the scanner searches by name only (its manifest's sniff.skipped_dirs); the sniff doesn't apply below them. const SCANNER_SKIP_NAMES = [ 'uploads', 'cache', 'upgrade', 'upgrade-temp-backup', 'node_modules', '.git' ]; @@ -2353,6 +2382,10 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( null === $at ) { return; } + // Only when the scanner read every code file: the text search below covers only what it read (K6). + if ( ! self::cross_ok( $this->cross ) ) { + return; + } // No extra mount at all: mounted code (anywhere) is read only in the container, where it could load predis.php (F4). if ( $this->mount_points ) { return; @@ -2368,15 +2401,19 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( ! in_array( self::dir_manifest( $dir ), self::NGINX_HELPER_RELEASES, true ) ) { return; } + // No link anywhere in app/ leads to the plugin or into it: code including the link names neither (K0). + if ( ! $this->no_link_into( $code, $dir ) ) { + return; + } // No other code the scanner read names the plugin or predis (a literal or glob include of predis.php, F5), predis - // matched at a word start so that "PhpRedis" (wp-redis, EE's object cache drop-in) doesn't count. A fully dynamic - // path naming neither is accepted residual R-PREDIS-DYN. + // matched at a word start so that "PhpRedis" (wp-redis, EE's object cache drop-in) doesn't count. A path whose raw + // bytes name neither is accepted residual R-PREDIS-DYN. The plugin's own language packs are data (K1). foreach ( $this->manifest_checked as $checked ) { if ( 0 === strpos( $checked, 'b64:' ) ) { return; } $host = $code . substr( $checked, strlen( '/var/www' ) ); - if ( 0 === strpos( $host, "$dir/" ) ) { + if ( 0 === strpos( $host, "$dir/" ) || self::nginx_helper_l10n( $host, $abspath ) ) { continue; } $text = @file_get_contents( $host ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- unreadable refuses. @@ -2393,6 +2430,10 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( 0 !== $fpm['code'] || ! preg_match( '/^redis$/mi', $fpm['stdout'] ) ) { return; } + // php-fpm -m reads the config as it is now: the running master must have loaded redis, from config older than it (K19). + if ( ! $this->fpm_master_has_redis() ) { + return; + } $component = $report['components'][ $at ]; $dropped = 0; foreach ( $component['findings'] as $i => $finding ) { @@ -2415,6 +2456,157 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { ]; } + /** + * Whether no link anywhere in app/ (old releases and core included) resolves to $dir or below it. A link this can't + * follow inside /var/www (one leaving it, or /var/www/../www) might, so it counts; /dev sinks and dangling links don't. + * + * @param string $code Real path of the site's app/. + * @param string $dir Real directory. + * + * @return bool False also when app/ can't be walked. + */ + protected function no_link_into( $code, $dir ) { + $into = false; + $error = $this->walk_tree( + $code, + function ( $path, $name, $type ) use ( $code, $dir, &$into ) { + if ( 'link' !== $type ) { + return 'dir' === $type; + } + if ( in_array( (string) @readlink( $path ), self::DEV_SINKS, true ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is no sink. + return false; + } + $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); + if ( null === $target ? 'escape' === $why : ( $target === $dir || 0 === strpos( $target, "$dir/" ) ) ) { + $into = true; + return 'stop'; + } + return false; + } + ); + + return null === $error && ! $into; + } + + /** + * Whether a file is a WordPress language pack of nginx-helper that is data only: exactly + * /wp-content/languages/plugins/nginx-helper-.l10n.php, a regular file with one name and no link + * on the way, holding ` self::L10N_MAX || realpath( $host ) !== $host ) { + return false; + } + $text = @file_get_contents( $host, false, null, 0, self::L10N_MAX + 1 ); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is handled. + if ( false === $text || strlen( $text ) > self::L10N_MAX ) { + return false; + } + $tokens = []; + foreach ( token_get_all( $text ) as $token ) { + if ( ! is_array( $token ) || T_WHITESPACE !== $token[0] ) { + $tokens[] = $token; + } + } + if ( ! isset( $tokens[1] ) || ! is_array( $tokens[0] ) || T_OPEN_TAG !== $tokens[0][0] || 0 !== strncasecmp( $tokens[0][1], ' value`, comma-separated with an optional trailing comma. Nothing else (no call, no variable) parses. + * + * @param array $tokens Tokens without whitespace. + * @param int $at Position; moved past the array. + * @param int $depth Nesting depth. + * + * @return bool + */ + protected static function l10n_array( array $tokens, &$at, $depth ) { + $literal = function ( $token ) { + return is_array( $token ) && ( in_array( $token[0], [ T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER ], true ) || ( T_STRING === $token[0] && in_array( strtolower( $token[1] ), [ 'true', 'false' ], true ) ) ); + }; + $open = isset( $tokens[ $at ] ) ? $tokens[ $at ] : null; + if ( '[' === $open ) { + $close = ']'; + ++$at; + } elseif ( is_array( $open ) && T_ARRAY === $open[0] && isset( $tokens[ $at + 1 ] ) && '(' === $tokens[ $at + 1 ] ) { + $close = ')'; + $at += 2; + } else { + return false; + } + if ( $depth > 16 ) { + return false; + } + while ( isset( $tokens[ $at ] ) && $close !== $tokens[ $at ] ) { + // An item: a literal (a key or a value), or an array value. + if ( $literal( $tokens[ $at ] ) ) { + ++$at; + if ( isset( $tokens[ $at ] ) && is_array( $tokens[ $at ] ) && T_DOUBLE_ARROW === $tokens[ $at ][0] ) { + ++$at; + if ( isset( $tokens[ $at ] ) && $literal( $tokens[ $at ] ) ) { + ++$at; + } elseif ( ! self::l10n_array( $tokens, $at, $depth + 1 ) ) { + return false; + } + } + } elseif ( ! self::l10n_array( $tokens, $at, $depth + 1 ) ) { + return false; + } + if ( isset( $tokens[ $at ] ) && ',' === $tokens[ $at ] ) { + ++$at; + } elseif ( ! isset( $tokens[ $at ] ) || $close !== $tokens[ $at ] ) { + return false; + } + } + if ( ! isset( $tokens[ $at ] ) ) { + return false; + } + ++$at; + + return true; + } + + /** + * Whether the php container's running PHP-FPM master (pid 1) is php-fpm under the image's stock title, has phpredis mapped, + * and started after its PHP and FPM config (all of /usr/local/etc) last changed. Anything unreadable gives false. + * + * @return bool + */ + protected function fpm_master_has_redis() { + $run = $this->docker( [ 'docker', 'exec', $this->php_container, 'php', '-r', self::FPM_PROBE ], 60 ); + $info = 0 === $run['code'] ? json_decode( trim( $run['stdout'] ), true ) : null; + if ( ! is_array( $info ) || ! isset( $info['exe'], $info['cmdline'], $info['stat'], $info['btime'], $info['maps'], $info['newest'] ) || ! is_int( $info['btime'] ) || ! is_int( $info['newest'] ) ) { + return false; + } + // Field 22 of /proc/1/stat (after the name, which may hold spaces): ticks after boot, USER_HZ 100 on Linux. Whole + // seconds round the start down and a change time up, so equal seconds count as changed after the start. + $after = strrchr( (string) $info['stat'], ')' ); + $fields = false === $after ? [] : preg_split( '/ +/', trim( substr( $after, 1 ) ) ); + if ( ! isset( $fields[19] ) || ! ctype_digit( $fields[19] ) ) { + return false; + } + $start = $info['btime'] + intdiv( (int) $fields[19], 100 ); + + return '/usr/local/sbin/php-fpm' === $info['exe'] && self::FPM_MASTER_TITLE === base64_decode( (string) $info['cmdline'], true ) && true === $info['maps'] && $info['newest'] < $start; + } + /** * sha256 of a directory's file list: sorted "relative pathsha256" lines, newline-terminated. Anything other than * regular files and directories (a link, a FIFO) gives null. @@ -3208,15 +3400,8 @@ protected function scanned_by_php_scan( $code, $real ) { if ( array_intersect( $parts, [ 'node_modules', '.git' ] ) ) { return false; } - $served = null === $this->scan_path ? null : self::resolve_in( $code, ltrim( substr( $this->scan_path, strlen( '/var/www' ) ), '/' ) ); - if ( null !== $served && 'releases' === basename( dirname( $served ) ) ) { - $releases = dirname( $served ); - if ( 0 === strpos( $real, "$releases/" ) && 0 !== strpos( $real, "$served/" ) ) { - return false; - } - } - - return true; + // The same old releases exempt shape (a) leaves unread; without a `current` link the scanner reads every release. + return null === self::under_any( $real, $code, $this->old_release_dirs( $code ) ); } /** diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 0d962ded..33a459c4 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3335,7 +3335,7 @@ protected function delete_stopped( $site ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, the site's PHP in app/ except old releases nginx doesn't serve (a current/ release link) and the www-data user's tool directories (.composer, .wp-cli and the like). A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked; code files the scanner didn't read, such as code in the www-data user's tool directories, a link to code outside what was scanned, or files that changed while the check ran; an older scanner image that lists no files; or WordPress hasn't declared support for the target). After the scan, every code file in the site's files is compared with the list of files the scanner read, and only WordPress core of the live WordPress, old releases nginx doesn't serve, EasyEngine's unused app/wp-config.php and the index.php that loads WordPress from a subdirectory are exempt. Outside the WordPress directory only files named as PHP count as code, so a non-PHP-named file there that holds PHP (a wp-config.php.bak) isn't compared. Errors in nginx-helper's bundled Predis (admin/predis.php) are ignored, and listed under `ignored`, when the whole plugin is a stock release, nothing else loads Predis and the running PHP has the redis extension: the plugin then never loads that file. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, the site's PHP in app/ except old releases nginx doesn't serve (a current/ release link) and the www-data user's tool directories (.composer, .wp-cli and the like). A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked; code files the scanner didn't read, such as code in the www-data user's tool directories, a link to code outside what was scanned, or files that changed while the check ran; an older scanner image that lists no files; or WordPress hasn't declared support for the target). After the scan, every code file in the site's files is compared with the list of files the scanner read, and only WordPress core of the live WordPress, old releases nginx doesn't serve, EasyEngine's unused app/wp-config.php and the index.php that loads WordPress from a subdirectory are exempt. Outside the WordPress directory only files named as PHP count as code, so a non-PHP-named file there that holds PHP (a wp-config.php.bak) isn't compared. Errors in nginx-helper's bundled Predis (admin/predis.php) are ignored, and listed under `ignored`, when the whole plugin is a stock release, the scanner read every code file, no other code names the plugin or links to it, and the running PHP-FPM loaded the redis extension: the plugin then never loads that file. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * From 376be47f6461761f15b68dcb998263aeb35f18da Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:14:06 +0530 Subject: [PATCH 50/53] fix(site): compare the FPM master's start with config times to the sub-second The Predis exemption's check that PHP and FPM config didn't change after the running FPM master started compared whole seconds with /proc/stat's truncated btime. A config written less than about a second before the master started then counted as changed after it, which is what site create (custom.ini, then a php restart) and site enable (conf.d chowned, then compose up) do. The probe now reads change times to the nanosecond and the start from the clock, the uptime and the master's start ticks, with a 0.05 s margin. --- src/helper/Site_PHP_Compat.php | 56 +++++++++++++++------------------- 1 file changed, 25 insertions(+), 31 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 8ea8f3db..b8096809 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -149,28 +149,13 @@ class Site_PHP_Compat { // Exact link targets that are a sink, never code. const DEV_SINKS = [ '/dev/null', '/dev/stdout', '/dev/stderr' ]; - // Run by the php container's PHP (5.6 and later): what its PHP-FPM master (pid 1) is and loaded, and the newest change - // below /usr/local/etc (PHP's and FPM's config). Unreadable gives null. - const FPM_PROBE = <<<'PHP' -$r = array( 'exe' => @readlink( '/proc/1/exe' ), 'cmdline' => base64_encode( (string) @file_get_contents( '/proc/1/cmdline' ) ), 'stat' => (string) @file_get_contents( '/proc/1/stat' ), 'btime' => preg_match( '/^btime (\d+)$/m', (string) @file_get_contents( '/proc/stat' ), $m ) ? (int) $m[1] : null, 'maps' => 1 === preg_match( '#\s/usr/local/lib/php/extensions/[^/\s]+/redis\.so$#m', (string) @file_get_contents( '/proc/1/maps' ) ), 'newest' => 0 ); -$todo = array( '/usr/local/etc' ); -while ( $todo ) { - $p = array_pop( $todo ); - $s = @lstat( $p ); - $e = false !== $s && 040000 === ( $s['mode'] & 0170000 ) ? @scandir( $p ) : array(); - if ( false === $s || false === $e ) { - $r['newest'] = null; - break; - } - $r['newest'] = max( $r['newest'], $s['mtime'], $s['ctime'] ); - foreach ( $e as $n ) { - if ( '.' !== $n && '..' !== $n ) { - $todo[] = "$p/$n"; - } - } -} -echo json_encode( $r ); -PHP; + // Run by the php container's sh: what its PHP-FPM master (pid 1) is and loaded, its clock, and the newest change below + // /usr/local/etc (PHP's and FPM's config) to the nanosecond. The clock is read before the uptime, so the boot time it + // gives is never later than the real one. A listing error fails the exec. + const FPM_PROBE = <<<'SH' +n=$(find /usr/local/etc -printf '%T@\n%C@\n') || exit 3 +printf 'exe %s\ncmdline %s\nmaps %s\nstat %s\nnow %s\nuptime %s\nnewest %s\n' "$(readlink /proc/1/exe)" "$(base64 -w0 /proc/1/cmdline)" "$(grep -c -E '[[:space:]]/usr/local/lib/php/extensions/[^/[:space:]]+/redis\.so$' /proc/1/maps)" "$(cat /proc/1/stat)" "$(date +%s.%N)" "$(cut -d' ' -f1 /proc/uptime)" "$(printf '%s\n' "$n" | sort -g | tail -n 1)" +SH; // php-fpm's process title for the image's stock command. It hides -c, -d and -n: container_config_check() pins those. const FPM_MASTER_TITLE = "php-fpm: master process (/usr/local/etc/php-fpm.conf)\0"; @@ -2590,21 +2575,30 @@ protected static function l10n_array( array $tokens, &$at, $depth ) { * @return bool */ protected function fpm_master_has_redis() { - $run = $this->docker( [ 'docker', 'exec', $this->php_container, 'php', '-r', self::FPM_PROBE ], 60 ); - $info = 0 === $run['code'] ? json_decode( trim( $run['stdout'] ), true ) : null; - if ( ! is_array( $info ) || ! isset( $info['exe'], $info['cmdline'], $info['stat'], $info['btime'], $info['maps'], $info['newest'] ) || ! is_int( $info['btime'] ) || ! is_int( $info['newest'] ) ) { - return false; + $run = $this->docker( [ 'docker', 'exec', $this->php_container, 'sh', '-c', self::FPM_PROBE ], 60 ); + $info = []; + foreach ( 0 === $run['code'] ? explode( "\n", trim( $run['stdout'] ) ) : [] as $line ) { + $pair = explode( ' ', $line, 2 ); + if ( 2 === count( $pair ) ) { + $info[ $pair[0] ] = $pair[1]; + } + } + $time = '/\A\d+(?:\.\d+)?\z/'; + foreach ( [ 'exe', 'cmdline', 'maps', 'stat', 'now', 'uptime', 'newest' ] as $key ) { + if ( ! isset( $info[ $key ] ) || ( in_array( $key, [ 'now', 'uptime', 'newest' ], true ) && ! preg_match( $time, $info[ $key ] ) ) ) { + return false; + } } - // Field 22 of /proc/1/stat (after the name, which may hold spaces): ticks after boot, USER_HZ 100 on Linux. Whole - // seconds round the start down and a change time up, so equal seconds count as changed after the start. - $after = strrchr( (string) $info['stat'], ')' ); + // Field 22 of /proc/1/stat (after the name, which may hold spaces): ticks after boot, USER_HZ 100 on Linux. The + // estimate is within about 0.02 s of the real start, so a change less than 0.05 s before it counts as after. + $after = strrchr( $info['stat'], ')' ); $fields = false === $after ? [] : preg_split( '/ +/', trim( substr( $after, 1 ) ) ); if ( ! isset( $fields[19] ) || ! ctype_digit( $fields[19] ) ) { return false; } - $start = $info['btime'] + intdiv( (int) $fields[19], 100 ); + $start = (float) $info['now'] - (float) $info['uptime'] + (int) $fields[19] / 100; - return '/usr/local/sbin/php-fpm' === $info['exe'] && self::FPM_MASTER_TITLE === base64_decode( (string) $info['cmdline'], true ) && true === $info['maps'] && $info['newest'] < $start; + return '/usr/local/sbin/php-fpm' === $info['exe'] && self::FPM_MASTER_TITLE === base64_decode( $info['cmdline'], true ) && ctype_digit( $info['maps'] ) && (int) $info['maps'] > 0 && (float) $info['newest'] + 0.05 < $start; } /** From 4f664cdc9df9986cff8a57123edb2415409a8b32 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:16:28 +0530 Subject: [PATCH 51/53] fix(site): judge the Predis exemption by the running FPM master's modules only Site create and enable chown the php conf.d while php runs, which moves every file's ctime past the FPM master's start, so the config-time condition refused the exemption on every stock --cache site. The exemption needs the running FPM to have redis, which the master's /proc/1/maps shows directly (a USR2 reload re-execs it in place), so the probe now checks only pid 1's binary, its stock title and a mapped redis.so. --- src/helper/Site_PHP_Compat.php | 29 ++++++++--------------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index b8096809..caf1ecf4 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -149,12 +149,9 @@ class Site_PHP_Compat { // Exact link targets that are a sink, never code. const DEV_SINKS = [ '/dev/null', '/dev/stdout', '/dev/stderr' ]; - // Run by the php container's sh: what its PHP-FPM master (pid 1) is and loaded, its clock, and the newest change below - // /usr/local/etc (PHP's and FPM's config) to the nanosecond. The clock is read before the uptime, so the boot time it - // gives is never later than the real one. A listing error fails the exec. + // Run by the php container's sh: what its PHP-FPM master (pid 1) is and which redis.so it mapped. const FPM_PROBE = <<<'SH' -n=$(find /usr/local/etc -printf '%T@\n%C@\n') || exit 3 -printf 'exe %s\ncmdline %s\nmaps %s\nstat %s\nnow %s\nuptime %s\nnewest %s\n' "$(readlink /proc/1/exe)" "$(base64 -w0 /proc/1/cmdline)" "$(grep -c -E '[[:space:]]/usr/local/lib/php/extensions/[^/[:space:]]+/redis\.so$' /proc/1/maps)" "$(cat /proc/1/stat)" "$(date +%s.%N)" "$(cut -d' ' -f1 /proc/uptime)" "$(printf '%s\n' "$n" | sort -g | tail -n 1)" +printf 'exe %s\ncmdline %s\nmaps %s\n' "$(readlink /proc/1/exe)" "$(base64 -w0 /proc/1/cmdline)" "$(grep -c -E '[[:space:]]/usr/local/lib/php/extensions/[^/[:space:]]+/redis\.so$' /proc/1/maps)" SH; // php-fpm's process title for the image's stock command. It hides -c, -d and -n: container_config_check() pins those. @@ -2415,7 +2412,7 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( 0 !== $fpm['code'] || ! preg_match( '/^redis$/mi', $fpm['stdout'] ) ) { return; } - // php-fpm -m reads the config as it is now: the running master must have loaded redis, from config older than it (K19). + // php-fpm -m reads the config as it is now: the running master must have loaded redis (K19). if ( ! $this->fpm_master_has_redis() ) { return; } @@ -2569,8 +2566,9 @@ protected static function l10n_array( array $tokens, &$at, $depth ) { } /** - * Whether the php container's running PHP-FPM master (pid 1) is php-fpm under the image's stock title, has phpredis mapped, - * and started after its PHP and FPM config (all of /usr/local/etc) last changed. Anything unreadable gives false. + * Whether the php container's running PHP-FPM master (pid 1), which every worker forks from, is php-fpm under the image's + * stock title and has phpredis mapped. A USR2 reload re-execs it in place, so its maps stay current. Anything unreadable + * gives false. * * @return bool */ @@ -2583,22 +2581,11 @@ protected function fpm_master_has_redis() { $info[ $pair[0] ] = $pair[1]; } } - $time = '/\A\d+(?:\.\d+)?\z/'; - foreach ( [ 'exe', 'cmdline', 'maps', 'stat', 'now', 'uptime', 'newest' ] as $key ) { - if ( ! isset( $info[ $key ] ) || ( in_array( $key, [ 'now', 'uptime', 'newest' ], true ) && ! preg_match( $time, $info[ $key ] ) ) ) { - return false; - } - } - // Field 22 of /proc/1/stat (after the name, which may hold spaces): ticks after boot, USER_HZ 100 on Linux. The - // estimate is within about 0.02 s of the real start, so a change less than 0.05 s before it counts as after. - $after = strrchr( $info['stat'], ')' ); - $fields = false === $after ? [] : preg_split( '/ +/', trim( substr( $after, 1 ) ) ); - if ( ! isset( $fields[19] ) || ! ctype_digit( $fields[19] ) ) { + if ( ! isset( $info['exe'], $info['cmdline'], $info['maps'] ) ) { return false; } - $start = (float) $info['now'] - (float) $info['uptime'] + (int) $fields[19] / 100; - return '/usr/local/sbin/php-fpm' === $info['exe'] && self::FPM_MASTER_TITLE === base64_decode( $info['cmdline'], true ) && ctype_digit( $info['maps'] ) && (int) $info['maps'] > 0 && (float) $info['newest'] + 0.05 < $start; + return '/usr/local/sbin/php-fpm' === $info['exe'] && self::FPM_MASTER_TITLE === base64_decode( $info['cmdline'], true ) && ctype_digit( $info['maps'] ) && (int) $info['maps'] > 0; } /** From c5c0dbc6485245e77f3a5bd47ad05f7b167e73a2 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:19:53 +0530 Subject: [PATCH 52/53] fix(site): close the Predis exemption's dangling-link and mount gaps, and read php sites' .user.ini behind links - nginx-helper's bundled Predis is ignored only when no link in app/ is dangling or unfollowable (PHP resolves a dangling link's `..` as text) or reaches the plugin in any case, the scanner reported no file unread, and the FPM master sees no mount below /var/www but the site's volume and EE's admin-tools. - The master's stock title is also accepted without its trailing NUL, as older kernels show it, and a broken language pack no longer prints a PHP 7.4 warning. - PHP settings right after a section header on the same line are read, a prepend under htdocs/ee-admin is refused, and php sites' .user.ini files are read wherever a link from htdocs leads, except in old releases nginx never serves. - The help text lists the exemption's real conditions. --- src/helper/Site_PHP_Compat.php | 167 ++++++++++++++++++++++++++++----- src/helper/class-ee-site.php | 2 +- 2 files changed, 145 insertions(+), 24 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index caf1ecf4..512dd911 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -149,12 +149,16 @@ class Site_PHP_Compat { // Exact link targets that are a sink, never code. const DEV_SINKS = [ '/dev/null', '/dev/stdout', '/dev/stderr' ]; - // Run by the php container's sh: what its PHP-FPM master (pid 1) is and which redis.so it mapped. + // Run by the php container's sh: what its PHP-FPM master (pid 1) is, which redis.so it mapped, and every mount point + // it sees (mountinfo field 5, octal-escaped). An unreadable mountinfo fails the exec. const FPM_PROBE = <<<'SH' +m=$(cut -d' ' -f5 /proc/1/mountinfo) || exit 4 printf 'exe %s\ncmdline %s\nmaps %s\n' "$(readlink /proc/1/exe)" "$(base64 -w0 /proc/1/cmdline)" "$(grep -c -E '[[:space:]]/usr/local/lib/php/extensions/[^/[:space:]]+/redis\.so$' /proc/1/maps)" +printf '%s\n' "$m" | sed 's/^/mount /' SH; // php-fpm's process title for the image's stock command. It hides -c, -d and -n: container_config_check() pins those. + // Kernels 4.2 to 4.17 leave the trailing NUL out of /proc//cmdline, so both forms are accepted. const FPM_MASTER_TITLE = "php-fpm: master process (/usr/local/etc/php-fpm.conf)\0"; // Largest WordPress language pack (.l10n.php) of nginx-helper this check reads as data. @@ -220,6 +224,9 @@ class Site_PHP_Compat { /** @var string The site's app/ with a trailing slash (resolve_layout()), for paths named in output. */ protected $app_path = ''; + /** @var bool Whether the php container has EE's admin-tools at /var/www/htdocs/ee-admin (extra_mounts()). */ + protected $admin_tools_mount = false; + /** @var string[] Resolved host paths of the accepted extra mounts (extra_mounts()). */ protected $mount_points = []; @@ -1103,20 +1110,11 @@ protected function resolve_layout( $site_data, $code ) { // The scanner checks all of htdocs for php sites, whatever the root nginx serves. $this->looked_in = $app . 'htdocs'; $htdocs = self::resolve_in( $code, 'htdocs' ); - $user_ini = []; - $error = null === $htdocs ? null : $this->walk_tree( - $htdocs, - function ( $path, $name, $type ) use ( &$user_ini ) { - if ( '.user.ini' === $name ) { - $user_ini[] = [ $path, $type ]; - } - return 'dir' === $type; - } - ); self::resolve_in( $code, $rel, $why, $hops ); self::resolve_in( $code, 'htdocs', $why, $more ); $this->cross_layout = [ 'wp' => false, 'scan' => $code, 'top' => self::resolve_in( $code, $rel ), 'abspath' => null, 'index' => null, 'links' => array_merge( $hops, $more ) ]; - $detail = null !== $error ? "can't look through {$app}htdocs for .user.ini files: $error" : $this->prepend_check( $site_data, $code, $user_ini, null ); + $user_ini = null === $htdocs ? [] : $this->php_site_user_ini( $code, $htdocs ); + $detail = is_string( $user_ini ) ? self::clean( str_replace( "$code/", $app, $user_ini ) ) : $this->prepend_check( $site_data, $code, $user_ini, null ); if ( null !== $detail ) { return $this->doc( 'tool_error', $detail ); } @@ -1368,6 +1366,86 @@ protected function check_wp_config( $code, $root, $abspath, $app ) { return $read; } + /** + * The .user.ini files PHP may read for a php site's scripts: walks all of app/ (no links followed) and keeps those in + * htdocs outside its old releases (old_release_dirs(), never served), and in any directory a link from there leads to, + * and from there on (PHP reads .user.ini along the script's path, through links; R15, R17). Release pointers beside + * `current` and /dev sinks lead nowhere; a link there this check can't follow is refused. + * + * @param string $code Real path of the site's app/. + * @param string $htdocs Real htdocs. + * + * @return array|string The files ([ path, type ] each), or a tool_error detail (host paths). + */ + protected function php_site_user_ini( $code, $htdocs ) { + $found = []; + $links = []; + $error = $this->walk_tree( + $code, + function ( $path, $name, $type ) use ( &$found, &$links ) { + if ( '.user.ini' === $name ) { + $found[] = [ $path, $type ]; + } + if ( 'link' === $type ) { + $links[] = $path; + } + return 'dir' === $type; + } + ); + if ( null !== $error ) { + return "can't look through $code/ for .user.ini files: $error"; + } + $old = $this->old_release_dirs( $code ); + $live = $this->live_release( $code ); + $releases = $old && null !== $live ? dirname( $live ) : null; + // Reached directories => the old releases left out below them. + $regions = []; + $regions[ $htdocs ] = $old; + $in = function ( $path ) use ( &$regions, $code ) { + foreach ( $regions as $root => $skip ) { + if ( ( $path === $root || 0 === strpos( $path, "$root/" ) ) && ( ! $skip || null === self::under_any( "$path/x", $code, $skip ) ) ) { + return true; + } + } + return false; + }; + do { + $grew = false; + foreach ( $links as $i => $path ) { + if ( ! $in( $path ) ) { + continue; + } + unset( $links[ $i ] ); + if ( in_array( (string) @readlink( $path ), self::DEV_SINKS, true ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is no sink. + continue; + } + $real = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); + if ( null === $real ) { + if ( 'missing' !== $why ) { + return "$path is a link this check can't follow the way the container does, so it can't look for .user.ini files behind it"; + } + continue; + } + if ( null !== $releases && self::release_pointer( $path, $real, $releases ) ) { + continue; + } + if ( is_dir( $real ) && ! isset( $regions[ $real ] ) ) { + $regions[ $real ] = []; + $grew = true; + } + } + } while ( $grew ); + + return array_values( + array_filter( + $found, + function ( $ini ) use ( $in ) { + return $in( $ini[0] ); + } + ) + ); + } + /** * Walks all of app/ (no links followed, time-bounded) for what the scan of the WordPress root would miss: any code file * or link outside it (besides the served index.php, the config files read, its own `current` link, dot-directories and @@ -2368,6 +2446,10 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { if ( ! self::cross_ok( $this->cross ) ) { return; } + // Files the scanner reported instead of reading (phar, unreadable, php_tag …) were never text-searched either (R1). + if ( ! empty( $doc['files_not_checked'] ) || ! empty( $report['not_checked'] ) ) { + return; + } // No extra mount at all: mounted code (anywhere) is read only in the container, where it could load predis.php (F4). if ( $this->mount_points ) { return; @@ -2439,8 +2521,8 @@ protected function ignore_unused_predis( $code, array &$doc, array &$report ) { } /** - * Whether no link anywhere in app/ (old releases and core included) resolves to $dir or below it. A link this can't - * follow inside /var/www (one leaving it, or /var/www/../www) might, so it counts; /dev sinks and dangling links don't. + * Whether no link anywhere in app/ (old releases and core included) resolves to $dir or below it. Any link this can't + * follow (dangling, leaving /var/www) counts; only /dev sinks don't. * * @param string $code Real path of the site's app/. * @param string $dir Real directory. @@ -2458,8 +2540,10 @@ function ( $path, $name, $type ) use ( $code, $dir, &$into ) { if ( in_array( (string) @readlink( $path ), self::DEV_SINKS, true ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is no sink. return false; } - $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ), $why ); - if ( null === $target ? 'escape' === $why : ( $target === $dir || 0 === strpos( $target, "$dir/" ) ) ) { + // PHP resolves a dangling link's `..` as text (missing/../../plugins/nginx-helper/... loads), so any counts (R0). Case + // is folded for case-insensitive filesystems (R3). + $target = self::resolve_in( $code, substr( $path, strlen( $code ) + 1 ) ); + if ( null === $target || strtolower( $target ) === strtolower( $dir ) || 0 === strpos( strtolower( $target ), strtolower( "$dir/" ) ) ) { $into = true; return 'stop'; } @@ -2493,7 +2577,7 @@ protected static function nginx_helper_l10n( $host, $abspath ) { return false; } $tokens = []; - foreach ( token_get_all( $text ) as $token ) { + foreach ( @token_get_all( $text ) as $token ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- PHP 7.4 warns on broken input, which refuses anyway. if ( ! is_array( $token ) || T_WHITESPACE !== $token[0] ) { $tokens[] = $token; } @@ -2573,19 +2657,47 @@ protected static function l10n_array( array $tokens, &$at, $depth ) { * @return bool */ protected function fpm_master_has_redis() { - $run = $this->docker( [ 'docker', 'exec', $this->php_container, 'sh', '-c', self::FPM_PROBE ], 60 ); - $info = []; + $run = $this->docker( [ 'docker', 'exec', $this->php_container, 'sh', '-c', self::FPM_PROBE ], 60 ); + $info = []; + $mounts = []; foreach ( 0 === $run['code'] ? explode( "\n", trim( $run['stdout'] ) ) : [] as $line ) { $pair = explode( ' ', $line, 2 ); - if ( 2 === count( $pair ) ) { + if ( 2 !== count( $pair ) ) { + continue; + } + if ( 'mount' === $pair[0] ) { + $mounts[] = preg_replace_callback( + '/\\\\([0-7]{3})/', + function ( $m ) { + return chr( octdec( $m[1] ) ); + }, + $pair[1] + ); + } else { $info[ $pair[0] ] = $pair[1]; } } if ( ! isset( $info['exe'], $info['cmdline'], $info['maps'] ) ) { return false; } + // Below /var/www only the site's volume itself and EE's admin-tools: a bind below app/ (a second name of predis.php + // that nlink and lstat don't show) would be one more (R2). + $expected = $this->admin_tools_mount ? [ '/var/www', '/var/www/htdocs/ee-admin' ] : [ '/var/www' ]; + $below = array_values( + array_filter( + $mounts, + function ( $point ) { + return '/var/www' === $point || 0 === strpos( $point, '/var/www/' ); + } + ) + ); + sort( $below ); + if ( $below !== $expected ) { + return false; + } + $title = base64_decode( $info['cmdline'], true ); - return '/usr/local/sbin/php-fpm' === $info['exe'] && self::FPM_MASTER_TITLE === base64_decode( $info['cmdline'], true ) && ctype_digit( $info['maps'] ) && (int) $info['maps'] > 0; + return '/usr/local/sbin/php-fpm' === $info['exe'] && ( self::FPM_MASTER_TITLE === $title || rtrim( self::FPM_MASTER_TITLE, "\0" ) === $title ) && ctype_digit( $info['maps'] ) && (int) $info['maps'] > 0; } /** @@ -2788,9 +2900,11 @@ public static function php_settings( $text, $kind ) { // PHP's ini scanner ends a line at \r\n, \n or a bare \r; a UTF-8 BOM before the first key is skipped. $text = str_replace( [ "\r\n", "\r" ], "\n", preg_replace( '/^\xEF\xBB\xBF/', '', $text ) ); $keys = '(auto_prepend_file|auto_append_file|opcache\.preload|include_path|user_ini\.filename|zend\.multibyte|zend\.script_encoding)'; + // PHP's scanner takes an assignment right after a section header on the same line (`[PHP] auto_prepend_file=…`, R16). + $section = '(?:\[[^\]\n]*\][ \t]*)*'; $pattern = 'fpm' === $kind - ? '/^[ \t]*(?:php(?:_admin)?_(?:value|flag)[ \t]*\[[ \t]*["\']?' . $keys . '["\']?[ \t]*\]|(include|security\.limit_extensions))[ \t]*=[ \t]*([^\n]*)$/mi' - : '/^[ \t]*' . $keys . '()[ \t]*=[ \t]*([^\n]*)$/mi'; + ? '/^[ \t]*' . $section . '(?:php(?:_admin)?_(?:value|flag)[ \t]*\[[ \t]*["\']?' . $keys . '["\']?[ \t]*\]|(include|security\.limit_extensions))[ \t]*=[ \t]*([^\n]*)$/mi' + : '/^[ \t]*' . $section . $keys . '()[ \t]*=[ \t]*([^\n]*)$/mi'; $out = []; preg_match_all( $pattern, $text, $all, PREG_SET_ORDER ); foreach ( $all as $m ) { @@ -2849,6 +2963,11 @@ protected function php_setting_ok( $code, $key, $value, $layout, $quoted = false if ( 'ok' !== $file['state'] ) { return false; } + // EE mounts admin-tools over htdocs/ee-admin in the php container: the host file there isn't what PHP loads (R23). + $htdocs = self::resolve_in( $code, 'htdocs' ); + if ( 0 === strpos( $value, '/var/www/htdocs/ee-admin/' ) || ( null !== $htdocs && 0 === strpos( $file['real'], "$htdocs/ee-admin/" ) ) ) { + return false; + } if ( null === $layout ) { return $this->scanned_by_php_scan( $code, $file['real'] ); } @@ -2940,6 +3059,7 @@ protected function extra_mounts( $site_data, $code ) { $this->extra_mounts = []; $this->mount_points = []; $this->php_container = null; + $this->admin_tools_mount = false; $ps = $this->docker( [ 'docker', 'ps', '-q', '--no-trunc', '--filter', 'label=io.easyengine.site=' . $this->site, '--filter', 'label=com.docker.compose.service=php' ], 60 ); if ( 0 !== $ps['code'] ) { return 'could not list the site\'s php container: ' . self::first_line( $ps['stderr'] ); @@ -3008,6 +3128,7 @@ protected function extra_mounts( $site_data, $code ) { } // EE's own admin tools (ee site admin-tools): not the site's code. if ( '/var/www/htdocs/ee-admin' === $dst && false !== $admin && realpath( $src ) === $admin ) { + $this->admin_tools_mount = true; continue; } // The mount point is in the htdocs volume (Docker made it there), so the read-only bind below can use it. diff --git a/src/helper/class-ee-site.php b/src/helper/class-ee-site.php index 33a459c4..be3f660c 100644 --- a/src/helper/class-ee-site.php +++ b/src/helper/class-ee-site.php @@ -3335,7 +3335,7 @@ protected function delete_stopped( $site ) { /** * Checks a site's PHP code for compatibility with a PHP version. * - * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, the site's PHP in app/ except old releases nginx doesn't serve (a current/ release link) and the www-data user's tool directories (.composer, .wp-cli and the like). A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked; code files the scanner didn't read, such as code in the www-data user's tool directories, a link to code outside what was scanned, or files that changed while the check ran; an older scanner image that lists no files; or WordPress hasn't declared support for the target). After the scan, every code file in the site's files is compared with the list of files the scanner read, and only WordPress core of the live WordPress, old releases nginx doesn't serve, EasyEngine's unused app/wp-config.php and the index.php that loads WordPress from a subdirectory are exempt. Outside the WordPress directory only files named as PHP count as code, so a non-PHP-named file there that holds PHP (a wp-config.php.bak) isn't compared. Errors in nginx-helper's bundled Predis (admin/predis.php) are ignored, and listed under `ignored`, when the whole plugin is a stock release, the scanner read every code file, no other code names the plugin or links to it, and the running PHP-FPM loaded the redis extension: the plugin then never loads that file. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. + * Runs PHPCompatibility in a throwaway container with no network against a read-only mount of the site's code: for WordPress sites, the WordPress directory nginx serves (plugins, themes, mu-plugins, drop-ins and its other PHP, not WordPress core), and code mounted below its wp-content while the site runs; for PHP sites, the site's PHP in app/ except old releases nginx doesn't serve (a current/ release link) and the www-data user's tool directories (.composer, .wp-cli and the like). A WordPress site gets a verdict only when the check recognises its whole layout: WordPress at the public directory (any --public-dir, a current/ release link) or below it, loaded by WordPress's own index.php, a wp-config.php made only of the settings WordPress, EasyEngine and common plugins write, no other PHP in the site's files outside WordPress, and EasyEngine's own nginx, PHP-FPM and container setup. Anything else (a moved wp-content, a custom index.php, a config that runs or loads other code, a file PHP runs before WordPress other than one in the scanned directory) gets no verdict, with the reason. It ends with a verdict: no problems found in what was checked (every file checked, no errors, and for WordPress a core version that WordPress lists as supporting the target PHP; the JSON field safe_to_upgrade is then true), not safe (at least one error, or a WordPress version that doesn't support the target), or can't confirm (some files couldn't be checked; code files the scanner didn't read, such as code in the www-data user's tool directories, a link to code outside what was scanned, or files that changed while the check ran; an older scanner image that lists no files; or WordPress hasn't declared support for the target). After the scan, every code file in the site's files is compared with the list of files the scanner read, and only WordPress core of the live WordPress, old releases nginx doesn't serve, EasyEngine's unused app/wp-config.php and the index.php that loads WordPress from a subdirectory are exempt. Outside the WordPress directory only files named as PHP count as code, so a non-PHP-named file there that holds PHP (a wp-config.php.bak) isn't compared. Errors in nginx-helper's bundled Predis (admin/predis.php) are ignored, and listed under `ignored`, when the whole plugin is a stock release, the site's php container has no extra mount, the scanner read every code file and reported none it couldn't read, no other code names the plugin (WordPress's own language packs of the plugin don't count) and no link in the site's files leads to it or can't be followed, and the running PHP-FPM has loaded the redis extension: the plugin then never loads that file. It never says the whole site is safe: WordPress core files are not scanned, only its version is compared with WordPress's own list of supported PHP versions (a WordPress newer than that list counts as supporting what the newest listed version supports, and says so). Warnings never change the verdict. The verdict comes from static analysis, which can't see breakage that only shows at runtime. * * The command exits 0 whenever it printed a result, including when a check of the site is already running (`busy`), was stopped with --cancel (`cancelled`) or couldn't run (`tool_error`). * From cc4e36654c3b290748ab50d9485e67aa4d809eb2 Mon Sep 17 00:00:00 2001 From: Riddhesh Sanghvi Date: Thu, 26 Nov 2026 06:23:07 +0530 Subject: [PATCH 53/53] fix(site): refuse quoted ini section names and links inside mounted code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PHP takes an assignment after a quoted section name that may hold `]`, `;` or a newline (`["a]b"] auto_prepend_file=…`), which php-compat's setting reader can't see. A file with such a header, or with a guarded key set more often than the reader found, is now refused. - A link inside an accepted mount lets PHP read a .user.ini no walk reads, so a mount holding any link but a /dev sink is refused. --- src/helper/Site_PHP_Compat.php | 59 ++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 3 deletions(-) diff --git a/src/helper/Site_PHP_Compat.php b/src/helper/Site_PHP_Compat.php index 512dd911..9a4eff9a 100644 --- a/src/helper/Site_PHP_Compat.php +++ b/src/helper/Site_PHP_Compat.php @@ -2876,7 +2876,12 @@ function ( $name ) use ( $conf ) { if ( false === $text ) { return "can't read $shown, which may set a file PHP runs before WordPress"; } - foreach ( self::php_settings( $text, $kind ) as list( $key, $value, $quoted ) ) { + $settings = self::php_settings( $text, $kind ); + $unread = self::unread_setting( $text, $kind, $settings ); + if ( null !== $unread ) { + return "$shown $unread, which this check can't confirm"; + } + foreach ( $settings as list( $key, $value, $quoted ) ) { if ( ! $this->php_setting_ok( $code, $key, $value, $layout, $quoted ) ) { return "$shown sets $key to " . self::clean( '' === $value ? '""' : $value ) . ', which this check can\'t confirm'; } @@ -2886,6 +2891,45 @@ function ( $name ) use ( $conf ) { return null; } + /** + * A guarded setting php_settings() didn't read: a quoted section header (PHP takes `["a]b"] auto_prepend_file=…`, and a + * quoted name may hold `]`, `;` or a newline), or a key followed by `=` more often than php_settings() found it, outside + * comment lines and `;` comments. + * + * @param string $text The file's text. + * @param string $kind ini or fpm. + * @param array[] $settings php_settings() of it. + * + * @return string|null What it may set, or null. + */ + public static function unread_setting( $text, $kind, array $settings ) { + $text = str_replace( [ "\r\n", "\r" ], "\n", preg_replace( '/^\xEF\xBB\xBF/', '', $text ) ); + if ( preg_match( '/^[ \t]*(?:\[[^\]"\'\n]*\][ \t]*)*\[[^\]\n]*["\']/m', $text ) ) { + return 'has a quoted section name, after which PHP may take a setting this check can\'t read'; + } + $keys = [ 'auto_prepend_file', 'auto_append_file', 'opcache.preload', 'include_path', 'user_ini.filename', 'zend.multibyte', 'zend.script_encoding' ]; + if ( 'fpm' === $kind ) { + array_push( $keys, 'include', 'security.limit_extensions' ); + } + $lines = ''; + foreach ( explode( "\n", $text ) as $line ) { + if ( ! preg_match( '/^[ \t]*[;#]/', $line ) ) { + $lines .= preg_replace( '/;.*$/', '', $line ) . "\n"; + } + } + foreach ( $keys as $key ) { + $read = 0; + foreach ( $settings as $setting ) { + $read += $key === $setting[0] ? 1 : 0; + } + if ( preg_match_all( '/(? $read ) { + return "may set $key in a form this check can't read"; + } + } + + return null; + } + /** * Every assignment of the settings that load or change code (auto_prepend_file, auto_append_file, opcache.preload, * include_path, user_ini.filename, zend.multibyte, zend.script_encoding) and FPM's include= and @@ -3152,18 +3196,27 @@ protected function extra_mounts( $site_data, $code ) { if ( $outside ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' at ' . self::clean( '/var/www' . substr( $at, strlen( $code ) ) ) . ', where the scanner doesn\'t look'; } - // A .user.ini there is seen only inside the container: its prepend/append settings would go unchecked. + // A .user.ini there is seen only inside the container: its prepend/append settings would go unchecked. A link there + // leads PHP to .user.ini files no walk reads (src/lnk -> /var/www/other), so any but a /dev sink refuses. $user_ini = null; + $link = null; $error = is_dir( $src ) ? $this->walk_tree( realpath( $src ), - function ( $path, $name, $type ) use ( &$user_ini ) { + function ( $path, $name, $type ) use ( &$user_ini, &$link ) { if ( '.user.ini' === $name ) { $user_ini = $path; return 'stop'; } + if ( 'link' === $type && ! in_array( (string) @readlink( $path ), self::DEV_SINKS, true ) ) { // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- false is no sink. + $link = $path; + return 'stop'; + } return 'dir' === $type; } ) : null; + if ( null !== $link ) { + return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ', which holds a link (' . self::clean( $link ) . ") this check can't confirm"; + } if ( null !== $error || null !== $user_ini ) { return 'the site\'s php container mounts ' . self::clean( $dst ) . ' from ' . self::clean( $src ) . ( null !== $user_ini ? ', which holds a .user.ini (' . self::clean( $user_ini ) . ') this check doesn\'t read' : ", which can't be looked through: $error" ); }