Esempio n. 1
0
  initialize : function initialize() {
    // initialize internals
    this._maxResults = 3;
    // cache of current search terms
    this._terms = "";
    // timer for pausing requests awaiting term changes
    this._suggestionTimer = null;
    // cache of the default engines with suggestion urls
    this._engines = [];

    this._set_engines();

    SearchEngines.on("defaults.added", this._reset_engines.bind(this));
    SearchEngines.on("defaults.removed", this._reset_engines.bind(this));

    this.on("change:terms", this._warm_up_network.bind(this));
    this.on("change:engines", this._warm_up_network.bind(this));

    ObserverService.add("search:debug", this._debug.bind(this), this);
    this.unload = function unload(reason) {
      ObserverService.remove("search:debug", this._debug, this);
      off(this);
    };
    require("unload").ensure(this);
  }
Esempio n. 2
0
 _initFrame: function _initFrame(frame) {
   // We need to remove observers from the current iframe
   // before adding new ones to avoid leaking the iframe,
   // whether initFrame is being called with a new iframe
   // or an existing one (which happens when page-worker
   // calls initFrame multiple times with the same iframe).
   if (this._frame)
     this._cleanUpFrame();
   
   this._frame = frame;
   frame.docShell.allowJavascript = this.allow.script;
   frame.setAttribute("src", this._contentURL);
   if (frame.contentDocument.readyState == "complete" && 
       frame.contentDocument.location == this._contentURL) {
     // In some cases src doesn't change and document is already ready
     // (for ex: when the user moves a widget while customizing toolbars.)
     this._window = frame.contentWindow.wrappedJSObject;
     this._onInit();
   }
   else if ('ready' === this.contentScriptWhen) {
     frame.addEventListener(
       ON_READY,
       this._onReady = this._onReady.bind(this),
       true
     );
   } else {
     observers.add(ON_START, this._onStart = this._onStart.bind(this));
   }
 },
Esempio n. 3
0
 init: function CO_init(aConfig)
 {
   this.config = aConfig;
   for (let index in this.config) {
     if (!(typeof this.config[index] == "function")) {
       throw new Error("ConsoleObserver configuration object property should be a function");
     }
     if (index == "created") {
       observers.add(CONSOLE_CREATED, this.handleCreate.bind(this));
     }
     else if (index == "destroyed") {
       observers.add(CONSOLE_DESTROYED, this.handleDestroy.bind(this));
     }
     else if (index == "message") {
       observers.add(CONSOLE_MESSAGE_CREATED, this.handleMessage.bind(this));
     }
   }
 },
exports.main = function (options, callbacks) {
  if (!prefs.isSet(URL_PREF)) {
    prefs.set(URL_PREF, URL);
  }

  var windowTracker = new winUtils.WindowTracker(mailWindowManager);
  require("unload").ensure(windowTracker);
  obService.add(NETWORK_STATUS_CHANGED, networkStatusObserver);
};
Esempio n. 5
0
/**
 * @class
 */ 
