Multiple sockets override itself - javascript

My Code
I want to make a multiple connection to a telnet console. This project is for Teamspeak and Teamspeak just communicate with telnet. I´ve a object that create a telnet connection as socket with the net lib. If we have just one instance to connect all works fine and I get the serverlist over the telnet connection back. But if I´ve two instance he says invalid loginname or password. That login informations are correct and he also try just to connect to one server.
My Class:
/*
Teamspeak query client class
#instance: Instance object of the teamspeak query client
*/
function TeamspeakQueryClient(instance) {
events.EventEmitter.call(this);
var $this = this,
socket = net.connect(instance.port, instance.ip),
reader = null,
skipLines = -2,
queue = [ ],
executing = null,
server = null;
this.Type = 'Unknown';
this.Id = null;
this.Connected = false;
this.Banned = false;
/*
Socket settings
*/
socket.setKeepAlive(true, 60000);
/*
Socket connect to the teamspeak instance
*/
socket.on("connect", function() {
reader = LineInputStream(socket);
reader.on("line", function(line) {
var s = line.trim();
console.log(line);
// Skipp the first lines
if(skipLines < 0){
if(line === 'TS3') {
this.Type = 'Teamspeak';
};
skipLines++;
if(skipLines === 0) {
checkQueue();
if(server === null) {
$this.SendCommand("login", {client_login_name: instance.client, client_login_password: instance.password}, function(err, response, rawResponse) {
console.log(err);
if(err === null) {
if(err.id === 3329) {
$this.Banned = true;
};
$this.CloseSocket();
} else {
$this.SendCommand("serverlist", null, function(err, response, rawResponse){
console.log(response);
if(response[0] === undefined) {
console.log('1 server');
} else {
console.log('mehrere server');
};
//console.log(rawResponse);
/*cl.send("clientlist", function(err, response, rawResponse){
console.log(util.inspect(response));
});*/
});
};
});
} else {
console.log(server);
};
};
return;
};
// Parse server request
var response = undefined;
if(s.indexOf("error") === 0){
response = parseResponse(s.substr("error ".length).trim());
executing.error = response;
if(executing.error.id === 0) delete executing.error;
if(executing.cb) executing.cb.call(executing, executing.error, executing.response,
executing.rawResponse);
executing = null;
checkQueue();
} else if(s.indexOf("notify") === 0){
s = s.substr("notify".length);
response = parseResponse(s);
$this.emit(s.substr(0, s.indexOf(" ")), response);
} else if(executing) {
response = parseResponse(s);
executing.rawResponse = s;
executing.response = response;
};
});
$this.emit("connect");
});
/*
Socket error
*/
socket.on("error", function(err){
log.LogLine(1, 'TeamspeakQueryClient: We got a error');
log.LogLine(1, 'Message: '+err);
$this.emit("error", err);
});
/*
Socket close
*/
socket.on("close", function(){
log.LogLine(3, 'TeamspeakQueryClient: Socket from '+instance.alias+' closeing...');
$this.emit("close", queue);
});
/*
Function to send a custom command to the telnet console
*/
TeamspeakQueryClient.prototype.SendCommand = function SendCommand() {
var args = Array.prototype.slice.call(arguments);
//console.log(args);
var options = [], params = {};
var callback = undefined;
var cmd = args.shift();
args.forEach(function(v){
if(util.isArray(v)){
options = v;
} else if(typeof v === "function"){
callback = v;
} else {
params = v;
}
});
var tosend = tsescape(cmd);
options.forEach(function(v){
tosend += " -" + tsescape(v);
});
for(var k in params){
var v = params[k];
if(util.isArray(v)){ // Multiple values for the same key - concatenate all
var doptions = v.map(function(val){
return tsescape(k) + "=" + tsescape(val);
});
tosend += " " + doptions.join("|");
} else {
tosend += " " + tsescape(k.toString()) + "=" + tsescape(v.toString());
}
}
queue.push({cmd: cmd, options: options, parameters: params, text: tosend, cb: callback});
if(skipLines === 0) checkQueue();
};
/*
Function to close the socket
*/
TeamspeakQueryClient.prototype.CloseSocket = function CloseSocket() {
socket.destroy();
$this.emit("close");
};
/*
Function to parse a string to a object
#s: String of the object that will be parsed
#return: Object of the parsed string
*/
function parseResponse(s){
var response = [];
var records = s.split("|");
response = records.map(function(k){
var args = k.split(" ");
var thisrec = { };
args.forEach(function(v) {
if(v.indexOf("=") > -1) {
var key = tsunescape(v.substr(0, v.indexOf("=")));
var value = tsunescape(v.substr(v.indexOf("=")+1));
if(parseInt(value, 10) == value) value = parseInt(value, 10);
thisrec[key] = value;
} else {
thisrec[v] = "";
};
});
return thisrec;
});
if(response.length === 0) {
response = null;
} else if(response.length === 1) {
response = response.shift();
};
return response;
};
/*
Function to write commands into the socket
*/
function checkQueue() {
if(!executing && queue.length >= 1){
executing = queue.shift();
socket.write(executing.text + "\n");
};
};
/*
Function to escape a telnet string
#s: String that want to be escaped
#return: The escaped string
*/
function tsescape(s) {
return s
.replace(/\\/g, "\\\\")
.replace(/\//g, "\\/")
.replace(/\|/g, "\\p")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\v/g, "\\v")
.replace(/\f/g, "\\f")
.replace(/ /g, "\\s");
};
/*
Function to unescape a telnet string
#s: String that want to be unescaped
#return: The unescaped string
*/
function tsunescape(s) {
return s
.replace(/\\s/g, " ")
.replace(/\\p/g, "|")
.replace(/\\n/g, "\n")
.replace(/\\f/g, "\f")
.replace(/\\r/g, "\r")
.replace(/\\t/g, "\t")
.replace(/\\v/g, "\v")
.replace(/\\\//g, "\/")
.replace(/\\\\/g, "\\");
};
};
util.inherits(TeamspeakQueryClient, events.EventEmitter);
How I open the class
if I call example one all works fine but example two has the descriped error.
Example 1:
test1 = new TeamspeakQueryClient({
"alias": "First-Coder Testinsance",
"ip": "first-coder.de",
"port": 10011,
"client": "serveradmin",
"password": "SECURE"
});
Example 2:
test1 = new TeamspeakQueryClient({
"alias": "First Insance",
"ip": "HIDDEN",
"port": HIDDEN,
"client": "serveradmin",
"password": "SECURE"
});
test2 = new TeamspeakQueryClient({
"alias": "Second Instance",
"ip": "HIDDEN",
"port": HIDDEN,
"client": "serveradmin",
"password": "SECURE"
});
Screenshots
Picture of the error in the console

According to your error, your second instance is not sending the correct login:
error id=520 msg=invalid\sloginname\sor\spassword
The additional errors displayed are due to your code not handling errors correctly.
For example:
socket.on("connect", function() {
...
if(err === null) {
if(err.id === 3329) {
If err === null, why would err have an element id?
Most likely this is code error, and you actually meant err !== null
$this.SendCommand("serverlist", null, function(err, response, rawResponse){
console.log(response);
if(response[0] === undefined) {
This error triggers because the (above) previous error was not caught.
At this point, the client is not logged in (authorized).
So when the serverlist command is sent, it riggers another error.
This additional error is also no handled, instead response is immediately used.

Related

How can I check if ECC Key and Public Key are being passed through Js file?

I'm having a problem locating where my problem is. I'm using PubNub for realtime messaging and the example project is using ECC (elliptical curve cryptography) encrypted messaging.
Every thing in the file works(animation, channel presence, etc.) except for sending the message. Every time I hit send I get this message:
Here is my chat-app.js file:
(function() {
if (typeof(user) === 'undefined') {
return;
}
var output = document.getElementById('output'),
input = document.getElementById('input'),
picture = document.getElementById('picture'),
presence = document.getElementById('presence'),
action = document.getElementById('action'),
send = document.getElementById('send');
var channel = 'fun';
var keysCache = {};
var pubnub = PUBNUB.init({
subscribe_key: 'sub-c-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
publish_key: 'pub-c-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
uuid: user.name,
auth_key: user.gtoken,
ssl: true
});
function displayOutput(message) {
if(!message) return;
if(typeof(message.text) === 'undefined') return;
var html = '';
if ('userid' in message && message.userid in keysCache) {
var signature = message.signature;
delete message.signature;
var result = ecc.verify(keysCache[message.userid].publicKey, signature, JSON.stringify(message));
if(result) {
html = '<p><img src="'+ keysCache[message.userid].picture +'" class="avatar"><strong>' + keysCache[message.userid].name + '</strong><br><span>' + message.text + '</span></p>';
} else {
html = '<p><img src="images/troll.png" class="avatar"><strong></strong><br><em>A troll tried to spoof '+ keysCache[message.userid].name +' (but failed).</em></p>';
}
output.innerHTML = html + output.innerHTML;
} else {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/user/' + message.userid, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var res = JSON.parse(xhr.responseText);
keysCache[message.userid] = {
'publicKey': res.publicKey,
'name': res.name,
'artist': res.artist,
'picture': res.picture,
'id': res.id
}
displayOutput(message);
}
};
xhr.send(null);
}
}
function getHistory() {
pubnub.history({
channel: channel,
count: 30,
callback: function(messages) {
messages[0].forEach(function(m){
displayOutput(m);
});
}
});
}
pubnub.subscribe({
channel: channel,
restore: true,
connect: getHistory,
disconnect: function(res){
console.log('disconnect called');
},
reconnect: function(res){
console.log('reconnecting to pubnub');
},
callback: function(m) {
displayOutput(m);
},
presence: function(m){
if(m.occupancy === 1) {
presence.textContent = m.occupancy + ' person online';
} else {
presence.textContent = m.occupancy + ' people online';
}
if((m.action === 'join') || (m.action === 'timeout') || (m.action === 'leave')){
var status = (m.action === 'join') ? 'joined' : 'left';
action.textContent = m.uuid + ' ' + status +' room';
action.classList.add(m.action);
action.classList.add('poof');
action.addEventListener('animationend', function(){action.className='';}, false);
}
}
});
function post() {
var safeText = input.value.replace(/\&/g, '&').replace( /</g, '<').replace(/>/g, '>');
var message = { text: safeText, userid: user.id };
var signature = ecc.sign(user.eccKey, JSON.stringify(message));
message['signature'] = signature;
pubnub.publish({
channel: channel,
message: message
});
input.value = '';
}
input.addEventListener('keyup', function(e) {
if(input.value === '') return;
(e.keyCode || e.charCode) === 13 && post();
}, false);
send.addEventListener('click', function(e) {
if(input.value === '') return;
post();
}, false);
})();
This error is coming from my ecc.js file
Uncaught TypeError: Cannot read property 'r' of undefined
However, I'm assuming the error is in the chat-app.js file because I didn't touch the ecc.js file. I got it from the project -- https://github.com/pubnub/auth-chat-demo
More info on ECC can be found here: https://github.com/jpillora/eccjs
According to your description, it looks like this line is giving you the error:
var signature = ecc.sign(user.eccKey, JSON.stringify(message));
So I am guessing you are not properly passing user.eccKey?
Do you have all the user data from oAuth (or any login auth)? or is the eccKey generated correctly upon the user sign-up?
Also, try include the non-minified version of ecc.js so you can track where the error is coming from more easily.
https://raw.githubusercontent.com/jpillora/eccjs/gh-pages/dist/0.3/ecc.js

Use TripleSec encryption with Node.js Socket.io Chat

I am new to Node.js and I've created a simple chat application using Socket.io. I am trying to encrypt the messages using the triplesec library but I am having some issues. What would be the best approach to add this encryption/decryption:
var triplesec = require('triplesec');
// Encrypt Function
triplesec.encrypt({
key: new triplesec.Buffer('secretkey'),
data: new triplesec.Buffer('secretthings'),
}, function (err, buff) {
if(!err) {
var ciphertext = buff.toString('hex')
console.log(buff.toString('hex'))
}
// Decrypt Function
triplesec.decrypt({
data: new triplesec.Buffer(ciphertext, "hex"),
key: new triplesec.Buffer('secretkey')
}, function (err, buff) {
if(!err) {
console.log(buff.toString());
}
});
});
To this client: (All encryption on the messages coming in and going out will be handled client side, assuming this is the best approach?)
// imports
var readline = require('readline');
var socketio = require('socket.io-client');
var util = require('util');
var clc = require("cli-color");
var async = require("async");
// globals
var nick;
var serverAddress;
var serverPort;
var socket;
var rl = readline.createInterface(process.stdin, process.stdout);
// message types
var chat = clc.green;
var pm = clc.yellow;
var notice = clc.cyan;
var emote = clc.blue;
var error = clc.red;
// function definitions
function consoleOut (msg) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
console.log(msg);
rl.prompt(true);
}
// handle a command that the user has entered
function handleCommand (commandType, arg) {
switch (commandType) {
case 'nick': // set the nickname and send a message with the updated nickname
var notice = nick + " changed their name to " + arg;
nick = arg;
socket.emit('send', { type: 'notice', message: notice });
break;
case 'pm': // private message another user
var to = arg.match(/[a-z]+\b/)[0];
var message = arg.substr(to.length, arg.length);
socket.emit('send', { type: 'pm', message: message, to: to, from: nick });
break;
case 'me': // the user performs some emote
var emote = nick + " " + arg;
socket.emit('send', { type: 'emote', message: emote });
break;
default: // invalid command type
consoleOut(error("That is not a valid command."));
}
}
// start of execution
async.series([
function(callback) {
// get the address
rl.question("Please enter the address of the server, such as 192.168.0.10: ", function(address) {
serverAddress = address;
callback();
});
},
function(callback) {
// get the port
rl.question("Please enter the port the server is listening on, such as 8080: ", function(port) {
serverPort = port;
socket = socketio.connect('http://' + serverAddress + ':' + serverPort);
// register the sockets on message event handler
socket.on('message', function (data) {
var leader;
// process message, these are pretty self explainitory
if (data.type == 'chat' && data.nick != nick) {
leader = chat("<" + data.nick + "> ");
consoleOut(leader + data.message);
}
else if (data.type == "notice") {
consoleOut(notice(data.message));
}
else if (data.type == "pm" && data.to == nick) {
leader = pm("["+data.from+"->"+data.to+"]");
consoleOut(leader + data.message);
}
else if (data.type == "emote") {
consoleOut(emote(data.message));
}
});
callback();
});
},
function(callback) {
// get the users nickname
rl.question("Please enter a nickname: ", function(name) {
nick = name;
var msg = nick + " has joined the chat";
socket.emit('send', { type: 'notice', message: msg });
rl.prompt(true);
callback();
});
}
]);
// called when the user hits enter on the command line
// parses what ever they typed into either a command or a chat message
rl.on('line', function (line) {
if (line[0] == "/" && line.length > 1) {
var cmd = line.match(/[a-z]+\b/)[0];
var arg = line.substr(cmd.length+2, line.length);
handleCommand(cmd, arg);
rl.prompt(true);
} else {
// send chat message
socket.emit('send', { type: 'chat', message: line, nick: nick });
rl.prompt(true);
}
});

Remote Video Element shows nothing in webrtc

I am new to WebRTC, I want to setup a video call by using web socket over node.js,I am Unable Display the Remote video screen but local video element works fine.
May be I am missing the flow which i could not figure it out.
I am posting my html code with java script here.
HTML Code
<!---display sharing screen--->
<div id="video_container" style="display:none;">
This Streams Remote Video
<video controls autoplay id="remotevideo"></video><br>
This Streams Local Video
<video controls autoplay id="local_video"></video>
</div>
The below is my javascript
var webrtc_capable = true;
var rtc_peer_connection = null;
var rtc_session_description = null;
var get_user_media = null;
var connect_stream_to_src = null;
var stun_server = "stun.l.google.com:19302";
if (navigator.getUserMedia) { // WebRTC 1.0 standard compliant browser
rtc_peer_connection = RTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.getUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.srcObject = media_stream;
media_element.play();
};
} else if (navigator.mozGetUserMedia) { // early firefox webrtc implementation
rtc_peer_connection = mozRTCPeerConnection;
rtc_session_description = mozRTCSessionDescription;
get_user_media = navigator.mozGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.mozSrcObject = media_stream;
media_element.play();
};
stun_server = "74.125.31.127:19302";
} else if (navigator.webkitGetUserMedia) { // early webkit webrtc implementation
rtc_peer_connection = webkitRTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.webkitGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.src = URL.createObjectURL(media_stream);
};
} else {
alert("This browser does not support WebRTC - visit WebRTC.org for more info");
webrtc_capable = false;
}
</script>
<!---Javascript for splitting screen--->
<script>
function splitScreen()
{
var z;
document.getElementById("chat").style.display="block";
z=document.getElementById("video_container");
z.className="videoContainer";
z.style.display="block";
}
var call_token; // unique token for this call
var signaling_server; // signaling server for this call
var local_peer_connection;
//function to establish webrtc connection
function start(){
peer_connection=new rtc_peer_connection({ // RTCPeerConnection configuration
"iceServers": [ // information about ice servers
{ "url": "stun:"+stun_server }, // stun server info
]
});
setup_video();
peer_connection.onicecandidate== function (ice_event) {
if (ice_event.candidate) {
signaling_server.send(
JSON.stringify({
token:call_token,
type: "new_ice_candidate",
candidate: ice_event.candidate ,
})
);
}
};
peer_connection.onaddstream=function(event){
//alert("remote video is getting called!!");
connect_stream_to_src(event.stream,document.getElementById("remotevideo"));
};
signaling_server = new WebSocket("ws://localhost:3455");
if (document.location.hash === "" || document.location.hash === undefined) { // you are the Caller
// create the unique token for this call
var token = Date.now()+"-"+Math.round(Math.random()*10000);
call_token = "#"+token;
// set location.hash to the unique token for this call
document.location.hash = token;
signaling_server.onopen = function() {
// setup caller signal handler
signaling_server.onmessage = caller_signal_handler;
// tell the signaling server you have joined the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
}
document.title = "You are the Caller";
//document.getElementById("loading_state").innerHTML = "Ready for a call...ask your friend to visit:<br/><br/>"+document.location;
} else { // you have a hash fragment so you must be the Callee
// get the unique token for this call from location.hash
call_token = document.location.hash;
signaling_server.onopen = function() {
// setup caller signal handler
signaling_server.onmessage = callee_signal_handler;
// tell the signaling server you have joined the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
// let the caller know you have arrived so they can start the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"callee_arrived",
})
);
}
document.title = "You are the Callee";
// document.getElementById("loading_state").innerHTML = "One moment please...connecting your call...";
}
// setup message bar handlers
document.getElementById("message_input").onkeydown = send_chat_message;
document.getElementById("message_input").onfocus = function() { this.value = ""; }
}
/* functions used above are defined below */
// handler to process new descriptions
function new_description_created(description) {
peer_connection.setLocalDescription(
description,
function () {
// connect_stream_to_src(event.stream,document.getElementById("remotevideo"));
signaling_server.send(
JSON.stringify({
token:call_token,
type:"new_description",
sdp:description
})
);
},
log_error
);
}
// handle signals as a caller
function caller_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "callee_arrived") {
peer_connection.createOffer(
new_description_created,
log_error
);
} else if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(
new RTCIceCandidate(signal.candidate)
);
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
peer_connection.addStream(remotevideo);
connect_stream_to_src(event.stream, document.getElementById("remotevideo"));
if (peer_connection.remoteDescription.type == "answer") {
// extend with your own custom answer handling here
//connect_stream_to_src(remotevideo, document.getElementById("remotevideo"));
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
} else {
// extend with your own signal types here
}
}
// handle signals as a callee
function callee_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(
new RTCIceCandidate(signal.candidate)
);
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
if (peer_connection.remoteDescription.type == "offer") {
peer_connection.createAnswer(new_description_created, log_error);
connect_stream_to_src(event.stream, document.getElementById("remotevideo"));
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
}
}
// add new chat message to messages list
function add_chat_message(signal) {
var messages = document.getElementById("messages");
var user = signal.user || "them";
messages.innerHTML = user+": "+signal.message+"<br/>\n"+messages.innerHTML;
}
// send new chat message to the other browser
function send_chat_message(e) {
if (e.keyCode == 13)
{
var new_message = this.value;
this.value = "";
signaling_server.send(
JSON.stringify(
{
token:call_token,
type: "new_chat_message",
message: new_message
})
);
add_chat_message({ user: "you", message: new_message });
}
}
function setup_video()
{//alert("In setup_video function");
get_user_media({
"audio":true,
"video":true
},
function (local_stream) { // success callback
// display preview from the local camera & microphone using local <video> MediaElement
connect_stream_to_src(local_stream, document.getElementById("local_video"));
// add local camera stream to peer_connection ready to be sent to the remote peer
peer_connection.addStream(local_stream);
},
log_error
);
}
// generic error handler
function log_error(error) {
console.log(error);
}
Server.js
// useful libs
var http = require("http");
var fs=require("fs");
var websocket = require("websocket").server;
// general variables
var port = 3455;
var webrtc_clients = [];
var webrtc_discussions = {};
// web server functions
var http_server = http.createServer(function(request, response) {
var matches = undefined;
if (matches = request.url.match("^/images/(.*)")) {
var path = process.cwd()+"/images/"+matches[1];
fs.readFile(path, function(error, data) {
if (error) {
log_error(error);
} else {
response.end(data);
}
});
} else {
response.end(page);
}
});
http_server.listen(port, function() {
log_comment("server listening (port "+port+")");
});
var page = undefined;
fs.readFile("htmlfilename",function(error,data){
if(error){
log_comment(error);
}
else{
page=data;
}
});
// web socket functions
var websocket_server = new websocket({
httpServer: http_server
});
websocket_server.on("request", function(request) {
log_comment("new request ("+request.origin+")");
var connection = request.accept(null, request.origin);
log_comment("new connection ("+connection.remoteAddress+")");
webrtc_clients.push(connection);
connection.id = webrtc_clients.length-1;
connection.on("message", function(message) {
if (message.type === "utf8") {
log_comment("got message "+message.utf8Data);
var signal = undefined;
try { signal = JSON.parse(message.utf8Data); } catch(e) { };
if (signal) {
if (signal.type === "join" && signal.token !== undefined) {
try {
if (webrtc_discussions[signal.token] === undefined) {
webrtc_discussions[signal.token] = {};
}
} catch(e) { };
try {
webrtc_discussions[signal.token][connection.id] = true;
} catch(e) { };
} else if (signal.token !== undefined) {
try {
Object.keys(webrtc_discussions[signal.token]).forEach(function(id) {
if (id != connection.id) {
webrtc_clients[id].send(message.utf8Data, log_error);
}
});
} catch(e) { };
} else {
log_comment("invalid signal: "+message.utf8Data);
}
} else {
log_comment("invalid signal: "+message.utf8Data);
}
}
});
connection.on("close", function(connection) {
log_comment("connection closed ("+connection.remoteAddress+")");
Object.keys(webrtc_discussions).forEach(function(token) {
Object.keys(webrtc_discussions[token]).forEach(function(id) {
if (id === connection.id) {
delete webrtc_discussions[token][id];
}
});
});
});
});
// utility functions
function log_error(error) {
if (error !== "Connection closed" && error !== undefined) {
log_comment("ERROR: "+error);
}
}
function log_comment(comment) {
console.log((new Date())+" "+comment);
}

