summaryrefslogtreecommitdiff
path: root/src/bootstrap.js
blob: e98037bca34710adc6df5ba805864293ee71aaf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
if (typeof EIB === "undefined")
    var EIB = {
        headers: {},
        pending: []
    };

const Cc = Components.classes, Ci = Components.interfaces, Cu = Components.utils, CC = Components.Constructor, Cr = Components.results;
const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream", "init");
const FileInputStream = CC("@mozilla.org/network/file-input-stream;1", "nsIFileInputStream", "init");
const LocalFileFromPath = CC("@mozilla.org/file/local;1", "nsILocalFile", "initWithPath");

Cu.import("resource://gre/modules/Services.jsm");

function install() {}
function uninstall() {}

var ServerListener = {
    onSocketAccepted: function (socket, transport) {
        var is = transport.openInputStream(0, 0, 0);
        var os = transport.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);
        var sis = new ScriptableInputStream(is);
        var buf = "";
        // TODO: run on separate thread
        is.asyncWait({
            onInputStreamReady: function () {
                while (sis.available())
                    buf += sis.read(2048);

                if (buf.indexOf("\r\n\r\n") > -1) {
                    is.close();

                    var path = / ([^ ]*) /.exec(buf)[1];

                    var headers = {};
                    var rx = /\n(EVE_[^:]*): (.*)$/gm, arr;
                    while ((arr = rx.exec(buf)) !== null)
                        headers[arr[1]] = arr[2];

                    if (headers.EVE_TRUSTED == "Yes")
                        EIB.headers = headers;

                    var type, file;
                    switch (path) {
                    case '/':
                        type = "text/html";
                        file = headers.EVE_TRUSTED === "Yes" ? "trusted.html" :
                               headers.EVE_TRUSTED === "No" ? "untrusted.html" :
                               "unknown.html";
                        break;
                    case '/trusted.js':
                        type = "application/javascript";
                        file = "trusted.js";
                        break;
                    case '/trusted':
                        type = "text/html";
                    }

                    var resp = "HTTP/1.0 " + type ?
                               "200 OK\r\nContent-Type: " + type + "\r\n\r\n" :
                               "404 Not Found\r\nContent-Type: text/plain\r\n\r\n404 Not Found\r\n";
                    if (!type) {
                        os.close();
                    } else if (file) {
                        var channel = Services.io.newChannel("chrome://eib/content/igb/" + file, null, null);
                        channel.asyncOpen({
                            onStartRequest: function () {},
                            onDataAvailable: function (req, ctx, fis, offset, cnt) {
                                os.writeFrom(fis, cnt);
                            },
                            onStopRequest: function (req, ctx, status) {
                                os.close();
                                channel.close();
                            }
                        }, null);
                    }

                }
            }
        }, 0, 0, Services.tm.mainThread);
    }
};

EIB.listen = function () {
    this.serverSocket = Cc["@mozilla.org/network/server-socket;1"]
                       .createInstance(Ci.nsIServerSocket);
    this.serverSocket.init(26001, true, -1);
    this.serverSocket.asyncListen(ServerListener);
};

var HttpObserver = {
    observe: function (subject, topic, data) {
        var channel = subject.QueryInterface(Ci.nsIHttpChannel);
        // TODO: is this secure?
        if (checkTrusted(channel.URI.specIgnoringRef)) {
            for (var header in EIB.headers) {
                channel.setRequestHeader(header, EIB.headers[header], false);
            }
            channel.setRequestHeader("User-Agent", channel.getRequestHeader("User-Agent") + " EVE-IGB", false);
        }
    }
};

function forEachOpenWindow(todo) {
    var windows = Services.wm.getEnumerator("navigator:browser");
    while (windows.hasMoreElements())
        todo(windows.getNext().QueryInterface(Ci.nsIDOMWindow));
}

var WindowListener = {
    onOpenWindow: function(xulWindow)
    {
        var window = xulWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                              .getInterface(Ci.nsIDOMWindow);
        function onWindowLoad()
        {
            window.removeEventListener("load", onWindowLoad);
            if (window.document.documentElement.getAttribute("windowtype") == "navigator:browser")
                loadIntoWindow(window);
        }
        window.addEventListener("load", onWindowLoad);
    },
};

var TrustedReparser = {
    observe: function () {
        EIB.trusted = EIB.prefs.prefHasUserValue("trusted") ?
                      JSON.parse(EIB.prefs.getCharPref("trusted")).map(function (v) { return new RegExp(v); }) :
                      [];
    }
};

function startup(data, reason) {
    EIB.listen();

    forEachOpenWindow(loadIntoWindow);
    Services.wm.addListener(WindowListener);

    Services.obs.addObserver(HttpObserver, "http-on-modify-request", false);

    EIB.prefs = Services.prefs.getBranch("extensions.eib.");
    EIB.prefs.addObserver("trusted", TrustedReparser, false);
    TrustedReparser.observe();
}

function shutdown(data, reason) {
    if (reason === APP_SHUTDOWN)
        return;

    if (EIB.serverSocket)
        EIB.serverSocket.close();
    delete EIB.serverSocket;

    forEachOpenWindow(unloadFromWindow);
    Services.wm.removeListener(WindowListener);

    Services.obs.removeObserver(HttpObserver, "http-on-modify-request");

    EIB.prefs.removeObserver("trusted", TrustedReparser);
}

function checkTrusted(href) {
    return EIB.trusted.some(function (v) {
        return v.test(href);
    });
}

const exportFunctions = ["openEveMail", "showInfo", "showPreview", "showRouteTo", "showMap", "showFitting", "showContract", "showMarketDetails", "setDestination", "addWaypoint", "joinChannel", "joinMailingList", "createContract", "buyType", "findInContracts", "addToMarketQuickBar", "addContact", "removeContact", "addCorpContact", "removeCorpContact", "block", "addBounty", "inviteToFleet", "startConversation", "showContracts", "showOnMap", "editMember", "awardDecoration", "sendMail", "showContents", "bookmark"];

function injectCCPEVE(e) {
    var window = e.originalTarget.defaultView;
    if (checkTrusted(window.location.href)) {
        var CCPEVE = Cu.createObjectIn(window, {defineAs: "CCPEVE"});
        exportFunctions.forEach(function (n) {
            Object.defineProperty(CCPEVE, n, {
                value: Cu.exportFunction(function () {
                    EIB.pending.push('CCPEVE.' + n + '(' + JSON.stringify([].slice.call(arguments)).slice(1, -1) + ');');
                    return null;
                }, CCPEVE)
            });
        });
    }
}

function loadIntoWindow(window) {
    window.document.getElementById("appcontent").addEventListener("DOMContentLoaded", injectCCPEVE, false);
}

function unloadFromWindow(window) {
    window.document.getElementById("appcontent").removeEventListener("DOMContentLoaded", injectCCPEVE, false);
}