Spoofing an IP using a node.js server? - javascript

I am coding a proxy for Minecraft servers, and would like to be able to forward the original user's IP address. The issue is, through the 'proxy', the proxy's IP is seen. I know this is the idea behind proxies, but I would like to keep the original sender's IP, and forward them to another IP.
My current code;
var net = require('net');
var sourceport = 25555;
var destport = 25565;
function bufferTrim(buf, trm){
var len = buf.length;
return buf.slice(0, len-trm);
}
net.createServer(function(s)
{
var buff = "";
var connected = false;
var cli = net.createConnection(destport);
s.on('data', function(d) {
var hex = d.toString('hex').substr(0,2);
if (connected)
{
if (hex == "fe")
{
var sName = "Faker";
var sMaxSlots = "8";
var sUsedSlots = "0";
s.write(bufferTrim(new Buffer(String.fromCharCode(0xFF).concat(String.fromCharCode(sName.length + sMaxSlots.length + sUsedSlots.length + 2)).concat(sName).concat(String.fromCharCode(0xA7)).concat(sUsedSlots).concat(String.fromCharCode(0xA7)).concat(sMaxSlots), 'ucs2'), 1));
} else {
cli.write(d);
}
} else {
buff += d.toString();
}
});
cli.on('connect', function() {
connected = true;
cli.write(buff);
});
cli.pipe(s);
}).listen(sourceport);

Related

JavaScript Web Resource issue: getGrid() suddenly started failing

