Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
272 changes: 272 additions & 0 deletions app/Console/Commands/DownloadSubmission.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,272 @@
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\Submission;
use App\Utils\ConsoleUtils;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use Throwable;

class DownloadSubmission extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'submission:download
{id : The submission\'s ID, as listed by submission:list}
{--output= : Write the file here instead of to stdout. A directory gets the file under its default name}
{--force : Overwrite the file at --output if there is one}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Write out a submitted file as it was received';

/**
* The file is read in parts of this size. A NUL byte in the first marks it as binary.
*/
private const CHUNK_LENGTH = 8192;

/**
* The most of a client's filename kept in a default name, leaving room for the ID within the 255 bytes that most
* filesystems allow.
*/
private const MAX_CLIENT_NAME_LENGTH = 200;

/**
* Execute the console command.
*/
public function handle(): int
{
$id = (string) $this->argument('id');
if (!Str::isUuid($id)) {
return $this->failWith("{$id} is not a valid submission ID");
}

$output = $this->option('output');
$writes_to_file = is_string($output) && $output !== '';
if (!$writes_to_file && $this->input->hasParameterOption('--output')) {
return $this->failWith('--output needs a path');
}

$submission = Submission::find($id);
if ($submission === null) {
return $this->failWith("Submission {$id} does not exist");
}

// The target is checked before reading the file, which on S3 downloads it.
$target = null;
if ($writes_to_file) {
$target = $this->checkedTarget($submission, (string) $output);
if ($target === null) {
return self::FAILURE;
}
}

try {
if (!Storage::fileExists($submission->path)) {
return $this->failWith("The file of submission {$id} was not found at {$submission->path}");
}
$source = Storage::readStream($submission->path);
if ($source === null) {
throw new RuntimeException("Unable to read {$submission->path}");
}
} catch (Throwable $e) {
return $this->failWith("The file of submission {$id} could not be read: " . ConsoleUtils::errorCause($e));
}

try {
return $target === null ? $this->writeToStdout($source) : $this->writeToFile($source, $target);
} finally {
fclose($source);
}
}

/**
* Copy the file to stdout. The file is the command's output rather than a message, so it's written even with
* --quiet, and a failure to write it, such as to a closed pipe or a full disk, fails the command. On a terminal, a
* binary file isn't written, and any other file is shown with its control characters escaped.
*
* @param resource $source
*/
private function writeToStdout($source): int
{
try {
$chunk = stream_get_contents($source, self::CHUNK_LENGTH);
if ($chunk === false) {
throw new RuntimeException('Unable to read the file');
}
$terminal = $this->writesToTerminal();
if ($terminal && str_contains($chunk, "\0")) {
return $this->failWith('This file is binary, so it isn\'t written to the terminal. Redirect the output or use --output.');
}
Comment thread
williamjallen marked this conversation as resolved.
Resolved

$output = $this->output->getOutput();
$held = '';
while (true) {
$at_end = feof($source);
if ($terminal) {
// Unless the file ends there, a "\r" or "\xC2" at the end of a part is held back for the next, which
// could finish it as a line break or a C1 control.
$chunk = $held . $chunk;
$held = !$at_end && (str_ends_with($chunk, "\r") || str_ends_with($chunk, "\xC2")) ? $chunk[-1] : '';
$chunk = ConsoleUtils::printable(substr($chunk, 0, strlen($chunk) - strlen($held)));
}
self::writeRaw($output, $chunk);
if ($at_end) {
break;
}
$chunk = fread($source, self::CHUNK_LENGTH);
if ($chunk === false) {
throw new RuntimeException('Unable to read the file');
}
}
if ($output instanceof StreamOutput && !fflush($output->getStream())) {
throw new RuntimeException('Unable to write to stdout');
}
} catch (Throwable $e) {
// A reader that stops early, such as head, closes the pipe. Like cat, the command says nothing about it.
if (str_contains($e->getMessage(), 'Broken pipe')) {
return self::FAILURE;
}
return $this->failWith('The file could not be copied: ' . ConsoleUtils::errorCause($e));
}

return self::SUCCESS;
}

/**
* Write to stdout as is. Output that isn't a stream, such as when the command is called from code, reports no
* write errors.
*/
private static function writeRaw(OutputInterface $output, string $data): void
{
if (!$output instanceof StreamOutput) {
$output->write($data, false, OutputInterface::OUTPUT_RAW | OutputInterface::VERBOSITY_QUIET);
} elseif (fwrite($output->getStream(), $data) !== strlen($data)) {
throw new RuntimeException('Unable to write to stdout');
}
}

/**
* The file to write to: the given path, or the default name inside it if it's a directory. Null after reporting
* a target that mustn't or can't be written.
*/
private function checkedTarget(Submission $submission, string $output): ?string
{
$target = is_dir($output) ? rtrim($output, '/') . '/' . self::defaultName($submission) : $output;
if (str_ends_with($target, '/')) {
$this->failWith("{$output} isn't a directory");
return null;
}
if (file_exists($target) && !is_file($target)) {
$this->failWith("{$target} exists and isn't a regular file");
return null;
}
if ((is_link($target) || file_exists($target)) && $this->option('force') !== true) {
$this->failWith("{$target} already exists. Use --force to overwrite it.");
Comment thread
williamjallen marked this conversation as resolved.
Resolved
return null;
}
$directory = dirname($target);
if (!is_dir($directory) || !is_writable($directory)) {
$this->failWith("Can't write to the directory {$directory}");
return null;
}
return $target;
}

/**
* Copy the file to the given path. The copy goes to a temporary file beside the target, which only replaces the
* target once it's complete.
*
* @param resource $source
*/
private function writeToFile($source, string $target): int
{
$directory = dirname($target);
$temporary = false;
try {
// tempnam() creates the file readable by its owner only. If it can't create it here, it creates it in
// the system's temporary directory instead, with a notice.
$temporary = @tempnam($directory, '.' . basename($target) . '.');
if ($temporary === false || dirname($temporary) !== realpath($directory)) {
throw new RuntimeException("Unable to create a temporary file in {$directory}");
}
$destination = fopen($temporary, 'wb');
if ($destination === false) {
throw new RuntimeException("Unable to write {$target}");
}
try {
$bytes = stream_copy_to_stream($source, $destination);
if ($bytes === false || !fflush($destination)) {
throw new RuntimeException("Unable to write {$target}");
}
} finally {
fclose($destination);
}
if (!rename($temporary, $target)) {
throw new RuntimeException("Unable to move {$temporary} to {$target}");
}
} catch (Throwable $e) {
if ($temporary !== false) {
@unlink($temporary);
}
return $this->failWith('The file could not be copied: ' . ConsoleUtils::errorCause($e));
}

$this->output->getErrorStyle()->writeln(
OutputFormatter::escape("Wrote {$target} (" . number_format((int) ceil($bytes / 1024)) . ' KB)')
);
return self::SUCCESS;
}

/**
* The name the file is written under in a directory: the submission's ID, followed by ".xml" for an XML file, or
* the name the client gave a data file. That name comes from the uploader, so only the end of its base name is
* kept, in safe characters.
*/
private static function defaultName(Submission $submission): string
{
if ($submission->filename === null) {
return "{$submission->id}.xml";
}

$filename = basename(str_replace('\\', '/', $submission->filename));
$filename = substr((string) preg_replace('/[^A-Za-z0-9._-]/', '_', $filename), -self::MAX_CLIENT_NAME_LENGTH);
return $filename === '' ? $submission->id : "{$submission->id}-{$filename}";
}

/**
* Whether stdout is a terminal, which control characters in the file could act on.
*/
protected function writesToTerminal(): bool
{
$output = $this->output->getOutput();
return $output instanceof StreamOutput && stream_isatty($output->getStream());
}

/**
* Report an error on stderr, so that it never mixes with a file written to stdout, even with --quiet. A message can
* include text from elsewhere, such as a storage error, so its control characters are escaped.
*/
private function failWith(string $message): int
{
$this->output->getErrorStyle()->writeln(
'<error>' . OutputFormatter::escape(ConsoleUtils::printable($message)) . '</error>',
OutputInterface::VERBOSITY_QUIET,
);
return self::FAILURE;
}
}
21 changes: 4 additions & 17 deletions app/Console/Commands/ShowSubmission.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use App\Enums\SubmissionStatus;
use App\Models\Submission;
use App\Utils\ConsoleUtils;
use Carbon\CarbonInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
Expand Down Expand Up @@ -84,21 +85,13 @@ private function field(string $label, string ...$values): void
}

