&_wpnonce= */ final class Download implements Hookable { private const ACTION = 'migratex_download'; /** Bytes read and sent per step. */ private const CHUNK = 4194304; public function register(): void { add_action( 'wp_ajax_' . self::ACTION, array( $this, 'handle' ) ); } public static function url( string $file ): string { return add_query_arg( array( 'action' => self::ACTION, 'file' => $file, '_wpnonce' => Guard::createNonce(), ), admin_url( 'admin-ajax.php' ) ); } public function handle(): void { // Nothing else is read until the request has proved who it is. The same token and the same capability // as every other endpoint (see Guard): a backup holds the whole database, password hashes included. if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), Guard::NONCE_ACTION ) ) { wp_die( esc_html__( 'Security check failed.', 'migratex' ), '', array( 'response' => 403 ) ); } $auth = Guard::authorizeNonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) ); if ( is_wp_error( $auth ) ) { wp_die( esc_html( $auth->get_error_message() ), '', array( 'response' => (int) ( $auth->get_error_data()['status'] ?? 403 ) ) ); } $name = isset( $_GET['file'] ) ? sanitize_file_name( wp_unslash( $_GET['file'] ) ) : ''; $path = Library::path( $name ); if ( null === $path ) { wp_die( esc_html__( 'That backup does not exist.', 'migratex' ), '', array( 'response' => 404 ) ); } $this->stream( $path, $name ); } private function stream( string $path, string $name ): void { clearstatcache( true, $path ); $size = (int) filesize( $path ); $start = 0; $end = $size - 1; $code = 200; // Resumable (Range) downloads are off by default. A proxy or CDN that mishandles a resumed range // stitches the pieces together wrongly and the browser saves a file that is silently corrupt; without // ranges a broken transfer fails loudly instead. Sites whose stack handles ranges can turn them on. $ranges = (bool) apply_filters( 'migratex_download_ranges', false ); $range = ( $ranges && isset( $_SERVER['HTTP_RANGE'] ) ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_RANGE'] ) ) : ''; if ( '' !== $range && 1 === preg_match( '/^bytes=(\d*)-(\d*)$/', trim( $range ), $m ) && ( '' !== $m[1] || '' !== $m[2] ) ) { if ( '' === $m[1] ) { $start = max( 0, $size - (int) $m[2] ); // "-500": the last 500 bytes. } else { $start = (int) $m[1]; $end = '' === $m[2] ? $end : min( $end, (int) $m[2] ); } if ( $start > $end || $start >= $size ) { status_header( 416 ); header( 'Content-Range: bytes */' . $size ); exit; } $code = 206; } // A download may legitimately outlast a normal request, and it is not a pump step. Environment::ignoreUserAbort( false ); if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) { session_write_close(); } // Nothing between the file and the browser may buffer, compress or rewrite the bytes: a compressed // or re-chunked body no longer matches Content-Length. if ( function_exists( 'ini_set' ) ) { @ini_set( 'zlib.output_compression', 'Off' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.PHP.IniSet.Risky,Squiz.PHP.DiscouragedFunctions.Discouraged -- an unmodified body is the point of this endpoint. } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } while ( ob_get_level() ) { ob_end_clean(); } status_header( $code ); nocache_headers(); header( 'Cache-Control: private, no-transform, no-store, must-revalidate' ); header( 'Content-Type: application/octet-stream' ); header( 'Content-Disposition: attachment; filename="' . $name . '"' ); header( 'Content-Encoding: identity' ); header( 'X-Content-Type-Options: nosniff' ); header( 'X-Accel-Buffering: no' ); header( 'X-LiteSpeed-Cache-Control: no-cache' ); // Opt-in: let the web server send the file itself, so none of it passes through PHP. $offload = 200 === $code ? $this->offloadHeader( $path, $name ) : null; if ( null !== $offload ) { header( $offload ); exit; } header( 'Accept-Ranges: ' . ( $ranges ? 'bytes' : 'none' ) ); header( 'Content-Length: ' . ( $end - $start + 1 ) ); if ( 206 === $code ) { header( sprintf( 'Content-Range: bytes %d-%d/%d', $start, $end, $size ) ); } $handle = fopen( $path, 'rb' ); if ( false === $handle ) { exit; } fseek( $handle, $start ); $remaining = $end - $start + 1; while ( $remaining > 0 && ! connection_aborted() ) { // Each block gets a fresh allowance, so a download of any size outlasts a normal request. if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( 300 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- renewed per block of one long-running download, and only where the host allows it. } $chunk = fread( $handle, (int) min( self::CHUNK, $remaining ) ); if ( false === $chunk || '' === $chunk ) { break; // the file shrank under us: stop short so the browser sees a failed download, not a bad file. } echo $chunk; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary file contents. $remaining -= strlen( $chunk ); flush(); } fclose( $handle ); exit; } /** * The header that makes the web server serve the file itself, or null when that is not set up. * * Off unless the site opts in, because a server that ignores the header would send an empty file: * define( 'MIGRATEX_SENDFILE', 'x-sendfile' ); // Apache mod_xsendfile (path allowed with XSendFilePath) * define( 'MIGRATEX_SENDFILE', 'x-accel-redirect' ); // Nginx, with an internal location * define( 'MIGRATEX_ACCEL_PREFIX', '/migratex-archives' ); // ...that maps to the backups folder * or return the full header line from the migratex_download_offload_header filter. */ private function offloadHeader( string $path, string $name ): ?string { $header = null; $mode = defined( 'MIGRATEX_SENDFILE' ) ? strtolower( (string) constant( 'MIGRATEX_SENDFILE' ) ) : ''; if ( 'x-sendfile' === $mode ) { $header = 'X-Sendfile: ' . $path; } elseif ( 'x-accel-redirect' === $mode && defined( 'MIGRATEX_ACCEL_PREFIX' ) ) { $header = 'X-Accel-Redirect: ' . rtrim( (string) constant( 'MIGRATEX_ACCEL_PREFIX' ), '/' ) . '/' . rawurlencode( $name ); } $header = apply_filters( 'migratex_download_offload_header', $header, $path, $name ); return ( is_string( $header ) && '' !== $header && false === strpbrk( $header, "\r\n" ) ) ? $header : null; } }