function TabWatcher () {
    var that = this;
    this.openTabs = [];

    // Start tracking tabs
    var tracker = {
        onTrack: function(tab) {
            that.openTabs.push({
                tabBrowser: tab.linkedBrowser,
                traces: []
            });
            dump('Itrace - tab-watcher: A new tab is being tracked ' + '(' + that.openTabs.length + ')\n');
        },
        onUntrack: function(tab) {
            that.removeTab(tab.linkedBrowser);
            dump('Itrace - tab-watcher: A tab is no longer being tracked ' + '(' + that.openTabs.length + ')\n');
        }
    };
    TabBrowser.TabTracker(tracker);

    // Notify objects when a tab is activated
    Tabs.on('activate', function (tab) {
        dump('Itrace - tab-watcher: activate tab, "' + tab.title + '" (#' + tab.index + ')\n');
        var activeTabElement = TabBrowser.activeTab.linkedBrowser;
        var traceCount = that.getTab(activeTabElement).traces.length;
        var hasItraceInfo = traceCount > 0;
        ObserverService.notify('itrace-tab-watcher-tab-activate', {
            tabBrowser: activeTabElement,
            hasItraceInfo: hasItraceInfo,
            traceCount: traceCount
        });
    });

    // Add traces to tab when the info have arived from the lazy request.
    ObserverService.add('itrace-info-requester-on-response', function (arg) {
        that.pushTraceInfoToTab(arg.browser, arg.json);
    }, this);

    ObserverService.add('itrace-panel-clear-list', function (info) {
         resetTracesForTab(that.getTab(info.tabBrowser));
    }, this);

    dump('Itrace - tab-watcher: TabWatcher instantiated\n');
}
Esempio n. 6
0
org.todesschaf.cacheUsage.setup = function() {
    // Make sure our output directory exists
    var profileDir = Cc["@mozilla.org/file/directory_service;1"].
      getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile).path;

    var outDir = file.join(profileDir, "org.todesschaf.mozilla.cacheUsage");
    if (!file.exists(outDir)) {
        file.mkpath(outDir);
    }

    // Make up a filename for our output this time
    var now = new Date();
    this.startupTime = now.getTime();
    var month = now.getUTCMonth() + 1;
    var dd = now.getUTCDate();
    var hh = now.getUTCHours();
    var mm = now.getUTCMinutes();
    var ss = now.getUTCSeconds();

    var outFileName = "" + now.getUTCFullYear() + "-";
    if (month < 10) {
        outFileName += "0";
    }
    outFileName = outFileName + month + "-";

    if (dd < 10) {
        outFileName += "0";
    }
    outFileName = outFileName + dd + "-";

    if (hh < 10) {
        outFileName += "0";
    }
    outFileName = outFileName + hh + ":";

    if (mm < 10) {
        outFileName += "0";
    }
    outFileName = outFileName + mm + ":";

    if (ss < 10) {
        outFileName += "0";
    }
    outFileName = outFileName + ss + ".json";

    this.outputFile = file.join(outDir, outFileName);

    // Go through the cache and find out what we're starting with
    this.collectData(this.startupCacheInfo);

    // Finally, listen for the cache going away, so we can do our final data
    // collection when that happens
    obsSvc.add("quit-application-granted", this.onProfileDisappearing, this);
};
 _initFrame: function _initFrame(frame) {
   this._frame = frame;
   frame.docShell.allowJavascript = this.allow.script;
   frame.setAttribute("src", this._contentURL);
   if ('ready' === this.contentScriptWhen) {
     frame.addEventListener(
       ON_READY,
       this._onReady = this._onReady.bind(this),
       true
     );
   } else {
     observers.add(ON_START, this._onStart = this._onStart.bind(this));
   }
 },