db value becomes null or even on indexdb open it does not go into onsuccess or upgradeneeded functions

(function () {
var db;
function openDB(dbname, dbtable, keypath) {
var version = 1;
// open the database
var indexeddb_request = indexedDB.open( dbname, version ); // connect + open database
// if error
indexeddb_request.onerror = function ( event ) {
console.log( event.target );
console.trace();
}
// if success
indexeddb_request.onsuccess = function ( event ) {
console.log( event.target );
console.trace();
db = event.target.result;
}
// if onupgradeneeded
indexeddb_request.onupgradeneeded = function( event ) {
console.log( event.target );
console.trace();
db = event.target.result;
var objectStore = db.createObjectStore( dbtable, { keyPath: 'url' } );
}
}
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
function addPublication(dbtable, data) {
console.log("addPublication arguments:", arguments);
var store = getObjectStore(dbtable, 'readwrite');
var req;
try {
for (var i in data) {
req = store.add(data[i]);
}
//req = store.add(data);
} catch (e) {
if (e.name == 'DataCloneError')
displayActionFailure("This engine doesn't know how to clone a Blob, " +
"use Firefox");
throw e;
}
req.onsuccess = function (evt) {
console.log("Insertion in DB successful");
};
req.onerror = function() {
console.error("addPublication error", this.error);
};
}
function displayPubList(store, store_name) {
console.log("displayPubList");
if (typeof store == 'undefined')
store = getObjectStore(store_name, 'readonly');
var req;
req = store.count();
// Requests are executed in the order in which they were made against the
// transaction, and their results are returned in the same order.
// Thus the count text below will be displayed before the actual pub list
// (not that it is algorithmically important in this case).
req.onsuccess = function(evt) {
console.log("Count of records " + evt.target.result +
' record(s) in the object store.');
};
req.onerror = function(evt) {
console.error("add error", this.error);
};
var i = 0;
req = store.openCursor();
req.onsuccess = function(evt) {
var cursor = evt.target.result;
// If the cursor is pointing at something, ask for the data
if (cursor) {
console.log("displayPubList cursor:", cursor);
req = store.get(cursor.key);
req.onsuccess = function (evt) {
var value = evt.target.result;
console.log("Key :" + cursor.key + 'value :' + value.ssn );
};
// Move on to the next object in store
cursor.continue();
// This counter serves only to create distinct ids
i++;
} else {
console.log("No more entries");
}
};
}
openDB("abc","names","ssn");
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "bill#company.com" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "donna#home.org" }
];
addPublication("names",customerData);
displayPubList("abc","names");
})();
I'm trying to test the above code from chrome developer tools. But looks like some cases the call goes into sucess or upgradeneeded. And many times its always null. Please let me know if i'm doing something wrong here.

