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
2 changes: 1 addition & 1 deletion .github/workflows/phpunit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ jobs:
- name: Install archive backends needed by tests
run: |
sudo apt-get update -qq
sudo apt-get install -y -qq p7zip-full
sudo apt-get install -y -qq p7zip-full zstd

- name: Run unit tests
run: composer run test:unit -- --no-progress
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/playwright.yml
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,9 @@ jobs:
# These binaries are not installed by the stock Nextcloud image.
docker exec -u root extract-playwright-nextcloud sh -ec '
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq p7zip-full unrar-free >/dev/null
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq p7zip-full unrar-free zstd >/dev/null
command -v 7za
command -v zstd
command -v unrar
'
# The first-run wizard overlays the Files action menu on fresh NC
Expand Down
54 changes: 32 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,26 +75,29 @@ child processes on completion or failure. The PHP `rar` extension follows a
separate bounded streaming path with CRC checks rather than spawning a decoder,
but it still cannot provide an operating-system-enforced CPU or disk quota.

The `zip` PHP extension is required for Zip files. Rar needs either the PHP
`rar` extension or the `unrar` binary; every other format is handled by the
`7za` binary shipped with p7zip.
The `zip` PHP extension is required for ZIP files. RAR uses the PHP `rar`
extension, `unrar`, or full `7z`. TAR, XZ, 7z, gzip, bzip2, and DEB use `7za`.
Zstandard (`.zst` and `.tar.zst`) uses the optional `zstd` executable, or full
`7z` **24.01 or newer**. Zstandard archives do not reliably expose an expanded
size in archive listings, so the staging supervisor is the protection for these
formats; its limits are best-effort, not strict disk quotas.

#### Ubuntu / Debian

```bash
sudo apt-get install p7zip p7zip-full unrar
sudo apt-get install p7zip p7zip-full unrar zstd
```

#### Fedora / RHEL / CentOS

```bash
sudo dnf install p7zip p7zip-plugins unrar
sudo dnf install p7zip p7zip-plugins unrar zstd
```

#### macOS

```bash
brew install p7zip
brew install p7zip zstd
```

## 📦 Installation
Expand Down Expand Up @@ -179,14 +182,19 @@ user data.
| Tar | `.tar` | `7za` |
| Tar + Gzip | `.tar.gz`, `.tgz` | `7za` |
| Tar + Bzip2 | `.tar.bz2`, `.tbz2` | `7za` |
| Tar + XZ | `.tar.xz`, `.txz` | `7za` (two-pass) |
| Zstandard | `.zst`, `.zstd` | `zstd` or full `7z` 24.01+ |
| Tar + Zstandard | `.tar.zst`, `.tar.zstd`, `.tzst` | `zstd` or full `7z` 24.01+, then `7za` |
| Gzip | `.gz` | `7za` |
| 7z | `.7z` | `7za` |
| Deb | `.deb` | `7za` |

On systems without the PHP `rar` extension or `unrar`, the full `7z`
executable can extract supported RAR archives as an additional fallback.
The smaller `7za` executable does not necessarily support RAR; on Debian 13,
install the `7zip` package to obtain the full decoder.
The smaller `7za` executable does not necessarily support RAR or Zstandard;
on Debian 13, install the `7zip` package to obtain the full decoder. For
Zstandard, installing the `zstd` command is sufficient and works even when
older full 7z versions cannot decode `.zst`.

> **Note:** Archives protected by a password are not supported. Extraction works
> on a normal Nextcloud data directory, on object storage and with server-side
Expand All @@ -196,9 +204,10 @@ install the `7zip` package to obtain the full decoder.

### External storage

Archives on an external storage are unpacked through a temporary folder in the
app's own data directory, then moved into place. If a previous run was
interrupted, that temporary folder is removed before the new extraction starts.
Archives on external and local storage are unpacked into a request-owned
temporary directory and imported through the Nextcloud files API. This avoids
cross-device renames and updates the file cache for the destination. Temporary
staging content is removed after the request, including on failure.

## 🛠️ Development

