NS_ERROR_FAILURE - javascript

I'm trying to implement the basic XHR listener as described on "Ashita" however, when loading firefox with the extension I recieve this error on whenever a page tries to load which prevents anything from loading: Error: uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIBinaryInputStream.readBytes]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: chrome://xhrlogger/content/overlay.js :: anonymous :: line 68" data: no]
My overlay.js is:
if (typeof Cc == "undefined") {
var Cc = Components.classes;
}
if (typeof Ci == "undefined") {
var Ci = Components.interfaces;
}
if (typeof CCIN == "undefined") {
function CCIN(cName, ifaceName){
return Cc[cName].createInstance(Ci[ifaceName]);
}
}
if (typeof CCSV == "undefined") {
function CCSV(cName, ifaceName){
if (Cc[cName])
// if fbs fails to load, the error can be _CC[cName] has no properties
return Cc[cName].getService(Ci[ifaceName]);
else
dump("CCSV fails for cName:" + cName);
};
}
var httpRequestObserver = {
observe: function(request, aTopic, aData){
if (aTopic == "http-on-examine-response") {
var newListener = new TracingListener();
request.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = request.setNewListener(newListener);
}
},
QueryInterface: function(aIID){
if (aIID.equals(Ci.nsIObserver) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Components.results.NS_NOINTERFACE;
},
};
function TracingListener() {
this.receivedData = []; //initialize the array
}
TracingListener.prototype =
{
originalListener: null,
receivedData: null, //will be an array for incoming data.
onDataAvailable: function(request, context, inputStream, offset, count) {
var binaryInputStream = CCIN("#mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream");
binaryInputStream.setInputStream(inputStream);
var storageStream = CCIN("#mozilla.org/storagestream;1",
"nsIStorageStream");
//8192 is the segment size in bytes, count is the maximum size of the stream in bytes
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);
//Pass it on down the chain
this.originalListener.onDataAvailable(request, context, inputStream, offset, count);
},
onStartRequest: function(request, context) {
this.originalListener.onStartRequest(request, context);
},
onStopRequest: function(request, context, statusCode) {
try
{
//QueryInterface into HttpChannel to access originalURI and requestMethod properties
request.QueryInterface(Ci.nsIHttpChannel);
var data = null;
if (request.requestMethod.toLowerCase() == "post")
{
var postText = this.readPostTextFromRequest(request, context);
if (postText)
data = ((String)(postText)).parseQuery();
}
//Combine the response into a single string
var responseSource = this.receivedData.join('');
//fix leading spaces bug
//(FM occasionally adds spaces to the beginning of their ajax responses...
//which breaks the XML)
responseSource = responseSource.replace(/^\s+(\S[\s\S]+)/, "$1");
//gets the date from the response headers on the request.
//For PirateQuesting this was preferred over the date on the user's machine
var date = Date.parse(request.getResponseHeader("Date"));
//Again a PQ specific function call, but left as an example.
//This just passes a string URL, the text of the response,
//the date, and the data in the POST request (if applicable)
/* piratequesting.ProcessRawResponse(request.originalURI.spec,
responseSource,
date,
data); */
dump(date);
dump(data);
dump(responseSource);
}
catch (e)
{
//standard function to dump a formatted version of the error to console
dump(e);
}
this.originalListener.onStopRequest(request, context, statusCode);
},
readPostTextFromRequest : function(request, context) {
try
{
var is = request.QueryInterface(Ci.nsIUploadChannel).uploadStream;
if (is)
{
var ss = is.QueryInterface(Ci.nsISeekableStream);
var prevOffset;
if (ss)
{
prevOffset = ss.tell();
ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
}
// Read data from the stream..
var charset = "UTF-8";
var text = this.readFromStream(is, charset, true);
if (ss && prevOffset == 0)
ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
return text;
}
else {
dump("Failed to Query Interface for upload stream.\n");
}
}
catch(exc)
{
dump(exc);
}
return null;
},
QueryInterface: function (aIID) {
if (aIID.equals(Ci.nsIStreamListener) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Components.results.NS_NOINTERFACE;
},
readFromStream : function(stream, charset, noClose) {
var sis = CCSV("#mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream");
sis.setInputStream(stream);
var segments = [];
for (var count = stream.available(); count; count = stream.available())
segments.push(sis.readBytes(count));
if (!noClose)
sis.close();
var text = segments.join("");
return text;
}
}
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.addObserver(httpRequestObserver,
"http-on-examine-response", false);
dump("WTFBBQ");
Any help would be most appreciated.

Mine seems to work fine with less code. Try replacing your onDataAvailable function code with:
var binaryInputStream = Components.classes["#mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
binaryInputStream.setInputStream(inputStream);
this.receivedData.push(binaryInputStream.readBytes(count));

Related

Multiple sockets override itself

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.

A console application to get a web page resource, using c# (javascript may cause this)

Aim: To download a website source with using a console application. You can find the used class in the program below.
Question: I use the code below to download a data (source) of a web page. Imagine you use chrome; If you enter first this query string, the web page itself redirects you a view HTML page and you see the data.
Entering this URL, to show the results it redirects itself to second page below. I make it by using javascript.
www.xyz.com/aaa.html?search=aaa&id=1
it redirects here: www.xyz.com/ViewResult.html
In an explorer, It works fine . I see 4 HTML tables inside the page when I use google chrome view source option. Bu in my application I see only two tables of the 4 . The two tables inside the web page is missing.(the missing two tables are the second and third.)
How can I overcome to this problem? I want to get the source of the page as I see in chrome.
Bonus informations: There is no iframe.
The particular Code :
string url = "www.xyz.com/aaa.html?search=aaa&id=1";
WebPage pG = ss.RequestPage(url, "", "GET");
pG = ss.RequestPage("www.xyz.com/ViewResult.html");
string source= pG.Html;
public WebPage RequestPage(Uri url, string content, string method, string contentType)
{
string htmlResult;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = null;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] contentData = encoding.GetBytes(content);
request.Proxy = Proxy;
request.Timeout = 60000;
request.Method = method;
request.AllowAutoRedirect = false; // false
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Referer = LastUrl;
request.KeepAlive = true; //false,
request.UserAgent = UserAgent;
request.Headers.Add("Accept-Language", "en-us,en;q=0.5");
//request.Headers.Add("UA-CPU", "x86");
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Accept-Encoding", "gzip,deflate");
String cookieString = "";
foreach (KeyValuePair<String, String> cookiePair in Cookies)
cookieString += cookiePair.Key + "=" + cookiePair.Value + ";";
if (cookieString.Length > 2)
{
String cookie = cookieString.Substring(0, cookieString.Length - 1);
request.Headers.Add("Cookie", cookie);
}
if (method == "POST")
{
request.ContentLength = contentData.Length;
request.ContentType = contentType;
Stream contentWriter = request.GetRequestStream();
contentWriter.Write(contentData, 0, contentData.Length);
contentWriter.Close();
}
int attempts = 0;
while (true)
{
try
{
response = (HttpWebResponse)request.GetResponse();
if (response == null)
throw new WebException();
break;
}
catch (WebException)
{
if (response != null)
response.Close();
if (attempts == PageReattempts)
{
throw;
}
else { }
// Wait three seconds before trying again
Thread.Sleep(3000);
}
attempts += 1;
}
// Tokenize cookies
if (response.Headers["Set-Cookie"] != null)
{
String headers = response.Headers["Set-Cookie"].Replace("path=/,", ";").Replace("HttpOnly,", "");
foreach (String cookie in headers.Split(';'))
{
if (cookie.Contains("="))
{
String[] splitCookie = cookie.Split('=');
String cookieKey = splitCookie[0].Trim();
String cookieValue = splitCookie[1].Trim();
if (Cookies.ContainsKey(cookieKey))
Cookies[cookieKey] = cookieValue;
else
Cookies.Add(cookieKey, cookieValue);
}
else
{
if (Cookies.ContainsKey(cookie))
Cookies[cookie] = "";
else
Cookies.Add(cookie, "");
}
}
}
htmlResult = ReadResponseStream(response);
response.Close();
if (response.Headers["Location"] != null)
{
response.Close();
Thread.Sleep(1500);
String newLocation = response.Headers["Location"];
WebPage result = RequestPage(newLocation);
return new WebPage(result.Html, new WebPage(htmlResult));
}
LastUrl = url.ToString();
return new WebPage(htmlResult);
}
1-WebBrowser :
public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser
{
public ExtendedWebBrowser()
{
// Ensure that ScriptErrorsSuppressed is set to false.
this.ScriptErrorsSuppressed = true;
this.ProgressChanged += ExtendedWebBrowser_ProgressChanged;
}
private void ExtendedWebBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
// InjectAlertBlocker();
string alertBlocker = #"window.alert = function () { };
window.print = function () { };
window.open = function () { };
window.onunload = function () { };
window.onbeforeunload = function () { };";
var webBrowser = sender as WebBrowser;
webBrowser?.Document?.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
this.Document?.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
}
public void NavigationWaitToComplete(string url)
{
bool complete = false;
NavigationAsync(url).ContinueWith((t) => complete = true);
while (!complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
public void NavigationWaitToComplete(string url, string targetFrameName, byte[] postData, string additionalHeaders)
{
bool complete = false;
NavigationAsync(url, targetFrameName, postData, additionalHeaders).ContinueWith((t) => complete = true);
while (!complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
public async Task NavigationAsync(string url, string targetFrameName, byte[] postData, string additionalHeaders)
{
TaskCompletionSource<bool> tcsNavigation = new TaskCompletionSource<bool>(); ;
TaskCompletionSource<bool> tcsDocument = new TaskCompletionSource<bool>(); ;
Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
DocumentCompleted += (s, e) =>
{
if (ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
Navigate(url, targetFrameName, postData, additionalHeaders);
await tcsNavigation.Task;
// navigation completed, but the document may still be loading
await tcsDocument.Task;
// the document has been fully loaded, you can access DOM here
}
public async Task NavigationAsync(string url)
{
TaskCompletionSource<bool> tcsNavigation = new TaskCompletionSource<bool>(); ;
TaskCompletionSource<bool> tcsDocument = new TaskCompletionSource<bool>(); ;
Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
DocumentCompleted += (s, e) =>
{
if (ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
Navigate(url);
await tcsNavigation.Task;
// navigation completed, but the document may still be loading
await tcsDocument.Task;
// the document has been fully loaded, you can access DOM here
}
}
Calling:
var browser = new ExtendedWebBrowser();
browser.NavigationWaitToComplete("www.xyz.com/aaa.html?search=aaa&id=1");
var html = browser.Document.Body.OuterHtml();
2-CefSharp.OffScreen
private async Task<string> RequestPageAsync(string url, string cachePath, double zoomLevel)
{
var tcs = new TaskCompletionSource<string>();
var browserSettings = new BrowserSettings();
//Reduce rendering speed to one frame per second so it's easier to take screen shots
browserSettings.WindowlessFrameRate = 1;
var requestContextSettings = new RequestContextSettings { CachePath = cachePath };
// RequestContext can be shared between browser instances and allows for custom settings
// e.g. CachePath
using (var requestContext = new RequestContext(requestContextSettings))
using (var browser = new ChromiumWebBrowser(url, browserSettings, requestContext))
{
if (zoomLevel > 1)
{
browser.FrameLoadStart += (s, argsi) =>
{
var b = (ChromiumWebBrowser)s;
if (argsi.Frame.IsMain)
{
b.SetZoomLevel(zoomLevel);
}
};
}
browser.FrameLoadEnd += (s, argsi) =>
{
var b = (ChromiumWebBrowser)s;
if (argsi.Frame.IsMain)
{
b.GetSourceAsync().ContinueWith(taskHtml =>
{
tcs.TrySetResult(taskHtml.Result);
});
}
};
}
return tcs.Task.Result;
}
Calling :
RequestPageAsync("www.xyz.com/aaa.html?search=aaa&id=1", "cachePath1", 1.0);

Interaction in a Dynamic action between javascript and plsql tasks

I'm trying to execute several pl/sql blocks in a Dynamic Action, with feedback to the end user with a modal dialog reporting the current satus.
Something like:
Processing Step 1...
/*Run pl/sql code for step 1*/
Processing Step 2...
/*Run pl/sql code for Step 2*/
and so on...
Both, the pl/sql and javascript code, run as intended but when I combined them on a Dynamic Action in the sequence:
1 - Execute Javascript
2 - Execute PL/SQL block /* With wait for result option checked*/
3 - Execute Javascript
4 - Execute PL/SQL block
The status dialog is not been shown, however the pl/sql blocks are completed without problems.
I realize that this must be something related to javascript not been multithreaded, so I've moved the pl/sql block to application processes and run them as ajax calls like this:
function something(){
var get;
var result = 0;
updateStatus('Running Step1');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
result = get.get();
if(result > 0){
updateStatus('Running Step 2');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
result = get.get();
}
closeStatusDialog();
}
But still, as before, the processes run fine but the dialog doesn't appear. Finally I added a setTimeOut function to each call, like this:
function something(){
var get;
var result = 0;
updateStatus('Running Step1');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
result = setTimeOut(get.get(),500);
if(result > 0){
updateStatus('Running Step 2');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
result = setTimeOut(get.get(),500);
}
closeStatusDialog();
}
But still nothing. What can I do to get this running as needed?.
I've checked the browser console and no exeptions are been thrown, likewise with the pl/sql blocks.
I've solved it, although the solution doesn't rely on dynamic actions, just javascript and applicacion processes. I'm posting this for anyone with a similar problem.
The htmldb_Get Javascript object is an oracle-apex wrapper for the XMLHttpRequest AJAX object. Poorly documented though.
I've found a copy of the code (at the bottom) and it turns out it has another function called GetAsync that allows to pass a function as a parameter to asign it to the onreadystatechange attribute on the XMLHttpRequest object, which will be executed each time the attribute readyState of the underlying XMLHttpRequest changes.
The function passed as a parameter can't have parameters on its own definition.
So, instead of calling get() on the htmldb_Get object you need to call GetAsync(someFunction)
With this solution in my case:
function something(){
var get;
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
get.GetAsync(someFunctionStep1);
}
function someFunctionStep1(){
if(p.readyState == 0){ /*p is the underlying XMLHttpRequest object*/
console.log("request not initialized");
updateStatus('Running Step 1');
} else if(p.readyState == 1){
console.log("server connection established");
} else if(p.readyState == 2){
console.log("request received");
} else if(p.readyState == 3){
console.log("processing request");
} else if(p.readyState == 4){
console.log("request finished and response is ready");
callStep2();
}
}
function callStep2(){
var get;
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
get.GetAsync(someFunctionStep2);
}
function someFunctionStep2(){
if(p.readyState == 0){
console.log("request not initialized");
updateStatus('Running Step 2');
} else if(p.readyState == 1){
console.log("server connection established");
} else if(p.readyState == 2){
console.log("request received");
} else if(p.readyState == 3){
console.log("processing request");
} else if(p.readyState == 4){
console.log("request finished and response is ready");
closeDialog();
}
}
Here's the htmldb_get definition, at the end is the GetAsync function
/*
str should be in the form of a valid f?p= syntax
*/
function htmldb_Get(obj,flow,req,page,instance,proc,queryString) {
//
// setup variables
//
this.obj = $x(obj); // object to put in the partial page
this.proc = proc != null ? proc : 'wwv_flow.show'; // proc to call
this.flow = flow != null ? flow : $x('pFlowId').value; // flowid
this.request = req != null ? req : ''; // request
this.page = page; // page
this.params = ''; // holder for params
this.response = ''; // holder for the response
this.base = null; // holder fot the base url
this.queryString = queryString!= null ? queryString : null ; // holder for passing in f? syntax
this.syncMode = false;
//
// declare methods
//
this.addParam = htmldb_Get_addParam;
this.add = htmldb_Get_addItem;
this.getPartial = htmldb_Get_trimPartialPage;
this.getFull = htmldb_Get_fullReturn;
this.get = htmldb_Get_getData;
this.url = htmldb_Get_getUrl;
this.escape = htmldb_Get_escape;
this.clear = htmldb_Get_clear;
this.sync = htmldb_Get_sync;
this.setNode = setNode;
this.replaceNode = replaceNode
//
// setup the base url
//
var u = window.location.href.indexOf("?") > 0 ?
window.location.href.substring(0,window.location.href.indexOf("?"))
: window.location.href;
this.base = u.substring(0,u.lastIndexOf("/"));
if ( this.proc == null || this.proc == "" )
this.proc = u.substring(u.lastIndexOf("/")+1);
this.base = this.base +"/" + this.proc;
//
// grab the instance form the page form
//
if ( instance == null || instance == "" ) {
var pageInstance = document.getElementById("pInstance");
if ( typeof(pageInstance) == 'object' ) {
this.instance = pageInstance.value;
}
} else {
this.instance = instance;
}
//
// finish setiing up the base url and params
//
if ( ! queryString ) {
this.addParam('p_request', this.request) ;
this.addParam('p_instance', this.instance);
this.addParam('p_flow_id', this.flow);
this.addParam('p_flow_step_id',this.page);
}
function setNode(id) {
this.node = html_GetElement(id);
}
function replaceNode(newNode){
var i=0;
for(i=this.node.childNodes.length-1;i>=0;i--){
this.node.removeChild(this.node.childNodes[i]);
}
this.node.appendChild(newNode);
}
}
function htmldb_Get_sync(s){
this.syncMode=s;
}
function htmldb_Get_clear(val){
this.addParam('p_clear_cache',val);
}
//
// return the queryString
//
function htmldb_Get_getUrl(){
return this.queryString == null ? this.base +'?'+ this.params : this.queryString;
}
function htmldb_Get_escape(val){
// force to be a string
val = val + "";
val = val.replace(/\%/g, "%25");
val = val.replace(/\+/g, "%2B");
val = val.replace(/\ /g, "%20");
val = val.replace(/\./g, "%2E");
val = val.replace(/\*/g, "%2A");
val = val.replace(/\?/g, "%3F");
val = val.replace(/\\/g, "%5C");
val = val.replace(/\//g, "%2F");
val = val.replace(/\>/g, "%3E");
val = val.replace(/\</g, "%3C");
val = val.replace(/\{/g, "%7B");
val = val.replace(/\}/g, "%7D");
val = val.replace(/\~/g, "%7E");
val = val.replace(/\[/g, "%5B");
val = val.replace(/\]/g, "%5D");
val = val.replace(/\`/g, "%60");
val = val.replace(/\;/g, "%3B");
val = val.replace(/\?/g, "%3F");
val = val.replace(/\#/g, "%40");
val = val.replace(/\&/g, "%26");
val = val.replace(/\#/g, "%23");
val = val.replace(/\|/g, "%7C");
val = val.replace(/\^/g, "%5E");
val = val.replace(/\:/g, "%3A");
val = val.replace(/\=/g, "%3D");
val = val.replace(/\$/g, "%24");
//val = val.replace(/\"/g, "%22");
return val;
}
//
// Simple function to add name/value pairs to the url
//
function htmldb_Get_addParam(name,val){
if ( this.params == '' )
this.params = name + '='+ ( val != null ? this.escape(val) : '' );
else
//this.params = this.params + '&'+ name + '='+ ( val != null ? val : '' );
this.params = this.params + '&'+ name + '='+ ( val != null ? this.escape(val) : '' );
return;
}
//
// Simple function to add name/value pairs to the url
//
function htmldb_Get_addItem(name,value){
this.addParam('p_arg_names',name);
this.addParam('p_arg_values',value);
}
//
// funtion strips out the PPR sections and returns that
//
function htmldb_Get_trimPartialPage(startTag,endTag,obj) {
setTimeout(html_processing,1);
if (obj) {this.obj = $x(obj);}
if (!startTag){startTag = '<!--START-->'};
if (!endTag){endTag = '<!--END-->'};
var start = this.response.indexOf(startTag);
var part;
if ( start >0 ) {
this.response = this.response.substring(start+startTag.length);
var end = this.response.indexOf(endTag);
this.response = this.response.substring(0,end);
}
if ( this.obj ) {
if(this.obj.nodeName == 'INPUT'){
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,100);
}else{
this.obj.value = this.response;
}
}else{
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,100);
}else{
this.obj.innerHTML = this.response;
}
}
}
//window.status = 'Done'
setTimeout(html_Doneprocessing,1);
return this.response;
}
var gResult = null;
var gNode = null
function htmldb_get_WriteResult(){
if(gNode && ( gNode.nodeName == 'INPUT' || gNode.nodeName == 'TEXTAREA')){
gNode.value = gResult;
}else{
gNode.innerHTML = gResult;
}
gResult = null;
gNode = null;
return;
}
//
// function return the full response
//
function htmldb_Get_fullReturn(obj) {
setTimeout(html_processing,1);
if (obj) { this.obj = html_GetElement(obj);}
if ( this.obj ) {
if(this.obj.nodeName == 'INPUT'){
this.obj.value = this.response;
}else{
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,10);
}else{
this.obj.innerHTML = this.response;
}
}
}
setTimeout(html_Doneprocessing,1);
return this.response;
}
//
// Perform the actual get from the server
//
function htmldb_Get_getData(mode,startTag,endTag){
html_processing();
var p;
try {
p = new XMLHttpRequest();
} catch (e) {
p = new ActiveXObject("Msxml2.XMLHTTP");
}
try {
var startTime = new Date();
p.open("POST", this.base, this.syncMode);
p.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
p.send(this.queryString == null ? this.params : this.queryString );
this.response = p.responseText;
if ( this.node )
this.replaceNode(p.responseXML);
if ( mode == null || mode =='PPR' ) {
return this.getPartial(startTag,endTag);
} if ( mode == "XML" ) {
setTimeout(html_Doneprocessing,1);
return p.responseXML;
} else {
return this.getFull();
}
} catch (e) {
setTimeout(html_Doneprocessing,1);
return;
}
}
function html_Doneprocessing(){
document.body.style.cursor="default";
}
function html_processing(){
document.body.style.cursor="wait";
}
/*
this adds better aysnc functionality
to the htmldb_Get object
pVar is the function that you want to call when the xmlhttp state changes
in the function specified by pVar the xmlhttp object can be referenced by the variable p
*/
htmldb_Get.prototype.GetAsync = function(pVar){
try{
p = new XMLHttpRequest();
}catch(e){
p = new ActiveXObject("Msxml2.XMLHTTP");
}
try {
var startTime = new Date();
p.open("POST", this.base, true);
if(p) {
p.onreadystatechange = pVar;
p.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
p.send(this.queryString == null ? this.params : this.queryString );
return p;
}
}catch(e){
return false;
}
}
/* PDF OUTPUT */
/*Gets PDF src XML */
function htmldb_ExternalPost(pThis,pRegion,pPostUrl){
var pURL = 'f?p='+html_GetElement('pFlowId').value+':'+html_GetElement('pFlowStepId').value+':'+html_GetElement('pInstance').value+':FLOW_FOP_OUTPUT_R'+pRegion
document.body.innerHTML = document.body.innerHTML + '<div style="display:none;" id="dbaseSecondForm"><form id="xmlFormPost" action="' + pPostUrl + '?ie=.pdf" method="post" target="pdf"><textarea name="vXML" id="vXML" style="width:500px;height:500px;"></textarea></form></div>';
var l_El = html_GetElement('vXML');
var get = new htmldb_Get(l_El,null,null,null,null,'f',pURL.substring(2));
get.get();
get = null;
setTimeout('html_GetElement("xmlFormPost").submit()',10);
return;
}
function $xml_Control(pThis){
this.xsl_string = '<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html"/><xsl:param name="xpath" /><xsl:template match="/"><xsl:copy-of select="//*[#id=$xpath]"/></xsl:template></xsl:stylesheet>';
if(document.all){
this.xsl_object = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
this.xsl_object.async=false;
this.xsl_object.loadXML(this.xsl_string)
tmp = new ActiveXObject("Msxml2.XSLTemplate.3.0");
tmp.stylesheet = this.xsl_object;
this.xsl_processor = tmp.createProcessor();
}else{
this.xsl_object = (new DOMParser()).parseFromString(this.xsl_string, "text/xml");
this.xsl_processor = (new XSLTProcessor());
this.xsl_processor.importStylesheet(this.xsl_object);
this.ownerDocument = document.implementation.createDocument("", "test", null);
}
this.xml = pThis;
this.CloneAndPlace = _CloneAndPlace;
return
function _CloneAndPlace(pThis,pThat,pText){
var lThat = $x(pThat);
if(document.all){
this.xsl_processor.addParameter("xpath", pThis);
this.xsl_processor.input = this.xml;
this.xsl_processor.transform;
var newFragment = this.xsl_processor.output;
}else{
this.xsl_processor.setParameter(null, "xpath", pThis);
var newFragment = this.xsl_processor.transformToFragment(this.xml,this.ownerDocument);
}
if(lThat){
if(document.all){
lThat.innerHTML='';
lThat.innerHTML=newFragment;
}else{
lThat.innerHTML='';
lThat.appendChild(newFragment);
}
/*
in IE newFragment will be a string
in FF newFragment will be a dome Node (more useful)
*/
return newFragment;
}
}
}

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);

WinRT - StreamSocket - Connection closing while reading data via LoadAsync

I'm trying to send HTTP requests via StreamSocket, but response is truncated with
"failedWinRTError: The object has been closed."
Here is my code:
var count, hostName, raw_request, raw_response, reader, socketProtection, startReader, streamSocket, writer;
streamSocket = new Windows.Networking.Sockets.StreamSocket();
hostName = new Windows.Networking.HostName("www.reddit.com", "80");
raw_response = "";
count = 0;
startReader = function() {
return reader.loadAsync(8 * 1000).done(function(bytesRead) {
raw_response += reader.readString(reader.unconsumedBufferLength);
if (raw_response.indexOf("</html>") > 0) {
return;
} else {
startReader();
}
}, function(error) {
raw_response += reader.readString(reader.unconsumedBufferLength);
window.raw_response = raw_response;
return;
});
};
streamSocket.connectAsync(hostName, "80", 0).done(function(response) {
var string;
reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = 1;
writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);
string = "Hello world";
writer.writeString(raw_request);
return writer.storeAsync().done(function() {
writer.flushAsync();
writer.detachStream();
return startReader();
});
});
I noticed that the beginning of the response is truncated as well.
This is what I get at the beginning of HTTP responses.
/1.1 200 OK
Also strangely... HTTPS requests work perfectly.
Any idea what I'm doing wrong? Thanks :)
Remove http:// from the host name and the second parameter is not needed:
var hostName = new Windows.Networking.HostName("www.reddit.com");
Use this object in ConnectAsync, just hostname and service name parameters are needed:
streamSocket.connectAsync(hostName, "80").done(function (response) {
// ....
}, function (error) {
console.log(error);
});
UPDATE: Ok, if the connection is being closed, probably the server closes it. Are you sending a well formed request? Here is an example:
var raw_request, raw_response, reader, writer;
var streamSocket = new Windows.Networking.Sockets.StreamSocket();
function doRequest() {
var hostName = new Windows.Networking.HostName("www.reddit.com");
streamSocket.connectAsync(hostName, "808").then(function () {
reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = Windows.Storage.Streams.InputStreamOptions.partial;
writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);
raw_request = "GET / HTTP/1.1\r\nHost: www.reddit.com/\r\nConnection: close\r\n\r\n";
writer.writeString(raw_request);
return writer.storeAsync();
}).then(function () {
raw_response = "";
return startReader();
}, function (error) {
console.log(error);
});
}
function startReader() {
return reader.loadAsync(99999999).then(function (bytesRead) {
raw_response += reader.readString(reader.unconsumedBufferLength);
if (bytesRead === 0) {
window.raw_response.value = raw_response;
return;
}
return startReader();
});
};

Categories

Resources