$cursor Cursor. * @param array $components Selected components. * @param float $deadline Deadline. * @return array{done:bool,cursor:array,error?:string} */ public function tick( int $job_id, string $job_dir, string $zip_path, array $cursor, array $components, float $deadline ): array { $steps = isset( $cursor['steps'] ) && is_array( $cursor['steps'] ) && ! empty( $cursor['steps'] ) ? $cursor['steps'] : array( array( 'zip' => $zip_path, 'mode' => 'full', ), ); $ap = isset( $cursor['ap'] ) && is_array( $cursor['ap'] ) ? $cursor['ap'] : array( 's' => 0, 'st' => 'files', 'sh' => 0, 'so' => 0, 'n' => 0, 'd' => 0, ); $state_dir = State_Files::dir( $job_dir ); $targets = ( new Snapshot() )->component_targets( $components ); $prefixes = array(); foreach ( array_keys( $targets ) as $rel_prefix ) { $prefixes[] = 'files/' . $rel_prefix . '/'; } while ( (int) $ap['s'] < count( $steps ) ) { $step = $steps[ (int) $ap['s'] ]; $zip = (string) ( $step['zip'] ?? '' ); if ( 'files' === $ap['st'] ) { $check = new Archive_Check( $state_dir . '/check-' . (int) $ap['s'] ); $finished = $this->apply_members( $job_id, $zip, $check, $ap, $cursor, $targets, $prefixes, $deadline ); if ( ! $finished ) { break; } $ap['st'] = 'incremental' === (string) ( $step['mode'] ?? 'full' ) ? 'del' : 'next'; $ap['do'] = 0; unset( $ap['dl'] ); } if ( 'del' === $ap['st'] ) { if ( empty( $ap['dl'] ) ) { /** * Path to an NDJSON list of deletions for an incremental archive * (rows {"p":"wp-content/…"}), written into $state_dir; null for none. * * @param string|null $path Null. * @param string $zip Archive. * @param string $state_dir Job state dir. * @param int $job_id Job id. * @param int $step Step index. */ $list = apply_filters( 'brverify_restore_step_deletions', null, $zip, $state_dir, $job_id, (int) $ap['s'] ); $ap['dl'] = is_string( $list ) && '' !== $list ? basename( $list ) : '-'; } if ( '-' !== $ap['dl'] ) { $finished = $this->apply_deletions( $state_dir . '/' . (string) $ap['dl'], $ap, $targets, $deadline ); if ( ! $finished ) { break; } } $ap['st'] = 'next'; } if ( 'next' === $ap['st'] ) { $ap['s'] = (int) $ap['s'] + 1; $ap['st'] = 'files'; $ap['sh'] = 0; $ap['so'] = 0; unset( $ap['rs'], $ap['dl'], $ap['do'] ); } if ( microtime( true ) >= $deadline ) { break; } } $cursor['ap'] = $ap; $cursor['applied_files'] = (int) $ap['n']; $done = (int) $ap['s'] >= count( $steps ); if ( $done ) { Logger::info( $job_id, sprintf( 'File apply completed (%d file(s), %d deletion(s), %d archive(s)).', (int) $ap['n'], (int) $ap['d'], count( $steps ) ) ); } return array( 'done' => $done, 'cursor' => $cursor, ); } /** * Progress 0..1 (by archive step and approved-list shard). * * @param array $cursor Cursor. */ public static function progress( array $cursor ): float { $ap = isset( $cursor['ap'] ) && is_array( $cursor['ap'] ) ? $cursor['ap'] : array(); $steps = max( 1, isset( $cursor['steps'] ) && is_array( $cursor['steps'] ) ? count( $cursor['steps'] ) : 1 ); $frac = min( 1.0, (float) ( $ap['sh'] ?? 0 ) / (float) Archive_Check::SHARDS ); return min( 1.0, ( (int) ( $ap['s'] ?? 0 ) + $frac ) / $steps ); } /** * Extract members of one archive until done or the deadline. * * @param int $job_id Job id. * @param string $zip Archive. * @param array $ap Apply state (by reference). * @param array $cursor Cursor (for filters). * @param array $targets rel_prefix => abs root. * @param list $prefixes Member prefixes for selected components. * @param float $deadline Deadline. * @return bool Finished this archive. * @throws State_Exception On unsafe paths or I/O failure. */ private function apply_members( int $job_id, string $zip, Archive_Check $check, array &$ap, array $cursor, array $targets, array $prefixes, float $deadline ): bool { $check->assert_unchanged( $zip ); $reader = new Zip_Reader( $zip ); try { while ( (int) ( $ap['sh'] ?? 0 ) < Archive_Check::SHARDS ) { $batch = $check->approved( (int) $ap['sh'], (int) ( $ap['so'] ?? 0 ), 128 ); foreach ( $batch['rows'] as $k => $row ) { $entry = isset( $row['e'] ) && is_array( $row['e'] ) ? $row['e'] : array(); $name = str_replace( '\\', '/', (string) ( $entry['name'] ?? '' ) ); $take = false; if ( '' !== $name && ! \brverify_str_ends_with( $name, '/' ) ) { foreach ( $prefixes as $prefix ) { if ( \brverify_str_starts_with( $name, $prefix ) ) { $take = true; break; } } } /** * Skip one archive member during file restore (e.g. never overwrite the * running plugin during a site migration). Return true to skip. * * @param bool $skip Default false. * @param string $name Member name. * @param int $job_id Job id. * @param array $cursor Cursor. */ if ( $take && apply_filters( 'brverify_restore_skip_member', false, $name, $job_id, $cursor ) ) { $take = false; } if ( $take ) { if ( ! Validator::is_safe_zip_entry( $name ) ) { throw new State_Exception( esc_html( sprintf( /* translators: %s: zip entry */ __( 'Rejected unsafe zip entry during extract: %s', '007aj-backup-restore-verifier' ), $name ) ) ); } $mapped = $this->map_entry_to_target( $name, $targets ); if ( null !== $mapped ) { $dest = Validator::jail_destination( $mapped['root'], $mapped['rel_inside'] ); if ( null === $dest ) { throw new State_Exception( esc_html( sprintf( /* translators: %s: zip entry */ __( 'Path jail rejected extract target for: %s', '007aj-backup-restore-verifier' ), $name ) ) ); } $dest_dir = dirname( $dest ); if ( ! is_dir( $dest_dir ) && ! wp_mkdir_p( $dest_dir ) ) { throw new State_Exception( esc_html( State_Files::io_message( __( 'Failed creating destination directory during restore', '007aj-backup-restore-verifier' ), $dest_dir ) ) ); } $parent_real = realpath( $dest_dir ); if ( false === $parent_real || ! Path_Guard::is_under( $parent_real, $mapped['root'] ) ) { throw new State_Exception( esc_html( sprintf( /* translators: %s: zip entry */ __( 'Extract destination escaped allowed root: %s', '007aj-backup-restore-verifier' ), $name ) ) ); } if ( ! $this->extract_one( $reader, $entry, (string) ( $row['h'] ?? '' ), $dest, $ap, $deadline ) ) { return false; // Large member continues next tick. } ++$ap['n']; } } $ap['so'] = (int) $batch['ends'][ $k ]; if ( microtime( true ) >= $deadline ) { return false; } } if ( $batch['eof'] ) { $ap['sh'] = (int) $ap['sh'] + 1; $ap['so'] = 0; } if ( microtime( true ) >= $deadline ) { return (int) $ap['sh'] >= Archive_Check::SHARDS; } } } finally { $reader->close(); } return true; } /** * Stream one member to dest via a temporary file. Returns false when it must resume. * * @param Zip_Reader $reader Reader. * @param array $entry Entry (from the approved list). * @param string $expected Validated SHA-256 of the member. * @param string $dest Destination. * @param array $ap Apply state (by reference). * @param float $deadline Deadline. * @throws State_Exception On I/O failure. */ private function extract_one( Zip_Reader $reader, array $entry, string $expected, string $dest, array &$ap, float $deadline ): bool { if ( 1 !== preg_match( '/^[a-f0-9]{64}$/', $expected ) ) { throw new State_Exception( esc_html( sprintf( /* translators: %s: zip entry */ __( 'Archive member was not validated; restore stopped: %s', '007aj-backup-restore-verifier' ), (string) ( $entry['name'] ?? '' ) ) ) ); } $tmp = $dest . '.brv-part'; $resume = isset( $ap['rs'] ) && is_array( $ap['rs'] ) ? $ap['rs'] : array(); $from = (int) ( $resume['done'] ?? 0 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $out = @fopen( $tmp, $from > 0 ? 'cb' : 'wb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( false === $out ) { throw new State_Exception( esc_html( State_Files::io_message( __( 'Failed writing restored file', '007aj-backup-restore-verifier' ), $dest ) ) ); } if ( $from > 0 ) { ftruncate( $out, $from ); fseek( $out, $from ); } try { $res = $reader->stream( $entry, static function ( string $b ) use ( $out, $dest ): void { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite if ( strlen( $b ) !== fwrite( $out, $b ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite throw new State_Exception( esc_html( State_Files::io_message( __( 'Short write while restoring file (disk full?)', '007aj-backup-restore-verifier' ), $dest ) ) ); } }, $resume, $deadline ); } catch ( \Throwable $e ) { fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose $out = null; wp_delete_file( $tmp ); unset( $ap['rs'] ); throw $e; } finally { if ( null !== $out ) { fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose } } if ( empty( $res['done'] ) ) { $ap['rs'] = $res['resume']; return false; } unset( $ap['rs'] ); if ( ! hash_equals( $expected, (string) ( $res['sha256'] ?? '' ) ) ) { wp_delete_file( $tmp ); throw new State_Exception( esc_html( sprintf( /* translators: %s: zip entry */ __( 'Restored file does not match its validated checksum; restore stopped: %s', '007aj-backup-restore-verifier' ), (string) ( $entry['name'] ?? '' ) ) ) ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename if ( ! @rename( $tmp, $dest ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.rename_rename // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_copy if ( ! @copy( $tmp, $dest ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged wp_delete_file( $tmp ); throw new State_Exception( esc_html( State_Files::io_message( __( 'Failed writing restored file', '007aj-backup-restore-verifier' ), $dest ) ) ); } wp_delete_file( $tmp ); } // Keep the original modification time (stored in the archive) so the next incremental sees no change. if ( ! empty( $entry['mtime'] ) ) { @touch( $dest, (int) $entry['mtime'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_touch } return true; } /** * Apply an NDJSON deletions list (rows {"p":"wp-content/…"}). * * @param string $list List path. * @param array $ap Apply state (by reference). * @param array $targets Targets. * @param float $deadline Deadline. * @return bool Finished. * @throws State_Exception On a jail violation. */ private function apply_deletions( string $list, array &$ap, array $targets, float $deadline ): bool { while ( microtime( true ) < $deadline ) { $batch = State_Files::read_rows( $list, (int) ( $ap['do'] ?? 0 ), 500 ); if ( empty( $batch['rows'] ) ) { return true; } foreach ( $batch['rows'] as $k => $row ) { $rel = (string) ( $row['p'] ?? '' ); if ( '' !== $rel ) { $mapped = $this->map_entry_to_target( 'files/' . ltrim( str_replace( '\\', '/', $rel ), '/' ), $targets ); if ( null !== $mapped ) { $dest = Validator::jail_destination( $mapped['root'], $mapped['rel_inside'] ); if ( null === $dest ) { throw new State_Exception( esc_html( __( 'Path jail rejected delete target during chain restore.', '007aj-backup-restore-verifier' ) ) ); } if ( is_file( $dest ) ) { wp_delete_file( $dest ); $ap['d'] = (int) ( $ap['d'] ?? 0 ) + 1; } } } $ap['do'] = (int) $batch['ends'][ $k ]; } if ( $batch['eof'] ) { return true; } } return false; } /** * Map a zip member to live destination. * * @param string $entry Zip entry (files/wp-content/…). * @param array $targets rel_prefix => abs root. * @return array{dest:string,root:string,rel_inside:string}|null */ private function map_entry_to_target( string $entry, array $targets ): ?array { $entry = str_replace( '\\', '/', $entry ); if ( ! \brverify_str_starts_with( $entry, 'files/' ) ) { return null; } $without = substr( $entry, strlen( 'files/' ) ); // wp-content/plugins/… foreach ( $targets as $rel_prefix => $abs_root ) { $prefix = $rel_prefix . '/'; if ( $without === $rel_prefix || \brverify_str_starts_with( $without, $prefix ) ) { $rel_inside = ( $without === $rel_prefix ) ? '' : substr( $without, strlen( $prefix ) ); $root_real = realpath( $abs_root ); if ( false === $root_real ) { if ( ! wp_mkdir_p( $abs_root ) ) { return null; } $root_real = realpath( $abs_root ); if ( false === $root_real ) { return null; } } $dest = $root_real . ( '' === $rel_inside ? '' : DIRECTORY_SEPARATOR . str_replace( '/', DIRECTORY_SEPARATOR, $rel_inside ) ); return array( 'dest' => $dest, 'root' => $root_real, 'rel_inside' => $rel_inside, ); } } return null; } }