Gettings response (headers and body) in firefox extension

I'm trying to implement a feature that will give me the response text and (all the) response headers of each http request in the browser,
I've read a bit here: http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/
I had no idea how to extract the response from the TracingListener object. Anyone dealt with that before?? thanks!
My code:
const Cc = Components.classes;
const Ci = Components.interfaces;
// Helper function for XPCOM instanciation (from Firebug)
function CCIN(cName, ifaceName) {
return Cc[cName].createInstance(Ci[ifaceName]);
}
// get the observer service and register for the two coookie topics.
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
// Copy response listener implementation.
function TracingListener() {
this.originalListener = null;
this.receivedData = []; // array for incoming data.
}
TracingListener.prototype =
{
originalListener: null,
receivedData: null, // array for incoming data.
onDataAvailable: function(request, context, inputStream, offset, count)
{
var binaryInputStream = CCIN("#mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream");
var storageStream = CCIN("#mozilla.org/storagestream;1", "nsIStorageStream");
binaryInputStream.setInputStream(inputStream);
storageStream.init(8192, count, null);
var binaryOutputStream = CCIN("#mozilla.org/binaryoutputstream;1",
"nsIBinaryOutputStream");
binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));
// Copy received data as they come.
var data = binaryInputStream.readBytes(count);
this.receivedData.push(data);
binaryOutputStream.writeBytes(data, count);
this.originalListener.onDataAvailable(request, context,storageStream.newInputStream(0), offset, count);
},
onStartRequest: function(request, context) {
this.originalListener.onStartRequest(request, context);
},
onStopRequest: function(request, context, statusCode)
{
try {
if (request.originalURI && piratequesting.baseURL == request.originalURI.prePath && request.originalURI.path.indexOf("/index.php?ajax=") == 0) {
dump("\nProcessing: " + request.originalURI.spec + "\n");
var date = request.getResponseHeader("Date");
var responseSource = this.receivedData.join();
dump("\nResponse: " + responseSource + "\n");
piratequesting.ProcessRawResponse(request.originalURI.spec, responseSource, date);
}
} catch(e) { dumpError(e);}
this.originalListener.onStopRequest(request, context, statusCode);
},
QueryInterface: function (aIID) {
if (aIID.equals(Ci.nsIStreamListener) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Components.results.NS_NOINTERFACE;
}
}
// create an nsIObserver implementor
var listener = {
observe : function(aSubject, aTopic, aData) {
// Make sure it is our connection first.
//if (aSubject == gChannel) {
var httpChannel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
if (aTopic == "http-on-modify-request") {
// ...
httpChannel.setRequestHeader("X-Hello", "World", false);
} else if (aTopic == "http-on-examine-response") {
// ...
//alert(JSON.stringify(aData));
var newListener = new TracingListener();
aSubject.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = aSubject.setNewListener(newListener);
alert(httpChannel.getResponseHeader("Location"));
//alert(httpChannel.getAllResponseHeaders());
}
//}
},
QueryInterface : function(aIID) {
if (aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsIObserver))
return this;
throw Components.results.NS_NOINTERFACE;
}
};
observerService.addObserver(listener, "http-on-modify-request", false);
observerService.addObserver(listener, "http-on-examine-response", false);

Categories

Resources