I have a few different JavaScript web resources that use the getGrid(), all of which started failing this week after I enabled the 2020 Wave 1 Updates in D365. The error message shows:
"Error occurred :TypeError: Unable to get property 'getGrid' of undefined or null reference"
Here is my code:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
console.log("this resource name=" + thisResourceName)
}
});
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
console.log("duplicates found= " + duplicatesFound);
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Page.getAttribute("new_showduplicateerror").setValue(true);
Xrm.Page.getControl("new_showduplicateerror").setVisible(true);
Xrm.Page.getControl("new_showduplicateerror").setNotification("A duplicate resource was found. Please remove this before saving.");
} else {
Xrm.Page.getAttribute("new_showduplicateerror").setValue(false);
Xrm.Page.getControl("new_showduplicateerror").setVisible(false);
Xrm.Page.getControl("new_showduplicateerror").clearNotification();
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Here is a separate web resource that triggers the function:
function TriggerSalesQDResourceCount(executionContext){
var formContext = executionContext.getFormContext();
formContext.getControl("s_qd").addOnLoad(GetTotalResourceCount);
}
Any ideas how I can fix this? Is this a known issue with the new D365 wave 1 update?
Thanks!
This is the problem with unsupported (undocumented) code usage, which will break in future updates.
Unsupported:
var gridCtx = formContext._gridControl;
You have to switch to these supported methods.
function doSomething(executionContext) {
var formContext = executionContext.getFormContext(); // get the form Context
var gridContext = formContext.getControl("Contacts"); // get the grid context
// Perform operations on the subgrid
var grid = gridContext.getGrid();
}
References:
Client API grid context
Grid (Client API reference)

class inheritance in javascript/angular

I am working on my hello world project. I have two pages let's call them "configuration" and "add configuration" *.html. Each one has its own controller like this:
angular.module('MissionControlApp').controller('ConfigController', ConfigController);
angular.module('MissionControlApp').controller('AddConfigController', AddConfigController);
Now, each controller has some properties that very much overlap:
function ConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject;
vm.configurations;
vm.selectedConfig;
vm.selectedRecords;
vm.filteredConfig;
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
My AddConfigController also wants to have the same functionality for addFile() so I just copy pasted the same code, but coming from C# i am sure i can do some class inheritance here, and just inherit from ConfigController and extend...right?
If this is super noob question. then apologies. js is a bit of a mystery to me.
function AddConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject = {};
vm.newConfig = {};
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
Since you asked about inheritance and you appear to be using ECMAScript 5, let me suggest taking a look at Object.create(). Specifically, the classical inheritance example.
That said, in AngularJS, a better solution would be to create a Service that manages files or configurations and put the addFile function in there. That way, both controllers could inject the service and call the same function when it is time to add a file. Likewise, other services and controllers that may need access to this functionality could inject it as well.

How do I keep both the child process running and parent communicating in Node JS?

I'm using a blynk client written in Node JS on my raspberry pi that connects and authenticates to the blynk server. I have another process I want to run that scans for BLE beacons at the same time as keeping connected to the server and polling for button presses. I am getting them both to execute at the same time but the communication is only happening if I change the state of virtual pin "V0". I'm new to Node JS and perhaps I misunderstanding but, why does it stop my parent process once the child process authenticates and doesn't execute output the parent process unless I change the state of "V0"
//Parent Process
var Bleacon = require('./index');
var uuid = '3247ff7d3f0d4b2c9df61189398eb85e';
var arr = [];
var ledPin = 17;
var math = require('mathjs');
var child_process=require('child_process');
const child = child_process.fork("doorlock.js");
console.log("child scanning...");
Bleacon.startScanning(uuid);
Beacon()
function Beacon() {
Bleacon.on('discover', function(bleacon) {
if (bleacon.uuid == uuid) {
console.log("uuid matches");
if (bleacon.proximity == 'immediate') {
console.log('immediate: ' + bleacon.rssi);
arr.push(bleacon.rssi);
//console.log(arr);
//console.log(math.mean(arr));
if (arr.length>=20 && math.mean(arr)>=-65) {
child.send('unlock door');
arr = [];
}
} else if (bleacon.proximity == 'near') {
console.log('near: ' + bleacon.rssi);
arr.push(bleacon.rssi);
//console.log('avg rssi: ' + math.mean(arr));
//console.log(arr);
if (arr.length>=20 && math.mean(arr)<=-65) {
child.send('lock door');
arr = [];
}
} else {
arr = [];
}
}
//console.log('bleacon found: ' + JSON.stringify(bleacon));
});
}
The child process:
#!/usr/bin/env node
//Child Process
//*** SMARTPHONE DOORLOCK ***//
var unlockedState = 825;
var lockedState = 2100;
var motorPin = 18;
var buttonPin = 4;
var ledPin = 17;
var blynkToken = '191d2e5c8f754fad9af08a3b9cc81eaa';
var arr = [];
var len = 20;
var Bleacon = require('./index');
var math = require('mathjs');
var uuid = '3247ff7d3f0d4b2c9df61189398eb85e';
// *** Start code *** //
var locked = true;
//Setup servo
var Gpio = require('pigpio').Gpio,
motor = new Gpio(motorPin, {mode: Gpio.OUTPUT}),
button = new Gpio(buttonPin, {
mode: Gpio.INPUT,
pullUpDown: Gpio.PUD_DOWN,
edge: Gpio.FALLING_EDGE
}),
led = new Gpio(ledPin, {mode: Gpio.OUTPUT});
//Setup blynk
var Blynk = require('blynk-library');
var blynk = new Blynk.Blynk(blynkToken);
var v0 = new blynk.VirtualPin(0);
var v1 = new blynk.VirtualPin(1);
console.log("locking door")
lockDoor()
process.on('message', function(message) {
console.log('[child] received message from server:', message);
if (message == 'unlock door') {
console.log('I read from parent that I am to unlock the door');
}
});
button.on('interrupt', function (level) {
console.log("level: " + level + " locked: " + locked)
if (level == 0) {
if (locked) {
unlockDoor()
} else {
lockDoor()
}
}
});
v0.on('write', function(param) {
console.log('V0:', param);
if (param[0] === '0') { //unlocked
unlockDoor()
} else if (param[0] === '1') { //locked
lockDoor()
} else {
blynk.notify("Door lock button was pressed with unknown parameter");
}
});
blynk.on('connect', function() {
//console.log("Blynk ready.");
});
blynk.on('disconnect', function() { console.log("DISCONNECT"); });
function lockDoor() {
motor.servoWrite(lockedState);
led.digitalWrite(1);
locked = true
//notify
blynk.notify("Door has been locked!");
//After 1.5 seconds, the door lock servo turns off to avoid stall current
setTimeout(function(){motor.servoWrite(0)}, 1500)
}
function unlockDoor() {
motor.servoWrite(unlockedState);
led.digitalWrite(0);
locked = false
//notify
blynk.notify("Door has been unlocked!");
//After 1.5 seconds, the door lock servo turns off to avoid stall current
setTimeout(function(){motor.servoWrite(0)}, 1500)
}

Javascript with Ajax working fine in Mozilla but not in Chrome

I'm using XMLHTTPREQUEST synchronous and while the request is getting fulfilled, I hide everything on page and show a progress message. This works fine in Mozilla but doesn not in Chrome.
Mozilla firefox:
For chrome:
[after submit][3]
here is my javascript code:
if (valid) {
document.getElementById('contentwrapper').style.display="none";
document.getElementById('contentwrapper').style.visibility="hidden";
var cboxes = document.getElementsByName('items[]');
var len = cboxes.length;
var res1;
var res2;
var res3;
var res4;
var arrResult;
for (var i = 0; cboxes[i]; ++i) {
if (cboxes[i].checked) {
checkedValue = cboxes[i].value;
arrResult = checkedValue.split(',');
mobileNo=arrResult[0];
if(arrResult[0].trim().startsWith('0')){
res1 = arrResult[0].substring(1,arrResult[0].length);
}else{
res1 = arrResult[0];
}
res2 = arrResult[1];
res3 = arrResult[2];
res4 = arrResult[3];
requestSender(1, res1, res2, res3, res4);
}
}
function requestSender(code, mobile, operator, productCode, amount) {
var http = getHTTPObject();
var enterKeyHandler = true;
var reqNum = 0;
var seqNum = 0;
var dataCount = 0;
var Values = "";
var code;
var comments = "";
reqCode = code;
if (code == 1) {
var agentcode = '<%=payeeaccountno%>';
var pin = document.getElementById("mpin").value;
source = agentcode; // source and agent code both are same.
operator = operator;
destination = mobile;
productCode = productCode;
if (destination.charAt(0) == '0') {
destination = destination.replace(/^0+/, "");
}
var amt = amount;
var amtPrd = new Array();
amtPrd = amt.split("#");
if (amtPrd.length > 0)
{
amount = amtPrd[0];
// productCode = amtPrd[1];
}
else
{
amount = 0;
}
clienttype = "SELFCARE";
vendorcode = '<%=vendorcode%>';
dataCount = '<%=cryptHandler.encrypt("8",session.getId()+session.getId())%>';
reqNum = '<%=cryptHandler.encrypt("1",session.getId()+session.getId())%>';
seqNum = '<%=cryptHandler.encrypt("2",session.getId()+session.getId())%>';
Values = "&var1=" + escape(agentcode) + "&var2=" + escape(pin) + "&var3=" + escape(amount) + "&var4=" + escape(mobile) + "&var5=" + escape(productCode) + "&var6=" + escape(clienttype) + "&var7=" + escape(operator) + "&var8=" + escape(vendorcode);
}
var varReq = "../Comman/requestForwarder.jsp?page=" + escape("<%=reqPageName%>") + "&reqNum=" + escape(reqNum) + "&seqNum=" + escape(seqNum) + "&dataCount=" + escape(dataCount) + Values;
varReq = varReq.replace(/\+/g, "%2B");
http.open("GET", varReq, false);
httpBuffer = http;
reqCodeBuffer = reqCode;
http.onreadystatechange = responseHandler;
http.send(null);
}
You should actually post some code or at least print the messages in the developer console (ctr + shift + J)
However, the stem of your issue is probably the fact that you are trying to use a synchronous xmlhttpRequest on the "main" execution thread.
Its a bad practice (since It blocks all code from running until the server "answers" your request) and browsers are starting to phase it out. So, if you are using a newer version of chrome, its likely not running the code and complaining about the sync request.
Either use a Web Worker (js version of thread) to run the synchronous XMLHTTPRequest(s) or, better yet, if possible, use the asynchronous version.
Further reading:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

Get signed_request in Node.js (Express) Facebook canvas app

is there any way how to get and parse signed_request in Node.js Facebook page tab app? I need to know page id and if user liked the page...
I did this a little while ago, and ended up writing a small library to do it. The original CoffeeScript can be found at https://gist.github.com/fbef51815ab6f062b51a#file_signed_request.coffee, here is a JavaScript translation:
var crypto = require('crypto');
SignedRequest = (function() {
function SignedRequest(secret, request) {
this.secret = secret;
this.request = request;
this.verify = this.verify.bind(this);
var parts = this.request.split('.');
this.encodedSignature = parts[0];
this.encoded = parts[1];
this.signature = this.base64decode(this.encodedSignature);
this.decoded = this.base64decode(this.encoded);
this.data = JSON.parse(this.decoded);
}
SignedRequest.prototype.verify = function() {
if (this.data.algorithm !== 'HMAC-SHA256') {
return false;
}
var hmac = crypto.createHmac('SHA256', this.secret);
hmac.update(this.encoded);
var result = hmac.digest('base64').replace(/\//g, '_').replace(/\+/g, '-').replace(/\=/g, '');
return result === this.encodedSignature;
};
SignedRequest.prototype.base64encode = function(data) {
return new Buffer(data, 'utf8').toString('base64').replace(/\//g, '_').replace(/\+/g, '-').replace(/\=/g, '');
};
SignedRequest.prototype.base64decode = function(data) {
while (data.length % 4 !== 0) {
data += '=';
}
data = data.replace(/-/g, '+').replace(/_/g, '/');
return new Buffer(data, 'base64').toString('utf-8');
};
return SignedRequest;
})();
module.exports = SignedRequest;
Which you can use like this:
var verifier = new SignedRequest(clientSecret, signedRequest);
verifier.verify() // whether or not the signed request verifies
verifier.data // the data from the signed request

Categories

Resources