Example #1
0
    Ipc.on('login:succeed', function ( detail ) {
        var fireballProfile = Editor.loadProfile( 'fireball', 'global' );
        fireballProfile['last-login'] = detail.account;
        fireballProfile['login-type'] = detail['login-type'];
        fireballProfile['remember-passwd'] = detail['remember-passwd'];
        fireballProfile.save();

        if ( detail['remember-passwd'] ) {
            Getmac.getMac( function ( err, macAddress) {
                if ( err ) {
                    Editor.error( 'Failed to remember your passwd.');
                    return;
                }

                var chipher = Crypto.createCipher('aes-256-cbc', macAddress);
                chipher.update(detail.password,'utf8','hex');
                var crypted = chipher.final('hex');

                var infoFile = Path.join(Editor.dataPath,'.info');
                var info = {};

                if ( Fs.existsSync(infoFile) ) {
                    info = JSON.parse(Fs.readFileSync(infoFile));
                }
                info[detail.account] = crypted;
                Fs.writeFileSync(infoFile, JSON.stringify(info, null, 2));
            });
        }

        Editor.sendToWindows('popup:login');
    });
Example #2
0
exports.registerBridge = function (account, callback) {

  var bridgeCredentials = {
    profileId: account.profileId,
    serialNumber: account.serialNumber
  };

  getmac.getMac( function (err, macAddress) {

    if (macAddress) bridgeCredentials.macAddress = macAddress;
    fs.readFile(keyPath, 'utf8', function(err, data) {

      if (!err && data) bridgeCredentials.deviceKey = data;
      request.post(urls.registerDeviceUrl, { json: bridgeCredentials }, function (err, response, body) {
        if(err) return callback(err);

        if ((response.statusCode !== 200 && response.statusCode != 201) || !body.deviceKey) {
          return callback(new Error('Failed to obtain a valid device key'));
        }

        fs.writeFile(keyPath, body.deviceKey, function (err) {
          bridgeCredentials.deviceKey = body.deviceKey;
          return callback(err, bridgeCredentials);
        });
      });
    });
  });
};
Example #3
0
IoTKitUtils.prototype.getDeviceId = function(cb) {

  var me = this;
  if (!cb) throw "Callback required";

  // if use explicit Id if one was defined in the configuration file
  // account for the different ways people could spell it ;)
  var deviceId = me.config.device_id || me.config.deviceId;

  if (deviceId){
    cb(deviceId);
    return;
  }
  
  mac.getMac(function(err, macAddress){
      var result = null;
      if (err){
        //Unable to get MAC address
        result = os.hostname().toLowerCase();
      }else{
        result = macAddress.replace(/:/g, '-');; 
      }
      cb(result);
  });
};
Example #4
0
 return new Bluebird((resolve) => {
   getmac.getMac((err, addr) => {
     if (err) {
       winston.error("attempt to get mac addr failed, using fake mac.", err);
       addr = "abcde";
     }
     resolve(md5(addr));
   });
 });
Example #5
0
 socket.on('connect', function(){
   console.log('connected to server');
   getmac.getMac((err, mac) => {
     socket.emit('info', {
       ip: ip.address(),
       mac: mac
     });
   });
 });