Esempio n. 8
0
exports.setup = function() {
	// Set up logging
	var createPagesTable = data.load("create_pages_table.sql");
	loggingDB.executeSQL(createPagesTable, false);
	
	// Log new windows
	observerService.add("content-document-global-created", function(subject, data) {
		var window = subject;
		var pageID = pageIDFromWindow(window);
		var parentID = window.parent ? pageIDFromWindow(window.parent) : -1;
		var location = window.document && window.document.location ? window.document.location : "";
		insertPage(pageID, location, parentID);
	});
	
};
Esempio n. 9
0
exports.main = function(options, callbacks) {
    observer.add("final-ui-startup", function (s,d) {
	console.log("Hello World!");
	window = new contentWindow.Window({
	    // NOTE: point to the xul document into the data directory of the current package
	    url: packaging.getURLForData("/main.xul"),
	    width: 800,
	    height: 600,
	    onStartLoad: function() { 
		try { 
		    // NOTE: get the chrome window
		    window.contentWindow.wrappedJSObject.
			// NOTE: set the label4 value
			document.getElementById("label4").value ="OK"; 
		} 
		catch(e) {} 
	    }
	});
    });
}
Esempio n. 10
0
exports.testObserverService = function(test) {
  var ios = Cc['@mozilla.org/network/io-service;1']
            .getService(Ci.nsIIOService);
  var service = Cc["@mozilla.org/observer-service;1"].
                getService(Ci.nsIObserverService);
  var uri = ios.newURI("http://www.foo.com", null, null);
  var timesCalled = 0;
  var lastSubject = null;
  var lastData = null;

  var cb = function(subject, data) {
    timesCalled++;
    lastSubject = subject;
    lastData = data;
  };

  observers.add("blarg", cb);
  service.notifyObservers(uri, "blarg", "some data");
  test.assertEqual(timesCalled, 1,
                   "observer-service.add() should call callback");
  test.assertEqual(lastSubject, uri,
                   "observer-service.add() should pass subject");
  test.assertEqual(lastData, "some data",
                   "observer-service.add() should pass data");

  function customSubject() {}
  function customData() {}
  observers.notify("blarg", customSubject, customData);
  test.assertEqual(timesCalled, 2,
                   "observer-service.notify() should work");
  test.assertEqual(lastSubject, customSubject,
                   "observer-service.notify() should pass+wrap subject");
  test.assertEqual(lastData, customData,
                   "observer-service.notify() should pass data");

  observers.remove("blarg", cb);
  service.notifyObservers(null, "blarg", "some data");
  test.assertEqual(timesCalled, 2,
                   "observer-service.remove() should work");
};
Esempio n. 11
0
  constructor : function SearchEngines() {
    if (!storage.engines) {
      // list of currently used engines according to user order
      storage.engines = this._engines = [];
      // list of found engines according to how often they are seen
      storage.other = [];
      this._first_run();
    } else {
      this._engines = storage.engines.map(function (engine) {
        //console.log("engine", JSON.stringify(engine));
        return this._engineFromJSON(engine);
      }.bind(this));
      //storage.other.forEach(function(e) { console.log(JSON.stringify(e)); });
      this._upgrade();
    }

    this.on("defaults.added", function (engine) {
      StatisticsReporter.send("defaults.added", engine);
    });
    this.on("defaults.removed", function (engine) {
      StatisticsReporter.send("defaults.removed", engine);
    });

    this.on("others.added", function (engine) {
      StatisticsReporter.send("others.added", engine);
    });
    this.on("others.removed", function (engine) {
      StatisticsReporter.send("others.removed", engine);
    });

    ObserverService.add("search:debug", this._debug.bind(this), this);

    SearchEnginesCollector.on("engine", this._collector.bind(this));

    SimpleStorage.on("OverQuota", this._overQuota.bind(this));

    require("unload").ensure(this);
  },
