Skip to content

Commit fe03b81

Browse files
committed
feat(zip): windows and linux support
Windows: managed C# engine (platforms/windows/src/ZipArchiver.cs) on .NET DeflateStream and BCL cryptography, running off the JS thread. Linux: native engine (platforms/linux) on a vendored, pinned minizip-ng 4.2.2 with system zlib, GLib and OpenSSL libcrypto. Work runs on a GThread and reports progress/completion on the GLib main context. Both stream data (constant memory, ZIP64), write WinZip AES-256 when a password is given, read AES and ZipCrypto archives, and extract into temporary files that are only moved into place after the size, CRC and AES authentication checks pass.
1 parent 6a2496f commit fe03b81

35 files changed

Lines changed: 10647 additions & 3 deletions

‎packages/zip/README.md‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ A plugin to zip and unzip files.
1111
* [Zip a folder](#zip-a-folder)
1212
* [Get zip request progress](#get-zip-request-progress)
1313
* [Get unzip request progress](#get-unzip-request-progress)
14+
* [Platform notes](#platform-notes)
1415
* [API](#api)
1516
* [Zip class](#zip-class)
1617
* [debugEnabled](#debugenabled)
@@ -113,6 +114,29 @@ function onUnZipProgress(percent: number) {
113114
}
114115
```
115116

117+
## Platform notes
118+
119+
Supported on iOS, macOS, Android, Windows and Linux.
120+
121+
**Windows** uses a built-in C# engine, compiled into the app, that relies on .NET's `DeflateStream` and cryptography APIs. It needs no extra dependencies.
122+
123+
**Linux** uses a bundled, pinned copy of [minizip-ng](https://github.com/zlib-ng/minizip-ng), linked against the system zlib, GLib and OpenSSL (`libcrypto`). These are part of the base system on current desktop distributions, so end users don't need to install anything. Building an app that uses this plugin requires the OpenSSL development headers:
124+
125+
```bash
126+
sudo apt install libssl-dev # Debian / Ubuntu / Pop!_OS
127+
sudo dnf install openssl-devel # Fedora
128+
```
129+
130+
On both platforms:
131+
132+
- **Background work:** zipping and unzipping run on a background thread and stream data, so memory use doesn't depend on archive or file size. Archives over 4 GB (ZIP64) are supported.
133+
- **Passwords:**
134+
- Archives created with a `password` use WinZip AES-256 encryption, the same as iOS and Android.
135+
- When unzipping, both AES and legacy ZipCrypto archives are supported, and AES entries are authenticated.
136+
- **Extraction safety:**
137+
- Entries that would land outside the destination folder are skipped, and so are symbolic links.
138+
- Each file is written to a temporary file first and only moved into place after it has been verified, so a failed extraction never replaces an existing file.
139+
116140
## API
117141

118142
### Zip class
@@ -163,7 +187,7 @@ Extracts all the files from the zip file specified in the `archive` property of
163187
| `directory` | `string`| _Optional_: The path to extract the files to.
164188
| `archive` | `string` | _Optional_: The path of the zip file.
165189
| `onProgress` | `(progress: number) => void` | _Optional_: Unzip request progress listener.
166-
| `overwrite`| `boolean` | _Optional_: (`iOS-only`)
190+
| `overwrite`| `boolean` | _Optional_: Overwrite existing files (default `true`). Supported on iOS, macOS, Windows and Linux.
167191
| `password`| `string` | _Optional_: The password used to protect the zip file.
168192

169193
## License

‎packages/zip/index.linux.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { Folder, File, path, knownFolders } from '@nativescript/core';
2+
import { UnZipOptions, ZipOptions } from '.';
3+
4+
declare function nszip_zip(directory: string, archive: string, keepParent: number, password: string | null, progress: interop.Pointer, complete: interop.Pointer): void;
5+
declare function nszip_unzip(archive: string, destination: string, overwrite: number, password: string | null, progress: interop.Pointer, complete: interop.Pointer): void;
6+
declare const nativescript: { ref(): void; unref(): void };
7+
8+
function uuid(): string {
9+
return (globalThis as any).crypto?.randomUUID?.() ?? `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;
10+
}
11+
12+
function run(onProgress: ((percent: number) => void) | undefined, start: (progress: interop.Pointer, complete: interop.Pointer) => void): Promise<void> {
13+
return new Promise((resolve, reject) => {
14+
const native: any = interop;
15+
const progressFn = (percent: number) => {
16+
if (typeof onProgress === 'function') {
17+
onProgress(percent);
18+
}
19+
};
20+
const completeFn = (error: any) => {
21+
const failure = error ? native.stringFromCString(error) : null;
22+
setTimeout(() => {
23+
native.release(progressFn);
24+
native.release(completeFn);
25+
nativescript.unref();
26+
});
27+
if (failure) {
28+
reject(failure);
29+
} else {
30+
resolve();
31+
}
32+
};
33+
const progressPtr = native.callback(progressFn, { returns: native.types.void, args: [native.types.int32] });
34+
const completePtr = native.callback(completeFn, { returns: native.types.void, args: [native.types.pointer] });
35+
nativescript.ref();
36+
start(progressPtr, completePtr);
37+
});
38+
}
39+
40+
export class Zip {
41+
static debugEnabled = false;
42+
43+
private static debug(arg) {
44+
if (this.debugEnabled && console && console.log) {
45+
console.log(arg);
46+
}
47+
}
48+
49+
public static zip(options: ZipOptions): Promise<string> {
50+
if (!options?.directory || !Folder.exists(options.directory)) {
51+
return Promise.reject('Directory does not exist, invalid directory path: ' + options?.directory);
52+
}
53+
const archive = options.archive ?? path.join(knownFolders.temp().path, `${uuid()}_archive.zip`);
54+
const keepParent = (options.keepParent ?? true) ? 1 : 0;
55+
this.debug('Zip.zip - folder=' + options.directory + '\n' + 'Zip.zip - destinationPath=' + archive);
56+
return run(options.onProgress, (progress, complete) => nszip_zip(options.directory, archive, keepParent, options.password || null, progress, complete)).then(() => archive);
57+
}
58+
59+
public static unzip(options: UnZipOptions): Promise<any> {
60+
if (!options?.archive || !File.exists(options.archive)) {
61+
return Promise.reject(`File does not exist, invalid archive path: ${options?.archive}`);
62+
}
63+
const destination = options.directory ?? path.join(knownFolders.temp().path, uuid());
64+
const overwrite = (options.overwrite ?? true) ? 1 : 0;
65+
this.debug(`Zip.unzip - archive=${options.archive}`);
66+
return run(options.onProgress, (progress, complete) => nszip_unzip(options.archive, destination, overwrite, options.password || null, progress, complete)).then(() => destination);
67+
}
68+
}

‎packages/zip/index.windows.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { Folder, File, path, knownFolders } from '@nativescript/core';
2+
import { UnZipOptions, ZipOptions } from '.';
3+
4+
declare const NativeScriptZip: any;
5+
declare const NSWinRT: any;
6+
7+
function uuid(): string {
8+
return (globalThis as any).crypto?.randomUUID?.() ?? `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;
9+
}
10+
11+
function message(e: any): string {
12+
return typeof e === 'string' ? e : (e?.message ?? String(e));
13+
}
14+
15+
function progress(options: { onProgress?: (progress: number) => void }) {
16+
return (percent: number) => {
17+
if (typeof options.onProgress === 'function') {
18+
options.onProgress(percent);
19+
}
20+
};
21+
}
22+
23+
export class Zip {
24+
static debugEnabled = false;
25+
26+
private static debug(arg) {
27+
if (this.debugEnabled && console && console.log) {
28+
console.log(arg);
29+
}
30+
}
31+
32+
public static zip(options: ZipOptions): Promise<string> {
33+
if (!options?.directory || !Folder.exists(options.directory)) {
34+
return Promise.reject('Directory does not exist, invalid directory path: ' + options?.directory);
35+
}
36+
const archive = options.archive ?? path.join(knownFolders.temp().path, `${uuid()}_archive.zip`);
37+
this.debug('Zip.zip - folder=' + options.directory + '\n' + 'Zip.zip - destinationPath=' + archive);
38+
const task = NativeScriptZip.ZipArchiver.ZipAsync(options.directory, archive, options.keepParent ?? true, options.password ?? '', progress(options));
39+
return NSWinRT.dotnet.taskToPromise(task).then(
40+
() => archive,
41+
(e) => Promise.reject(message(e)),
42+
);
43+
}
44+
45+
public static unzip(options: UnZipOptions): Promise<any> {
46+
if (!options?.archive || !File.exists(options.archive)) {
47+
return Promise.reject(`File does not exist, invalid archive path: ${options?.archive}`);
48+
}
49+
const destination = options.directory ?? path.join(knownFolders.temp().path, uuid());
50+
this.debug(`Zip.unzip - archive=${options.archive}`);
51+
const task = NativeScriptZip.ZipArchiver.UnzipAsync(options.archive, destination, options.overwrite ?? true, options.password ?? '', progress(options));
52+
return NSWinRT.dotnet.taskToPromise(task).then(
53+
() => destination,
54+
(e) => Promise.reject(message(e)),
55+
);
56+
}
57+
}

‎packages/zip/package.json‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
"platforms": {
99
"ios": "6.0.0",
1010
"macos": "6.0.0",
11-
"android": "6.0.0"
11+
"android": "6.0.0",
12+
"windows": "9.1.0",
13+
"linux": "0.1.0-alpha.2"
1214
}
1315
},
1416
"repository": {
@@ -21,7 +23,9 @@
2123
"TypeScript",
2224
"iOS",
2325
"macOS",
24-
"Android"
26+
"Android",
27+
"Windows",
28+
"Linux"
2529
],
2630
"author": {
2731
"name": "NativeScript",
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#ifndef NSZIP_H
2+
#define NSZIP_H
3+
4+
#include <stdint.h>
5+
6+
#if defined(__GNUC__)
7+
#define NSZIP_EXPORT __attribute__((visibility("default")))
8+
#else
9+
#define NSZIP_EXPORT
10+
#endif
11+
12+
#ifdef __cplusplus
13+
extern "C" {
14+
#endif
15+
16+
typedef void (*nszip_progress_callback)(int32_t percent);
17+
18+
typedef void (*nszip_complete_callback)(const char *error);
19+
20+
NSZIP_EXPORT void nszip_zip(const char *directory, const char *archive, int32_t keep_parent, const char *password, nszip_progress_callback progress, nszip_complete_callback complete);
21+
22+
NSZIP_EXPORT void nszip_unzip(const char *archive, const char *destination, int32_t overwrite, const char *password, nszip_progress_callback progress, nszip_complete_callback complete);
23+
24+
#ifdef __cplusplus
25+
}
26+
#endif
27+
28+
#endif
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"pkg-config": ["zlib", "glib-2.0", "libcrypto"],
3+
"cflags": ["-O2", "-std=gnu11", "-fvisibility=hidden", "-Wno-deprecated-declarations", "-DHAVE_ZLIB", "-DZLIB_COMPAT", "-DHAVE_PKCRYPT", "-DHAVE_WZAES", "-DHAVE_GETRANDOM", "-D_POSIX_C_SOURCE=200809L", "-D_DEFAULT_SOURCE", "-D_BSD_SOURCE"]
4+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Condition of use and distribution are the same as zlib:
2+
3+
This software is provided 'as-is', without any express or implied
4+
warranty. In no event will the authors be held liable for any damages
5+
arising from the use of this software.
6+
7+
Permission is granted to anyone to use this software for any purpose,
8+
including commercial applications, and to alter it and redistribute it
9+
freely, subject to the following restrictions:
10+
11+
1. The origin of this software must not be misrepresented; you must not
12+
claim that you wrote the original software. If you use this software
13+
in a product, an acknowledgement in the product documentation would be
14+
appreciated but is not required.
15+
2. Altered source versions must be plainly marked as such, and must not be
16+
misrepresented as being the original software.
17+
3. This notice may not be removed or altered from any source distribution.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
minizip-ng 4.2.2 (https://github.com/zlib-ng/minizip-ng/releases/tag/4.2.2), zlib license (see LICENSE).
2+
3+
Only the sources for zlib + OpenSSL + PKWARE/WinZip AES encryption are included; `mz_config.h` replaces the CMake-generated header.
4+
5+
Local changes:
6+
- `mz_zip.c`: `mz_zip_entry_read_close` also closes the WinZip AES stream.
7+
- `mz_crypt_openssl.c`: `openssl/engine.h` is only included for OpenSSL < 1.1 (it is absent on systems built without the ENGINE API).

0 commit comments

Comments
 (0)