Example #6
0
function getWorkerIdFromEnvironment( done ) {
	getMac( function( err, address ) {
		var bytes, id;
		if ( err ) {
			address = os.hostname();
		}
		bytes = getNodeBytesFromSeed( address );
		done( bytes );
	} );
}
	function SensorTagNode( n ) {

		RED.nodes.createNode( this , n );
		var self = this;

		this.DEFAULT_SENSOR_FREQ = 1000;

		this.deviceFilter = n.devices;

		this.temperature = n.temperature;
		this.pressure = n.pressure;
		this.humidity = n.humidity;
		this.accelerometer = n.accelerometer;
		this.magnetometer = n.magnetometer;
		this.gyroscope = n.gyroscope;
		this.luxometer = n.luxometer;
		this.keys = n.keys;

		this.magnetometerPeriod = this.accelerometerPeriod = this.gyroscopePeriod = this.luxometerPeriod = this.DEFAULT_SENSOR_FREQ;

		if( n.magnetometerPeriod ) this.magnetometerPeriod = clamp( n.magnetometerPeriod , 10 , 2550 );
		if( n.accelerometerPeriod ) this.accelerometerPeriod = clamp( n.accelerometerPeriod , 10 , 2550 );
		if( n.gyroscopePeriod ) this.gyroscopePeriod = clamp( n.gyroscopePeriod , 10 , 2550 );
		if( n.luxometerPeriod ) this.luxometerPeriod = clamp( n.luxometerPeriod , 10 , 2550 );

		var tagOptionFields = [ "temperature" , "pressure" , "humidity" , "accelerometer" , "magnetometer" , "gyroscope" , "luxometer" , "keys" ,
		                        "magnetometerPeriod" , "accelerometerPeriod" , "gyroscopePeriod" , "luxometerPeriod" ];

		this.tagOptions = {};
		for( var i in tagOptionFields )
			this.tagOptions[ tagOptionFields[i] ] = this[ tagOptionFields[i] ];

		this.name = n.name;

		this.tags = [];
		this.connectedTagCount = 0;
		this.isConnected = false;

		this.macPrefix = "";

		if( this.deviceFilter.length > 0 ) this.updateStatus( "yellow" , "Waiting for tags..." );
		else this.updateStatus( "red" , "No tags configured." );

		this.on( "close" , function( done ) {
			self.prepareDisconnectAll();

			Manager.removeNode( self , done );
		} );

		libMAC.getMac( function( err , macAddress ) {
			if( !err ) self.macPrefix = macAddress.replace( /:/gi , "" ) + ".";

			Manager.addNode( self );
		} );
	}
			function(callback) { // fill deviceId
				if (qs_mode && !deviceId) {
					getmac.getMac(function(err, macAddress) {
						if (err)
							throw err;
						deviceId = macAddress.replace(/:/g, '').toLowerCase();
						callback();
					});
				} else
					callback();
			},
Example #9
0
function get_license() {
	//benchmarks.add('licensejs_get_license')
	getmac.getMac(function(err,macAddress){
		if (err)  throw err
		var hash = crypto.createHash('md5').update(macAddress).digest('hex')
		try {
			fs.writeFileSync('getlicense', hash)
		} catch (e) {
		}
	})
}
Example #10
0
  /**
   * 自动检测设备id
   *
   * @param params
   * @param cb
   */
  autoDeviceId(params, cb) {
    const that = this;
    if (that._options.device_id) {
      return cb(null, params);
    }

    MacAddr.getMac((err, mac) => {
      if (err) return cb(err);
      that._options.device_id = mac;
      return cb(null, params)
    });
  }
Example #11
0
    () => {
        leds.deviceready();
        audiotools.setup(Wakeword, config, logging);
        servertools.setup(Wakeword, config, audiotools, resetlisten, logging);
        getMac.getMac(function(err,macAddress){
            if (err)  console.warn('No Mac');
            logging.setup(macAddress.replace(/:/g,''));
            logging.addmetric("boot", "sucessfull", "ok", 1);
            Wakeword.logging = logging;
        });

    }
Example #12
0
Bridge.prototype.init = function (complete) {
    var _self = this;
    this.bc = null;
    mac.getMac(function (e, macAddress) {
        if (e) {
            complete(e);
        } else {
            _self.bridgeId = macAddress;
            complete(null);
        }
    });
};
// create a new session and update sessions array [login process]
function getDeviceData(user, req, callback) {

    // get the user agent
    var agent = getAgent(req);

    // get the user mac address
    getmac.getMac(function (err, mac) {
        if (err) {
            console.log(err);
        }
        return callback(null, user, agent, mac);
    });
}
Example #14
0
IoTKitUtils.prototype.getDeviceId = function(cb) {
  var me = this;
  if (!cb) throw "Callback required";
  
  mac.getMac(function(err, macAddress){
      var result = null;
      if (err){
        //Unable to get MAC address
        result = os.hostname().toLowerCase();
      }else{
        result = macAddress.replace(/:/g, '-');; 
      }
      cb(result);
  });
};
Example #15
0
    Ipc.on('login:query-info', function ( reply ) {
        var fireballProfile = Editor.loadProfile( 'fireball', 'global' );
        var lastLoginAccount = fireballProfile['last-login'];
        var rememberPasswd = fireballProfile['remember-passwd'];
        var loginType = fireballProfile['login-type'];
        // get password
        if ( rememberPasswd ) {
            Getmac.getMac( function ( err, macAddress) {
                if ( err ) {
                    reply({
                        'account': lastLoginAccount,
                        'remember-passwd': rememberPasswd,
                        'password': '',
                    });
                    return;
                }

                var infoFile = Path.join(Editor.dataPath,'.info');
                if ( Fs.existsSync(infoFile) ) {
                    var info = JSON.parse(Fs.readFileSync(infoFile));
                    var crypted = info[lastLoginAccount];
                    var passwd = '';
                    if ( crypted ) {
                        var decipher = Crypto.createDecipher('aes-256-cbc', macAddress);
                        decipher.update( crypted, 'hex', 'utf8' );
                        passwd = decipher.final('utf8');
                    }

                    reply({
                        'account': lastLoginAccount,
                        'remember-passwd': rememberPasswd,
                        'password': passwd,
                        'login-type': loginType,
                    });
                }
            });
        }
        else {
            reply({
                'account': lastLoginAccount,
                'remember-passwd': rememberPasswd,
                'password': '',
                'login-type': loginType,
            });
        }
    });