/**
* Split text into lines that print as written: console markup is escaped, and control characters other than tabs,
* including the C1 controls U+0080 to U+009F, are shown as \xNN so that they can't act on the terminal.
* Split text into lines that print as written, with their control characters escaped and console markup escaped.
*
* @return array<string>
*/
private static function printableLines(string $text): array
{
return array_map(
fn (string $line): string => OutputFormatter::escape((string) preg_replace_callback(
'/[\x00-\x08\x0B-\x1F\x7F]|\xC2[\x80-\x9F]/',
fn (array $match): string => sprintf('\x%02X', ord($match[0][-1])),
$line,
)),
explode("\n", str_replace(["\r\n", "\r"], "\n", $text)),
);
return array_map(OutputFormatter::escape(...), explode("\n", ConsoleUtils::printable($text)));
}

private function showBuild(Submission $submission): void
Expand Down Expand Up @@ -188,13 +181,7 @@ private static function describeFile(string $path): string
}
return "{$path} (" . number_format((int) ceil(Storage::size($path) / 1024)) . ' KB)';
} catch (Throwable $e) {
// Storage errors, such as the AWS SDK's, can spread their cause over several lines.
$message = trim($e->getPrevious()?->getMessage() ?? '');
if ($message === '') {
$message = trim($e->getMessage());
}
$cause = rtrim((string) preg_replace('/\s+/', ' ', $message), '. ');
return "{$path} (could not be checked: {$cause})";
return "{$path} (could not be checked: " . ConsoleUtils::errorCause($e) . ')';
}
}

