-
Notifications
You must be signed in to change notification settings - Fork 959
Expand file tree
/
Copy pathTerminal.js
More file actions
445 lines (382 loc) · 17.7 KB
/
Terminal.js
File metadata and controls
445 lines (382 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
const Executor = require("./Executor");
const Terminal = {
/**
* Starts the AXS environment by writing init scripts and executing the sandbox.
* @param {boolean} [installing=false] - Whether AXS is being started during installation.
* @param {Function} [logger=console.log] - Function to log standard output.
* @param {Function} [err_logger=console.error] - Function to log errors.
* @returns {Promise<boolean>} - Returns true if installation completes with exit code 0, void if not installing
*/
async startAxs(installing = false, logger = console.log, err_logger = console.error) {
const filesDir = await new Promise((resolve, reject) => {
system.getFilesDir(resolve, reject);
});
if (installing) {
return new Promise((resolve, reject) => {
readAsset("init-alpine.sh", async (content) => {
system.writeText(`${filesDir}/init-alpine.sh`, content, logger, err_logger);
});
readAsset("init-sandbox.sh", (content) => {
system.writeText(`${filesDir}/init-sandbox.sh`, content, logger, err_logger);
Executor.start("sh", (type, data) => {
logger(`${type} ${data}`);
// Check for exit code during installation
if (type === "exit") {
resolve(data === "0");
}
}).then(async (uuid) => {
await Executor.write(uuid, `source ${filesDir}/init-sandbox.sh ${installing ? "--installing" : ""}; exit`);
}).catch((error) => {
err_logger("Failed to start AXS:", error);
resolve(false);
});
});
});
} else {
readAsset("init-alpine.sh", async (content) => {
system.writeText(`${filesDir}/init-alpine.sh`, content, logger, err_logger);
});
readAsset("init-sandbox.sh", (content) => {
system.writeText(`${filesDir}/init-sandbox.sh`, content, logger, err_logger);
Executor.start("sh", (type, data) => {
logger(`${type} ${data}`);
}).then(async (uuid) => {
await Executor.write(uuid, `source ${filesDir}/init-sandbox.sh ${installing ? "--installing" : ""}; exit`);
});
});
}
},
/**
* Stops the AXS process by forcefully killing it.
* @returns {Promise<void>}
*/
async stopAxs() {
await Executor.execute(`kill -KILL $(cat $PREFIX/pid)`);
},
/**
* Checks if the AXS process is currently running.
* @returns {Promise<boolean>} - `true` if AXS is running, `false` otherwise.
*/
async isAxsRunning() {
const filesDir = await new Promise((resolve, reject) => {
system.getFilesDir(resolve, reject);
});
const pidExists = await new Promise((resolve, reject) => {
system.fileExists(`${filesDir}/pid`, false, (result) => {
resolve(result == 1);
}, reject);
});
if (!pidExists) return false;
const result = await Executor.execute(`kill -0 $(cat $PREFIX/pid) 2>/dev/null && echo "true" || echo "false"`);
return String(result).toLowerCase() === "true";
},
/**
* Installs Alpine by downloading binaries and extracting the root filesystem.
* Also sets up additional dependencies for F-Droid variant.
* @param {Function} [logger=console.log] - Function to log standard output.
* @param {Function} [err_logger=console.error] - Function to log errors.
* @returns {Promise<boolean>} - Returns true if installation completes with exit code 0
*/
async install(logger = console.log, err_logger = console.error) {
if (!(await this.isSupported())) return false;
try {
//cleanup before insatll
await this.uninstall();
} catch (e) {
//supress error
}
const filesDir = await new Promise((resolve, reject) => {
system.getFilesDir(resolve, reject);
});
const arch = await new Promise((resolve, reject) => {
system.getArch(resolve, reject);
});
try {
let alpineUrl;
let axsUrl;
let prootUrl;
let libTalloc;
let libproot = null;
let libproot32 = null;
if (arch === "arm64-v8a") {
libproot = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libproot.so";
libproot32 = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libproot32.so";
libTalloc = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libtalloc.so";
prootUrl = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm64/libproot-xed.so";
axsUrl = `https://github.com/bajrangCoder/acodex_server/releases/latest/download/axs-musl-android-arm64`;
alpineUrl = "https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/aarch64/alpine-minirootfs-3.21.0-aarch64.tar.gz";
} else if (arch === "armeabi-v7a") {
libproot = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm32/libproot.so";
libTalloc = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm32/libtalloc.so";
prootUrl = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/arm32/libproot-xed.so";
axsUrl = `https://github.com/bajrangCoder/acodex_server/releases/latest/download/axs-musl-android-armv7`;
alpineUrl = "https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/armhf/alpine-minirootfs-3.21.0-armhf.tar.gz";
} else if (arch === "x86_64") {
libproot = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libproot.so";
libproot32 = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libproot32.so";
libTalloc = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libtalloc.so";
prootUrl = "https://raw.githubusercontent.com/Acode-Foundation/Acode/main/src/plugins/proot/libs/x64/libproot-xed.so";
axsUrl = `https://github.com/bajrangCoder/acodex_server/releases/latest/download/axs-musl-android-x86_64`;
alpineUrl = "https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/x86_64/alpine-minirootfs-3.21.0-x86_64.tar.gz";
} else {
throw new Error(`Unsupported architecture: ${arch}`);
}
logger("⬇️ Downloading sandbox filesystem...");
await new Promise((resolve, reject) => {
cordova.plugin.http.downloadFile(
alpineUrl, {}, {},
cordova.file.dataDirectory + "alpine.tar.gz",
resolve, reject
);
});
logger("⬇️ Downloading axs...");
await new Promise((resolve, reject) => {
cordova.plugin.http.downloadFile(
axsUrl, {}, {},
cordova.file.dataDirectory + "axs",
resolve, reject
);
});
const isFdroid = await Executor.execute("echo $FDROID");
if (isFdroid === "true") {
logger("🐧 F-Droid flavor detected, downloading additional files...");
logger("⬇️ Downloading compatibility layer...");
await new Promise((resolve, reject) => {
cordova.plugin.http.downloadFile(
prootUrl, {}, {},
cordova.file.dataDirectory + "libproot-xed.so",
resolve, reject
);
});
logger("⬇️ Downloading supporting library...");
await new Promise((resolve, reject) => {
cordova.plugin.http.downloadFile(
libTalloc, {}, {},
cordova.file.dataDirectory + "libtalloc.so.2",
resolve, reject
);
});
if (libproot != null) {
await new Promise((resolve, reject) => {
cordova.plugin.http.downloadFile(
libproot, {}, {},
cordova.file.dataDirectory + "libproot.so",
resolve, reject
);
});
}
if (libproot32 != null) {
await new Promise((resolve, reject) => {
cordova.plugin.http.downloadFile(
libproot32, {}, {},
cordova.file.dataDirectory + "libproot32.so",
resolve, reject
);
});
}
}
logger("✅ All downloads completed");
logger("📁 Setting up directories...");
await new Promise((resolve, reject) => {
system.mkdirs(`${filesDir}/.downloaded`, resolve, reject);
});
const alpineDir = `${filesDir}/alpine`;
await new Promise((resolve, reject) => {
system.mkdirs(alpineDir, resolve, reject);
});
logger("📦 Extracting sandbox filesystem...");
await Executor.execute(`tar --no-same-owner -xf ${filesDir}/alpine.tar.gz -C ${alpineDir}`);
logger("⚙️ Applying basic configuration...");
system.writeText(`${alpineDir}/etc/resolv.conf`, `nameserver 8.8.4.4 \nnameserver 8.8.8.8`);
logger("✅ Extraction complete");
await new Promise((resolve, reject) => {
system.mkdirs(`${filesDir}/.extracted`, resolve, reject);
});
logger("⚙️ Updating sandbox enviroment...");
const installResult = await this.startAxs(true, logger, err_logger);
return installResult;
} catch (e) {
err_logger("Installation failed:", e);
console.error("Installation failed:", e);
return false;
}
},
/**
* Checks if alpine is already installed.
* @returns {Promise<boolean>} - Returns true if all required files and directories exist.
*/
isInstalled() {
return new Promise(async (resolve, reject) => {
const filesDir = await new Promise((resolve, reject) => {
system.getFilesDir(resolve, reject);
});
const alpineExists = await new Promise((resolve, reject) => {
system.fileExists(`${filesDir}/alpine`, false, (result) => {
resolve(result == 1);
}, reject);
});
const downloaded = alpineExists && await new Promise((resolve, reject) => {
system.fileExists(`${filesDir}/.downloaded`, false, (result) => {
resolve(result == 1);
}, reject);
});
const extracted = alpineExists && await new Promise((resolve, reject) => {
system.fileExists(`${filesDir}/.extracted`, false, (result) => {
resolve(result == 1);
}, reject);
});
const configured = alpineExists && await new Promise((resolve, reject) => {
system.fileExists(`${filesDir}/.configured`, false, (result) => {
resolve(result == 1);
}, reject);
});
resolve(alpineExists && downloaded && extracted && configured);
});
},
/**
* Checks if the current device architecture is supported.
* @returns {Promise<boolean>} - `true` if architecture is supported, otherwise `false`.
*/
isSupported() {
return new Promise((resolve, reject) => {
system.getArch((arch) => {
resolve(["arm64-v8a", "armeabi-v7a", "x86_64"].includes(arch));
}, reject);
});
},
/**
* Creates a backup of the Alpine Linux installation
* @async
* @function backup
* @description Creates a compressed tar archive of the Alpine installation
* @returns {Promise<string>} Promise that resolves to the file URI of the created backup file (aterm_backup.tar)
* @throws {string} Rejects with "Alpine is not installed." if Alpine is not currently installed
* @throws {string} Rejects with command output if backup creation fails
* @example
* try {
* const backupPath = await backup();
* console.log(`Backup created at: ${backupPath}`);
* } catch (error) {
* console.error(`Backup failed: ${error}`);
* }
*/
backup() {
return new Promise(async (resolve, reject) => {
if (!await this.isInstalled()) {
reject("Alpine is not installed.");
return;
}
const cmd = `
set -e
INCLUDE_FILES="alpine .downloaded .extracted axs"
if [ "$FDROID" = "true" ]; then
INCLUDE_FILES="$INCLUDE_FILES libtalloc.so.2 libproot-xed.so"
fi
EXCLUDE="--exclude=alpine/data --exclude=alpine/system --exclude=alpine/vendor --exclude=alpine/sdcard --exclude=alpine/storage --exclude=alpine/public"
tar -cf "$PREFIX/aterm_backup.tar" -C "$PREFIX" $EXCLUDE $INCLUDE_FILES
echo "ok"
`;
const result = await Executor.execute(cmd);
if (result === "ok") {
resolve(cordova.file.dataDirectory + "aterm_backup.tar");
} else {
reject(result);
}
});
},
/**
* Restores Alpine Linux installation from a backup file
* @async
* @function restore
* @description Restores the Alpine installation from a previously created backup file (aterm_backup.tar).
* This function stops any running Alpine processes, removes existing installation files, and extracts
* the backup to restore the previous state. The backup file must exist in the expected location.
* @returns {Promise<string>} Promise that resolves to "ok" when restoration completes successfully
* @throws {string} Rejects with "Backup File does not exist" if aterm_backup.tar is not found
* @throws {string} Rejects with command output if restoration fails
* @example
* try {
* await restore();
* console.log("Alpine installation restored successfully");
* } catch (error) {
* console.error(`Restore failed: ${error}`);
* }
*/
restore() {
return new Promise(async (resolve, reject) => {
if (await this.isAxsRunning()) {
await this.stopAxs();
}
const cmd = `
sleep 2
INCLUDE_FILES="$PREFIX/alpine $PREFIX/.downloaded $PREFIX/.extracted $PREFIX/axs"
if [ "$FDROID" = "true" ]; then
INCLUDE_FILES="$INCLUDE_FILES $PREFIX/libtalloc.so.2 $PREFIX/libproot-xed.so"
fi
for item in $INCLUDE_FILES; do
rm -rf -- "$item"
done
tar -xf "$PREFIX/aterm_backup.bin" -C "$PREFIX"
echo "ok"
`;
const result = await Executor.execute(cmd);
if (result === "ok") {
resolve(result);
} else {
reject(result);
}
});
},
/**
* Uninstalls the Alpine Linux installation
* @async
* @function uninstall
* @description Completely removes the Alpine Linux installation from the device by deleting all
* Alpine-related files and directories. This function stops any running Alpine processes before
* removal. NOTE: This does not perform cleanup of $PREFIX
* @returns {Promise<string>} Promise that resolves to "ok" when uninstallation completes successfully
* @throws {string} Rejects with command output if uninstallation fails
* @example
* try {
* await uninstall();
* console.log("Alpine installation removed successfully");
* } catch (error) {
* console.error(`Uninstall failed: ${error}`);
* }
*/
uninstall() {
return new Promise(async (resolve, reject) => {
if (await this.isAxsRunning()) {
await this.stopAxs();
}
const cmd = `
set -e
INCLUDE_FILES="$PREFIX/alpine $PREFIX/.downloaded $PREFIX/.extracted $PREFIX/axs"
if [ "$FDROID" = "true" ]; then
INCLUDE_FILES="$INCLUDE_FILES $PREFIX/libtalloc.so.2 $PREFIX/libproot-xed.so"
fi
for item in $INCLUDE_FILES; do
rm -rf -- "$item"
done
echo "ok"
`;
const result = await Executor.execute(cmd);
if (result === "ok") {
resolve(result);
} else {
reject(result);
}
});
}
};
function readAsset(assetPath, callback) {
const assetUrl = "file:///android_asset/" + assetPath;
window.resolveLocalFileSystemURL(assetUrl, fileEntry => {
fileEntry.file(file => {
const reader = new FileReader();
reader.onloadend = () => callback(reader.result);
reader.readAsText(file);
}, console.error);
}, console.error);
}
module.exports = Terminal;