Example #16
0
Auth.login = function login(username, password, deviceid, callback) {
	if (typeof(deviceid) === 'function') {
		if (cachedMac) {
			return Auth.login(username, password, cachedMac, deviceid);
		}
		return Mac.getMac(function (err, macAddress) {
			cachedMac = macAddress || '00-00-00-00-00-00';
			return Auth.login(username, password, cachedMac, deviceid);
		});
	}
	var session = new Session(),
		// jscs:disable jsDoc
		checkError = function (err, result) {
			if (err) {
				debug('login error %o', err);
				if (err.code) {
					switch (err.code) {
						case 'ECONNREFUSED':
							return callback(makeError('Connection refused to ' + AppC.baseurl, Auth.ERROR_CONNECTION_REFUSED));
						case 'ECONNRESET':
							return callback(makeError('Connection reset to ' + AppC.baseurl, Auth.ERROR_CONNECTION_RESET));
						case 'CERT_HAS_EXPIRED':
							return callback(makeError('The servers SSL certificate at ' + AppC.baseurl + ' has expired. Refusing to connect.', Auth.ERROR_CONNECTION_INVALID_SSL));
						case 400:
							return callback(makeError(err, Auth.ERROR_CONNECTION_SERVER_ERROR));
					}
				}
				return callback(makeError(err, Auth.ERROR_CONNECTION_SERVER_ERROR));
			}
			callback(null, result);
		};
	var r = AppC.createRequest(session, '/api/v1/auth/login', 'post', checkError, function mapper(obj, next) {
		session._set(obj);
		resolveUserOrg(session, next);
	}),
	form = r.form();
	form.append('username', username);
	form.append('password', password);
	form.append('keepMeSignedIn', 'true');
	form.append('from', 'cli');
	form.append('deviceid', deviceid);
	debug('device id is %s', deviceid);
	debug('form parameters for %s, %o', r.url, form);
};
Example #17
0
exports.check = function(){
	//benchmarks.add('licensejs_check')
	var key;
	try {
		key = fs.readFileSync('license', 'utf8')
	} catch (e) {
		get_license();
	}
	getmac.getMac(function(err,macAddress){
		if (err)  throw err
		var hash  = crypto.createHash('md5').update(macAddress).digest('hex')
		var hash2 = crypto.createHash('md5').update(hash).digest('hex')
		if (key == hash2) {
			logic.init();
		} else {
			get_license();
		}
	})
	return 0;
}
Example #18
0
	rmq.exchange(config.rabbitmq.exchange, {'durable': true, 'autoDelete': false}, function (xch) {

		// Use our MAC address as a source identifier for this scanner
		getmac.getMac(function (err, mac_address) {
			if (err) {
				console.log('Could not get MAC address.');
				console.log(err);
			} else {
				console.log('Found mac address: ' + mac_address);

				noble.on('discover', function (peripheral) {
					manufac_data = '';

					console.log('peripheral discovered (' + peripheral.uuid.match(/../g).join(':') + '):');
					console.log('\thello my local name is: ' + peripheral.advertisement.localName);
					console.log('\t\t' + peripheral.rssi);

					if (peripheral.advertisement.manufacturerData) {
						manufac_data = peripheral.advertisement.manufacturerData.toString('hex');
					}

					blob = {
						location_str: 'unknown',
						ble_addr: peripheral.uuid.match(/../g).join(':'),
						name: peripheral.advertisement.localName,
						scanner_macAddr: mac_address.toUpperCase(),
						service_uuids: peripheral.advertisement.serviceUuids,
						manufacturer_data: manufac_data,
						rssi: peripheral.rssi,
						time: Date.now()/1000,
					}

					// Publish advertisement to RabbitMQ
					xch.publish('scanner.bleScanner.'+mac_address.toUpperCase(), blob);
				});
			}

		});

	});
