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

326 lines
14 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
getBackupPath,
checkPreconditions,
upload,
download,
copy,
exists,
listDir,
2018-07-27 14:29:07 -07:00
remove,
removeDir,
2016-09-16 11:21:08 +02:00
testConfig,
removePrivateFields,
injectPrivateFields
};
2020-06-08 17:08:26 +02:00
const PROVIDER_FILESYSTEM = 'filesystem';
const PROVIDER_SSHFS = 'sshfs';
const PROVIDER_CIFS = 'cifs';
const PROVIDER_NFS = 'nfs';
2020-06-08 17:08:26 +02:00
var assert = require('assert'),
2019-10-22 20:36:20 -07:00
BoxError = require('../boxerror.js'),
DataLayout = require('../datalayout.js'),
debug = require('debug')('box:storage/filesystem'),
df = require('@sindresorhus/df'),
EventEmitter = require('events'),
fs = require('fs'),
2017-04-18 15:32:59 +02:00
path = require('path'),
2020-12-01 12:11:55 -08:00
paths = require('../paths.js'),
prettyBytes = require('pretty-bytes'),
readdirp = require('readdirp'),
safe = require('safetydance'),
shell = require('../shell.js');
2017-04-18 15:32:59 +02:00
// storage api
function getBackupPath(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
2020-06-08 17:08:26 +02:00
if (apiConfig.provider === PROVIDER_SSHFS) return path.join(apiConfig.mountPoint, apiConfig.prefix);
if (apiConfig.provider === PROVIDER_CIFS) return path.join(apiConfig.mountPoint, apiConfig.prefix);
if (apiConfig.provider === PROVIDER_NFS) return path.join(apiConfig.mountPoint, apiConfig.prefix);
2020-06-08 17:08:26 +02:00
return apiConfig.backupFolder;
}
// the du call in the function below requires root
function checkPreconditions(apiConfig, dataLayout, callback) {
assert.strictEqual(typeof apiConfig, 'object');
assert(dataLayout instanceof DataLayout, 'dataLayout must be a DataLayout');
assert.strictEqual(typeof callback, 'function');
let used = 0;
for (let localPath of dataLayout.localPaths()) {
debug(`checkPreconditions: getting disk usage of ${localPath}`);
let result = safe.child_process.execSync(`du -Dsb ${localPath}`, { encoding: 'utf8' });
if (!result) return callback(new BoxError(BoxError.FS_ERROR, safe.error));
used += parseInt(result, 10);
}
debug(`checkPreconditions: ${used} bytes`);
df.file(getBackupPath(apiConfig)).then(function (result) {
// Check filesystem is mounted so we don't write into the actual folder on disk
if (apiConfig.provider === PROVIDER_SSHFS || apiConfig.provider === PROVIDER_CIFS || apiConfig.provider === PROVIDER_NFS) {
if (result.mountpoint !== apiConfig.mountPoint) return callback(new BoxError(BoxError.FS_ERROR, `${apiConfig.mountPoint} is not mounted`));
} else if (apiConfig.provider === PROVIDER_FILESYSTEM && apiConfig.externalDisk) {
if (result.mountpoint === '/') return callback(new BoxError(BoxError.FS_ERROR, `${apiConfig.backupFolder} is not mounted`));
}
2020-11-02 23:42:53 -08:00
const needed = 0.6 * used + (1024 * 1024 * 1024); // check if there is atleast 1GB left afterwards. aim for 60% because rsync/tgz won't need full 100%
if (result.available <= needed) return callback(new BoxError(BoxError.FS_ERROR, `Not enough disk space for backup. Needed: ${prettyBytes(needed)} Available: ${prettyBytes(result.available)}`));
callback(null);
}).catch(function (error) {
callback(new BoxError(BoxError.FS_ERROR, error));
});
}
function upload(apiConfig, backupFilePath, sourceStream, callback) {
assert.strictEqual(typeof apiConfig, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof backupFilePath, 'string');
assert.strictEqual(typeof sourceStream, 'object');
assert.strictEqual(typeof callback, 'function');
fs.mkdir(path.dirname(backupFilePath), { recursive: true }, function (error) {
2019-10-22 20:36:20 -07:00
if (error) return callback(new BoxError(BoxError.EXTERNAL_ERROR, error.message));
2016-09-16 11:21:08 +02:00
2017-09-22 14:40:37 -07:00
safe.fs.unlinkSync(backupFilePath); // remove any hardlink
var fileStream = fs.createWriteStream(backupFilePath);
2016-09-16 11:21:08 +02:00
// this pattern is required to ensure that the file got created before 'finish'
fileStream.on('open', function () {
sourceStream.pipe(fileStream);
});
2017-04-20 15:35:52 +02:00
fileStream.on('error', function (error) {
debug('[%s] upload: out stream error.', backupFilePath, error);
2019-10-22 20:36:20 -07:00
callback(new BoxError(BoxError.EXTERNAL_ERROR, error.message));
2017-04-20 15:35:52 +02:00
});
2017-09-26 16:42:54 -07:00
fileStream.on('finish', function () {
2017-09-27 14:44:48 -07:00
// in test, upload() may or may not be called via sudo script
const BACKUP_UID = parseInt(process.env.SUDO_UID, 10) || process.getuid();
2020-06-08 17:08:26 +02:00
// sshfs and cifs handle ownership through the mount args
if (apiConfig.provider === PROVIDER_FILESYSTEM || apiConfig.provider === PROVIDER_NFS) {
if (!safe.fs.chownSync(backupFilePath, BACKUP_UID, BACKUP_UID)) return callback(new BoxError(BoxError.EXTERNAL_ERROR, 'Unable to chown:' + safe.error.message));
if (!safe.fs.chownSync(path.dirname(backupFilePath), BACKUP_UID, BACKUP_UID)) return callback(new BoxError(BoxError.EXTERNAL_ERROR, 'Unable to chown:' + safe.error.message));
}
2017-09-27 14:44:48 -07:00
debug('upload %s: done.', backupFilePath);
2017-09-27 14:44:48 -07:00
callback(null);
});
});
2016-09-16 11:21:08 +02:00
}
function download(apiConfig, sourceFilePath, callback) {
assert.strictEqual(typeof apiConfig, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof sourceFilePath, 'string');
assert.strictEqual(typeof callback, 'function');
2018-07-30 07:39:34 -07:00
debug(`download: ${sourceFilePath}`);
2019-10-22 20:36:20 -07:00
if (!safe.fs.existsSync(sourceFilePath)) return callback(new BoxError(BoxError.NOT_FOUND, `File not found: ${sourceFilePath}`));
2017-09-28 14:26:39 -07:00
var fileStream = fs.createReadStream(sourceFilePath);
2017-09-28 14:26:39 -07:00
callback(null, fileStream);
}
function exists(apiConfig, sourceFilePath, callback) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof sourceFilePath, 'string');
assert.strictEqual(typeof callback, 'function');
// do not use existsSync because it does not return EPERM etc
if (!safe.fs.statSync(sourceFilePath)) {
if (safe.error && safe.error.code === 'ENOENT') return callback(null, false);
if (safe.error) return callback(new BoxError(BoxError.EXTERNAL_ERROR, `Exists ${sourceFilePath}: ${safe.error.message}`));
}
callback(null, true);
}
function listDir(apiConfig, dir, batchSize, iteratorCallback, callback) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof dir, 'string');
assert.strictEqual(typeof batchSize, 'number');
assert.strictEqual(typeof iteratorCallback, 'function');
assert.strictEqual(typeof callback, 'function');
var entries = [];
2019-04-24 10:40:33 -07:00
var entryStream = readdirp(dir, { type: 'files', alwaysStat: true, lstat: true });
entryStream.on('data', function (entryInfo) {
if (entryInfo.stats.isSymbolicLink()) return;
2018-08-02 14:59:50 -07:00
2019-04-24 10:40:33 -07:00
entries.push({ fullPath: entryInfo.fullPath });
if (entries.length < batchSize) return;
entryStream.pause();
iteratorCallback(entries, function (error) {
if (error) return callback(error);
entries = [];
entryStream.resume();
});
});
entryStream.on('warn', function (error) {
debug('listDir: warning ', error);
});
entryStream.on('end', function () {
iteratorCallback(entries, callback);
});
}
function copy(apiConfig, oldFilePath, newFilePath) {
assert.strictEqual(typeof apiConfig, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof oldFilePath, 'string');
assert.strictEqual(typeof newFilePath, 'string');
var events = new EventEmitter();
fs.mkdir(path.dirname(newFilePath), { recursive: true }, function (error) {
2019-10-22 20:36:20 -07:00
if (error) return events.emit('done', new BoxError(BoxError.EXTERNAL_ERROR, error.message));
events.emit('progress', `Copying ${oldFilePath} to ${newFilePath}`);
2020-06-08 17:08:26 +02:00
// sshfs and cifs do not allow preserving attributes
var cpOptions = apiConfig.provider === PROVIDER_FILESYSTEM ? '-a' : '-dR';
2017-09-18 12:42:42 -07:00
// this will hardlink backups saving space
cpOptions += apiConfig.noHardlinks ? '' : 'l';
2018-11-17 19:26:19 -08:00
shell.spawn('copy', '/bin/cp', [ cpOptions, oldFilePath, newFilePath ], { }, function (error) {
2019-10-22 20:36:20 -07:00
if (error) return events.emit('done', new BoxError(BoxError.EXTERNAL_ERROR, error.message));
events.emit('done', null);
});
2017-04-20 15:41:25 +02:00
});
return events;
}
function remove(apiConfig, filename, callback) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof filename, 'string');
assert.strictEqual(typeof callback, 'function');
var stat = safe.fs.statSync(filename);
if (!stat) return callback();
if (stat.isFile()) {
2019-10-22 20:36:20 -07:00
if (!safe.fs.unlinkSync(filename)) return callback(new BoxError(BoxError.EXTERNAL_ERROR, safe.error.message));
} else if (stat.isDirectory()) {
2019-10-22 20:36:20 -07:00
if (!safe.fs.rmdirSync(filename)) return callback(new BoxError(BoxError.EXTERNAL_ERROR, safe.error.message));
}
2017-10-02 20:08:00 -07:00
callback(null);
}
2017-10-10 20:23:04 -07:00
function removeDir(apiConfig, pathPrefix) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof pathPrefix, 'string');
2017-10-10 20:23:04 -07:00
var events = new EventEmitter();
process.nextTick(() => events.emit('progress', `Removing directory ${pathPrefix}`));
2018-11-17 19:26:19 -08:00
shell.spawn('removeDir', '/bin/rm', [ '-rf', pathPrefix ], { }, function (error) {
2019-10-22 20:36:20 -07:00
if (error) return events.emit('done', new BoxError(BoxError.EXTERNAL_ERROR, error.message));
2017-10-10 20:23:04 -07:00
events.emit('done', null);
});
2017-10-10 20:23:04 -07:00
return events;
}
2020-12-01 12:11:55 -08:00
function validateBackupTarget(folder) {
assert.strictEqual(typeof folder, 'string');
2020-12-03 23:05:06 -08:00
if (path.normalize(folder) !== folder) return new BoxError(BoxError.BAD_FIELD, 'backupFolder must contain a normalized path', { field: 'backupFolder' });
2020-12-01 12:11:55 -08:00
if (!path.isAbsolute(folder)) return new BoxError(BoxError.BAD_FIELD, 'backupFolder must be an absolute path', { field: 'backupFolder' });
if (folder === '/') return new BoxError(BoxError.BAD_FIELD, 'backupFolder cannot be /', { field: 'backupFolder' });
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', { field: 'backupFolder' });
return null;
}
function testConfig(apiConfig, callback) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof callback, 'function');
2020-06-08 17:08:26 +02:00
if (apiConfig.provider === PROVIDER_FILESYSTEM) {
if (!apiConfig.backupFolder || typeof apiConfig.backupFolder !== 'string') return callback(new BoxError(BoxError.BAD_FIELD, 'backupFolder must be non-empty string', { field: 'backupFolder' }));
2020-12-01 12:11:55 -08:00
let error = validateBackupTarget(apiConfig.backupFolder);
if (error) return callback(error);
2020-06-08 17:08:26 +02:00
if ('externalDisk' in apiConfig && typeof apiConfig.externalDisk !== 'boolean') return callback(new BoxError(BoxError.BAD_FIELD, 'externalDisk must be boolean', { field: 'externalDisk' }));
}
if (apiConfig.provider === PROVIDER_SSHFS || apiConfig.provider === PROVIDER_CIFS || apiConfig.provider === PROVIDER_NFS) {
2020-06-08 17:08:26 +02:00
if (!apiConfig.mountPoint || typeof apiConfig.mountPoint !== 'string') return callback(new BoxError(BoxError.BAD_FIELD, 'mountPoint must be non-empty string', { field: 'mountPoint' }));
2020-12-01 12:11:55 -08:00
let error = validateBackupTarget(apiConfig.mountPoint);
if (error) return callback(error);
2020-06-08 17:08:26 +02:00
if (typeof apiConfig.prefix !== 'string') return callback(new BoxError(BoxError.BAD_FIELD, 'prefix must be a string', { field: 'prefix' }));
2020-12-18 14:41:59 -08:00
if (apiConfig.prefix !== '') {
if (path.isAbsolute(apiConfig.prefix)) return new BoxError(BoxError.BAD_FIELD, 'prefix must be a relative path', { field: 'backupFolder' });
if (path.normalize(apiConfig.prefix) !== apiConfig.prefix) return callback(new BoxError(BoxError.BAD_FIELD, 'prefix must contain a normalized relative path', { field: 'prefix' }));
}
const mounts = safe.fs.readFileSync('/proc/mounts', 'utf8');
const mountInfo = mounts.split('\n').filter(function (l) { return l.indexOf(apiConfig.mountPoint) !== -1; })[0];
if (!mountInfo) return callback(new BoxError(BoxError.BAD_FIELD, `${apiConfig.mountPoint} is not mounted`, { field: 'mountPoint' }));
if (apiConfig.provider === PROVIDER_SSHFS && !mountInfo.split(' ').find(i => i === 'fuse.sshfs')) return callback(new BoxError(BoxError.BAD_FIELD, 'mountPoint must be a "fuse.sshfs" filesystem', { field: 'mountPoint' }));
if (apiConfig.provider === PROVIDER_CIFS && !mountInfo.split(' ').find(i => i === 'cifs')) return callback(new BoxError(BoxError.BAD_FIELD, 'mountPoint must be a "cifs" filesystem', { field: 'mountPoint' }));
if (apiConfig.provider === PROVIDER_NFS && !mountInfo.split(' ').find(i => i === 'nfs')) return callback(new BoxError(BoxError.BAD_FIELD, 'mountPoint must be a "nfs" filesystem', { field: 'mountPoint' }));
2020-06-08 17:08:26 +02:00
}
2020-06-08 17:08:26 +02:00
// common checks
const backupPath = getBackupPath(apiConfig);
const field = apiConfig.provider === PROVIDER_FILESYSTEM ? 'backupFolder' : 'prefix';
2020-06-08 17:08:26 +02:00
const stat = safe.fs.statSync(backupPath);
if (!stat) return callback(new BoxError(BoxError.BAD_FIELD, 'Directory does not exist or cannot be accessed: ' + safe.error.message), { field });
if (!stat.isDirectory()) return callback(new BoxError(BoxError.BAD_FIELD, 'Backup location is not a directory', { field }));
2020-06-08 17:08:26 +02:00
if (!safe.fs.mkdirSync(path.join(backupPath, 'snapshot')) && safe.error.code !== 'EEXIST') {
if (safe.error && safe.error.code === 'EACCES') return callback(new BoxError(BoxError.BAD_FIELD, `Access denied. Run "chown yellowtent:yellowtent ${backupPath}" on the server`, { field }));
return callback(new BoxError(BoxError.BAD_FIELD, safe.error.message, { field }));
2020-05-26 14:57:20 -07:00
}
2020-06-08 17:08:26 +02:00
if (!safe.fs.writeFileSync(path.join(backupPath, 'cloudron-testfile'), 'testcontent')) {
return callback(new BoxError(BoxError.BAD_FIELD, `Unable to create test file as 'yellowtent' user in ${backupPath}: ${safe.error.message}. Check dir/mount permissions`, { field }));
2020-05-26 14:57:20 -07:00
}
2020-06-08 17:08:26 +02:00
if (!safe.fs.unlinkSync(path.join(backupPath, 'cloudron-testfile'))) {
return callback(new BoxError(BoxError.BAD_FIELD, `Unable to remove test file as 'yellowtent' user in ${backupPath}: ${safe.error.message}. Check dir/mount permissions`, { field }));
2020-05-26 14:57:20 -07:00
}
2020-06-08 17:08:26 +02:00
if ('noHardlinks' in apiConfig && typeof apiConfig.noHardlinks !== 'boolean') return callback(new BoxError(BoxError.BAD_FIELD, 'noHardlinks must be boolean', { field: 'noHardLinks' }));
2020-05-26 14:57:20 -07:00
callback(null);
}
2017-01-04 16:22:58 -08:00
function removePrivateFields(apiConfig) {
return apiConfig;
}
function injectPrivateFields(/* newConfig, currentConfig */) {
}