Files
cloudron-box/src/shell.js

137 lines
5.0 KiB
JavaScript
Raw Normal View History

'use strict';
2021-05-12 17:30:29 -07:00
const assert = require('assert'),
BoxError = require('./boxerror.js'),
child_process = require('child_process'),
2016-08-30 21:33:56 -07:00
debug = require('debug')('box:shell'),
path = require('path'),
_ = require('./underscore.js');
exports = module.exports = shell;
function shell(tag) {
assert.strictEqual(typeof tag, 'string');
return {
2024-10-16 10:25:07 +02:00
bash: bash.bind(null, tag),
spawn: spawn.bind(null, tag),
sudo: sudo.bind(null, tag),
};
}
const SUDO = '/usr/bin/sudo';
const KILL_CHILD_CMD = path.join(__dirname, 'scripts/kill-child.sh');
2024-11-18 07:59:05 +05:30
function lineCount(buffer) {
assert(Buffer.isBuffer(buffer));
const NEW_LINE = Buffer.from('\n');
let index = buffer.indexOf(NEW_LINE);
let count = 0;
while (index >= 0) {
index = buffer.indexOf(NEW_LINE, index+1);
++count;
}
return count;
}
function spawn(tag, file, args, options) {
2024-02-21 13:09:59 +01:00
assert.strictEqual(typeof tag, 'string');
assert.strictEqual(typeof file, 'string');
assert(Array.isArray(args));
2024-10-16 10:25:07 +02:00
assert.strictEqual(typeof options, 'object'); // note: spawn() has no encoding option of it's own
2024-02-21 13:09:59 +01:00
2024-10-16 10:25:07 +02:00
debug(`${tag}: ${file} ${args.join(' ').replace(/\n/g, '\\n')}`);
2024-11-18 07:59:05 +05:30
const maxLines = options.maxLines || Number.MAX_SAFE_INTEGER;
const logger = options.logger || null;
const signal = options.signal || null; // note: we use our own handler and not the child_process one
2024-11-18 07:59:05 +05:30
2024-02-21 19:40:27 +01:00
return new Promise((resolve, reject) => {
const spawnOptions = _.omit(options, [ 'maxLines', 'logger', 'signal', 'onMessage', 'input', 'encoding' ]);
const cp = child_process.spawn(file, args, spawnOptions);
const stdoutBuffers = [], stderrBuffers = [];
2024-11-18 07:59:05 +05:30
let stdoutLineCount = 0, stderrLineCount = 0;
2024-02-21 19:40:27 +01:00
2024-11-18 07:59:05 +05:30
cp.stdout.on('data', (data) => {
if (logger) return logger(data);
2024-11-18 07:59:05 +05:30
stdoutBuffers.push(data);
stdoutLineCount += lineCount(data);
if (stdoutLineCount >= maxLines) return cp.kill('SIGKILL');
});
cp.stderr.on('data', (data) => {
if (logger) return logger(data);
2024-11-18 07:59:05 +05:30
stderrBuffers.push(data);
stderrLineCount += lineCount(data);
if (stderrLineCount >= maxLines) return cp.kill('SIGKILL');
});
cp.on('close', function (code, signal) { // always called. after 'exit' or 'error'
const stdoutBuffer = Buffer.concat(stdoutBuffers);
const stdout = options.encoding ? stdoutBuffer.toString(options.encoding) : stdoutBuffer;
if (code === 0) return resolve(stdout);
const stderrBuffer = Buffer.concat(stderrBuffers);
const stderr = options.encoding ? stderrBuffer.toString(options.encoding) : stderrBuffer;
const e = new BoxError(BoxError.SHELL_ERROR, `${file} exited with code ${code} signal ${signal}`);
2024-02-21 13:09:59 +01:00
e.stdout = stdout; // when promisified, this is the way to get stdout
2024-11-18 07:59:05 +05:30
e.stdoutLineCount = stdoutLineCount;
2024-02-21 13:09:59 +01:00
e.stderr = stderr; // when promisified, this is the way to get stderr
2024-11-18 07:59:05 +05:30
e.stderrLineCount = stderrLineCount;
e.code = code;
e.signal = signal;
debug(`${tag}: ${file} ${args.join(' ').replace(/\n/g, '\\n')} errored`, e);
2024-02-21 19:40:27 +01:00
reject(e);
});
2024-02-21 13:09:59 +01:00
cp.on('error', function (error) { // when the command itself could not be started
debug(`${tag}: ${file} ${args.join(' ').replace(/\n/g, '\\n')} errored`, error);
});
signal?.addEventListener('abort', () => {
2025-07-17 02:04:50 +02:00
debug(`${tag}: aborting ${cp.pid}`);
child_process.execFile('/usr/bin/sudo', [ KILL_CHILD_CMD, cp.pid, process.pid ], { encoding: 'utf8' }, (error, stdout, stderr) => {
if (error) debug(`${tag}: failed to kill children`, stdout, stderr);
2025-07-17 02:04:50 +02:00
else debug(`${tag}: aborted ${cp.pid}`, stdout, stderr);
});
}, { once: true });
if (options.onMessage) cp.on('message', options.onMessage); // ipc mode messages
2024-02-21 19:40:27 +01:00
// https://github.com/nodejs/node/issues/25231
if ('input' in options) { // when empty, just closes
2024-02-21 19:40:27 +01:00
cp.stdin.write(options.input);
cp.stdin.end();
}
2024-02-21 13:09:59 +01:00
});
}
2024-10-16 10:25:07 +02:00
async function bash(tag, script, options) {
assert.strictEqual(typeof tag, 'string');
2024-10-16 10:25:07 +02:00
assert.strictEqual(typeof script, 'string');
assert.strictEqual(typeof options, 'object');
2024-10-16 10:25:07 +02:00
return await spawn(tag, '/bin/bash', [ '-c', script ], options);
}
async function sudo(tag, args, options) {
assert.strictEqual(typeof tag, 'string');
assert(Array.isArray(args));
assert.strictEqual(typeof options, 'object');
const sudoArgs = [];
if (options.preserveEnv) sudoArgs.push('-E'); // -E preserves environment
if (options.onMessage) { // enable ipc
sudoArgs.push('--close-from=4'); // keep the ipc open. requires closefrom_override in sudoers file
options.stdio = ['pipe', 'pipe', 'pipe', 'ipc'];
}
const spawnArgs = [ ...sudoArgs, ...args ];
return await spawn(tag, SUDO, spawnArgs, options);
}