Example #19
0
properties.parse('./config.properties', {path: true}, function(err, cfg) {
  if (err) {
    console.error('A file named config.properties containing the device registration from the IBM IoT Cloud is missing.');
    console.error('The file must contain the following properties: org, type, id, auth-token.');
    throw e;
  }
  macUtil.getMac(function(err, macAddress) {
    if (err) throw err;
    var deviceId = macAddress.replace(/:/gi, '');
    console.log('Device MAC Address: ' + deviceId);

    if(cfg.id != deviceId) {
    	console.warn('The device MAC address does not match the ID in the configuration file.');
    }

    var clientId = ['d', cfg.org, cfg.type, cfg.id].join(':');

    var client = mqtt.connect("mqtts://" + cfg.org + '.messaging.internetofthings.ibmcloud.com:8883', 
      {
        "clientId" : clientId,
        "keepalive" : 30,
        "username" : "use-token-auth",
        "password" : cfg['auth-token']
      });
    client.on('connect', function() {
	  console.log('MQTT client connected to IBM IoT Cloud.');
    });
    client.on('error', function(err) {
	  console.log('client error' + err);
	  process.exit(1);
    });
    client.on('close', function() {
	  console.log('client closed');
	  process.exit(1);
    });
    monitorSensorTag(client);
  });
});
  constructor(modes) {
    this.reportError = this.reportError.bind(this)
    this.onDidLogAPIError = this.onDidLogAPIError.bind(this);
    this.inSpecMode = modes.inSpecMode
    this.inDevMode = modes.inDevMode
    this.resourcePath = modes.resourcePath
    this.deviceHash = "Unknown Device Hash"
    this.rateLimitDataByKey = new Map()

    if (!this.inSpecMode) {
      try {
        getMac((err, macAddress) => {
          if (!err && macAddress) {
            this.deviceHash = crypto.createHash('md5').update(macAddress).digest('hex')
          }
          this._setupSentry();
        })
      } catch (err) {
        console.error(err);
        this._setupSentry();
      }
    }
  }
Example #21
0
 getDeviceId: function(callback) {
     macModule.getMac(function(err, macAddress) {
         if (err) throw err;
         callback(macAddress);    
     });
 },
Example #22
0
var macUtil = require('getmac');
var SensorTag = require('sensortag');

macUtil.getMac(function(err,macAddress) {
   if (err) throw err;
   var deviceId = macAddress.replace(/:/gi, '');
   //var deviceId = macAddress;
   console.log('Device MAC Address: ' + deviceId);
})