Expand Down
35 changes: 35 additions & 0 deletions app/Utils/ConsoleUtils.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace App\Utils;

use Throwable;

class ConsoleUtils
{
/**
* Text that can be shown on a terminal without acting on it: line breaks become "\n", and control characters other
* than tabs, including the C1 controls U+0080 to U+009F, are shown as \xNN.
*/
public static function printable(string $text): string
{
return (string) preg_replace_callback(
'/[\x00-\x08\x0B-\x1F\x7F]|\xC2[\x80-\x9F]/',
fn (array $match): string => sprintf('\x%02X', ord($match[0][-1])),
str_replace(["\r\n", "\r"], "\n", $text),
);
}

/**
* The cause of an error on one line. Storage errors such as the AWS SDK's spread it over several lines.
*/
public static function errorCause(Throwable $e): string
{
$message = trim($e->getPrevious()?->getMessage() ?? '');
if ($message === '') {
$message = trim($e->getMessage());
}
return rtrim((string) preg_replace('/\s+/', ' ', $message), '. ');
}
}
2 changes: 2 additions & 0 deletions app/cdash/tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,8 @@ add_feature_test_in_transaction(/Feature/Console/ListSubmissionsCommandTest)

add_feature_test_in_transaction(/Feature/Console/ShowSubmissionCommandTest)

add_feature_test_in_transaction(/Feature/Console/DownloadSubmissionCommandTest)

add_feature_test_in_transaction(/Feature/Submission/XmlSubmissionTest)

add_feature_test_in_transaction(/Feature/Submission/UnparsedSubmissionTest)
Expand Down
Loading