Files
cloudron-box/src/storage/filesystem.js

354 lines
16 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
setup,
teardown,
cleanup,
verifyConfig,
removePrivateFields,
injectPrivateFields,
getAvailableSize,
upload,
download,
copy,
exists,
listDir,
2018-07-27 14:29:07 -07:00
remove,
removeDir,
};
2021-05-17 15:58:38 -07:00
const assert = require('assert'),
2019-10-22 20:36:20 -07:00
BoxError = require('../boxerror.js'),
2021-05-17 15:58:38 -07:00
constants = require('../constants.js'),
debug = require('debug')('box:storage/filesystem'),
df = require('../df.js'),
fs = require('fs'),
mounts = require('../mounts.js'),
2017-04-18 15:32:59 +02:00
path = require('path'),
2020-12-01 12:11:55 -08:00
paths = require('../paths.js'),
safe = require('safetydance'),
shell = require('../shell.js')('filesystem'),
_ = require('../underscore.js');
async function getAvailableSize(config) {
assert.strictEqual(typeof config, 'object');
// note that df returns the disk size (as opposed to the apparent size)
const [error, dfResult] = await safe(df.file(config.rootPath));
if (error) throw new BoxError(BoxError.FS_ERROR, `Error when checking for disk space: ${error.message}`);
return dfResult.available;
}
function hasChownSupportSync(config) {
switch (config.provider) {
case mounts.MOUNT_TYPE_NFS:
case mounts.MOUNT_TYPE_EXT4:
case mounts.MOUNT_TYPE_XFS:
case mounts.MOUNT_TYPE_DISK:
case mounts.MOUNT_TYPE_FILESYSTEM:
return true;
case mounts.MOUNT_TYPE_SSHFS:
// sshfs can be mounted as root or normal user. when mounted as root, we have to chown since we remove backups as the yellowtent user
// when mounted as non-root user, files are created as yellowtent user but they are still owned by the non-root user (thus del also works)
return config.mountOptions.user === 'root';
case mounts.MOUNT_TYPE_CIFS:
return true;
case mounts.MOUNT_TYPE_MOUNTPOINT:
return config.chown;
}
}
async function upload(config, backupFilePath) {
assert.strictEqual(typeof config, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof backupFilePath, 'string');
const [mkdirError] = await safe(fs.promises.mkdir(path.dirname(backupFilePath), { recursive: true }));
if (mkdirError) throw new BoxError(BoxError.FS_ERROR, `Error creating directory ${backupFilePath}: ${mkdirError.message}`);
2016-09-16 11:21:08 +02:00
2024-09-08 15:25:49 +02:00
await safe(fs.promises.unlink(backupFilePath)); // remove any hardlink
2017-09-22 14:40:37 -07:00
return {
stream: fs.createWriteStream(backupFilePath, { autoClose: true }),
async finish() {
const backupUid = parseInt(process.env.SUDO_UID, 10) || process.getuid(); // in test, upload() may or may not be called via sudo script
if (hasChownSupportSync(config)) {
if (!safe.fs.chownSync(backupFilePath, backupUid, backupUid)) throw new BoxError(BoxError.EXTERNAL_ERROR, `Unable to chown ${backupFilePath}: ${safe.error.message}`);
if (!safe.fs.chownSync(path.dirname(backupFilePath), backupUid, backupUid)) throw new BoxError(BoxError.EXTERNAL_ERROR, `Unable to chown parentdir ${backupFilePath}: ${safe.error.message}`);
}
}
};
2016-09-16 11:21:08 +02:00
}
async function download(config, sourceFilePath) {
assert.strictEqual(typeof config, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof sourceFilePath, 'string');
2018-07-30 07:39:34 -07:00
debug(`download: ${sourceFilePath}`);
if (!safe.fs.existsSync(sourceFilePath)) throw new BoxError(BoxError.NOT_FOUND, `File not found: ${sourceFilePath}`);
2017-09-28 14:26:39 -07:00
return fs.createReadStream(sourceFilePath);
}
async function exists(config, sourceFilePath) {
assert.strictEqual(typeof config, 'object');
assert.strictEqual(typeof sourceFilePath, 'string');
// do not use existsSync because it does not return EPERM etc
if (!safe.fs.statSync(sourceFilePath)) {
2022-04-14 08:07:03 -05:00
if (safe.error && safe.error.code === 'ENOENT') return false;
if (safe.error) throw new BoxError(BoxError.EXTERNAL_ERROR, `Exists ${sourceFilePath}: ${safe.error.message}`);
}
2022-04-14 08:07:03 -05:00
return true;
}
async function listDir(config, dir, batchSize, marker) {
assert.strictEqual(typeof config, 'object');
assert.strictEqual(typeof dir, 'string');
assert.strictEqual(typeof batchSize, 'number');
assert(typeof marker !== 'undefined');
const stack = marker ? marker.stack : [dir];
const fileStream = marker ? marker.fileStream : [];
if (!marker) marker = { stack, fileStream };
while (stack.length > 0) {
const currentDir = stack.pop();
const dirents = await fs.promises.readdir(currentDir, { withFileTypes: true });
for (const dirent of dirents) {
const fullPath = path.join(currentDir, dirent.name);
if (dirent.isDirectory()) {
stack.push(fullPath);
} else if (dirent.isFile()) { // does not include symlink
const stat = await fs.promises.lstat(fullPath);
fileStream.push({ fullPath, size: stat.size });
}
}
if (fileStream.length >= batchSize) return { entries: fileStream.splice(0, batchSize), marker }; // note: splice also modifies the array
}
if (fileStream.length === 0) return { entries: [], marker: null };
return { entries: fileStream.splice(0, batchSize), marker }; // note: splice also modifies the array
}
async function copy(config, oldFilePath, newFilePath, progressCallback) {
assert.strictEqual(typeof config, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof oldFilePath, 'string');
assert.strictEqual(typeof newFilePath, 'string');
2022-04-30 16:01:42 -07:00
assert.strictEqual(typeof progressCallback, 'function');
2022-04-30 16:01:42 -07:00
const [mkdirError] = await safe(fs.promises.mkdir(path.dirname(newFilePath), { recursive: true }));
if (mkdirError) throw new BoxError(BoxError.EXTERNAL_ERROR, mkdirError.message);
2022-04-30 16:01:42 -07:00
progressCallback({ message: `Copying ${oldFilePath} to ${newFilePath}` });
let cpOptions = ((config.provider !== mounts.MOUNT_TYPE_MOUNTPOINT && config.provider !== mounts.MOUNT_TYPE_CIFS) || config.preserveAttributes) ? '-a' : '-dR';
cpOptions += config.noHardlinks ? '' : 'l'; // this will hardlink backups saving space
if (config.provider === mounts.MOUNT_TYPE_SSHFS) {
const identityFilePath = path.join(paths.SSHFS_KEYS_DIR, `id_rsa_${config.mountOptions.host}`);
const sshOptions = [ '-o', '"StrictHostKeyChecking no"', '-i', identityFilePath, '-p', config.mountOptions.port, `${config.mountOptions.user}@${config.mountOptions.host}` ];
const sshArgs = sshOptions.concat([ 'cp', cpOptions, oldFilePath.replace('/mnt/cloudronbackup/', ''), newFilePath.replace('/mnt/cloudronbackup/', '') ]);
const [remoteCopyError] = await safe(shell.spawn('ssh', sshArgs, { shell: true }));
if (!remoteCopyError) return;
if (remoteCopyError.code === 255) throw new BoxError(BoxError.EXTERNAL_ERROR, `SSH connection error: ${remoteCopyError.message}`); // do not attempt fallback copy for ssh errors
debug('SSH remote copy failed, trying sshfs copy'); // this can happen for sshfs mounted windows server
}
const [copyError] = await safe(shell.spawn('cp', [ cpOptions, oldFilePath, newFilePath ], {}));
if (copyError) throw new BoxError(BoxError.EXTERNAL_ERROR, copyError.message);
}
async function remove(config, filename) {
assert.strictEqual(typeof config, 'object');
assert.strictEqual(typeof filename, 'string');
const stat = safe.fs.statSync(filename);
if (!stat) return;
if (stat.isFile()) {
if (!safe.fs.unlinkSync(filename)) throw new BoxError(BoxError.EXTERNAL_ERROR, safe.error.message);
} else if (stat.isDirectory()) {
if (!safe.fs.rmdirSync(filename, { recursive: false })) throw new BoxError(BoxError.EXTERNAL_ERROR, safe.error.message);
}
}
async function removeDir(config, pathPrefix, progressCallback) {
assert.strictEqual(typeof config, 'object');
assert.strictEqual(typeof pathPrefix, 'string');
assert.strictEqual(typeof progressCallback, 'function');
2017-10-10 20:23:04 -07:00
progressCallback({ message: `Removing directory ${pathPrefix}` });
2017-10-10 20:23:04 -07:00
if (config.provider === mounts.MOUNT_TYPE_SSHFS) {
const identityFilePath = path.join(paths.SSHFS_KEYS_DIR, `id_rsa_${config.mountOptions.host}`);
const sshOptions = [ '-o', '"StrictHostKeyChecking no"', '-i', identityFilePath, '-p', config.mountOptions.port, `${config.mountOptions.user}@${config.mountOptions.host}` ];
const sshArgs = sshOptions.concat([ 'rm', '-rf', pathPrefix.replace('/mnt/cloudronbackup/', '') ]);
const [remoteRmError] = await safe(shell.spawn('ssh', sshArgs, { shell: true }));
if (!remoteRmError) return;
if (remoteRmError.code === 255) throw new BoxError(BoxError.EXTERNAL_ERROR, `SSH connection error: ${remoteRmError.message}`); // do not attempt fallback copy for ssh errors
debug('SSH remote rm failed, trying sshfs rm'); // this can happen for sshfs mounted windows server
}
const [error] = await safe(shell.spawn('rm', [ '-rf', pathPrefix ], {}));
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, error.message);
}
function validateDestPath(folder) {
2020-12-01 12:11:55 -08:00
assert.strictEqual(typeof folder, 'string');
if (path.normalize(folder) !== folder) return new BoxError(BoxError.BAD_FIELD, 'backupFolder/mountpoint must contain a normalized path');
if (!path.isAbsolute(folder)) return new BoxError(BoxError.BAD_FIELD, 'backupFolder/mountpoint must be an absolute path');
2020-12-01 12:11:55 -08:00
if (folder === '/') return new BoxError(BoxError.BAD_FIELD, 'backupFolder/mountpoint cannot be /');
2020-12-01 12:11:55 -08:00
if (!folder.endsWith('/')) folder = folder + '/'; // ensure trailing slash for the prefix matching to work
const PROTECTED_PREFIXES = [ '/boot/', '/usr/', '/bin/', '/lib/', '/root/', '/var/lib/', paths.baseDir() ];
if (PROTECTED_PREFIXES.some(p => folder.startsWith(p))) return new BoxError(BoxError.BAD_FIELD, 'backupFolder path is protected');
2020-12-01 12:11:55 -08:00
return null;
}
async function cleanup(config, progressCallback) {
assert.strictEqual(typeof config, 'object');
assert.strictEqual(typeof progressCallback, 'function');
}
async function setupManagedMount(provider, mountOptions, hostPath) {
assert.strictEqual(typeof provider, 'string');
assert.strictEqual(typeof mountOptions, 'object');
assert.strictEqual(typeof hostPath, 'string');
debug(`setupManagedMount: setting up mount at ${hostPath} with ${provider}`);
const newMount = {
description: `Cloudron Managed Mount`,
hostPath,
mountType: provider,
mountOptions
};
await mounts.tryAddMount(newMount, { timeout: 10 }); // 10 seconds
return newMount;
}
async function setup(config) {
assert.strictEqual(typeof config, 'object');
debug('setup: removing old storage configuration');
if (!mounts.isManagedProvider(config.provider)) return;
const mountPath = path.join(paths.MANAGED_BACKUP_MOUNT_DIR, config.id);
await safe(mounts.removeMount(mountPath), { debug }); // ignore error
debug('setup: setting up new storage configuration');
await setupManagedMount(config.provider, config.mountOptions, mountPath);
}
async function teardown(config) {
assert.strictEqual(typeof config, 'object');
if (!mounts.isManagedProvider(config.provider)) return;
const mountPath = path.join(paths.MANAGED_BACKUP_MOUNT_DIR, config.id);
await safe(mounts.removeMount(mountPath), { debug }); // ignore error
}
async function verifyConfig({ id, provider, config }) {
assert.strictEqual(typeof id, 'string');
assert.strictEqual(typeof provider, 'string');
assert.strictEqual(typeof config, 'object');
if ('noHardlinks' in config && typeof config.noHardlinks !== 'boolean') throw new BoxError(BoxError.BAD_FIELD, 'noHardlinks must be boolean');
if ('chown' in config && typeof config.chown !== 'boolean') throw new BoxError(BoxError.BAD_FIELD, 'chown must be boolean');
if ('preserveAttributes' in config && typeof config.preserveAttributes !== 'boolean') throw new BoxError(BoxError.BAD_FIELD, 'preserveAttributes must be boolean');
2021-05-17 15:58:38 -07:00
const managedMountValidationPath = path.join(paths.MANAGED_BACKUP_MOUNT_DIR, `${id}-validation`);
let rootPath;
if (provider === mounts.MOUNT_TYPE_FILESYSTEM) {
if (!config.backupFolder || typeof config.backupFolder !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'backupFolder must be non-empty string');
const error = validateDestPath(config.backupFolder);
2022-04-14 07:59:50 -05:00
if (error) throw error;
rootPath = config.backupFolder;
} else {
if (typeof config.prefix !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'prefix must be a string');
if (config.prefix !== '') {
if (path.isAbsolute(config.prefix)) throw new BoxError(BoxError.BAD_FIELD, 'prefix must be a relative path');
if (path.normalize(config.prefix) !== config.prefix) throw new BoxError(BoxError.BAD_FIELD, 'prefix must contain a normalized relative path');
2020-12-18 14:41:59 -08:00
}
if (mounts.isManagedProvider(provider)) {
if (!config.mountOptions || typeof config.mountOptions !== 'object') throw new BoxError(BoxError.BAD_FIELD, 'mountOptions must be an object');
const error = mounts.validateMountOptions(provider, config.mountOptions);
if (error) throw error;
await setupManagedMount(provider, config.mountOptions, managedMountValidationPath);
rootPath = path.join(managedMountValidationPath, config.prefix);
} else if (provider === mounts.MOUNT_TYPE_MOUNTPOINT) {
if (!config.mountPoint || typeof config.mountPoint !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'mountPoint must be non-empty string');
const error = validateDestPath(config.mountPoint);
if (error) throw error;
const [mountError] = await safe(shell.spawn('mountpoint', ['-q', '--', config.mountPoint], { timeout: 5000 }));
if (mountError) throw new BoxError(BoxError.BAD_FIELD, `${config.mountPoint} is not mounted: ${mountError.message}`);
rootPath = path.join(config.mountPoint, config.prefix);
} else {
throw new BoxError(BoxError.BAD_FIELD, `Unknown provider: ${provider}`);
}
2021-06-22 15:28:48 -07:00
}
if (!safe.fs.mkdirSync(path.join(rootPath, 'snapshot'), { recursive: true }) && safe.error.code !== 'EEXIST') {
if (safe.error && safe.error.code === 'EACCES') throw new BoxError(BoxError.BAD_FIELD, `Access denied. Create ${rootPath}/snapshot and run "chown yellowtent:yellowtent ${rootPath}" on the server`);
throw new BoxError(BoxError.BAD_FIELD, safe.error.message);
}
if (!safe.fs.writeFileSync(path.join(rootPath, 'cloudron-testfile'), 'testcontent')) {
throw new BoxError(BoxError.BAD_FIELD, `Unable to create test file as 'yellowtent' user in ${rootPath}: ${safe.error.message}. Check dir/mount permissions`);
}
2020-05-26 14:57:20 -07:00
if (!safe.fs.unlinkSync(path.join(rootPath, 'cloudron-testfile'))) {
throw new BoxError(BoxError.BAD_FIELD, `Unable to remove test file as 'yellowtent' user in ${rootPath}: ${safe.error.message}. Check dir/mount permissions`);
2020-05-26 14:57:20 -07:00
}
if (mounts.isManagedProvider(provider)) await mounts.removeMount(managedMountValidationPath);
const newConfig = _.pick(config, ['noHardlinks', 'chown', 'preserveAttributes', 'backupFolder', 'prefix', 'mountOptions', 'mountPoint']);
return { provider, id, ...newConfig };
}
2017-01-04 16:22:58 -08:00
function removePrivateFields(config) {
if (config.mountOptions && config.mountOptions.password) config.mountOptions.password = constants.SECRET_PLACEHOLDER;
if (config.mountOptions && config.mountOptions.privateKey) config.mountOptions.privateKey = constants.SECRET_PLACEHOLDER;
2021-07-09 15:29:29 -07:00
delete config.id;
delete config.provider;
return config;
}
2021-05-17 15:58:38 -07:00
function injectPrivateFields(newConfig, currentConfig) {
if (newConfig.mountOptions && currentConfig.mountOptions && newConfig.mountOptions.password === constants.SECRET_PLACEHOLDER) newConfig.mountOptions.password = currentConfig.mountOptions.password;
2021-07-09 15:29:29 -07:00
if (newConfig.mountOptions && currentConfig.mountOptions && newConfig.mountOptions.privateKey === constants.SECRET_PLACEHOLDER) newConfig.mountOptions.privateKey = currentConfig.mountOptions.privateKey;
newConfig.id = currentConfig.id;
newConfig.provider = currentConfig.provider;
}