function monitorSensorTag() {
   console.log('Mulai');
   SensorTag.discover(function(device){
      console.log('Discovering');
      console.log('Discovered device with UUID: ' + device['uuid']);

      device.connect(function(){
         connected = true;
         console.log('Connected to SensorTag');
         device.discoverServicesAndCharacteristics(function(callback){});
         getDeviceInfo();
         //.initKeys();
         //initAirSensors();
         //initAccelAndGyro();
      }); // end device.connect

      device.on('disconnect', function(onDisconnect){
         connected = false;
         console.log('Device disconnected');
         client.end();
      }); // end device.on disconnect
Example #23
0
/**
 * Created by gunpower on 2015. 10. 21..
 */

    //첫번째 방법
var getmac = require('getmac');
getmac.getMac(function(err,macAddress){
    if (err)  throw err
    console.log(macAddress)
})

//두번째 방법
var macaddress = require('node-macaddress');
console.log(JSON.stringify(macaddress.networkInterfaces(), null,2));
Example #24
0
$(function(){
    /* disable eval
    window.eval = global.eval = function() {
      throw new Error("Sorry, BlankE does not support window.eval() for security reasons.");
    };
    */
    b_ide.setTitleColor("#2196f3");

    $("#main_window").addClass(nwOS.type());

    // title bar buttons
    $(".title-bar #btn-close").on("click", function() {
        eIPC.send('close');
    });
    $(".title-bar #btn-maximize").on("click", function() {
        eIPC.send('maximize');
    });
    $(".title-bar #btn-minimize").on("click", function() {
        eIPC.send('minimize');
    });

    // set user id
    nwMAC.getMac(function(err, address) {
       if (!err && !DEV_MODE) {
            var hash = address.hashCode();
        //   analytics.userID = hash;
        //   analytics.clientID = hash;
            
            console.log("userID: " + hash);
       }
    });

    //analytics.event('UI', 'initialize', 'main_window', '');


    b_ide.loadData();
    b_plugin.loadOfficialPlugins();

    ace.require("ace/ext/language_tools");
    editor = ace.edit("editor");
    editor.$blockScrolling = Infinity;
    aceModeList = ace.require("ace/ext/modelist");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
        fontFamily: "Courier New",
        scrollPastEnd: true
    });

    b_editor.setMode('Text');
    editor.setTheme("ace/theme/chrome");

    // set events for window close
    eIPC.on('window-close', function(event) {
        b_ide.saveData();
        eIPC.send('confirm-window-close');
    });

    eIPC.on('focus-search', function(event) {
        b_search.focus();
    });

    var drop_mainwin = document.getElementById("main_window");
	drop_mainwin.ondragover = () => {
        // console.log(e.dataTransfer.files);
		if ($(".filedrop-overlay").hasClass("inactive")) {
			//$(".filedrop-overlay").removeClass("inactive");
		}
		return false;
	};
	drop_mainwin.ondragleave = drop_mainwin.ondragend = () => {
		//$(".filedrop-overlay").addClass("inactive");
		return false;
	};
	drop_mainwin.ondrop = (e) => {
		e.preventDefault();

		for (var f of e.dataTransfer.files) {
			var in_path = f.path;

            handleDropFile(in_path);

		}
		$(".filedrop-overlay").addClass("inactive");
		return false;
	};

    var args = eREMOTE.getGlobal("shareVars").args;

    if (args.length >= 3) {
        var in_file = args[2];

        handleDropFile(in_file);
    }


    $("#editor").on("keydown", function(evt) {
        var keyCode = evt.keyCode || evt.which;
        var key = evt.key;
        // command 224

        // uses mdi
        var special_chars = {
            13: 'keyboard-return', // enter
            16: 'chevron-up', // shift
            20: 'chevron-double-up', // caps lock
            32: 'dots-horizontal', // space
            91: 'apple-keyboard-command', // apple META/command
            93: 'apple-keyboard-command', // apple META/command
        };

        // doesn't use mdi
        var special_chars2 = {
            12: 'Clr', // clear
            17: 'Ctrl', // ctrl
            18: 'Alt',  // alt
            27: 'Esc', // escape
        };

        // zoom in
        if (evt.ctrlKey && keyCode == 187) {
            b_editor.zoom(ZOOM_AMT);
        }
        // zoom out
        if (evt.ctrlKey && keyCode == 189) {
            b_editor.zoom(-ZOOM_AMT);
        }

        var is_special = false;
        if (Object.keys(special_chars).includes(keyCode+"")) {
            key = '<i class="mdi mdi-' + special_chars[keyCode] + '"></i>';
            is_special = true;
        }
        else if (Object.keys(special_chars2).includes(keyCode+"")) {
            key = special_chars2[keyCode];
            is_special = true;
        }

        $(".status-bar .keycode").html('<span class="char">' + key + '</span>' + keyCode);

        // text changes autosave
        if (b_ide.isProjectSet() && !is_special) {
            b_project.getSetting('unsaved_text')[b_project.getSetting('curr_file')] = editor.getValue();
            b_history.refreshList();
        }

        saveCursor();
    });

    // remember cursor position
    $("#editor").on('click', function(e) {
        saveCursor();
    });

    // saving
    editor.commands.addCommand({
        name: 'save_file',
        bindKey: {win: 'Ctrl-S',  mac: 'Command-S'},
        exec: function(editor) {
            b_editor.saveFile()
        },
        readOnly: true // false if this command should not apply in readOnly mode
    });

    // history
    editor.commands.addCommand({
        name: 'history_back',
        bindKey: {win: 'Ctrl-Left',  mac: 'Command-Left'},
        exec: function(editor) {
            b_history.back();
        },
        readOnly: true // false if this command should not apply in readOnly mode
    });
    editor.commands.addCommand({
        name: 'history_forward',
        bindKey: {win: 'Ctrl-Right',  mac: 'Command-Right'},
        exec: function(editor) {
            b_history.forward();
        },
        readOnly: true // false if this command should not apply in readOnly mode
    });

    editor.resize();


});
Example #25
0
      database : aws_config.sql_db
    });
}
else {
    console.log("Connecting to " + aws_config.test_ip);
    var db_connection = mysql.createConnection({
      host     : aws_config.test_ip,
      user     : aws_config.test_usr,
      password : aws_config.test_pw,
      database : aws_config.test_db
    }); 
}

