`

Creating Sandboxed HTTP Connections

阅读更多

Introduction

Starting with Gecko 1.8.1 (Firefox 2 ), it is possible to create sandboxed HTTP connections which don't affect the user's cookies. This article will cover the basics of doing HTTP connections from XPCOM JavaScript, and should easily translate to C++ XPCOM.

Setting up an HTTP connection

The first step in setting up an HTTP connection from an URL (stored in a string) is to create an nsIURI out of it. nsIURI is an XPCOM representation of an URI, with useful methods to query and manipulate the URI. To create an nsIURI from an string, we use the newURI method of nsIIOService :

1 // the IO service
2 var ioService = Components.classes[ "@mozilla.org/network/io-service;1" ]
3 .getService(Components.interfaces.nsIIOService);
4
5 // create an nsIURI
6 var uri = ioService.newURI(myURLString, null , null );

Once the nsIURI has been created, a nsIChannel can be generated from it using nsIIOService 's newChannelFromURI method:

1 // get a channel for that nsIURI
2 var channel = ioService.newChannelFromURI(uri);

To initiate the connection, the asyncOpen method is called. It takes two arguments: a listener and a context that is passed to the listener's methods.

1 channel.asyncOpen(listener, null );

HTTP notifications

The above mentioned listener is a nsIStreamListener , which gets notified about events such as HTTP redirects and data availability.

  • onStartRequest - gets called when a new request is initiated.
  • onDataAvailable - new data is available. Since this is a stream, it could be called multiple times (depending on the size of the returned data, networking conditions, etc).
  • onStopRequest - the request has finished.
  • onChannelRedirect - when a redirect happens, a new nsIChannel is created, and both the old and new ones are passed in as arguments.

Since nsIStreamListener does not cover cookies, the current channel being used will need to be stored as a global, since another listener will be used for cookie notifications (covered in the next section). It is usually best to use a JavaScript wrapper that implements all the required methods and calls the specified callback function when the connection has completed. Below is an example:

01 // global channel
02 var gChannel;
03
04 // init the channel
05
06 // the IO service
07 var ioService = Components.classes[ "@mozilla.org/network/io-service;1" ]
08 .getService(Components.interfaces.nsIIOService);
09
10 // create an nsIURI
11 var uri = ioService.newURI(myURLString, null , null );
12
13 // get a channel for that nsIURI
14 gChannel = ioService.newChannelFromURI(uri);
15
16 // get an listener
17 var listener = new StreamListener(callbackFunc);
18
19 gChannel.notificationCallbacks = listener;
20 gChannel.asyncOpen(listener, null );
21
22 function StreamListener(aCallbackFunc) {
23 this .mCallbackFunc = aCallbackFunc;
24 }
25
26 StreamListener.prototype = {
27 mData: "" ,
28
29 // nsIStreamListener
30 onStartRequest: function (aRequest, aContext) {
31 this .mData = "" ;
32 },
33
34 onDataAvailable: function (aRequest, aContext, aStream, aSourceOffset, aLength) {
35 var scriptableInputStream =
36 Components.classes[ "@mozilla.org/scriptableinputstream;1" ]
37 .createInstance(Components.interfaces.nsIScriptableInputStream);
38 scriptableInputStream.init(aStream);
39
40 this .mData += scriptableInputStream.read(aLength);
41 },
42
43 onStopRequest: function (aRequest, aContext, aStatus) {
44 if (Components.isSuccessCode(aStatus)) {
45 // request was successfull
46 this .mCallbackFunc( this .mData);
47 } else {
48 // request failed
49 this .mCallbackFunc( null );
50 }
51
52 gChannel = null ;
53 },
54
55 // nsIChannelEventSink
56 onChannelRedirect: function (aOldChannel, aNewChannel, aFlags) {
57 // if redirecting, store the new channel
58 gChannel = aNewChannel;
59 },
60
61 // nsIInterfaceRequestor
62 getInterface: function (aIID) {
63 try {
64 return this .QueryInterface(aIID);
65 } catch (e) {
66 throw Components.results.NS_NOINTERFACE;
67 }
68 },
69
70 // nsIProgressEventSink (not implementing will cause annoying exceptions)
71 onProgress : function (aRequest, aContext, aProgress, aProgressMax) { },
72 onStatus : function (aRequest, aContext, aStatus, aStatusArg) { },
73
74 // nsIHttpEventSink (not implementing will cause annoying exceptions)
75 onRedirect : function (aOldChannel, aNewChannel) { },
76
77 // we are faking an XPCOM interface, so we need to implement QI
78 QueryInterface : function (aIID) {
79 if (aIID.equals(Components.interfaces.nsISupports) ||
80 aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
81 aIID.equals(Components.interfaces.nsIChannelEventSink) ||
82 aIID.equals(Components.interfaces.nsIProgressEventSink) ||
83 aIID.equals(Components.interfaces.nsIHttpEventSink) ||
84 aIID.equals(Components.interfaces.nsIStreamListener))
85 return this ;
86
87 throw Components.results.NS_NOINTERFACE;
88 }
89 };

Quick note: storing the channel in a global (especially in an extension) isn't a good idea, but was done to make the code easier to read. It would be better to have the entire implementation inside a class and storing the channel as a member:

01 function myClass() {
02 this .mChannel = null ;
03 ...
04 var listener = new this .StreamListener(callbackFunc);
05 ...
06 }
07
08 myClass.prototype.StreamListener = function (aCallbackFunc) {
09 return ({
10 mData: "" ,
11 ...
12 })
13 }

Handling cookies

When sending a request, cookies that apply to the URL are sent with the HTTP request. The HTTP response can also contain cookies, which the browser processes. As of Mozilla 1.8.1 (Firefox 2 ), it is now possible to intercept those two cases.

For example, this means that if the user was logged into an webmail account, another account on the same domain could be checked without changing the user's cookies.

The observer service (nsIObserverService ) is used to send general notifications, including the two cookie ones. The addObserver method is used to add an observer for a certain topic and takes in three agruments:

  • an object than implements nsIObserver
  • the topic to listen for. For cookies, the two topics are:
    • http-on-modify-request - happens after the cookie data has been loaded into the request, but before the request is sent.
    • http-on-examine-response - happens after the response is received, but before the cookies are processed
  • whether to hold a weak reference to the observer argument. Use false .

In order to avoid memory leaks , the observer needs to be removed at one point. The removeObserver method takes in the listener object and the topic and removes it from the notification list.

As with the above stream listener, an nsIObserver implementing object is needed, which only needs to implement one method, observe . The observe method gets passed in three arguments, which for the two cookie topics are:

  • aSubject : the channel (nsIChannel ) that caused this notification to happen.
  • aTopic : the notification topic.
  • aData : null for the two topics.

Since the observers get notified for the registered topic for any connection, the listener needs to make sure that the notification is for the HTTP connection our code created. Since the channel that causes the notification is passed in as the first argument, comparing it to the globally stored channel (gChannel ) in the previous section (which also gets updated each time a redirect happens).

01 // create an nsIObserver implementor
02 var listener = {
03 observe : function (aSubject, aTopic, aData) {
04 // Make sure it is our connection first.
05 if (aSubject == gChannel) {
06 var httpChannel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
07 if (aTopic == "http-on-modify-request" ) {
08 // ...
09 } else if (aTopic == "http-on-examine-response" ) {
10 // ...
11 }
12 }
13 },
14
15 QueryInterface : function (aIID) {
16 if (aIID.equals(Components.interfaces.nsISupports) ||
17 aIID.equals(Components.interfaces.nsIObserver))
18 return this ;
19 throw Components.results.NS_NOINTERFACE;
20 }
21 };
22
23 // get the observer service and register for the two coookie topics.
24 var observerService = Components.classes[ "@mozilla.org/observer-service;1" ]
25 .getService(Components.interfaces.nsIObserverService);
26 observerService.addObserver(listener, "http-on-modify-request" , false );
27 observerService.addObserver(listener, "http-on-examine-response" , false );

The final piece is to manipulate the cookies. In order to manipulate cookies, the nsIChannel needs to be converted into a nsIHttpChannel by using QueryInterface (QI):

1 var httpChannel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);

Cookies are actually part of the HTTP header, nsIHttpChannel provides four methods for working with headers: two for getting and setting request headers, and two for getting and setting response headers. The cookie header for requests is called "Cookie", while for responses it is "Set-Cookie".

  • getRequestHeader(aHeader) - returns the request header value for the requested header.
  • setRequestHeader(aHeader, aValue, aMerge) - sets the request header's value. If aMerge is true , the new value is appened, otherwise the old value is overwritten.
  • getResponseHeader(aHeader) - returns the response header value for the requested header.
  • setResponseHeader(aHeader, aValue, aMerge) - sets the response header's value. If aMerge is true , the new value is appened, otherwise the old value is overwritten.

These methods provide all the required functionality needed to modify cookies before they are processed/sent, allowing for sandboxed cookie connections that don't affect the user's cookies.

HTTP referrer

If the HTTP request needs to have a referrer set, two additional steps are needed after the nsIChannel is created, but before it is opened. First, a nsIURI needs to be generated for the referrer URL. Like before, the nsIIOService is used:

1 var referrerURI = ioService.newURI(referrerURL, null , null );

Next, the nsIChannel is QIed to nsIHttpChannel and the referrer property is set to the generated nsIURI :

1 var httpChannel = channel.QueryInterface(Components.interfaces.nsIHttpChannel);
2 httpChannel.referrer = referrerURI;

Creating HTTP POSTs

To create an HTTP POST, a few additional steps are required after the nsIChannel is created.

First, a nsIInputStream instance is created, after which the setData method is called. The first argument is the POST data as a string, while the second argument is the length of that data. In this case, the data is URL encoded, meaning that the string should look like this: foo=bar&baz=eek .

1 var inputStream = Components.classes[ "@mozilla.org/io/string-input-stream;1" ]
2 .createInstance(Components.interfaces.nsIStringInputStream);
3 inputStream.setData(postData, postData.length);

Next, the nsIChannel is QIed to an nsIUploadChannel . Its setUploadStream method is called, passing in the nsIInputStream and the type (in this case, "application/x-www-form-urlencoded"):

1 var uploadChannel = gChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
2 uploadChannel.setUploadStream(inputStream, "application/x-www-form-urlencoded" , -1);

Due to a bug, calling setUploadStream will reset the nsIHttpChannel to be a PUT request, so now the request type is set to POST:

1 // order important - setUploadStream resets to PUT
2 httpChannel.requestMethod = "POST" ;
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics