yunkong2.socketio
Version:
This adapter allows to communicate different web applications with yunkong2.
1,118 lines (1,027 loc) • 76.7 kB
JavaScript
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
/* jshint -W061 */
'use strict';
const socketio = require('socket.io');
const path = require('path');
const fs = require('fs');
const cookieParser = require('cookie-parser');
const EventEmitter = require('events');
const util = require('util');
let request = null;
// From settings used only secure, auth and crossDomain
function IOSocket(server, settings, adapter) {
if (!(this instanceof IOSocket)) return new IOSocket(server, settings, adapter);
this.settings = settings || {};
this.adapter = adapter;
this.webServer = server;
this.subscribes = {};
let that = this;
// do not send too many state updates
let eventsThreshold = {
count: 0,
timeActivated: 0,
active: false,
accidents: 0,
repeatSeconds: 3, // how many seconds continuously must be number of events > value
value: 200, // how many events allowed in one check interval
checkInterval: 1000 // duration of one check interval
};
// Extract user name from socket
function getUserFromSocket(socket, callback) {
let wait = false;
try {
if (socket.handshake.headers.cookie && (!socket.request || !socket.request._query || !socket.request._query.user)) {
let cookie = decodeURIComponent(socket.handshake.headers.cookie);
let m = cookie.match(/connect\.sid=(.+)/);
if (m) {
// If session cookie exists
let c = m[1].split(';')[0];
let sessionID = cookieParser.signedCookie(c, that.settings.secret);
if (sessionID) {
// Get user for session
wait = true;
that.settings.store.get(sessionID, function (err, obj) {
if (obj && obj.passport && obj.passport.user) {
socket._sessionID = sessionID;
if (typeof callback === 'function') {
callback(null, obj.passport.user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
}
if (!wait) {
let user = socket.request._query.user;
let pass = socket.request._query.pass;
if (user && pass) {
wait = true;
that.adapter.checkPassword(user, pass, function (res) {
if (res) {
that.adapter.log.debug('Logged in: ' + user);
if (typeof callback === 'function') {
callback(null, user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
that.adapter.log.warn('Invalid password or user name: ' + user + ', ' + pass[0] + '***(' + pass.length + ')');
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
} catch (e) {
that.adapter.log.error(e);
wait = false;
}
if (!wait && typeof callback === 'function') {
callback('Cannot detect user');
}
}
function disableEventThreshold(readAll) {
if (eventsThreshold.active) {
eventsThreshold.accidents = 0;
eventsThreshold.count = 0;
eventsThreshold.active = false;
eventsThreshold.timeActivated = 0;
that.adapter.log.info('Subscribe on all states again');
setTimeout(function () {
if (readAll) {
that.adapter.getForeignStates('*', function (err, res) {
that.adapter.log.info('received all states');
for (let id in res) {
if (res.hasOwnProperty(id) && JSON.stringify(states[id]) !== JSON.stringify(res[id])) {
that.server.sockets.emit('stateChange', id, res[id]);
states[id] = res[id];
}
}
});
}
that.server.sockets.emit('eventsThreshold', false);
that.adapter.unsubscribeForeignStates('system.adapter.*');
that.adapter.subscribeForeignStates('*');
}, 50);
}
}
function enableEventThreshold() {
if (!eventsThreshold.active) {
eventsThreshold.active = true;
setTimeout(function () {
that.adapter.log.info('Unsubscribe from all states, except system\'s, because over ' + eventsThreshold.repeatSeconds + ' seconds the number of events is over ' + eventsThreshold.value + ' (in last second ' + eventsThreshold.count + ')');
eventsThreshold.timeActivated = new Date().getTime();
that.server.sockets.emit('eventsThreshold', true);
that.adapter.unsubscribeForeignStates('*');
that.adapter.subscribeForeignStates('system.adapter.*');
}, 100);
}
}
function getClientAddress(socket) {
let address;
if (socket.handshake) {
address = socket.handshake.address;
}
if (!address && socket.request && socket.request.connection) {
address = socket.request.connection.remoteAddress;
}
return address;
}
this.initSocket = function (socket) {
if (!socket._acl) {
if (that.settings.auth) {
getUserFromSocket(socket, function (err, user) {
if (err || !user) {
socket.emit('reauthenticate');
that.adapter.log.error('socket.io ' + (err || 'No user found in cookies'));
socket.disconnect();
} else {
socket._secure = true;
that.adapter.log.debug('socket.io client ' + user + ' connected');
that.adapter.calculatePermissions('system.user.' + user, commandsPermissions, function (acl) {
let address = getClientAddress(socket);
// socket._acl = acl;
socket._acl = mergeACLs(address, acl, that.settings.whiteListSettings);
socketEvents(socket, address);
});
}
});
} else {
that.adapter.calculatePermissions(that.settings.defaultUser, commandsPermissions, function (acl) {
let address = getClientAddress(socket);
// socket._acl = acl;
socket._acl = mergeACLs(address, acl, that.settings.whiteListSettings);
socketEvents(socket, address);
});
}
} else {
let address = getClientAddress(socket);
socketEvents(socket, address);
}
};
this.getWhiteListIpForAddress = function (address, whiteList){
return getWhiteListIpForAddress(address, whiteList);
};
function getWhiteListIpForAddress(address, whiteList) {
if (!whiteList) return null;
// check IPv6 or IPv4 direct match
if (whiteList.hasOwnProperty(address)) {
return address;
}
// check if address is IPv4
let addressParts = address.split('.');
if (addressParts.length !== 4) {
return null;
}
// do we have settings for wild carded ips?
let wildCardIps = Object.keys(whiteList).filter(function (key) {
return key.indexOf('*') !== -1;
});
if (wildCardIps.length === 0) {
// no wild carded ips => no ip configured
return null;
}
wildCardIps.forEach(function (ip) {
let ipParts = ip.split('.');
if (ipParts.length === 4) {
for (let i = 0; i < 4; i++) {
if (ipParts[i] === '*' && i === 3) {
// match
return ip;
}
if (ipParts[i] !== addressParts[i]) break;
}
}
});
return null;
}
function getPermissionsForIp(address, whiteList) {
return whiteList[getWhiteListIpForAddress(address, whiteList) || 'default'];
}
function mergeACLs(address, acl, whiteList) {
if (whiteList && address) {
let whiteListAcl = getPermissionsForIp(address, whiteList);
if (whiteListAcl) {
['object', 'state', 'file'].forEach(function (key) {
if (acl.hasOwnProperty(key) && whiteListAcl.hasOwnProperty(key)) {
Object.keys(acl[key]).forEach(function (permission) {
if (whiteListAcl[key].hasOwnProperty(permission)) {
acl[key][permission] = acl[key][permission] && whiteListAcl[key][permission];
}
})
}
});
if (whiteListAcl.user !== 'auth') {
acl.user = 'system.user.' + whiteListAcl.user;
}
}
}
return acl;
}
function pattern2RegEx(pattern) {
if (!pattern) {
return null;
}
if (pattern !== '*') {
if (pattern[0] === '*' && pattern[pattern.length - 1] !== '*') pattern += '$';
if (pattern[0] !== '*' && pattern[pattern.length - 1] === '*') pattern = '^' + pattern;
}
pattern = pattern.replace(/\./g, '\\.');
pattern = pattern.replace(/\*/g, '.*');
pattern = pattern.replace(/\[/g, '\\[');
pattern = pattern.replace(/]/g, '\\]');
pattern = pattern.replace(/\(/g, '\\(');
pattern = pattern.replace(/\)/g, '\\)');
return pattern;
}
this.subscribe = function (socket, type, pattern) {
//console.log((socket._name || socket.id) + ' subscribe ' + pattern);
if (socket) {
socket._subscribe = socket._subscribe || {};
}
if (!this.subscribes[type]) this.subscribes[type] = {};
let s;
if (socket) {
s = socket._subscribe[type] = socket._subscribe[type] || [];
for (let i = 0; i < s.length; i++) {
if (s[i].pattern === pattern) return;
}
}
let p = pattern2RegEx(pattern);
if (p === null) {
this.adapter.log.warn('Empty pattern!');
return;
}
if (socket) {
s.push({pattern: pattern, regex: new RegExp(p)});
}
if (this.subscribes[type][pattern] === undefined) {
this.subscribes[type][pattern] = 1;
if (type === 'stateChange') {
this.adapter.subscribeForeignStates(pattern);
} else if (type === 'objectChange') {
if (this.adapter.subscribeForeignObjects) {
this.adapter.subscribeForeignObjects(pattern);
}
} else if (type === 'log') {
if (this.adapter.requireLog) this.adapter.requireLog(true);
}
} else {
this.subscribes[type][pattern]++;
}
};
function showSubscribes(socket, type) {
if (socket && socket._subscribe) {
let s = socket._subscribe[type] || [];
let ids = [];
for (let i = 0; i < s.length; i++) {
ids.push(s[i].pattern);
}
that.adapter.log.debug('Subscribes: ' + ids.join(', '));
} else {
that.adapter.log.debug('Subscribes: no subscribes');
}
}
this.unsubscribe = function (socket, type, pattern) {
//console.log((socket._name || socket.id) + ' unsubscribe ' + pattern);
if (!this.subscribes[type]) this.subscribes[type] = {};
if (socket) {
if (!socket._subscribe || !socket._subscribe[type]) return;
for (let i = socket._subscribe[type].length - 1; i >= 0; i--) {
if (socket._subscribe[type][i].pattern === pattern) {
// Remove pattern from global list
if (this.subscribes[type][pattern] !== undefined) {
this.subscribes[type][pattern]--;
if (this.subscribes[type][pattern] <= 0) {
if (type === 'stateChange') {
//console.log((socket._name || socket.id) + ' unsubscribeForeignStates ' + pattern);
this.adapter.unsubscribeForeignStates(pattern);
} else if (type === 'objectChange') {
//console.log((socket._name || socket.id) + ' unsubscribeForeignObjects ' + pattern);
if (this.adapter.unsubscribeForeignObjects) this.adapter.unsubscribeForeignObjects(pattern);
} else if (type === 'log') {
//console.log((socket._name || socket.id) + ' requireLog false');
if (this.adapter.requireLog) this.adapter.requireLog(false);
}
delete this.subscribes[type][pattern];
}
}
delete socket._subscribe[type][i];
socket._subscribe[type].splice(i, 1);
return;
}
}
} else if (pattern) {
// Remove pattern from global list
if (this.subscribes[type][pattern] !== undefined) {
this.subscribes[type][pattern]--;
if (this.subscribes[type][pattern] <= 0) {
if (type === 'stateChange') {
//console.log((socket._name || socket.id) + ' unsubscribeForeignStates ' + pattern);
this.adapter.unsubscribeForeignStates(pattern);
} else if (type === 'objectChange') {
//console.log((socket._name || socket.id) + ' unsubscribeForeignObjects ' + pattern);
if (this.adapter.unsubscribeForeignObjects) this.adapter.unsubscribeForeignObjects(pattern);
} else if (type === 'log') {
//console.log((socket._name || socket.id) + ' requireLog false');
if (this.adapter.requireLog) this.adapter.requireLog(false);
}
delete this.subscribes[type][pattern];
}
}
} else {
for (pattern in this.subscribes[type]) {
if (!this.subscribes[type].hasOwnProperty(pattern)) continue;
if (type === 'stateChange') {
//console.log((socket._name || socket.id) + ' unsubscribeForeignStates ' + pattern);
this.adapter.unsubscribeForeignStates(pattern);
} else if (type === 'objectChange') {
//console.log((socket._name || socket.id) + ' unsubscribeForeignObjects ' + pattern);
if (this.adapter.unsubscribeForeignObjects) this.adapter.unsubscribeForeignObjects(pattern);
} else if (type === 'log') {
//console.log((socket._name || socket.id) + ' requireLog false');
if (this.adapter.requireLog) this.adapter.requireLog(false);
}
delete this.subscribes[type][pattern];
}
}
};
this.unsubscribeAll = function () {
if (this.server && this.server.sockets) {
for (let s in this.server.sockets) {
if (this.server.sockets.hasOwnProperty(s)) {
unsubscribeSocket(s, 'stateChange');
unsubscribeSocket(s, 'objectChange');
unsubscribeSocket(s, 'log');
}
}
}
};
function unsubscribeSocket(socket, type) {
if (!socket._subscribe || !socket._subscribe[type]) return;
for (let i = 0; i < socket._subscribe[type].length; i++) {
let pattern = socket._subscribe[type][i].pattern;
if (that.subscribes[type][pattern] !== undefined) {
that.subscribes[type][pattern]--;
if (that.subscribes[type][pattern] <= 0) {
if (type === 'stateChange') {
that.adapter.unsubscribeForeignStates(pattern);
} else if (type === 'objectChange') {
if (that.adapter.unsubscribeForeignObjects) that.adapter.unsubscribeForeignObjects(pattern);
} else if (type === 'log') {
if (that.adapter.requireLog) that.adapter.requireLog(false);
}
delete that.subscribes[type][pattern];
}
}
}
}
function subscribeSocket(socket, type) {
//console.log((socket._name || socket.id) + ' subscribeSocket');
if (!socket._subscribe || !socket._subscribe[type]) return;
for (let i = 0; i < socket._subscribe[type].length; i++) {
let pattern = socket._subscribe[type][i].pattern;
if (that.subscribes[type][pattern] === undefined) {
that.subscribes[type][pattern] = 1;
if (type === 'stateChange') {
that.adapter.subscribeForeignStates(pattern);
} else if (type === 'objectChange') {
if (that.adapter.subscribeForeignObjects) that.adapter.subscribeForeignObjects(pattern);
} else if (type === 'log') {
if (that.adapter.requireLog) that.adapter.requireLog(true);
}
} else {
that.subscribes[type][pattern]++;
}
}
}
function publish(socket, type, id, obj) {
if (!socket._subscribe || !socket._subscribe[type]) return;
let s = socket._subscribe[type];
for (let i = 0; i < s.length; i++) {
if (s[i].regex.test(id)) {
updateSession(socket);
socket.emit(type, id, obj);
return;
}
}
}
// update session ID, but not offter than 60 seconds
function updateSession(socket) {
if (socket._sessionID) {
let time = (new Date()).getTime();
if (socket._lastActivity && time - socket._lastActivity > settings.ttl * 1000) {
socket.emit('reauthenticate');
socket.disconnect();
return false;
}
socket._lastActivity = time;
if (!socket._sessionTimer) {
socket._sessionTimer = setTimeout(function () {
socket._sessionTimer = null;
that.settings.store.get(socket._sessionID, function (err, obj) {
if (obj) {
that.adapter.setSession(socket._sessionID, settings.ttl, obj);
} else {
socket.emit('reauthenticate');
socket.disconnect();
}
});
}, 60000);
}
}
return true;
}
// static information
let commandsPermissions = {
getObject: {type: 'object', operation: 'read'},
getObjects: {type: 'object', operation: 'list'},
getObjectView: {type: 'object', operation: 'list'},
setObject: {type: 'object', operation: 'write'},
requireLog: {type: 'object', operation: 'write'}, // just mapping to some command
delObject: {type: 'object', operation: 'delete'},
extendObject: {type: 'object', operation: 'write'},
getHostByIp: {type: 'object', operation: 'list'},
subscribeObjects: {type: 'object', operation: 'read'},
unsubscribeObjects: {type: 'object', operation: 'read'},
getStates: {type: 'state', operation: 'list'},
getState: {type: 'state', operation: 'read'},
setState: {type: 'state', operation: 'write'},
delState: {type: 'state', operation: 'delete'},
createState: {type: 'state', operation: 'create'},
subscribe: {type: 'state', operation: 'read'},
unsubscribe: {type: 'state', operation: 'read'},
getStateHistory: {type: 'state', operation: 'read'},
getVersion: {type: '', operation: ''},
addUser: {type: 'users', operation: 'create'},
delUser: {type: 'users', operation: 'delete'},
addGroup: {type: 'users', operation: 'create'},
delGroup: {type: 'users', operation: 'delete'},
changePassword: {type: 'users', operation: 'write'},
httpGet: {type: 'other', operation: 'http'},
cmdExec: {type: 'other', operation: 'execute'},
sendTo: {type: 'other', operation: 'sendto'},
sendToHost: {type: 'other', operation: 'sendto'},
readLogs: {type: 'other', operation: 'execute'},
readDir: {type: 'file', operation: 'list'},
createFile: {type: 'file', operation: 'create'},
writeFile: {type: 'file', operation: 'write'},
readFile: {type: 'file', operation: 'read'},
deleteFile: {type: 'file', operation: 'delete'},
readFile64: {type: 'file', operation: 'read'},
writeFile64: {type: 'file', operation: 'write'},
unlink: {type: 'file', operation: 'delete'},
rename: {type: 'file', operation: 'write'},
mkdir: {type: 'file', operation: 'write'},
chmodFile: {type: 'file', operation: 'write'},
authEnabled: {type: '', operation: ''},
disconnect: {type: '', operation: ''},
listPermissions: {type: '', operation: ''},
getUserPermissions: {type: 'object', operation: 'read'}
};
function addUser(user, pw, options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
if (!user.match(/^[-.A-Za-züäößÖÄÜа-яА-Я@+$§0-9=?!&# ]+$/)) {
if (typeof callback === 'function') {
callback('Invalid characters in the name. Only following special characters are allowed: -@+$§=?!&# and letters');
}
return;
}
that.adapter.getForeignObject('system.user.' + user, options, (err, obj) => {
if (obj) {
if (typeof callback === 'function') {
callback('User yet exists');
}
} else {
that.adapter.setForeignObject('system.user.' + user, {
type: 'user',
common: {
name: user,
enabled: true,
groups: []
}
}, options, () => {
that.adapter.setPassword(user, pw, options, callback);
});
}
});
}
function delUser(user, options, callback) {
that.adapter.getForeignObject('system.user.' + user, options, (err, obj) => {
if (err || !obj) {
if (typeof callback === 'function') {
callback('User does not exist');
}
} else {
if (obj.common.dontDelete) {
if (typeof callback === 'function') {
callback('Cannot delete user, while is system user');
}
} else {
that.adapter.delForeignObject('system.user.' + user, options, err => {
// Remove this user from all groups in web client
if (typeof callback === 'function') {
callback(err);
}
});
}
}
});
}
function addGroup(group, desc, acl, options, callback) {
let name = group;
if (typeof acl === 'function') {
callback = acl;
acl = null;
}
if (typeof desc === 'function') {
callback = desc;
desc = null;
}
if (typeof options === 'function') {
callback = options;
options = null;
}
if (name && name.substring(0, 1) !== name.substring(0, 1).toUpperCase()) {
name = name.substring(0, 1).toUpperCase() + name.substring(1);
}
group = group.substring(0, 1).toLowerCase() + group.substring(1);
if (!group.match(/^[-.A-Za-züäößÖÄÜа-яА-Я@+$§0-9=?!&#_ ]+$/)) {
if (typeof callback === 'function') {
callback('Invalid characters in the group name. Only following special characters are allowed: -@+$§=?!&# and letters');
}
return;
}
that.adapter.getForeignObject('system.group.' + group, options, (err, obj) => {
if (obj) {
if (typeof callback === 'function') {
callback('Group yet exists');
}
} else {
obj = {
_id: 'system.group.' + group,
type: 'group',
common: {
name: name,
desc: desc,
members: [],
acl: acl
}
};
that.adapter.setForeignObject('system.group.' + group, obj, options, err => {
if (typeof callback === 'function') {
callback(err, obj);
}
});
}
});
}
function delGroup(group, options, callback) {
that.adapter.getForeignObject('system.group.' + group, options, (err, obj) => {
if (err || !obj) {
if (typeof callback === 'function') {
callback('Group does not exist');
}
} else {
if (obj.common.dontDelete) {
if (typeof callback === 'function') {
callback('Cannot delete group, while is system group');
}
} else {
that.adapter.delForeignObject('system.group.' + group, options, err => {
// Remove this group from all users in web client
if (typeof callback === 'function') {
callback(err);
}
});
}
}
});
}
function checkPermissions(socket, command, callback, arg) {
if (socket._acl.user !== 'system.user.admin') {
// type: file, object, state, other
// operation: create, read, write, list, delete, sendto, execute, sendToHost, readLogs
if (commandsPermissions[command]) {
// If permission required
if (commandsPermissions[command].type) {
if (socket._acl[commandsPermissions[command].type] &&
socket._acl[commandsPermissions[command].type][commandsPermissions[command].operation]) {
return true;
} else {
that.adapter.log.warn('No permission for "' + socket._acl.user + '" to call ' + command + '. Need "' + commandsPermissions[command].type + '"."' + commandsPermissions[command].operation + '"');
}
} else {
return true;
}
} else {
that.adapter.log.warn('No rule for command: ' + command);
}
if (typeof callback === 'function') {
callback('permissionError');
} else {
if (commandsPermissions[command]) {
socket.emit('permissionError', {
command: command,
type: commandsPermissions[command].type,
operation: commandsPermissions[command].operation,
arg: arg
});
} else {
socket.emit('permissionError', {
command: command,
arg: arg
});
}
}
return false;
} else {
return true;
}
}
function checkObject(obj, options, flag) {
// read rights of object
if (!obj || !obj.common || !obj.acl || flag === 'list') {
return true;
}
if (options.user !== 'system.user.admin' &&
options.groups.indexOf('system.group.administrator') === -1) {
if (obj.acl.owner !== options.user) {
// Check if the user is in the group
if (options.groups.indexOf(obj.acl.ownerGroup) !== -1) {
// Check group rights
if (!(obj.acl.object & (flag << 4))) {
return false
}
} else {
// everybody
if (!(obj.acl.object & flag)) {
return false
}
}
} else {
// Check group rights
if (!(obj.acl.object & (flag << 8))) {
return false
}
}
}
return true;
}
this.send = function (socket, cmd, id, data) {
if (socket._apiKeyOk) {
socket.emit(cmd, id, data);
}
};
function stopAdapter(reason, callback) {
reason && that.adapter.log.warn('Adapter stopped. Reason: ' + reason);
that.adapter.getForeignObject('system.adapter.' + that.adapter.namespace, function (err, obj) {
if (err) that.adapter.log.error('[getForeignObject]: ' + err);
if (obj) {
obj.common.enabled = false;
setTimeout(function () {
that.adapter.setForeignObject(obj._id, obj, function (err) {
if (err) that.adapter.log.error('[setForeignObject]: ' + err);
callback && callback();
});
}, 5000);
} else {
callback && callback();
}
});
}
function redirectAdapter(url, callback) {
if (!url) {
that.adapter.log.warn('Received redirect command, but no URL');
} else {
that.adapter.getForeignObject('system.adapter.' + that.adapter.namespace, function (err, obj) {
if (err) that.adapter.log.error('redirectAdapter [getForeignObject]: ' + err);
if (obj) {
obj.native.cloudUrl = url;
setTimeout(function () {
that.adapter.setForeignObject(obj._id, obj, function (err) {
if (err) that.adapter.log.error('redirectAdapter [setForeignObject]: ' + err);
callback && callback();
});
}, 3000);
} else {
callback && callback();
}
});
}
}
function waitForConnect(delaySeconds) {
that.emit && that.emit('connectWait', delaySeconds);
}
function socketEvents(socket, address) {
if (socket.conn) {
that.adapter.log.info('==>Connected ' + socket._acl.user + ' from ' + address);
} else {
that.adapter.log.info('Trying to connect as ' + socket._acl.user + ' from ' + address);
}
if (!that.infoTimeout) {
that.infoTimeout = setTimeout(updateConnectedInfo, 1000);
}
socket.on('authenticate', function (user, pass, callback) {
that.adapter.log.debug((new Date()).toISOString() + ' Request authenticate [' + socket._acl.user + ']');
if (typeof user === 'function') {
callback = user;
user = undefined;
}
if (socket._acl.user !== null) {
if (typeof callback === 'function') {
callback(socket._acl.user !== null, socket._secure);
}
} else {
that.adapter.log.debug((new Date()).toISOString() + ' Request authenticate [' + socket._acl.user + ']');
socket._authPending = callback;
}
});
socket.on('name', function (name, cb) {
that.adapter.log.debug('Connection from ' + name);
updateSession(socket);
if (this._name === undefined) {
this._name = name;
if (!that.infoTimeout) that.infoTimeout = setTimeout(updateConnectedInfo, 1000);
} else if (this._name !== name) {
that.adapter.log.warn('socket ' + this.id + ' changed socket name from ' + this._name + ' to ' + name);
this._name = name;
}
if (typeof cb === 'function') {
cb();
}
});
/*
* objects
*/
socket.on('getObject', function (id, callback) {
if (updateSession(socket) && checkPermissions(socket, 'getObject', callback, id)) {
that.adapter.getForeignObject(id, {user: socket._acl.user}, callback);
}
});
socket.on('getObjects', function (callback) {
if (updateSession(socket) && checkPermissions(socket, 'getObjects', callback)) {
that.adapter.getForeignObjects('*', 'state', 'rooms', {user: socket._acl.user}, function (err, objs) {
if (typeof callback === 'function') {
callback(err, objs);
} else {
that.adapter.log.warn('[getObjects] Invalid callback')
}
});
}
});
socket.on('subscribeObjects', function (pattern, callback) {
if (updateSession(socket) && checkPermissions(socket, 'subscribeObjects', callback, pattern)) {
if (pattern && typeof pattern === 'object' && pattern instanceof Array) {
for (let p = 0; p < pattern.length; p++) {
that.subscribe(this, 'objectChange', pattern[p]);
}
} else {
that.subscribe(this, 'objectChange', pattern);
}
if (typeof callback === 'function') {
setImmediate(callback, null);
}
}
});
socket.on('unsubscribeObjects', function (pattern, callback) {
if (updateSession(socket) && checkPermissions(socket, 'unsubscribeObjects', callback, pattern)) {
if (pattern && typeof pattern === 'object' && pattern instanceof Array) {
for (let p = 0; p < pattern.length; p++) {
that.unsubscribe(this, 'objectChange', pattern[p]);
}
} else {
that.unsubscribe(this, 'objectChange', pattern);
}
if (typeof callback === 'function') {
setImmediate(callback, null);
}
}
});
socket.on('getObjectView', function (design, search, params, callback) {
if (updateSession(socket) && checkPermissions(socket, 'getObjectView', callback, search)) {
that.adapter.objects.getObjectView(design, search, params, {user: socket._acl.user}, callback);
}
});
socket.on('setObject', function (id, obj, callback) {
if (updateSession(socket) && checkPermissions(socket, 'setObject', callback, id)) {
that.adapter.setForeignObject(id, obj, {user: socket._acl.user}, callback);
}
});
/*
* states
*/
socket.on('getStates', function (pattern, callback) {
if (updateSession(socket) && checkPermissions(socket, 'getStates', callback, pattern)) {
if (typeof pattern === 'function') {
callback = pattern;
pattern = null;
}
that.adapter.getForeignStates(pattern || '*', {user: socket._acl.user}, callback);
}
});
socket.on('error', function (err) {
that.adapter.log.error('Socket error: ' + err);
});
// allow admin access
if (that.settings.allowAdmin) {
socket.on('getAllObjects', function (callback) {
if (updateSession(socket) && checkPermissions(socket, 'getObjects', callback)) {
that.adapter.objects.getObjectList({include_docs: true}, function (err, res) {
that.adapter.log.info('received all objects');
res = res.rows;
let objects = {};
if (socket._acl &&
socket._acl.user !== 'system.user.admin' &&
socket._acl.groups.indexOf('system.group.administrator') === -1) {
for (let i = 0; i < res.length; i++) {
if (checkObject(res[i].doc, socket._acl, 4 /* 'read' */)) {
objects[res[i].doc._id] = res[i].doc;
}
}
if (typeof callback === 'function') {
callback(null, objects);
} else {
that.adapter.log.warn('[getAllObjects] Invalid callback')
}
} else {
for (let j = 0; j < res.length; j++) {
objects[res[j].doc._id] = res[j].doc;
}
if (typeof callback === 'function') {
callback(null, objects);
} else {
that.adapter.log.warn('[getAllObjects] Invalid callback')
}
}
});
}
});
socket.on('delObject', function (id, callback) {
if (updateSession(socket) && checkPermissions(socket, 'delObject', callback, id)) {
that.adapter.delForeignObject(id, {user: socket._acl.user}, callback);
}
});
socket.on('extendObject', function (id, obj, callback) {
if (updateSession(socket) && checkPermissions(socket, 'extendObject', callback, id)) {
that.adapter.extendForeignObject(id, obj, {user: socket._acl.user}, callback);
}
});
socket.on('getHostByIp', function (ip, callback) {
if (updateSession(socket) && checkPermissions(socket, 'getHostByIp', ip)) {
that.adapter.objects.getObjectView('system', 'host', {}, {user: socket._acl.user}, function (err, data) {
if (data.rows.length) {
for (let i = 0; i < data.rows.length; i++) {
if (data.rows[i].value.common.hostname === ip) {
if (typeof callback === 'function') {
callback(ip, data.rows[i].value);
} else {
that.adapter.log.warn('[getHostByIp] Invalid callback')
}
return;
}
if (data.rows[i].value.native.hardware && data.rows[i].value.native.hardware.networkInterfaces) {
let net = data.rows[i].value.native.hardware.networkInterfaces;
for (let eth in net) {
if (!net.hasOwnProperty(eth)) continue;
for (let j = 0; j < net[eth].length; j++) {
if (net[eth][j].address === ip) {
if (typeof callback === 'function') {
callback(ip, data.rows[i].value);
} else {
that.adapter.log.warn('[getHostByIp] Invalid callback')
}
return;
}
}
}
}
}
}
if (typeof callback === 'function') {
callback(ip, null);
} else {
that.adapter.log.warn('[getHostByIp] Invalid callback')
}
});
}
});
socket.on('getForeignObjects', function (pattern, type, callback) {
if (updateSession(socket) && checkPermissions(socket, 'getObjects', callback)) {
if (typeof type === 'function') {
callback = type;
type = undefined;
}
that.adapter.getForeignObjects(pattern, type, {user: socket._acl.user}, function (err, objs) {
if (typeof callback === 'function') {
callback(err, objs);
} else {
that.adapter.log.warn('[getObjects] Invalid callback')
}
});
}
});
socket.on('getForeignStates', function (pattern, callback) {
if (updateSession(socket) && checkPermissions(socket, 'getStates', callback)) {
that.adapter.getForeignStates(pattern, {user: socket._acl.user}, function (err, objs) {
if (typeof callback === 'function') {
callback(err, objs);
} else {
that.adapter.log.warn('[getObjects] Invalid callback')
}
});
}
});
socket.on('requireLog', function (isEnabled, callback) {
if (updateSession(socket) && checkPermissions(socket, 'setObject', callback)) {
if (isEnabled) {
that.subscribe(this, 'log', 'dummy')
} else {
that.unsubscribe(this, 'log', 'dummy')
}
if (that.adapter.log.level === 'debug') showSubscribes(socket, 'log');
if (typeof callback === 'function') {
setImmediate(callback, null);
}
}
});
socket.on('readLogs', function (callback) {
if (updateSession(socket) && checkPermissions(socket, 'readLogs', callback)) {
let result = {list: []};
// deliver file list
try {
let config = adapter.systemConfig;
// detect file log
if (config && config.log && config.log.transport) {
for (let transport in config.log.transport) {
if (config.log.transport.hasOwnProperty(transport) && config.log.transport[transport].type === 'file') {
let filename = config.log.transport[transport].filename || 'log/';
let parts = filename.replace(/\\/g, '/').split('/');
parts.pop();
filename = parts.join('/');
if (filename[0] === '.') {
filename = path.normalize(__dirname + '/../../../') + filename;
}
if (fs.existsSync(filename)) {
let files = fs.readdirSync(filename);
for (let f = 0; f < files.length; f++) {
try {
if (!fs.lstatSync(filename + '/' + files[f]).isDirectory()) {
result.list.push('log/' + transport + '/' + files[f]);
}
} catch (e) {
// push unchecked
// result.list.push('log/' + transport + '/' + files[f]);
adapter.log.error('Cannot check file: ' + filename + '/' + files[f]);
}
}
}
}
}
} else {
result.error = 'no file loggers';
result.list = undefined;
}
} catch (e) {
adapter.log.error(e);
result.error = e;
result.list = undefined;
}
if (typeof callback === 'function') {
callback(result.error, result.list);
}
}
});
} else {
// only flot allowed
socket.on('delObject', function (id, callback) {
if (id.match(/^flot\./)) {
if (updateSession(socket) && checkPermissions(socket, 'delObject', callback, id)) {
that.adapter.delForeignObject(id, {user: socket._acl.user}, callback);
}
} else {
if (typeof callback === 'function') {
callback('permissionError');
}
}
});
}
socket.on('getState', function (id, callback) {
if (updateSession(socket) && checkPermissions(socket, 'getState', callback, id)) {
that.adapter.getForeignState(id, {