var gateway_mac;
getmac.getMac(function(err,macAddress) {
    if (err) throw err;
    gateway_mac = macAddress.replace(new RegExp(':', 'g'), '');
});

// settings
var POST_BUFFER_LEN = 4; // group N packets into a single post
var POST_TIMEOUT = 30; // after 30 seconds, just post anyway

// add a watchdog for mqtt packets
mqtt_down = false;
var mqtt_watchdog = new watchout(1*60*1000, function(didCancelWatchdog) {
    if (didCancelWatchdog) {
        // benign
    } else {
        console.log("MQTT watchdog tripped");
        mqtt_down = true;
        process.exit(1);
Example #26
0
getMac((err, mac) => {
  const archonID = `A-${(mac || require('node-uuid').v4())}`
  const argv = process.argv.splice(2)
  const host = argv.length ? argv[0] : ASSIMILATOR_HOST

  const state = {
    waiting: false,
    execMode: false,
    execBuffer: '',
    zealotID: null,
    lineBuffer: []
  }

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    completer: (line) => {
      if (state.execMode) {
        return [[], line]
      } else {
        var hits = COMMANDS.filter((c) => c.indexOf(line) == 0)
        return [hits.length ? hits : COMMANDS, line]
      }
    }
  })

  function sendMessage(msg, callback) {
    state.waiting = true
    msg.archonID = archonID
    o.e(msg, data => {
      socket.write(data, error => {
        state.waiting = false
        if (error) {
          console.error(error)
        }
        void(callback && callback(error))
      })
    })
  }

  rl.setPrompt('> ')
  rl.on('line', line => {
    state.lineBuffer.push(line)
    if (!state.waiting) {
      processLine()
    }
  })

  function processLine() {

    if (!state.lineBuffer.length) {
      // out of input
      return
    }

    let line = state.lineBuffer.splice(0,1)[0]

    if (!line.trim()) {
      commandLoop()
      return
    }

    if (state.execMode) {
      if (line.trim() == 'EOF') {
        // send data
        // wait for response
        var exec = state.execBuffer.trim()
        let postExec = () => {
          state.execMode = false
          rl.setPrompt('> ')
          state.execBuffer = ''
          commandLoop()
        }
        if (!exec) {
          postExec()
        } else {
          sendMessage({cmd: 'exec', arg: exec, zealotID: state.zealotID}, postExec)
        }
      } else {
        state.execBuffer += line + '\n'
      }
    } else {
      var args = line.split(/[ \t]+/)
      var cmd = args[0]
      var arg = line.substr(cmd.length).trim()
      switch (cmd) {
        case 'ls':
          // do ls
          sendMessage({cmd: 'ls', arg: arg})
          break
        case 'use':
        case 'info':
          // do use
          if (!arg) {
            console.log('error: please specify a zealot')
            commandLoop()
          } else {
            sendMessage({cmd: cmd, arg: arg})
          }
          break
        case 'exec':
          // do exec
          if (!state.zealotID) {
            console.error(`error: no zealot selected`)
            commandLoop()
          } else {
            state.execMode = true
            state.execBuffer = arg
            console.log('<<EOF')
            console.log(state.execBuffer)
            rl.setPrompt('')
          }
          break
        case 'quit':
          // quit
          console.log('Goodbye\n')
          socket.end()
          rl.close()
          break
        default:
          console.log(`unknown action: '${cmd}'`)
          commandLoop()
          break
      }
    }
  }

  socket.on('data', (data) => {
    o.d(data, msg => {
      if (msg.error) {
        console.error(msg.error)
      } else {
        switch (msg.cmd) {
          case 'ls':
            let fmt = (s, n) => {
              if (!s) s = ' '
              else if (typeof s != 'string') s = s.toString() + ' '
              while (s.length < n)
                s += ' '
              return s
            }

            let timeDiff = (d) => {
              if (d) {
                let diff = Date.now() - new Date(d).getTime()
                let units = [
                  { val: 1,    name: 'ms'},
                  { val: 1000, name: 's' },
                  { val: 60,   name: 'm' },
                  { val: 60,   name: 'h' },
                  { val: 24,   name: 'd' },
                  { val: 365,  name: 'y' }
                ]
                let uName = 'ms'
                units.find(unit => {
                  if (diff / unit.val < 1)
                    return true
                  diff /= unit.val
                  uName = unit.name
                })
                return `${diff}`.replace(/(\...).*/, '$1') + uName
              } else {
                return '-'
              }
            }
            console.log(
              fmt('name', 16) +
              fmt('state', 10) +
              fmt('connected', 16) +
              fmt('disconnected', 16) +
              fmt('checked in', 16))

            msg.zealots.forEach(zealot => {

              console.log(
                fmt(zealot.name, 16) +
                fmt(zealot.state, 10) +
                fmt(timeDiff(zealot.connected), 16) +
                fmt(timeDiff(zealot.disconnected), 16) +
                fmt(timeDiff(zealot.lastCheckIn), 16))
            })
            console.log()
            break
          case 'info':
            if (msg.zealot) {
              console.log(msg.zealot)
              console.log()
            } else {
              console.log(`Not found`)
            }
            break
          case 'use':
            if (msg.zealotID) {
              state.zealotID = msg.zealotID
              console.log(`switched to zealot ${msg.name}`)
            } else {
              console.log(`Not found`)
            }
            break
          case 'print':
            console.log(`"${msg.name}" - ${msg.kind}:`)
            console.log(msg.data)
            break
          case 'eof':
            // noop
            break
          default:
            console.log(`error - invalid message from assimilator: ${JSON.stringify(msg)}`)
            break
        }
      }
      commandLoop()
    })
  })

  function commandLoop() {
    void(state.lineBuffer.length ? processLine() : rl.prompt())
  }

  var connectDelay = 100

  socket.on('connect', () => {
    connectDelay = 100
    o = obfuscator.create()
    commandLoop()
  })

  socket.connect({
    host: host,
    port: ASSIMILATOR_PORT
  })

  socket.on('error', (error) => {
    console.log(error)

    // exponential retry
    if (connectDelay < 10000)
      connectDelay *= 1.5

    setTimeout(() => {
      console.log('Reconnecting')
      socket.connect({host: host, port: ASSIMILATOR_PORT})
    }, connectDelay)
  })
})
Example #27
0
		userHash: function(done) {
			getmac.getMac(function(err, addr) {
				done(err, md5(addr));
			});
		},
Example #28
0
    self.certificates = {
        key: fs.readFileSync(__dirname + '/certificates/example.key').toString(),
        cert: fs.readFileSync(__dirname + '/certificates/example.crt').toString(),
        ca: [ ]
    }

	var router = zrpc.Router({
		port : 6699,
		auth : "f72d7c54d7354f7a8f9d111c6033b6281e7096acc4dcb198763a4555f264259d",
		certificates : self.certificates,
		client : {
			address : "127.0.0.1:4488",
			node : mac
		}
	})
}

// obtain node id (mac of the first network adaptor)
getmac.getMac(function (err, mac) {
    if (err)
        throw err;

    mac = mac.split(process.platform == 'win32' ? '-' : ':').join('').toLowerCase();
    global.application = {
    	server : new Server(mac),
    	client : new Client(mac),
    	router : new Router(mac)
    }
})
Example #29
0
sysinfo.getUserHash = function(callback) {
  getmac.getMac(function(err, addr) {
    callback(err, md5(addr));
  });
}
Example #30
0
exports.mac = function(done) {
    getmac.getMac(done);
};