Expand Down Expand Up @@ -293,17 +302,19 @@ not introduce automatic release publishing.

The archive tool could not unpack the file. Common causes:

- **Tool missing**: for Rar archives install the PHP `rar` extension or the
`unrar` binary; for every other format install `p7zip` and `p7zip-full` and
check that `7za` is on the `PATH` of the web server user.
- **Tool missing**: for RAR install the PHP `rar` extension, `unrar`, or full
`7z`; for TAR, XZ, 7z, gzip, bzip2 and DEB install `p7zip-full` and check
that `7za` is on the web server user's `PATH`. For Zstandard install `zstd`
or full `7z` version 24.01 or newer.
- **Damaged or unreadable archive**: the file is truncated, corrupt, or not
actually an archive of that format.
- **Permissions**: the web server user cannot read the archive or write into the
target folder.
- **Insufficient space** on the volume holding the archive.

For a failed `7za` or `unrar` run the Nextcloud log records the exit code and the
tool output. Zip extraction and a missing tool are not logged with that detail.
For a failed external decoder, the Nextcloud log records the rejection reason
(for example a timeout, output limit or nonzero exit). To avoid unbounded
memory consumption, raw decoder output is not retained in extraction logs.

### "Unsupported archive type"

Expand All @@ -322,18 +333,17 @@ app like any other folder.
- **Server-side encryption enabled.** The encryption storage wrapper does the
same, because it has to decrypt to a temporary file first.

The app detects both through `Storage::isLocal()`. On local storage it keeps
unpacking the archive next to the original file, which avoids copying the
payload a second time.
Both local and non-local archives are staged separately and published through
Nextcloud's files API. The backend never unpacks into an untracked path next
to the original file.

If extraction used to report "Extraction is only supported on local storage" on
these setups, update to a version that includes the import step.

### A password-protected archive

Password-protected archives are not supported. Zip and the 7-Zip formats report
"Oops something went wrong."; Rar with the PHP `rar` extension is the exception,
because that path does not surface a failure.
Password-protected archives are not supported, including ZIP, 7z, and RAR.
An encrypted archive must not be reported as successfully extracted.

### Large archives

Expand Down
13 changes: 6 additions & 7 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@
* 7z
* Deb
* Bzip2
* Xz / tar.xz
* Zstandard / tar.zst

* **Requirements :**
* Rar PHP extension (pecl -v install rar)

* **OR**
* unrar (sudo apt-get install unrar)

* **AND**
* p7zip (sudo apt-get install p7zip p7zip-full)
* PHP zip extension for ZIP
* p7zip / p7zip-full (7za) for 7z, TAR, XZ, GZIP, BZIP2 and DEB
* PHP rar, unrar or full 7z for RAR
* zstd or full 7z (24.01+) for Zstandard

* **Note :** Password-protected archives are not supported yet. Object storage
and server-side encryption are supported: the archive is unpacked into a
Expand Down
2 changes: 2 additions & 0 deletions lib/Capabilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ final class Capabilities implements IPublicCapability {
'extract-tar-gz',
'extract-tar-bz2',
'extract-tar-xz',
'extract-zstd',
'extract-tar-zstd',
'extract-7z',
];

Expand Down
20 changes: 17 additions & 3 deletions lib/Controller/ExtractionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ final class ExtractionController extends AEnvironmentAwareController {
'application/x-bzip2' => 'other',
'application/x-deb' => 'other',
'application/x-compressed' => 'other',
'application/x-xz' => 'other',
'application/x-xz-compressed-tar' => 'other',
'application/zstd' => 'zstd',
'application/x-zstd' => 'zstd',
'application/x-zstd-compressed-tar' => 'zstd',
];

/**
Expand All @@ -64,7 +69,7 @@ final class ExtractionController extends AEnvironmentAwareController {
* expands it in a single pass, so treating it as wrapped would make the
* controller look for a second archive inside the extracted payload.
*/
private const WRAPPED_TARBALL_EXTENSIONS = ['tar.gz', 'tgz', 'tar.bz2', 'tbz', 'tbz2', 'tar.xz', 'txz'];
private const WRAPPED_TARBALL_EXTENSIONS = ['tar.gz', 'tgz', 'tar.bz2', 'tbz', 'tbz2', 'tar.xz', 'txz', 'tar.zst', 'tar.zstd', 'tzst'];