Esempio n. 12
0
exports.run = function() {

	// Set up logging
	var createCookiesTable = data.load("create_cookies_table.sql");
	loggingDB.executeSQL(createCookiesTable, false);

	// Instrument cookie changes
	observerService.add("cookie-changed", function(subject, data) {
		// TODO: Support other cookie operations
		if(data == "deleted" || data == "added" || data == "changed") {	
			var update = {};
			update["change"] = loggingDB.escapeString(data);
			
			var cookie = subject.QueryInterface(Ci.nsICookie2);
			update["creationTime"] = cookie.creationTime;
			update["expiry"] = cookie.expiry;
			update["is_http_only"] = loggingDB.boolToInt(cookie.isHttpOnly);
			update["is_session"] = loggingDB.boolToInt(cookie.isSession);
			update["last_accessed"] = cookie.lastAccessed;
			update["raw_host"] = loggingDB.escapeString(cookie.rawHost);
			
			cookie = cookie.QueryInterface(Ci.nsICookie);
			update["expires"] = cookie.expires;
			update["host"] = loggingDB.escapeString(cookie.host);
			update["is_domain"] = loggingDB.boolToInt(cookie.isDomain);
			update["is_secure"] = loggingDB.boolToInt(cookie.isSecure);
			update["name"] = loggingDB.escapeString(cookie.name);
			update["path"] = loggingDB.escapeString(cookie.path);
			update["policy"] = cookie.policy;
			update["status"] = cookie.status;
			update["value"] = loggingDB.escapeString(cookie.value);
			
			loggingDB.executeSQL(loggingDB.createInsert("cookies", update), true);
		}
	});
	
};
Esempio n. 13
0
exports.run = function() {
	function copyLocalStorage() {
		var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
		file.append('webappsstore.sqlite');

		var storageService = Cc["@mozilla.org/storage/service;1"].getService(Ci.mozIStorageService);
		var storageConn = storageService.openDatabase(file);

		var statement = storageConn.createStatement('select * from webappsstore2');

		while (statement.executeStep()) {
	  	var update = {};

	  	update['scope'] = loggingDB.escapeString(statement.row.scope);
	  	update['key'] = loggingDB.escapeString(statement.row.key);
			update['value'] = loggingDB.escapeString(statement.row.value);
	  	update['secure'] = statement.row.secure;
	  	update['owner'] = loggingDB.escapeString(statement.row.owner);

	  	loggingDB.executeSQL(loggingDB.createInsert("local_storage", update), false);
		}
	}

	// Set up logging
	var createLocalStorageTable = data.load("create_local_storage_table.sql");
	loggingDB.executeSQL(createLocalStorageTable, false);

	// tying to a particular page since applicaiton shutdown events are passed after the databases are no longer available
	observerService.add("content-document-global-created", function(subject, data) {
		var window = subject;
		var location = window.document && window.document.location ? window.document.location : "";

		if (location == 'http://www.josesignanini.com/') {
			copyLocalStorage();
		}
	});
};
Esempio n. 14
0
function loginManagerObserver() {
    function onStorageChanged(aSubject, aData) {
        if (aData == 'modifyLogin')
            aSubject = aSubject.QueryInterface(Ci.nsIArray).queryElementAt(1, Ci.nsILoginMetaInfo);

        var loginInfo = aSubject.QueryInterface(Ci.nsILoginMetaInfo).QueryInterface(Ci.nsILoginInfo);

        switch(aData) {
            case 'modifyLogin':
                // modifyLogin fires even when an old login is used, and not modified. (?)
                
                // TODO: find a better way of doing this. For now, look to see if the
                // password was just modified.
                if ((Date.now() - aSubject.timePasswordChanged) < 100) {
                    Alerts.AlertManager.passwordChanged(url.URL(loginInfo.hostname).host);
                }
                else {
                    var passwordAgeInDays = (Date.now() - aSubject.timePasswordChanged)/1000/60/60/24;
                    if (passwordAgeInDays > 90) {
                        Alerts.PopupAlertsManager.displayPopupAlert({
                           type: 'stale_password',
                           password: loginInfo.password,
                           age_in_days: passwordAgeInDays,
                           threshold: 90,
                           hostname: url.URL(loginInfo.hostname).host
                        });                        
                    }
                }
                
                break;
        }


    }
    observers.add('passwordmgr-storage-changed', onStorageChanged);
}
Esempio n. 15
0
 function init() {
     observers.add(ON_CONTENT, doInject);
     haveInit = true;
 }
Esempio n. 16
0
  function(t){
    obs_svc.add(t, function(subj){
      console.log(JSON.stringify({msg:t,data:subj,ts:Date.now()}))
    })
})
Esempio n. 17
0
var PF_Eventer = function(){

    var subs = {};

    this.on  = function(type, listener) {
	if (!subs[type])
	    subs[type] = [];
	subs[type].push({times: -1, signal: listener});
	console.log("Added listener for " + type);
	return;
    };

    this.once = function(type, listener) {
	if (!subs[type])
	    subs[type] = [];
	subs[type].push({times: 1, signal: listener});
	console.log("Added once-listnere for " + type);
    };

    this.removeListener = function(type, listener) {
	if (!subs[type]) return;
	
	var retained = [];
	for (var i=0; i < subs[type][i]; i++) {
	    if (subs[type][i].signal !== listener) {
		retained.push(subs[type][i]);
	    }
	}
	
	subs[type] = retained;	
	console.log("Removed listnere for " + type);
    };

    var listenersFor = function(type) {
	var ret  = subs[type] || [];
	return ret;
    };
    
    this.anyListeners = function(type) {
	return (listenersFor(type).length > 0);
    };

    this.emit = function(type, val) {
	listenersFor(type).forEach(
	    function(l){
		l.signal(val);
		if (l.count === 1)
		    _pfl.removeListener(type, l.signal);
	    });
    };

    var _pfl = this;

    os.add("http-on-examine-response", function(s,d) {
	s.QueryInterface(Ci.nsIHttpChannel);
	s.QueryInterface(Ci.nsITraceableChannel);
	var pfService = s.name.match(/.*\/emr.*\/(.*?)\.asmx/i);

	if (pfService === null) 
	    return;

	pfService = pfService[1];

	var routeResponse = function(status, data, post){
	    data = data.replace(/^<\?xml.*\?>/,"");
	    var replydom = domparser.parseFromString(data, "application/xml");
	    var pfResponse = replydom.documentElement.firstElementChild.firstElementChild;
	    var responseType = pfResponse.nodeName;
	    
	    if (PF[pfService] && PF[pfService].wsdl.types[responseType]) {		
		var pfOperation = Object.keys(PF[pfService].wsdl.operations).filter(
		    function (k) {
			var o = PF[pfService].wsdl.operations[k];
			return (o.outtype === "tns:"+responseType || 
				o.inttype === "tns:"+responseType);
		});

//		console.log("found op " + pfOperation);
		
		if (pfOperation.length === 0) {
		    console.log("no operation for for " + pfService+"." + responseType);
		    return;
		} 
		else if (pfOperation.length > 1) {
		    console.log("Ambiguous mapping for " + pfOperation);
		}

		var evName = pfService + "." + pfOperation[0];

		// Optimization:  only parse the payload 
		// if someone is listening! 
		if (! _pfl.anyListeners(evName)) 
		    return;
		
		var jsonpayload = PF[pfService].interface.
		    parse_type(responseType, pfResponse);
		
		_pfl.emit(evName, jsonpayload);

	    }
	};
	
	var listener = new TracingListener(routeResponse);
	listener.next = s.setNewListener(listener);		
    });	
};
Esempio n. 18
0
		httpChannel.setRequestHeader(headerName, headerValue, false);		
	}
	catch(error) {
	}
}

