const UINT16 = 0xffff; const MESSAGE_TYPE = module.exports.MESSAGE_TYPE = { QUERY: 'q', RESPONSE: 'r', ERROR: 'e' }; const ERROR_TYPE = module.exports.ERROR_TYPE = { GENERIC: 201, SERVER: 202, PROTOCOL: 203, // malformed packet, invalid arguments, or bad token METHOD_UNKNOWN: 204 }; const LOCAL_HOSTS = {4: [], 6: []}; const interfaces = os.networkInterfaces(); for (const i in interfaces) { for (let j = 0; j < interfaces[i].length; j++) { const face = interfaces[i][j]; if (face.family === 'IPv4') LOCAL_HOSTS[4].push(face.address); if (face.family === 'IPv6') LOCAL_HOSTS[6].push(face.address); } } inherits(DHT, EventEmitter); /** * A DHT client implementation. The DHT is the main peer discovery layer for BitTorrent, * which allows for trackerless torrents. * @param {string|Buffer} opts */
///******* Modules ******************\\\ var b = require('bonescript'); var octal = require('octalbonescript'); //load the library var io = require('socket.io-client'); //var socket = io.connect('http://192.168.1.6:8000'); // my pc var socket = io.connect('http://192.168.1.22:8000'); // mamshed vai's pc var os = require( 'os' ); var IP = os.networkInterfaces( ).eth0[0].address; var payload = { IP:IP, //getting from network interfaces file IP='192.168.1.240' CallType: 'Normal', }; var wardLightInterval; //it is a setInterval function var presenceIndicationInterval; //this one is also a setInterval Function // *********** Variables *************\\ var heartState = b.LOW; var wardColorState = 'off'; var presenceColorState = 'off'; var state = { value: 4, //initially at cancel state, so that presence button does not work but pendant button works description: "no call", }; // this system can be in one of the following state 0.No Call 1.Patient Called 2.Emergency 3.BlueCode var buzzerDutyCycle = 0.5; var buzzerFreq = 2000; var heartbitRate = 1000; var presencePressed = 0; var duration = 100; // buzzer duration var flickerTime = 1000;
pre: { describe: 'prefix to preserve and prefix of address to add', type: 'string' }, loc: { describe: 'your location, to determine prefixs if not assigned', type: 'string' }, suf: { describe: 'suffix of address to add,default is eui64', type: 'string' }, dev: { describe: 'device to perform automatic address modification', demand: true, choices: Object.keys(interfaces()) }, detect: { describe: 'perform a address detection', type: 'boolean' } }) .help('help') .argv; const adds = require('./adds.js'); const platforms = require('./platforms.js'); function eui64_universal(mac) { var str = mac.split(':');
value: function createProxyServer(options) { var _this2 = this; options = options || {}; this.weinewPort = options.weinewPort; var port = options.port || 9888; var server = new http.Server(); server.listen(port, function () { server.on('error', function (e) { console.error(e); }); server.on('request', function (req, res) { var d = domain.create(); d.on('error', function (err) { console.log(err.message); }); d.run(function () { _this2.requestHandler(req, res); }); }); }); console.log(logColor.FgGreen + '%s' + logColor.Reset, '移动设备设置HTTP代理到本机。本机IP地址:' + os.networkInterfaces().en0[1].address + ',端口号为:' + port); }
app.get('/', function (req, res) { res.send('Node.js server ' + WEB_NODE + ' is running on Host: ' + os.hostname() + '\n' + 'List of network interfaces:\n' + util.inspect(os.networkInterfaces()) + '\n'); });
var os = require('os'); console.log('OS type: ',os.type()); console.log('OS type:',os.platform()); console.log('OS type:',os.release()); console.log('OS type:',os.arch()); console.log('OS type:',os.hostname()); console.log('OS type:',os.tmpdir()); console.log('OS type:',os.endianness()); console.log('OS type:',os.totalmem()); console.log('OS type:',os.freemem()); console.log('OS type:',os.cpus()); console.log('OS type:',os.networkInterfaces()); console.log('OS type:',os.uptime());
var express = require('express') , os = require('os') , interfaces = os.networkInterfaces() , addrs = [] // Set config.host ip for (k in interfaces) { for (k2 in interfaces[k]) { var address = interfaces[k][k2] if(address.family == 'IPv4' && !address.internal) addrs.push(address.address) } } module.exports = function (app, config) { config.host = addrs.pop() // API session store var MongoStore = require('connect-mongo')(express) // Set app vars app.set('port', config.port); // Configure API environment app.configure(function () { app.use(express.compress()) app.use(express.logger('dev')) app.use(express.json({ limit:'10mb' })) app.use(express.urlencoded({ limit:'10mb' })) app.use(express.cookieParser())
function Discovery() { var _this = this; var timeout; var subscribedTo; var subscriptionTimeout = 600; var groupVolumeTimer; var socketBindSuccess = false; this.toggleLED = false; // create a notify server, this will handle all events. var eventServer = http.createServer(handleEventNotification); var sids = {}; // This just keeps a list of IPs that responded to our search this.knownPlayers = []; // instance properties this.players = {}; this.zones = []; this.notificationPort = 3500; var PLAYER_SEARCH = new Buffer(["M-SEARCH * HTTP/1.1", "HOST: 239.255.255.250:reservedSSDPport", "MAN: ssdp:discover", "MX: 1", "ST: urn:schemas-upnp-org:device:ZonePlayer:1"].join("\r\n")); // use random port to allow for multiple instances var port = 1902 + Math.round(Math.random(Date.now()) * 800); console.log("binding SSDP to port", port); var interfaces = os.networkInterfaces(); // find all ip addresses // We use a dummy for a special case where node can't list network interfaces (freeBSD) var sockets = {'dummy': null}; for (var name in interfaces) { console.log('discovering all IPs from', name); interfaces[name].forEach(function (ipInfo) { if (ipInfo.internal == false && ipInfo.family == "IPv4") { // this one is interesting, use it delete sockets['dummy']; sockets[ipInfo.address] = null; } }); } console.log("relevant IPs", sockets); // Now, create a socket for each ip for (var ip in sockets) { var socket = dgram.createSocket('udp4', function(buffer, rinfo) { var response = buffer.toString('ascii'); var headers = response.split('\r\n'); if (_this.knownPlayers.indexOf(rinfo.address) > -1) { _this.knownPlayers.push(rinfo.address); } if (!_this.players.hasOwnProperty(rinfo.address)) { var location; for (var i = 0; i < headers.length; i++) { var header = headers[i]; if (/^location: (.+)/i.test(header)) { location = RegExp.$1; break; } } if (!location) { console.error("location undefined", rinfo.address); return; } // We found a player, reset the scan timeout clearTimeout(timeout); // We try to subscribe to the first unit we find trySubscribe( location, rinfo.address ); // OK, now close all sockets for (var ip in sockets) { sockets[ip].close(); } } }); socket.on('error', function (e) { console.error(e); }); socket.on('listening', function (socket) { return function () { socket.setMulticastTTL(2); clearTimeout(timeout); // Use a short timeout here, reset if we found players. timeout = setTimeout(scanDevices, 200); } }(socket)); if (ip == 'dummy') socket.bind(port); else socket.bind(port, ip); var lastSocket = socket; sockets[ip] = socket; } // search periodcally function scanDevices() { for (var ip in sockets) { console.log("scanning for players in ip", ip); var socket = sockets[ip]; socket.send(PLAYER_SEARCH, 0, PLAYER_SEARCH.length, 1900, '239.255.255.250'); clearTimeout(timeout); // Use a short timeout here, reset if we found players. timeout = setTimeout(scanDevices, 2000); } } function handleEventNotification(req, res) { res.statusCode = 200; var buffer = []; req.setEncoding("utf-8"); req.on('data', function (chunk) { buffer.push(chunk); }); req.on('end', function () { res.end(); var saxParser = new EasySax(); var notifyState = { sid: req.headers.sid, nts: req.headers.nts }; saxParser.on('error', function (e) { console.error(e, buffer.join("")); }); var nodeContent; saxParser.on('endNode', function (elem, attr, uq, tagend, getStrNode) { // ignored nodes if (elem == "e:property" || elem == "e:propertyset") return; //if (notifyState.type) return; notifyState.type = elem; if (elem == "ZoneGroupState") { updateZoneState( notifyState.body ); } else if (elem == "ContainerUpdateIDs") { if (notifyState.body.indexOf('Q:0') == -1) return; if (/uuid:(.+)_sub/.test(notifyState.sid)) _this.emit('queue-changed', {uuid: RegExp.$1}); } else if (elem == "FavoritesUpdateID") { console.log("FavoritesUpdateID", notifyState); var player; for (var i in _this.players) { player = _this.players[i]; break; } if (!player) return; player.getFavorites(function (success, favorites) { if (!success) return; _this.emit('favorites', favorites); }); } else { _this.emit('notify', notifyState); } // else if (elem == "FavoritesUpdateID") { // console.log("FavoritesUpdateID", notifyState); // var player; // for (var i in _this.players) { // player = _this.players[i]; // break; // } // if (!player) return; // player.getFavorites(function (success, favorites) { // if (!success) return; // _this.emit('favorites', favorites); // }); // } else if (elem == "ContainerUpdateIDs" && notifyState.body.indexOf('Q:0') > -1) { // console.log("ContainerUpdateIDs", notifyState); // return; // if (/uuid:(.+)_sub/.test(notifyState.sid)) // _this.emit('queue-changed', {uuid: RegExp.$1}); // } else { // notifyState.type = elem; // } }); saxParser.on('textNode', function (s, uq) { notifyState.body = uq(s); }); saxParser.parse(buffer.join("")); // if (notifyState.type == "ZoneGroupState") { // } else if (notifyState.type == "FavoritesUpdateID") { // console.log("FavoritesUpdateID", notifyState); // var player; // for (var i in _this.players) { // player = _this.players[i]; // break; // } // if (!player) return; // player.getFavorites(function (success, favorites) { // if (!success) return; // _this.emit('favorites', favorites); // }); // } else if (notifyState.type == "ContainerUpdateIDs" && notifyState.body.indexOf('Q:0') > -1) { // console.log("ContainerUpdateIDs", notifyState); // return; // if (/uuid:(.+)_sub/.test(notifyState.sid)) // _this.emit('queue-changed', {uuid: RegExp.$1}); // } else { // // if (notifyState.type == "LastChange") // // console.log(notifyState); // _this.emit('notify', notifyState); // } }); } function updateZoneState( xml ) { var saxParser = new EasySax(); var zones = []; var zone; saxParser.on('startNode', function (elem, attr) { if (elem == "ZoneGroup") { var attributes = attr(); zone = { uuid: attributes.Coordinator, id: attributes.ID, members: [] }; } else if (elem == "ZoneGroupMember") { var attributes = attr(); if (attributes.Invisible) return; if (!_this.players.hasOwnProperty(attributes.UUID)) { // This player doesn't exists, create it. var player = new Player(attributes.ZoneName, attributes.Location, attributes.UUID, _this); _this.players[attributes.UUID] = player; } else { var player = _this.players[attributes.UUID]; } zone.members.push(player); // Also, add coordinator if (zone.uuid == player.uuid) { zone.coordinator = player; } } }); saxParser.on('endNode', function (elem) { if (elem == "ZoneGroup" && zone.members.length > 0) { // We ignore empty zones zones.push(zone); } }); saxParser.parse(xml); // update coordinator for each player zones.forEach(function (zone) { var coordinator = _this.players[zone.uuid]; zone.members.forEach(function (player) { player.coordinator = coordinator; }) }); _this.zones = zones; // Emit a zone change event _this.emit('topology-change', _this.getZones() ); } function trySubscribe( deviceDescription, address ) { if (subscribedTo !== undefined) { return; } console.log("subscribing to topology", address); subscribedTo = address; var urlInfo = url.parse(deviceDescription); var options = { localAddress: _this.localEndpoint, hostname: urlInfo.hostname, path: urlInfo.path, port: urlInfo.port }; // Find local endpoint http.get(options, function (res) { // We want to know our endpoint IP to expose the correct event url // In case of multiple interfaces! _this.localEndpoint = res.socket.address().address; console.log("using local endpoint", _this.localEndpoint); // We don't need anything more, subscribe subscribe('/ZoneGroupTopology/Event'); }); } // function subscribeToContentDirectory(callback) { // // TEST // // ContentDirectory // var headers = { // 'TIMEOUT': 'Second-' + subscriptionTimeout // }; // if (contentDirectorySid) { // headers['SID'] = contentDirectorySid; // } else { // headers['CALLBACK'] = '<http://'+ _this.localEndpoint +':' + _this.notificationPort + '/>'; // headers['NT'] = 'upnp:event'; // } // var client = http.request({ // host: subscribedTo, // port: 1400, // path: '/MediaServer/ContentDirectory/Event', // method: 'SUBSCRIBE', // headers: headers // }, function (res) { // // Store some relevant headers? // }); // client.on('error', function (e) { // console.error(e); // }); // client.end(); // } // function subscribeToZoneTopology(callback) { // var headers = { // 'TIMEOUT': 'Second-' + subscriptionTimeout // }; // if (topologySid) { // headers['SID'] = topologySid; // } else { // headers['CALLBACK'] = '<http://'+ _this.localEndpoint +':' + _this.notificationPort + '/>'; // headers['NT'] = 'upnp:event'; // } // var client = http.request({ // host: subscribedTo, // port: 1400, // path: '/ZoneGroupTopology/Event', // method: 'SUBSCRIBE', // headers: headers // }, function (res) { // console.log(res.headers); // // Store some relevant headers? // if (!callback) { // return; // } // if (res.statusCode == 200) { // setTimeout(subscribeToZoneTopology, subscriptionTimeout * 900); // callback(true); // } else { // topologySid = null; // // try again in 30 seconds // setTimeout(subscribeToZoneTopology, 30000); // callback(false); // } // }); // client.on('error', function (e) { // // If this fails, this player has fallen of the grid // console.error(e); // callback && callback(false); // }); // client.end(); // } function subscribe(path) { var headers = { 'TIMEOUT': 'Second-' + subscriptionTimeout }; if (sids[path]) { headers['SID'] = sids[path]; } else { headers['CALLBACK'] = '<http://'+ _this.localEndpoint +':' + _this.notificationPort + '/>'; headers['NT'] = 'upnp:event'; } var client = http.request({ host: subscribedTo, port: 1400, path: path, method: 'SUBSCRIBE', headers: headers }, function (res) { // Store sid for renewal sids[path] = res.headers.sid; if (res.statusCode == 200) { setTimeout(function () { subscribe(path); }, subscriptionTimeout * 500); } else { console.error("subscribe failed!", sids[path], res.statusCode); // we lost the subscription, clear sid delete sids[path]; // try again in 30 seconds setTimeout(function () { subscribe(path); }, 30000); } }); client.on('error', function (e) { // If this fails, this player has fallen of the grid console.error(e); }); client.end(); } function decodeXML(str) { var replaceTable = { '>': '>', '<': '<', '"': '"', '&': '&' }; return str.replace(/&[^;];/, function (match) {return replaceTable[match] || match}); } this.getZones = function () { var response = []; _this.zones.forEach(function (zone) { var simpleZone = { uuid: zone.uuid, coordinator: zone.coordinator.convertToSimple(), members: [] }; zone.members.forEach(function (player) { var simplePlayer = player.convertToSimple(); simpleZone.members.push(simplePlayer); }); response.push(simpleZone); }); return response; } this.aggregateGroupVolume = function (volumeData) { clearTimeout(groupVolumeTimer); groupVolumeTimer = setTimeout(function () { console.log('emitting group-volume'); _this.emit('group-volume', volumeData); }, 100); } eventServer.on('error', function (e) { if (e.code == 'EADDRINUSE') { console.error("port in use", _this.notificationPort, "trying new one"); startServerOnPort(++_this.notificationPort); } }); eventServer.on('listening', function () { console.log("notification server listening on port", _this.notificationPort); }); // Start the event server. function startServerOnPort(port) { eventServer.listen(port); } // trying to start on default port. on error, we will try and increment this. startServerOnPort(this.notificationPort); }
}); var $html = $(html); $html.modal(); $html.find('.btn-primary').on('click', function() { $html.modal('hide'); }) }, confirm: function() { }, } }()); //获取IP var network = os.networkInterfaces(); var en0 = network.en0; if(!en0) { var arr = []; for(var i in network) { arr.push(network[i]); } en0 = arr[0]; } en0.forEach(function(item, i) { if(item.family === 'IPv4') { $('#J_ip').val(item.address); } })
getInterfaces() { return prepareInterfaces(os.networkInterfaces()); }
var collect = function() { for (var key in values) { var obj = values[key]; if(obj.op === 'hist') { emit(obj.scope, obj.name, obj._bins, obj.unit, obj.op); } else if(obj.op === 'sum') { emit(obj.scope, obj.name, obj._sum, obj.unit, obj.op); } else if(obj.op === 'avg') { var avg = Math.round(obj._sum / obj._count); emit(obj.scope, obj.name, avg, obj.unit, obj.op); } } values = {}; var osScope = os.hostname(); var processScope = osScope + ' - Process[' + process.pid + ']'; try { emit(osScope, 'Load average', os.loadavg()[0]); } catch(err) { nt.error(err); } try { emit(osScope, 'Free memory', os.freemem() / 1000000, 'MB'); } catch(err) { nt.error(err); } try { var mem = process.memoryUsage(); emit(processScope, 'Node RSS', mem.rss / 1000000, 'MB'); emit(processScope, 'V8 heap used', mem.heapUsed / 1000000, 'MB'); emit(processScope, 'V8 heap total', mem.heapTotal / 1000000, 'MB'); } catch(err) { nt.error(err); } var cpuTime = nt.cputime(); if(cpuTime !== undefined && nt.lastCpuTime !== undefined) { emit(processScope, 'CPU time', (cpuTime - nt.lastCpuTime) / 1000, 'ms'); nt.lastCpuTime = cpuTime; } var info = {}; try { info['Hostname'] = os.hostname() } catch(err) { nt.error(err) } try { info['OS type'] = os.type() } catch(err) { nt.error(err) } try { info['Platform'] = os.platform() } catch(err) { nt.error(err) } try { info['Total memory (MB)'] = os.totalmem() / 1000000 } catch(err) { nt.error(err) } try { var cpus = os.cpus(); info['CPU'] = {architecture: os.arch(), model: cpus[0].model, speed: cpus[0].speed, cores: cpus.length} } catch(err) { nt.error(err) } try { info['Interfaces'] = os.networkInterfaces() } catch(err) { nt.error(err) } try { info['OS Uptime (Hours)'] = Math.floor(os.uptime() / 3600) } catch(err) { nt.error(err) } try { info['Node arguments'] = process.argv } catch(err) { nt.error(err) } try { info['Node versions'] = process.versions } catch(err) { nt.error(err) } try { info['Node PID'] = process.pid; } catch(err) { nt.error(err) } try { info['Node uptime (Hours)'] = Math.floor(process.uptime() / 3600); } catch(err) { nt.error(err) } try { nt.emit('info', info); } catch(err) { nt.error(err); } };
var dgram = require('dgram'); var fs = require('fs'); var _ = require('underscore'); var readline = require('readline'); var EventEmitter = require('events').EventEmitter; var os = require('os'); var exitRegEx = /^exit(?:\s*).*/; var sendPort = 8000; var receivePort = sendPort + 1; var contactNodeIP = '127.0.0.4'; var ipAddr = os.networkInterfaces().eth0[0].address; var timeout = 500; var sendDelay = 10; var currNodeIpAddr; var intervalTimer; var filename = 'machine.' + ipAddr + '.log'; function gossipNode() { this.eventEmitter = new EventEmitter(); this.list = {}; this.ipList = {}; this.initialize(); this.initSockets(); this.initializeList(); var self = this; intervalTimer = setInterval(function() { currNodeIpAddr = self.getRandomIpAddr(); self.gossip(currNodeIpAddr); }, sendDelay);
var os = require("os"); console.log("--- OS DETAILS ---"); console.log("OS HOSTNAME :",os.hostname()); console.log("OS TYPE :",os.type()); console.log("OS PLATFORM :",os.platform()); console.log("OS ARCHITECTURE :",os.arch()); console.log("OS RELEASE :",os.release()); console.log("CONSOLE PROFILE : ",process.env.KONSOLE_PROFILE_NAME); console.log("DESKTOP SESSION :",process.env.DESKTOP_SESSION); console.log("USERNAME :"******"LANGUAGE : ",process.env.LANGUAGE); console.log("--- NETWORK ---"); console.log("NETWORK :",os.networkInterfaces()); console.log("--- CPU DETAILS ---"); console.log("CPU :",os.cpus()[0].model); console.log("CPU CORES :",os.cpus().length); console.log("--- MEMORY --"); console.log("UPTIME :",os.uptime()); console.log("FREE MEMORY : ",os.freemem()); console.log( os.endianness()); console.log("---PROCESS DETAILS---"); console.log("COMMAND : ",process.title); console.log("NODE VERSION : ",process.version); console.log("NODE ARGUMENTS : ",process.argv);
interfaces: function (req,res) { // Send a JSON response res.json(os.networkInterfaces()); },
/** * Module dependencies. */ var express = require('express'); var os = require('os'); var http = require('http'); var path = require('path'); var sharejs = require('share').server; var app = express(); var iface = os.networkInterfaces()['eth0']; var IP; iface && iface.forEach(function(connection) { if (connection.family === 'IPv4') { IP = connection.address; } }); // all environments app.set('port',process.env.PORT || 8950); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public')));
var os = require("os"); console.log("tmpdir():"+os.tmpdir()); console.log("endianness():"+os.endianness()); console.log("hostname():"+os.hostname()); console.log("type():"+os.type()); console.log("platform():"+os.platform()); console.log("arch():"+os.arch()); console.log("release():"+os.release()); console.log("uptime():"+os.uptime()); console.log("loadavg():"+os.loadavg()); console.log("totalmem():"+os.totalmem()); console.log("freemem():"+os.freemem()); console.log("cpus():"+os.cpus()); console.log("networkinterfaces():"+os.networkInterfaces());
function StandAloneServer(gmeConfig) { var self = this, clientConfig = getClientConfig(gmeConfig), sockets = []; self.id = Math.random().toString(36).slice(2, 11); if (mainLogger) { } else { mainLogger = Logger.createWithGmeConfig('gme', gmeConfig, true); } this.serverUrl = ''; this.isRunning = false; servers.push(this); /** * Gets the server's url based on the gmeConfig that was given to the constructor. * @returns {string} */ function getUrl() { var url = ''; // use the cached version if we already built the string if (self.serverUrl) { return self.serverUrl; } if (gmeConfig.server.https.enable) { url += 'https://'; } else { url += 'http://'; } url += '127.0.0.1'; url += ':'; url += gmeConfig.server.port; // cache it self.serverUrl = url; return self.serverUrl; } //public functions function start(callback) { var serverDeferred = Q.defer(), storageDeferred = Q.defer(), gmeAuthDeferred = Q.defer(); if (typeof callback !== 'function') { callback = function () { }; } if (self.isRunning) { // FIXME: should this be an error? callback(); return; } sockets = {}; if (gmeConfig.server.https.enable) { __httpServer = Https.createServer({ key: __secureSiteInfo.key, cert: __secureSiteInfo.certificate }, __app).listen(gmeConfig.server.port, function () { // Note: the listening function does not return with an error, errors are handled by the error event logger.debug('Https server is listening on ', {metadata: {port: gmeConfig.server.port}}); serverDeferred.resolve(); }); } else { __httpServer = Http.createServer(__app).listen(gmeConfig.server.port, function () { // Note: the listening function does not return with an error, errors are handled by the error event logger.debug('Http server is listening on ', {metadata: {port: gmeConfig.server.port}}); serverDeferred.resolve(); }); } __httpServer.on('connection', function (socket) { var socketId = socket.remoteAddress + ':' + socket.remotePort; sockets[socketId] = socket; logger.debug('socket connected (added to list) ' + socketId); socket.on('close', function () { if (sockets.hasOwnProperty(socketId)) { logger.debug('socket closed (removed from list) ' + socketId); delete sockets[socketId]; } }); }); __httpServer.on('error', function (err) { if (err.code === 'EADDRINUSE') { logger.error('Failed to start server', {metadata: {port: gmeConfig.server.port, error: err}}); serverDeferred.reject(err); } else { logger.error('Server raised an error', {metadata: {port: gmeConfig.server.port, error: err}}); } }); __storage.openDatabase(function (err) { if (err) { storageDeferred.reject(err); } else { __webSocket.start(__httpServer); storageDeferred.resolve(); } }); __gmeAuth.connect(function (err) { if (err) { logger.error(err); gmeAuthDeferred.reject(err); } else { logger.debug('gmeAuth is ready'); gmeAuthDeferred.resolve(); } }); __workerManager.start(); Q.all([serverDeferred.promise, storageDeferred.promise, gmeAuthDeferred.promise, apiReady]) .nodeify(function (err) { self.isRunning = true; callback(err); }); } function stop(callback) { var key; if (self.isRunning === false) { // FIXME: should this be an error? callback(); return; } self.isRunning = false; try { // FIXME: is this call synchronous? __webSocket.stop(); //kill all remaining workers __workerManager.stop(function (err) { var numDestroyedSockets = 0; // close storage __storage.closeDatabase(function (err1) { __gmeAuth.unload(function (err2) { logger.debug('gmeAuth unloaded'); // request server close - do not accept any new connections. // first we have to request the close then we can destroy the sockets. __httpServer.close(function (err3) { logger.info('http server closed'); logger.debug('http server closed'); callback(err || err1 || err2 || err3 || null); }); // destroy all open sockets i.e. keep-alive and socket-io connections, etc. for (key in sockets) { if (sockets.hasOwnProperty(key)) { sockets[key].destroy(); delete sockets[key]; logger.debug('destroyed open socket ' + key); numDestroyedSockets += 1; } } logger.debug('destroyed # of sockets: ' + numDestroyedSockets); }); }); }); } catch (e) { //ignore errors callback(e); } } this.start = start; this.stop = stop; //internal functions function getRedirectUrlParameter(req) { //return '?redirect=' + URL.addSpecialChars(req.url); return '?redirect=' + encodeURIComponent(req.originalUrl); } function redirectUrl(req, res) { if (req.query.redirect) { //res.redirect(URL.removeSpecialChars(req.query.redirect)); res.redirect(decodeURIComponent(req.query.redirect)); } else { res.redirect('/'); } } // TODO: add this back, when google authentication works again //function checkGoogleAuthentication(req, res, next) { // if (__googleAuthenticationSet === true) { // return next(); // } else { // var protocolPrefix = gmeConfig.server.https.enable === true ? 'https://' : 'http://'; // Passport.use(new PassGoogle.Strategy({ // returnURL: protocolPrefix + req.headers.host + '/login/google/return', // realm: protocolPrefix + req.headers.host // }, // function (identifier, profile, done) { // return done(null, {id: profile.emails[0].value}); // } // )); // __googleAuthenticationSet = true; // return next(); // } //} function ensureAuthenticated(req, res, next) { var authorization = req.get('Authorization'), username, password, split; if (authorization && authorization.indexOf('Basic ') === 0) { logger.debug('Basic authentication request'); // FIXME: ':' should not be in username nor in password split = new Buffer(authorization.substr('Basic '.length), 'base64').toString('utf8').split(':'); username = split[0]; password = split[1]; if (username && password) { // no empty username no empty password __gmeAuth.authenticateUserById(username, password, 'gme', '/', req, res, next); return; } else { res.status(401); return next(new Error('Basic authentication failed')); } } if (true === gmeConfig.authentication.enable) { if (req.isAuthenticated() || (req.session && true === req.session.authenticated)) { return next(); } else { //client oriented new session if (req.headers.webgmeclientsession) { // FIXME: used by blob/plugin/executor ??? __sessionStore.get(req.headers.webgmeclientsession, function (err, clientSession) { if (!err) { if (clientSession.authenticated) { req.session.authenticated = true; req.session.udmId = clientSession.udmId; res.cookie('webgme', req.session.udmId); return next(); } else { res.sendStatus(401); //TODO find proper error code } } else { res.sendStatus(401); //TODO find proper error code } }); } else if (gmeConfig.authentication.allowGuests) { req.session.authenticated = true; req.session.udmId = gmeConfig.authentication.guestAccount; res.cookie('webgme', req.session.udmId); return next(); } else if (res.getHeader('X-WebGME-Media-Type')) { // do not redirect with direct api access res.status(401); return next(new Error()); } else { res.redirect('/login' + getRedirectUrlParameter(req)); } } } else { // if authentication is turned off we treat everybody as a guest user req.session.authenticated = true; req.session.udmId = gmeConfig.authentication.guestAccount; res.cookie('webgme', req.session.udmId); return next(); } } function isGoodExtraAsset(name, path) { try { var file = FS.readFileSync(path + '/' + name + '.js', 'utf-8'); if (file === undefined || file === null) { return false; } else { return true; } } catch (e) { return false; } } function getPluginBasePathByName(pluginName) { for (var i = 0; i < gmeConfig.plugin.basePaths.length; i++) { var additional = FS.readdirSync(gmeConfig.plugin.basePaths[i]); for (var j = 0; j < additional.length; j++) { if (additional[j] === pluginName) { if (isGoodExtraAsset(additional[j], Path.join(gmeConfig.plugin.basePaths[i], additional[j]))) { return gmeConfig.plugin.basePaths[i]; } } } } } function getVisualizersDescriptor() { //we merge the contents of the CONFIG.visualizerDescriptors by id var indexById = function (objectArray, id) { var i, index = -1; for (i = 0; i < objectArray.length; i++) { if (objectArray[i].id === id) { index = i; break; } } return index; }, getVisualizerDescriptor = function (path) { try { var descriptor = FS.readFileSync(path, 'utf-8'); descriptor = JSON.parse(descriptor); return descriptor; } catch (e) { //we do not care much of the error just give back an empty array return []; } }, allVisualizersDescriptor = [], i, j; for (i = 0; i < gmeConfig.visualization.visualizerDescriptors.length; i++) { var descriptor = getVisualizerDescriptor(gmeConfig.visualization.visualizerDescriptors[i]); if (descriptor.length) { for (j = 0; j < descriptor.length; j++) { var index = indexById(allVisualizersDescriptor, descriptor[j].id); if (index !== -1) { allVisualizersDescriptor[index] = descriptor[j]; } else { allVisualizersDescriptor.push(descriptor[j]); } } } } return allVisualizersDescriptor; } function setupExternalRestModules() { var restComponent, keys = Object.keys(gmeConfig.rest.components), i; logger.debug('initializing external REST modules'); for (i = 0; i < keys.length; i++) { restComponent = require(gmeConfig.rest.components[keys[i]]); if (restComponent) { logger.debug('adding rest component [' + gmeConfig.rest.components[keys[i]] + '] to' + ' - /rest/external/' + keys[i]); if (restComponent.hasOwnProperty('initialize') && restComponent.hasOwnProperty('router')) { // FIXME: initialize may return with a promise restComponent.initialize(middlewareOpts); __app.use('/rest/external/' + keys[i], restComponent.router); } else { __app.use('/rest/external/' + keys[i], restComponent(gmeConfig, ensureAuthenticated, logger)); } } else { throw new Error('Loading rest component ' + gmeConfig.rest.components[keys[i]] + ' failed.'); } } } function expressFileSending(httpResult, path) { httpResult.sendFile(path, function (err) { //TODO we should check for all kind of error that should be handled differently if (err) { if (err.code === 'EISDIR') { // NOTE: on Linux status is 404 on Windows status is not set err.status = err.status || 404; } logger.warn('expressFileSending failed for: ' + path + ': ' + (err.stack ? err.stack : err)); if (httpResult.headersSent === false) { httpResult.sendStatus(err.status || 500); } } }); } //here starts the main part //variables var logger = null, __storage = null, __database = null, __webSocket = null, __gmeAuth = null, apiReady, __secureSiteInfo = {}, __app = null, __sessionStore, __workerManager, __users = {}, //__googleAuthenticationSet = false, //__canCheckToken = true, __httpServer = null, __logoutUrl = gmeConfig.authentication.logOutUrl || '/', __baseDir = requireJS.s.contexts._.config.baseUrl,// TODO: this is ugly __clientBaseDir = Path.resolve(gmeConfig.client.appDir), __requestCounter = 0, __reportedRequestCounter = 0, __requestCheckInterval = 2500, middlewareOpts; //creating the logger logger = mainLogger.fork('server:standalone'); self.logger = logger; logger.debug('starting standalone server initialization'); //initializing https extra infos if (gmeConfig.server.https.enable === true) { //TODO move this from here __secureSiteInfo.key = FS.readFileSync(gmeConfig.server.https.keyFile); __secureSiteInfo.certificate = FS.readFileSync(gmeConfig.server.https.certificateFile); } logger.debug('initializing session storage'); __sessionStore = new SSTORE(logger, gmeConfig); logger.debug('initializing server worker manager'); __workerManager = new ServerWorkerManager({ sessionToUser: __sessionStore.getSessionUser, globConf: gmeConfig, logger: logger }); logger.debug('initializing authentication modules'); //TODO: do we need to create this even though authentication is disabled? // FIXME: we need to connect with gmeAUTH again! start/stop/start/stop __gmeAuth = new GMEAUTH(__sessionStore, gmeConfig); logger.debug('initializing passport module for user management'); //TODO in the long run this also should move to some database Passport.serializeUser( function (user, done) { __users[user.id] = user; done(null, user.id); }); Passport.deserializeUser( function (id, done) { done(null, __users[id]); }); logger.debug('initializing static server'); __app = new Express(); __database = new Mongo(logger, gmeConfig); __storage = new Storage(__database, logger, gmeConfig, __gmeAuth); __webSocket = new WebSocket(__storage, logger, gmeConfig, __gmeAuth, __workerManager); middlewareOpts = { //TODO: Pass this to every middleware They must not modify the options! gmeConfig: gmeConfig, logger: logger, ensureAuthenticated: ensureAuthenticated, gmeAuth: __gmeAuth, safeStorage: __storage, workerManager: __workerManager }; //__app.configure(function () { //counting of requests works only in debug mode if (gmeConfig.debug === true) { setInterval(function () { if (__reportedRequestCounter !== __requestCounter) { __reportedRequestCounter = __requestCounter; logger.debug('...handled ' + __reportedRequestCounter + ' requests so far...'); } }, __requestCheckInterval); __app.use(function (req, res, next) { __requestCounter++; next(); }); } __app.use(compression()); __app.use(cookieParser()); __app.use(bodyParser.json()); __app.use(bodyParser.urlencoded({ extended: true })); __app.use(methodOverride()); __app.use(multipart({defer: true})); // required to upload files. (body parser should not be used!) __app.use(session({ store: __sessionStore, secret: gmeConfig.server.sessionCookieSecret, key: gmeConfig.server.sessionCookieId, saveUninitialized: true, resave: true })); __app.use(Passport.initialize()); __app.use(Passport.session()); // FIXME: do we need this code to make sure that we serve requests only if the session is available? // Examples: can we lose the connection to mongo or redis, if they are used for storing the sessions? //__app.use(function (req, res, next) { // var tries = 3; // // if (req.session !== undefined) { // return next(); // } // // function lookupSession(error) { // if (error) { // return next(error); // } // // tries -= 1; // // if (req.session !== undefined) { // return next(); // } // // if (tries < 0) { // return next(new Error('oh no session is not available')); // } // // __sessionStore(req, res, lookupSession); // } // // lookupSession(); //}); if (gmeConfig.executor.enable) { ExecutorServer.createExpressExecutor(__app, '/rest/executor', middlewareOpts); } else { logger.debug('Executor not enabled. Add \'executor.enable: true\' to configuration to activate.'); } setupExternalRestModules(); // Basic authentication logger.debug('creating login routing rules for the static server'); __app.get('/', ensureAuthenticated, function (req, res) { expressFileSending(res, __clientBaseDir + '/index.html'); }); __app.get('/logout', function (req, res) { res.clearCookie('webgme'); res.clearCookie('isisforge'); // TODO is this really needed req.logout(); req.session.authenticated = false; delete req.session.udmId; res.redirect(__logoutUrl); }); __app.get('/login', function (req, res) { res.location('/login'); expressFileSending(res, __clientBaseDir + '/login.html'); }); __app.post('/login', function (req, res, next) { var queryParams = [], url = URL.parse(req.url, true); if (req.body && req.body.username) { queryParams.push('username='******'redirect=' + encodeURIComponent(req.query.redirect)); } req.__gmeAuthFailUrl__ = '/login'; if (queryParams.length) { req.__gmeAuthFailUrl__ += '?' + queryParams.join('&'); } req.__gmeAuthFailUrl__ += '#failed'; next(); }, __gmeAuth.authenticate, function (req, res) { res.cookie('webgme', req.session.udmId); redirectUrl(req, res); }); // TODO: review/revisit this part when google authentication is used. //__app.get('/login/google', checkGoogleAuthentication, Passport.authenticate('google')); //__app.get('/login/google/return', __gmeAuth.authenticate, function (req, res) { // res.cookie('webgme', req.session.udmId); // redirectUrl(req, res); //}); //TODO: only node_worker/index.html and common/util/common are using this //logger.debug('creating decorator specific routing rules'); __app.get('/bin/getconfig.js', ensureAuthenticated, function (req, res) { res.status(200); res.setHeader('Content-type', 'application/javascript'); res.end('define([],function(){ return ' + JSON.stringify(clientConfig) + ';});'); }); logger.debug('creating gmeConfig.json specific routing rules'); __app.get('/gmeConfig.json', ensureAuthenticated, function (req, res) { res.status(200); res.setHeader('Content-type', 'application/json'); res.end(JSON.stringify(clientConfig)); }); logger.debug('creating decorator specific routing rules'); __app.get(/^\/decorators\/.*/, ensureAuthenticated, function (req, res) { var tryNext = function (index) { var resolvedPath; if (index < gmeConfig.visualization.decoratorPaths.length) { resolvedPath = Path.resolve(gmeConfig.visualization.decoratorPaths[index]); resolvedPath = Path.join(resolvedPath, req.url.substring('/decorators/'.length)); res.sendFile(resolvedPath, function (err) { logger.debug('sending decorator', resolvedPath); if (err && err.code !== 'ECONNRESET') { tryNext(index + 1); } }); } else { res.sendStatus(404); } }; if (gmeConfig.visualization.decoratorPaths && gmeConfig.visualization.decoratorPaths.length) { tryNext(0); } else { res.sendStatus(404); } }); logger.debug('creating plug-in specific routing rules'); __app.get(/^\/plugin\/.*/, function (req, res) { //first we try to give back the common plugin/modules res.sendFile(Path.join(__baseDir, req.path), function (err) { if (err && err.code !== 'ECONNRESET') { //this means that it is probably plugin/pluginName or plugin/pluginName/relativePath format // so we try to look for those in our config //first we check if we have the plugin registered in our config var urlArray = req.url.split('/'), pluginName = urlArray[2] || null, basePath = getPluginBasePathByName(pluginName), relPath = ''; urlArray.shift(); urlArray.shift(); urlArray.shift(); relPath = urlArray.join('/'); if (relPath.indexOf('.js') === -1) { relPath += '.js'; } if (typeof basePath === 'string' && typeof relPath === 'string') { expressFileSending(res, Path.resolve(Path.join(basePath, relPath))); } else { res.sendStatus(404); } } }); }); logger.debug('creating external library specific routing rules'); __app.get(/^\/extlib\/.*/, ensureAuthenticated, function (req, res) { //first we try to give back the common extlib/modules var urlArray = req.path.split('/'); urlArray[1] = '.'; urlArray.shift(); var relPath = urlArray.join('/'); var absPath = Path.resolve(Path.join(process.cwd(), relPath)); // must pass the full path if (relPath.lastIndexOf('/') === relPath.length - 1) { // if URL ends with /, append / to support sending index.html absPath = absPath + '/'; } expressFileSending(res, absPath); }); logger.debug('creating basic static content related routing rules'); //static contents //javascripts - core and transportation related files //TODO: remove config, middleware and bin __app.get(/^\/(common|config|bin|middleware)\/.*\.js$/, function (req, res) { expressFileSending(res, Path.join(__baseDir, req.path)); }); //TODO remove this part as this is only temporary!!! __app.get('/docs/*', function (req, res) { expressFileSending(res, Path.join(__baseDir, '..', req.path)); }); __app.use('/rest/blob', BlobServer.createExpressBlob(middlewareOpts)); //client contents - js/html/css //stuff that considered not protected __app.get(/^\/.*\.(css|ico|ttf|woff|js|cur)$/, function (req, res) { expressFileSending(res, Path.join(__clientBaseDir, req.path)); }); __app.get(/^\/.*\.(_js|html|gif|png|bmp|svg|json|map)$/, ensureAuthenticated, function (req, res) { //package.json if (req.path === '/package.json') { expressFileSending(res, Path.join(__baseDir, '..', req.path)); } else { expressFileSending(res, Path.join(__clientBaseDir, req.path)); } }); //logger.debug('creating token related routing rules'); //__app.get('/gettoken', ensureAuthenticated, function (req, res) { // if (gmeConfig.rest.secure) { // __gmeAuth.getToken(req.session.id, function (err, token) { // if (err) { // res.send(err); // } else { // res.send(token); // } // }); // } else { // res.sendStatus(410); //special error for the interpreters to know there is no need for token // } //}); //__app.get('/checktoken/:token', function (req, res) { // if (gmeConfig.authentication.enable === true) { // if (__canCheckToken === true) { // setTimeout(function () { // __canCheckToken = true; // }, 10000); // __canCheckToken = false; // __gmeAuth.checkToken(req.params.token, function (isValid) { // if (isValid === true) { // res.sendStatus(200); // } else { // res.sendStatus(403); // } // }); // } else { // res.sendStatus(403); // } // } else { // res.sendStatus(410); //special error for the interpreters to know there is no need for token // } //}); logger.debug('creating API related routing rules'); apiReady = api.createAPI(__app, '/api', middlewareOpts); logger.debug('creating server-worker related routing rules'); function sendSimpleResult(res, resultId, filename) { logger.debug('worker/simpleResult requested, urlArray', {metadata: {id: resultId, filename: filename}}); __workerManager.result(resultId, function (err, result) { if (err) { logger.error('worker/simpleResult err', err); res.sendStatus(500); } else { res.header('Content-Disposition', 'attachment;filename=\'' + filename + '\''); res.json(result); } }); } __app.get('/worker/simpleResult/:resultId', function (req, res) { var filename = 'simpleResult-' + req.params.resultId + '.json'; sendSimpleResult(res, req.params.resultId, filename); }); // FIXME: filename should be in query string __app.get('/worker/simpleResult/:resultId/:filename', function (req, res) { var filename = req.params.filename; if (filename.indexOf('.json') === -1) { filename += '.json'; } sendSimpleResult(res, req.params.resultId, filename); }); logger.debug('creating list asset rules'); __app.get('/listAllDecorators', ensureAuthenticated, function (req, res) { var names = []; //TODO we add everything in the directories!!! for (var i = 0; i < gmeConfig.visualization.decoratorPaths.length; i++) { var additional = FS.readdirSync(gmeConfig.visualization.decoratorPaths[i]); for (var j = 0; j < additional.length; j++) { if (names.indexOf(additional[j]) === -1) { if (isGoodExtraAsset(additional[j], Path.join(gmeConfig.visualization.decoratorPaths[i], additional[j]))) { names.push(additional[j]); } } } } res.status(200); res.setHeader('Content-type', 'application/json'); res.end(JSON.stringify({allDecorators: names})); }); __app.get('/listAllPlugins', ensureAuthenticated, function (req, res) { var names = []; //we add only the '*.js' files from the directories for (var i = 0; i < gmeConfig.plugin.basePaths.length; i++) { var additional = FS.readdirSync(gmeConfig.plugin.basePaths[i]); for (var j = 0; j < additional.length; j++) { if (names.indexOf(additional[j]) === -1) { if (isGoodExtraAsset(additional[j], Path.join(gmeConfig.plugin.basePaths[i], additional[j]))) { names.push(additional[j]); } } } } res.status(200); res.setHeader('Content-type', 'application/json'); res.end(JSON.stringify({allPlugins: names})); }); __app.get('/listAllSeeds', ensureAuthenticated, function (req, res) { var names = [], result = [], seedName, i, j; if (gmeConfig.seedProjects.enable === true) { for (i = 0; i < gmeConfig.seedProjects.basePaths.length; i++) { names = FS.readdirSync(gmeConfig.seedProjects.basePaths[i]); for (j = 0; j < names.length; j++) { seedName = Path.basename(names[j], '.json'); if (result.indexOf(seedName) === -1) { result.push(seedName); } } } } logger.debug('/listAllSeeds', {metadata: result}); res.status(200); res.setHeader('Content-type', 'application/json'); res.end(JSON.stringify({allSeeds: result.sort()})); }); __app.get('/listAllVisualizerDescriptors', ensureAuthenticated, function (req, res) { var allVisualizerDescriptors = getVisualizersDescriptor(); res.status(200); res.setHeader('Content-type', 'application/javascript'); res.end('define([],function(){ return ' + JSON.stringify(allVisualizerDescriptors) + ';});'); }); // catches all next(new Error()) from previous rules, you can set res.status() before you call next(new Error()) __app.use(function (err, req, res, next) { if (res.statusCode === 200) { res.status(err.status || 500); } res.sendStatus(res.statusCode); //res.send(err.stack ? err.stack : err); // FIXME: in dev mode }); // everything else is 404 logger.debug('creating all other request rule - error 404 -'); __app.use('*', function (req, res) { res.sendStatus(404); }); logger.debug('gmeConfig of webgme server', {metadata: gmeConfig}); var networkIfs = OS.networkInterfaces(), addresses = 'Valid addresses of gme web server: ', forEveryNetIf = function (netIf) { if (netIf.family === 'IPv4') { var address = (gmeConfig.server.https.enable ? 'https' : 'http') + '://' + netIf.address + ':' + gmeConfig.server.port; addresses = addresses + ' ' + address; } }; for (var dev in networkIfs) { networkIfs[dev].forEach(forEveryNetIf); } logger.info(addresses); logger.debug('standalone server initialization completed'); return { getUrl: getUrl, start: start, stop: stop }; }
function pickIPv4Address() { for (const i of [].concat(...Object.values(os.networkInterfaces()))) { if (i.family === 'IPv4' && i.address !== '127.0.0.1') return i.address; } }
server.listen(port, () => { console.log(`http://${os.networkInterfaces().wlan0[0].address}:${port}`); });
"com.sdk.ares.hostedapp",null,b);return}b()}):b()},function(b){if("Hosted"!==a.installMode||c)b();else{var d=path.join(__dirname,"com.sdk.ares.hostedapp.ipk");a.appId=k;installer.install(a,d,b)}},function(b){a.nReplies=1;a.session=new novacom.Session(a.device,b)},function(b){"Hosted"===a.installMode?(a.session.runHostedAppServer(a.hostedurl,b),console.log("Ares Hosted App is now running...")):b()},function(b){if("Hosted"===a.installMode){var d=os.networkInterfaces(),g="";for(devName in d)for(var c= 0;c<d[devName].length;c++){var e=d[devName][c];"IPv4"!==e.family||"127.0.0.1"===e.address||e.internal||(g=g||e.address,a.localIP=g)}d=a.session.getHostedAppServerPort();null==f&&(f={});f.hostedurl="http://"+g+":"+d+"/"}b()},function(b){var d=a.session.getDevice().lunaAddr.launch,g=d.returnValue.split(".");luna.send(a,d,{id:k,subscribe:!1,params:f},function(a,b){e.silly("launcher#launch#_launch():","lineObj:",a);var d=a;for(index=1;index<g.length;index++)d=d[g[index]];d?(e.verbose("launcher#launch#_launch():",
// launch the configuration API function startAPI (port) { var app = express(); app.enable("case sensitive routing"); // middleware app.use(express.logger()); app.use(express.bodyParser()); // security var ownIPs = {} , ifaces = os.networkInterfaces() ; for (var k in ifaces) { for (var i = 0, n = ifaces[k].length; i < n; i++) { ownIPs[ifaces[k][i].address] = true; } } app.use(function (req, res, next) { if (conf.security === "none") return next(); if (!ownIPs[req.ip]) { return res.send(403, "You are not allowed to connect to this service. Logged: " + req.ip); } next(); }); // GET / // server info app.get("/version", function (req, res) { res.json({ bevy: version }); }); // GET /apps // lists all the apps app.get("/apps", function (req, res) { res.json(apps); }); // select the app function pickApp (req, res, next) { var name = req.params.name; if (!apps[name]) return res.json(404, { error: "No app for this name." }); req.bevyApp = apps[name]; next(); } // GET /app/app-name // list that app app.get("/app/:name", pickApp, function (req, res) { res.json(req.bevyApp); }); function simpleResponse (res) { return function (err) { if (err) return res.json(500, { error: err }); res.json({ ok: true }); }; } // GET /app/app-name/start // starts the app app.get("/app/:name/start", pickApp, function (req, res) { if (req.bevyApp.running) return res.json(418, { error: "App already running." }); spawnApp(req.bevyApp, simpleResponse(res)); }); // GET /app/app-name/stop // stops the app app.get("/app/:name/stop", pickApp, function (req, res) { if (!req.bevyApp.running) return res.json(418, { error: "App already stopped." }); stopApp(req.bevyApp, simpleResponse(res)); }); function sessionReponse (res) { return function (err, session) { if (err) return res.json(500, { error: err }); if (!session) return res.json({ ok: true }); res.json(202, { session: true, id: session.id, path: "/session/" + session.id }); }; } // GET /app/app-name/update // causes the source of the app to update from the repo app.get("/app/:name/update", pickApp, function (req, res) { updateApp(req.bevyApp, sessionReponse(res)); }); // PUT /app/app-name // create or update a new app, with JSON // { // environment: dev|prod|test // , domain: "foo.bast" // , dependencies: {} // , repository: { // type: "git" // , url: "..." // } // , scripts: { // start: "start-script.js" // default to app.js // } // , static: true|false // } app.put("/app/:name", function (req, res) { var name = req.params.name , desc = req.body; if (!/^[a-zA-Z0-9-_]+$/.test(name)) return res.json(400, { error: "Bad name, rule: /^[a-zA-Z0-9-_]+$/." }); if (!desc) return res.json(400, { error: "No JSON configuration provided." }); if (!desc.repository) return res.json(400, { error: "Field 'repository' required." }); if (!desc.domain) return res.json(400, { error: "Field 'domain' required." }); if (!desc.repository.type) desc.repository.type = "git"; if (!desc.static) { if (!desc.dependencies) desc.dependencies = {}; if (!desc.environment) desc.environment = "dev"; if (!desc.scripts) desc.scripts = {}; if (!desc.scripts.start) desc.scripts.start = "app.js"; } desc.running = apps[name] ? apps[name].running : false; apps[name] = desc; desc.name = name; desc.storePath = pth.join(conf.store, name); desc.configPath = pth.join(desc.storePath, "config.json"); desc.runningPath = pth.join(desc.storePath, "RUNNING"); desc.contentPath = (desc.repository.type === "local") ? desc.repository.path : pth.join(desc.storePath, "content"); if (!desc.static) desc.startPath = pth.join(desc.contentPath, desc.scripts.start); updateApp(desc, sessionReponse(res)); }); // DELETE /app/app-name // stops and deletes the app app.del("/app/:name", pickApp, function (req, res) { var app = req.bevyApp; stopApp(app, function (err) { if (err) return res.json(500, { error: "Failed to stop app, cannot remove: " + err }); utile.rimraf(app.storePath, function (err) { if (err) return res.json(500, { error: "Failed to remove app: " + err }); delete apps[app.name]; res.json({ ok: true }); }); }); }); // GET /session/:id // returns the last messages of a session for a long-running job (e.g npm) // this is meant for polling app.get("/session/:id", function (req, res) { var id = req.params.id , session = sessions[id] ; if (!session) return res.json(404, { error: "No such running session." }); if (session === "done") return res.json({ done: true }); res.json({ messages: session.messages() }); if (session.done) sessions[id] = "done"; }); app.listen(port); // load existing apps from store // the store is created if it doesn't exist // inside the store, each directory that contains a "config.json" is an app // if the app directory contains a "RUNNING" file, then it's running // the app directory has a content directory that's the app's content and has a name that // depends on the repo type if (!fs.existsSync(conf.store)) fs.mkdirSync(conf.store); fs.readdir(conf.store, function (err, files) { if (err) return error("Failed to read directory " + conf.store, err); files.forEach(function (name) { var dir = pth.join(conf.store, name); fs.stat(dir, function (err, stat) { if (err) return error("Failed to stat directory " + dir, err); if (!stat.isDirectory()) return; var configPath = pth.join(dir, "config.json") , runningPath = pth.join(dir, "RUNNING") , running = fs.existsSync(runningPath); if (!fs.existsSync(configPath)) return; fs.readFile(configPath, function (err, data) { if (err) return error("Could not read app configuration " + configPath, err); var appConfig; try { appConfig = JSON.parse(data); } catch (e) { return error("Failed to parse app configuration" + configPath, err); } apps[name] = appConfig; if (running) spawnApp(appConfig); }); }); }); console.log("Bevy up, management API available on port(s) ", conf.ports); }); }
}); if(relevantFamily) // If we have an IPv4 address, return it return relevantFamily.address; return interfaceFamilies[0].address; // Otherwise return the secondary address (likely IPv6) }; module.exports = { /** * Looks up this machine's IP address on the local network * @param {Function} done callback */ getLocalIPAddress(done){ var interfaces = os.networkInterfaces(); // Get a list of all network interfaces on this machine if(interfaces['Ethernet']) // In our lab demo, we use the Ethernet interface if it exists return done(null, getInterfaceIP(interfaces['Ethernet']), os.hostname()); var keys = Object.keys(interfaces).filter(function(interfaceName){ // Get all interfaces named "Local Area Connection *" return interfaceName.indexOf('Local Area Connection') === 0; }); if(!keys.length || !keys[0].length) // If we don't have a Local Area Connection or it is missing an external interface return done(new Error('Could not find local IP address')); return done(null, getInterfaceIP(interfaces[keys[0]]), os.hostname()) // Assume the first local area interface is publicly reachable. }
var Highway = function (settings) { var ObjectId = require('mongojs') .ObjectId; var _ = require('underscore'); var express = require('express'); var Email = require('./src/email.js'); var DB = require('./src/crud.js'); var reststop = require('./src/rest-stop.js'); var SocketServer = require('./src/socket.js'); var Auth = require('./src/auth.js'); var winston = require('winston'); var defaults = { io: false, http: false, uri: false, database: false, auth: [], email: {}, log: false }; if (!settings) { throw new Error('No settings provided'); } // logger crap if (settings && settings.log) { winston.add(winston.transports.File, { filename: '/var/log/highway.log', json: false }); winston.remove(winston.transports.Console); } var self = this; self.settings = _.defaults(settings || {}, defaults); self.io = self.settings.io; self.socketservers = self.sockets = {}; self.mailer = new Email(self.settings.email); self.logger = self.settings.log ? winston.log : function () {}; // get the IP address of the device this is running on var os = require('os'); var ifaces = os.networkInterfaces(); Object.keys(ifaces).forEach(function (ifname) { var alias = 0; ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false) { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; } if (alias >= 1) { // this single interface has multiple ipv4 addresses self.ip = iface.address; } else { // this interface has only one ipv4 adress self.ip = iface.address; } ++alias; }); }); function PrepareHTTP() { if (!self.settings.http) return; var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); self.settings.http.use(cookieParser()); self.settings.http.use(bodyParser.urlencoded({ extended: true })); self.settings.http.use(bodyParser.json()); return true; } return new Promise(function (success, failure) { PrepareHTTP(); var db = new DB(settings.uri + '/' + settings.database, settings.hooks, self); db.connect() .then(function (d) { self.db = d; var auth = new Auth(self) .then(function (s) { collections = _.clone(self.db.collections); while ((collection = collections.pop()) !== undefined) { if (collection.trim() !== '' && collection != 'system.indexes') { self.sockets[collection] = self.io.of('/' + settings.database + '/' + collection); self.socketservers[collection] = new SocketServer(self.io, collection, self.db); //SetUpSockets( collection ); if (self.settings.http) { self.settings.http.use('/' + settings.database + '/' + collection, new reststop(collection, self.db, self.io.of('/' + settings.database + '/' + collection))); } } } if (typeof self.settings.onComplete == 'function') { self.settings.onComplete(self, _, ObjectId); } success(self); }); }, function (err) { failure(err); console.error('Unable to connect to database: ', err); }); }); };
/** * Created by kevin on 15/11/15. */ var os = require('os'); module.exports = { mysql_dev: { host: 'localhost', user: '******', password: '******', database: 'root', connectionLimit: 10, supportBigNumbers: true }, }; var ipv4; for(var i=0;i<os.networkInterfaces().eth1.length;i++){ if(os.networkInterfaces().eth1[i].family=='IPv4'){ ipv4=os.networkInterfaces().eth1[i].address; } } var hostname = os.hostname(); console.log(hostname,ipv4); if(ipv4 == '121.41.41.46'){ }
app.get('/search_get',function(req,res){ var networkInterfaces = os.networkInterfaces(); var ipAddr = networkInterfaces.eth0[0].address; res.render('search',{ip:ipAddr}); });
// ubuntu var os = require('os'); var IPv4,hostName; hostName=os.hostname(); for(var i=0;i<os.networkInterfaces().eth0.length;i++){ if(os.networkInterfaces().eth0[i].family=='IPv4'){ IPv4=os.networkInterfaces().eth0[i].address; } } console.log('----------local IP: '+IPv4); console.log('----------local host: '+hostName); // win32 var os = require('os'); var IPv4,hostName; hostName=os.hostname(); for(var i=0;i<os.networkInterfaces()['Local Area Connection'].length;i++){ if(os.networkInterfaces()['Local Area Connection'][i].family=='IPv4'){ IPv4=os.networkInterfaces()['Local Area Connection'][i].address; } } console.log('----------local IP: '+IPv4); console.log('----------local host: '+hostName); // mac var os = require('os'); var IPv4, hostName; hostName = os.hostname();
var register = function(sps){ if(registered || !Array.isArray(sps)){ fw.log('register failed : invalid arguments or repeating record'); return; } var len = sps.length, sp = null; var save = { Unique_Key : Unique_Key, serverPort:[], online:Date.now(), status:{} }; if(len === 0){ throw 'ERR: sps.length == 0'; } if(len === 1){ sp = sps[0]; if(sp.port <= 0){ throw 'ERR: port <= 0'; } if(sp.addr === '0.0.0.0'){ // 读取本机网卡信息 var nifs = os.networkInterfaces(); for(var key in nifs){ nifs[key].forEach(function(item){ // 只记录非internal的IPV4地址. if(!item.internal && item.family === "IPv4"){ save.serverPort.push({ addr:item.address, port:sp.port }); } }); } } }else{ sps.forEach(function(item){ if(item.port <= 0){ throw 'ERR: port <= 0'; } if(item.addr === '0.0.0.0'){ throw 'addr can not be [0.0.0.0]'; } save.serverPort.push({ addr : item.addr, port : item.port }); }); } /* * 在db中去重,去重后,插入新的记录. * * 去重规则: * 1.删去指向同一个server的其它记录. * db中所记录的所有记录的serverPort中,如果存在任意ip与port相同,即认为指相同一server. * 2.删除当前server上次的记录,无论是否相同 * 查询tmp目录下的groupInfo._info,删除其中记录的id, * 为防止在不同server间复制文件所以删除时先验证是否groupInfo中的hostName是当前server名称,如果不是,则不删除该项. * */ getDbCollectionHandler(collectionName,function(err,collection){ var removeItems = []; save.serverPort.forEach(function(item){ removeItems.push({serverPort:{addr:item.addr,port:item.port}}); }); // 如果存在lastUK,证明上次启动时在DB中存在记录,需要删除 if(lastUK){ removeItems.push({Unique_Key:lastUK}); } collection.remove({"$or":removeItems},function(){ // 去重后,将新值插入数据库 collection.save(save,function(){ fw.log("\n==========\nServer Port : "); fw.log(save); fw.log("Server Port END\n==========\n"); }); }); }); };
console.log(error.message); } else if(data){ // curConn.setNoDelay(true); curConn.write(data, function(){ curConn.write("#END#"); }); } }); } }); console.log("server listenning at port 9000"); var os = require('os'); var ifaces = os.networkInterfaces(); Object.keys(ifaces).forEach(function (ifname) { var alias = 0; ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false) { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; } if (alias >= 1) { // this single interface has multiple ipv4 addresses console.log(ifname + ':' + alias, iface.address); } else { // this interface has only one ipv4 adress
var updateInterval = 1000; // in milliseconds var memToGB = 1024 * 1024 * 1024; // convert bytes to gigs var cpus = []; var myData = {}; var setup_obj = {}; var usage = {}; setup_obj.hostname = os.hostname(); setup_obj.platform = os.platform(); setup_obj.type = os.type(); setup_obj.release = os.release(); setup_obj.uptime = convertUptime(os.uptime()); setup_obj.totalmem = os.totalmem(); setup_obj.freemem = os.freemem(); setup_obj.networkInterfaces = os.networkInterfaces(); setup_obj.cpus = os.cpus(); setup_obj.loadavg = os.loadavg(); //console.log(setup_obj); //console.log(setup_obj.uptime); //throw ''; app.listen(8080); function convertUptime(s) { var d, h, m; s = Math.floor(s); m = Math.floor(s / 60); s = s % 60; h = Math.floor(m / 60); m = m % 60;