/** @var Folder */
private $userFolder;
Expand Down Expand Up @@ -176,12 +181,14 @@ private static function isUsableRelativeDestinationPath(string $path): bool {
* @param string $extractTo The local file-system path of the destination.
* @return array{code: 0|1, desc?: string}
*/
private function extractWrappedTarball(string $file, string $extractTo, ?int $availableBytes = null): array {
private function extractWrappedTarball(string $file, string $extractTo, ?int $availableBytes = null, bool $zstd = false, ?string $archiveName = null): array {
// A unique scratch directory: a predictable sibling name could collide
// with, and then delete, an unrelated folder in the same directory.
$scratch = $extractTo . '.unwrapped.' . bin2hex(random_bytes(8));

$response = $this->extractionService->extractOther($file, $scratch, $availableBytes);
$response = $zstd
? $this->extractionService->extractZstd($file, $scratch, $availableBytes, $archiveName)
: $this->extractionService->extractOther($file, $scratch, $availableBytes);
if (($response['code'] ?? 0) === 0) {
$this->removeDirectory($scratch);
return $response;
Expand Down Expand Up @@ -536,6 +543,13 @@ public function execute(
case 'rar':
$response = $this->extractionService->extractRar($file, $extractTo, $destinationParent->getFreeSpace());
break;
case 'zstd':
if (self::isWrappedTarball($nameOfFile)) {
$response = $this->extractWrappedTarball($file, $extractTo, $destinationParent->getFreeSpace(), true, $nameOfFile);
} else {
$response = $this->extractionService->extractZstd($file, $extractTo, $destinationParent->getFreeSpace(), $nameOfFile);
}
break;
default:
if (self::isWrappedTarball($nameOfFile) === true) {
$response = $this->extractWrappedTarball($file, $extractTo, $destinationParent->getFreeSpace());
Expand Down
54 changes: 54 additions & 0 deletions lib/Service/CliArchiveExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,60 @@ public function extractOther(string $file, string $extractTo, ?int $availableByt
return $this->runExternalDecoder(['7za', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes);
}

/**
* Zstandard is a single-file stream, not a multi-entry archive. The format
* does not require an uncompressed length in its header, so a declared-size
* preflight cannot reliably protect its output. Use the staging supervisor
* for both optional decoders and never let a temporary source basename
* decide the user-visible output filename.
*/
public function extractZstd(string $file, string $extractTo, ?int $availableBytes = null, ?string $archiveName = null): array {
$name = $archiveName ?? basename($file);
$targetName = preg_replace('/\.(?:zst|zstd)$/i', '', $name);
if (!is_string($targetName) || $targetName === '' || $targetName === '.' || $targetName === '..'
|| str_contains($targetName, '/') || str_contains($targetName, '\\')
|| preg_match('/[\x00-\x1f\x7f]/', $targetName) === 1 || preg_match('//u', $targetName) !== 1) {
return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')];
}

if ($this->isCommandAvailable('zstd')) {
if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) {
return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')];
}
return $this->runExternalDecoder(
['zstd', '-d', '-q', '-f', '-o', $extractTo . '/' . $targetName, '--', $file],
$extractTo,
$availableBytes,
);
}

if (!$this->isCommandAvailable('7z')) {
return ['code' => 0, 'desc' => $this->l->t('Zstandard extraction requires zstd or full 7z version 24.01 or newer')];
}
$listing = $this->listWithLimits(['7z', 'l', '-slt', $file]);
if ($listing === null || !in_array('Type = zstd', array_map('trim', $listing), true)) {
return ['code' => 0, 'desc' => $this->l->t('Could not inspect Zstandard archive with full 7z')];
}
$response = $this->runExternalDecoder(['7z', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes);
if ($response['code'] === 0) {
return $response;
}

// Full 7z names the output after the local archive copy. Rename the
// single decoded stream to the original Nextcloud filename when needed.
if (!is_dir($extractTo)) {
return ['code' => 0, 'desc' => $this->l->t('Could not extract archive')];
}
$entries = iterator_to_array(new \FilesystemIterator($extractTo, \FilesystemIterator::SKIP_DOTS), false);
if (count($entries) !== 1 || !$entries[0]->isFile() || $entries[0]->isLink()) {
return ['code' => 0, 'desc' => $this->l->t('Could not extract archive')];
}
if ($entries[0]->getFilename() !== $targetName && !rename($entries[0]->getPathname(), $extractTo . '/' . $targetName)) {
return ['code' => 0, 'desc' => $this->l->t('Could not prepare extracted filename')];
}
return $response;
}

private function assertSafeRarSevenZip(string $file): ?array {
$output = $this->listWithLimits(['7z', 'l', '-ba', '-slt', $file]);
if ($output === null) {
Expand Down
5 changes: 5 additions & 0 deletions lib/Service/ExtractionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,9 @@ public function extractRar(string $file, string $extractTo, ?int $availableBytes
public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array {
return $this->cli->extractOther($file, $extractTo, $availableBytes);
}

/** @return array{code: 0|1, desc?: string} */
public function extractZstd(string $file, string $extractTo, ?int $availableBytes = null, ?string $archiveName = null): array {
return $this->cli->extractZstd($file, $extractTo, $availableBytes, $archiveName);
}
}
25 changes: 23 additions & 2 deletions src/actions/extract-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { ActionContext, ActionContextSingle, IFileAction, IFolder, INode }
import ArchiveArrowUpSvg from '@mdi/svg/svg/archive-arrow-up.svg?raw'
import axios from '@nextcloud/axios'
import { emit } from '@nextcloud/event-bus'
import { Folder, Permission, registerFileAction } from '@nextcloud/files'
import { FileType, Folder, Permission, registerFileAction } from '@nextcloud/files'
import { translate as t } from '@nextcloud/l10n'
import { generateOcsUrl } from '@nextcloud/router'
import { createApp } from 'vue'
Expand All @@ -32,6 +32,11 @@ export const SUPPORTED_ARCHIVE_MIME_TYPES = [
'application/x-bzip2',
'application/x-deb',
'application/x-compressed',
'application/x-xz',
'application/x-xz-compressed-tar',
'application/zstd',
'application/x-zstd',
'application/x-zstd-compressed-tar',
]

interface ExtractedFolder {
Expand Down Expand Up @@ -75,7 +80,22 @@ function archiveMimeOf(node: INode): string | undefined {
if (mime !== '' && mime !== 'application/octet-stream') {
return mime
}
return node.attributes?.getcontenttype as string | undefined
const davMime = node.attributes?.getcontenttype as string | undefined
if (davMime && davMime !== 'application/octet-stream') {
return davMime
}

// Nextcloud 33–35 may classify XZ archives as octet-stream, leaving the
// Files action hidden despite a working server decoder. Infer only these
// known extensions when both reported MIME values are unspecified.
const fileName = node.basename.toLowerCase()
if (fileName.endsWith('.tar.xz') || fileName.endsWith('.txz') || fileName.endsWith('.xz')) {
return 'application/x-xz'
}
if (fileName.endsWith('.zst') || fileName.endsWith('.zstd') || fileName.endsWith('.tzst')) {
return 'application/zstd'
}
return undefined
}

/**
Expand Down Expand Up @@ -200,6 +220,7 @@ function isEnabled(context: ActionContext): boolean {

const [node] = context.nodes
return node !== undefined
&& node.type === FileType.File
&& isSupportedArchive(node)
&& (node.permissions & Permission.READ) !== 0
&& (context.folder.permissions & Permission.CREATE) !== 0
Expand Down
Binary file added tests/Fixtures/valid.tar.xz
Binary file not shown.
Binary file added tests/Fixtures/valid.tar.zst
Binary file not shown.
Binary file added tests/Fixtures/valid.zst
Binary file not shown.
Loading
Loading