function windowFromHttpChannel(httpChannel) {
	try {
		var notificationCallbacks = null;
		if(httpChannel.notificationCallbacks)
			notificationCallbacks = httpChannel.notificationCallbacks;
		else
			notificationCallbacks = httpChannel.loadGroup.notificationCallbacks;
		if(notificationCallbacks) {
			var interfaceRequestor = notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
			return interfaceRequestor.getInterface(Ci.nsIDOMWindow);
		}
	}
	catch(error) {
	}
	return null;
}

function topWindowFromWindow(currentWindow) {
	while(currentWindow.parent != currentWindow)
		currentWindow = currentWindow.parent;
	return currentWindow;
}

observerService.add("http-on-modify-request", httpModificationCallback);
Esempio n. 19
0
(function(global) {
    "use strict";
    let obSvc = require('observer-service');
    let Connection = require('connection').Connection;
    let chrometab = require('chrometab');
    // var prefs = require('simple-prefs').prefs;
    // var url = require('url');
    // var data = require("self").data;
    // var xhr = require("xhr");
    // var timers = require("timers");
    // var storage = require("simple-storage").storage;
    // var windowUtils = require("window-utils");
    // var addontab = require('addon-page');
    var allConnections = [];
    var connectionFilter = function(connection){ return true; };
    obSvc.add("http-on-examine-response", function(subject) {
        var connection = new Connection(subject);
        if (connection.valid){
            allConnections.push(connection);
            // FIXME: Save less frequently
            saveConnections();
            if (uiworker && connectionFilter(connection)){
                uiworker.port.emit('connection', connection);
            }
        }
    });

    chrometab.on('activate', function(tabinfo){
        var items = currentConnectionsForTab(tabinfo);
        // visualize items
    });


    function matchesCurrentTab(connection){
        // this is a tabinfo object
        var tabinfo = this;
        if (!tabinfo) return false;
        if (!tabinfo.uri) return false;
        if (tabinfo.uri.spec === mainPage){ return false; }
        return (connection._sourceTab === tabinfo.tab) && (connection.timestamp > tabinfo.loadTime);
    }

    function currentConnectionsForTab(tabinfo){
        return allConnections.filter(matchesCurrentTab, tabinfo);
    }

    // START SERIALIZATION
    var storage = require("simple-storage").storage;
    if (storage.connections){
        allConnections = JSON.parse(storage.connections).map(function(connection){
            connection.__proto__ = Connection.prototype;
            connection.valid = true;
            connection.timestamp = new Date(connection.timestamp);
            return connection;
        });
    }
    if (!storage.collusionToken){
        storage.collusionToken = require('sdk/util/uuid').uuid().toString();
    }
    var collusionToken = storage.collusionToken;


    function saveConnections(){
        storage.connections = JSON.stringify(allConnections);
    }
    // END SERIALIZATION

    // Handle Private Browsing

    let privateBrowsing = require("private-browsing");

      // Clear graph when going into private browsing mode:
    privateBrowsing.on("start", function() {
        storage.allConnections = JSON.stringify(allConnections);
        allConnections = [];
    });

    // Restore original graph when leaving private browsing mode:
    privateBrowsing.on("stop", function() {
        if (storage.allConnections) {
            allConnections = JSON.parse(storage.allConnections);
        }
    });


    // Add Menu item and widget for opening collusion
    //
    // 1. There should never be two Collusion tabs open
    // 2. We should be able to switch to the Collusion tab if it exists
    // 3. We should be able to close the Collusion tab if it is open

    let tabs = require('tabs');
    let data = require("self").data;
    let mainPage = data.url("index.html");
    let uiworker = null;

    function attachToCollusionPage(worker) {
      /* Set up channel of communication between this add-on and the script (content-script.js)
       * that we attached to the web page running the Collusion UI. */
        // FIXME, this is drawn directly from old Collusion
        uiworker = worker;
        // worker.port.emit('log', 'attaching worker');
        worker.port.on("detach", function() {
            uiworker = null;
        });
        worker.port.on("reset", function() {
            allConnections = [];
        });
        worker.port.on("save", function() {
            // Don't permanently store data about graph in private browsing mode
            if (!privateBrowsing.isActive) {
                storage.allConnections = allConnections;
            }
        });
        worker.port.on('uiready', function(){
            // worker.port.emit('log', 'addon received uiready: "' + JSON.stringify(allConnections) + '"');
            worker.port.emit('init', allConnections || []); // FIXME, should used filtered connections
        });

        worker.port.on('debug', function(){
            worker.port.emit('log', 'There are ' + allConnections.length + ' connections stored');
        });

        worker.port.on('export', function(){
            worker.port.emit('log', 'exporting data from addon');
            worker.port.emit('export-data', exportWrap(allConnections));
        });
    }

    function exportWrap(connections){
        return JSON.stringify({
            format: 'Collusion Save File',
            version: '1.0',
            token: collusionToken,
            connections: connections.map(function(connection){
                if (connection && connection.toLog){
                    return connection.toLog();
                }else{
                    console.log('Could not convert ' + JSON.stringify(connection) + ' to log format');
                }
            })
        });
    }



    require("page-mod").PageMod({
        include: mainPage,
        contentScriptWhen: 'start',
        contentScriptFile: data.url('content-script.js'),
        onAttach: attachToCollusionPage
    });

    function getCollusionTab(){
        for(var i = 0; i < tabs.length; i++){
            var tab = tabs[i];
            if (tab.url === mainPage){
                return tab;
            }
        }
    }

     // Set up the menu item to open the main UI page:
    var menuitem = require("shared/menuitems").Menuitem({
        id: "collusion_openUITab",
        menuid: "menu_ToolsPopup",
        label: "Show Collusion",
        onCommand: function() {
            openOrSwitchToOrClose(mainPage);
        },
        insertbefore: "sanitizeItem",
        image: data.url("favicon.ico")
    });

    function collusionTabOpened(tab){
        console.log('collusionTabOpened: ', tab);
    }

    function collusionTabClosed(tab){
        console.log('collusionTabClosed: ', tab);
        // Stop all Collusion processes, close worker(s)
    }

    function collusionTabReady(tab){
        console.log('collusionTabReady: ', tab);
        // add-on page should be ready to go, attach scripts
        var worker = attachToExistingCollusionPages(tab);
        // worker.port.emit('log', 'collusionTabReady');
        worker.port.emit('init', allConnections || []); // FIXME: Send appropriate data
    }

    function collusionTabActivate(tab){
        console.log('collusionTabActivate: ', tab);
        // restart any paused processing, send data through that has changed since pause
    }

    function collusionTabDeactivate(tab){
        console.log('collusionTabDeactivate: ', tab);
        // pause processing, queue data to be processed on reactivate
    }

    function openOrSwitchToOrClose(url){
        // is there a tab open for Collusion?
        var tab = getCollusionTab();
        // if not, open one
        if (!tab){
            return tabs.open({
                url: url,
                onOpen: collusionTabOpened,
                onClose: collusionTabClosed,
                onReady: collusionTabReady,
                onActivate: collusionTabActivate,
                onDeactivate: collusionTabDeactivate
            });
        }
        // if we're on the collusion tab, close it
        if (tab === tabs.activeTab){
            tab.close();
        }else{
            // otherwise, switch to this tab
            tab.activate();
        }
    }

    // Set up the status bar button to open the main UI page:
    var widget = require("widget").Widget({
        id: "collusion_Widget",
        label: "Show Collusion",
        contentURL: data.url("favicon.ico"),
        onClick: function() {
            openOrSwitchToOrClose(mainPage);
        }
    });

    // attachToExistingCollusionPages();

})(this);
Esempio n. 20
0
exports.run = function() {

	// Set up logging
	var createHttpRequestTable = data.load("create_http_request_table.sql");
	loggingDB.executeSQL(createHttpRequestTable, false);
	var createHttpRequestHeadersTable = data.load("create_http_request_headers_table.sql");
	loggingDB.executeSQL(createHttpRequestHeadersTable, false);
	var requestID = 0;
	
	var createHttpResponseTable = data.load("create_http_response_table.sql");
	loggingDB.executeSQL(createHttpResponseTable, false);
	var createHttpResponseHeadersTable = data.load("create_http_response_headers_table.sql");
	loggingDB.executeSQL(createHttpResponseHeadersTable, false);
	var responseID = 0;

	// Instrument HTTP requests
	observerService.add("http-on-modify-request", function(subject, data) {
		var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
		
		var update = {};
		
		update["id"] = requestID;
		
		var url = httpChannel.URI.spec;
		update["url"] = loggingDB.escapeString(url);
		
		var requestMethod = httpChannel.requestMethod;
		update["method"] = loggingDB.escapeString(requestMethod);
		
		var referrer = "";
		if(httpChannel.referrer)
			referrer = httpChannel.referrer.spec;
		update["referrer"] = loggingDB.escapeString(referrer);
		
		update["page_id"] = pageManager.pageIDFromHttpChannel(httpChannel);
		
		loggingDB.executeSQL(loggingDB.createInsert("http_requests", update), true);
		
		httpChannel.visitRequestHeaders({visitHeader: function(name, value) {
			var update = {};
			update["http_request_id"] = requestID;
			update["name"] = loggingDB.escapeString(name);
			update["value"] = loggingDB.escapeString(value);
			loggingDB.executeSQL(loggingDB.createInsert("http_request_headers", update), true);
		}});
		
		requestID++;
	});
	
	// Instrument HTTP responses
	var httpResponseHandler = function(subject, data, isCached) {
		var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
		
		var update = {};
		
		update["id"] = responseID;
		
		var url = httpChannel.URI.spec;
		update["url"] = loggingDB.escapeString(url);
		
		var requestMethod = httpChannel.requestMethod;
		update["method"] = loggingDB.escapeString(requestMethod);
		
		var referrer = "";
		if(httpChannel.referrer)
			referrer = httpChannel.referrer.spec;
		update["referrer"] = loggingDB.escapeString(referrer);
		
		var responseStatus = httpChannel.responseStatus;
		update["response_status"] = responseStatus;
		
		var responseStatusText = httpChannel.responseStatusText;
		update["response_status_text"] = loggingDB.escapeString(responseStatusText);
		
		update["page_id"] = pageManager.pageIDFromHttpChannel(httpChannel);
		
		update["is_cached"] = loggingDB.boolToInt(isCached);
		
		loggingDB.executeSQL(loggingDB.createInsert("http_responses", update), true);
		
		httpChannel.visitResponseHeaders({visitHeader: function(name, value) {
			var update = {};
			update["http_response_id"] = responseID;
			update["name"] = loggingDB.escapeString(name);
			update["value"] = loggingDB.escapeString(value);
			loggingDB.executeSQL(loggingDB.createInsert("http_response_headers", update), true);
		}});
		
		responseID++;
	};
	
	observerService.add("http-on-examine-response", function(subject, data) {
		httpResponseHandler(subject, data, false);
	});
	
	// Instrument cached HTTP responses
	observerService.add("http-on-examine-cached-response", function(subject, data) {
		httpResponseHandler(subject, data, true);
	});

};