This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
/
bootstrap.js
459 lines (384 loc) · 14.1 KB
/
bootstrap.js
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
function startup(data, reason) {
const CC = Components.Constructor;
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import('resource://gre/modules/Services.jsm');
try {
// Gecko < 21
Cu.import('resource:///modules/devtools/dbg-client.jsm');
} catch (e) {
// Gecko >= 21
Cu.import('resource://gre/modules/devtools/dbg-client.jsm');
}
// Make sure all applications are considered launchable
Cu.import('resource://gre/modules/Webapps.jsm');
const env = Cc['@mozilla.org/process/environment;1'].
getService(Ci.nsIEnvironment);
DOMApplicationRegistry.allAppsLaunchable = true;
const LANG_EN = 'en-US';
const GAIA_DOMAIN = Services.prefs.getCharPref("extensions.gaia.domain");
const GAIA_APPDIRS = Services.prefs.getCharPref("extensions.gaia.appdirs");
const GAIA_ALLAPPDIRS = Services.prefs.getCharPref("extensions.gaia.allappdirs");
const GAIA_DIR = Services.prefs.getCharPref("extensions.gaia.dir");
const GAIA_PORT = Services.prefs.getIntPref("extensions.gaia.port");
const GAIA_OFFICIAL = Services.prefs.getBoolPref("extensions.gaia.official");
const LOCALES_FILE =
Services.prefs.getCharPref("extensions.gaia.locales_file");
const LOCALE_BASEDIR =
Services.prefs.getCharPref("extensions.gaia.locale_basedir");
const LocalFile = CC('@mozilla.org/file/local;1',
'nsILocalFile',
'initWithPath');
const ScriptableInputStream = CC('@mozilla.org/scriptableinputstream;1',
'nsIScriptableInputStream',
'init');
let DEBUG = false;
let l10nManager, utils;
function debug(data) {
if (!DEBUG)
return;
dump(data + '\n');
}
function isl10nFile(fname) {
var matched;
return fname.contains('.ini') || fname.contains('manifest.webapp');
}
function startupHttpd(baseDir, port) {
const httpdURL = 'chrome://httpd.js/content/httpd.js';
let httpd = {};
env.set('GAIA_DIR', GAIA_DIR);
Services.scriptloader.loadSubScript(httpdURL, httpd);
let server = new httpd.nsHttpServer();
server.registerDirectory('/', new LocalFile(baseDir));
server.registerContentType('appcache', 'text/cache-manifest');
server.start(port);
// Add {appname}.domain.tld:port to the list of domains handle by httpd
let identity = server.identity;
let scheme = 'http';
let host = GAIA_DOMAIN;
identity.add(scheme, host, port);
let directories = getDirectories(GAIA_ALLAPPDIRS.split(' '));
directories.forEach(function appendDir(name) {
// Some app names can cause a raise here, preventing other apps
// from being added.
try {
identity.add(scheme, name + '.' + host, port);
} catch (e) {
dump(e);
}
});
if (LOCALE_BASEDIR) {
let appDirs = GAIA_APPDIRS.split(' ');
let commonjs = {
GAIA_BUILD_DIR: 'file://' + GAIA_DIR.replace(/\\/g, '/') + '/build/'
};
// Loading |require| then we can use build scripts of gaia.
Services.scriptloader.loadSubScript(commonjs.GAIA_BUILD_DIR +
'/xpcshell-commonjs.js', commonjs);
utils = commonjs.require('./utils');
let multilocale = commonjs.require('./multilocale');
let sharedDir = utils.getFile(GAIA_DIR, 'shared');
l10nManager = new multilocale.L10nManager(GAIA_DIR,
LOCALES_FILE, LOCALE_BASEDIR);
let filesInShared = utils.ls(sharedDir, true);
let localesFile = utils.resolve(LOCALES_FILE, GAIA_DIR);
// Finding out which file we need to handle.
appDirs.forEach(function(appDir) {
let appDirFile = utils.getFile(appDir);
let filesInApp = utils.ls(appDirFile, true);
[...filesInApp, ...filesInShared].forEach(function(file) {
let fname = file.leafName;
let relativePath = file.path.substr(GAIA_DIR.length);
// localized ini and manifest files will be generated in runtime
// so we need handle path if client request those files.
// and we use "LocalizationHandler" to handle them.
if (isl10nFile(fname)) {
server.registerPathHandler(relativePath, LocalizationHandler);
}
});
});
// languages.json
server.registerFile('/shared/resources/languages.json', localesFile);
server.registerDirectory('/locales/',
new LocalFile(l10nManager.localeBasedir));
}
server.registerPathHandler('/marionette', MarionetteHandler);
server.registerDirectory(
'/common/', new LocalFile(baseDir + '/dev_apps/test-agent/common')
);
server.registerDirectory('/shared/', new LocalFile(baseDir + '/shared'));
let brandingLocalFile = new LocalFile(
baseDir + '/shared/branding/' + GAIA_OFFICIAL ? 'official' : 'unofficial'
);
server.registerDirectory('/shared/branding/', brandingLocalFile);
}
function getDirectories(appDirs) {
return appDirs.map(function (path) {
let appsDir = Cc['@mozilla.org/file/local;1']
.createInstance(Ci.nsILocalFile);
appsDir.initWithPath(path);
return appsDir.leafName;
});
}
function LongPoll(connid, transport) {
this.transport = transport;
this.connid = connid;
this.buffer = [];
this.outstanding = {
push: null,
noop: null,
timeout: null
};
}
LongPoll.prototype = {
cast: function cast(msg) {
let outstanding = this.outstanding;
clearTimeout(outstanding.noop);
this.buffer.push(msg);
if (outstanding.push === null)
return;
debug('cast ' + JSON.stringify(msg) + ' ' + outstanding.push);
this.drain_queue(outstanding.push);
outstanding.push.finish();
outstanding.push = null;
outstanding.timeout = setTimeout(function close(uid) {
Connections.close(uid);
}, 5000, this.connid);
},
drain_queue: function drain_queue(response) {
let queue = this.buffer;
this.buffer = [];
let json = { 'messages': [] };
queue.forEach(function(chunk) {
if (chunk.noop) {
//we need to send something to keep the client polling
json.messages.push({});
return;
}
json.messages.push({ 'id': this.connid, 'response': chunk });
}.bind(this));
response.write(JSON.stringify(json));
},
send: function send(obj) {
this.transport.send(obj);
}
};
let transports = {};
function getUID() {
return Cc['@mozilla.org/uuid-generator;1'].getService(Ci.nsIUUIDGenerator)
.generateUUID()
.toString();
}
var Connections = {
_connections: {},
close: function connections_close(uid) {
if (uid in this._connections) {
this._connections[uid].transport.close();
delete this._connections[uid];
}
},
add: function connections_add(uid, connection) {
this._connections[uid] = connection;
},
get: function connections_get(uid) {
return this._connections[uid] || null;
}
};
var LocalizationHandler = {
// we only handle GET method because we always use GET method to get those
// files.
handle: function lh_handle(request, response) {
if (request.method === 'GET' && l10nManager) {
let locales = JSON.parse(JSON.stringify(l10nManager.locales));
// no need to handle en-US.
var enIndex = locales.indexOf('en-US');
if (enIndex !== -1) {
locales.splice(enIndex, 1);
}
let {getFile, getFileContent} = utils;
let {modifyLocaleIni, serializeIni} = l10nManager;
let file = getFile(GAIA_DIR, request.path);
if (file.leafName.contains('.ini')) {
response.setHeader('Content-Type', 'text/plain');
let iniOriginal = getFileContent(file);
let modifiedIni = serializeIni(modifyLocaleIni(iniOriginal, locales));
response.write(modifiedIni);
} else if (file.leafName.contains('manifest.webapp')) {
let buildDirectoryFile = getFile(GAIA_DIR, 'build_stage',
file.parent.leafName);
response.setHeader('Content-Type', 'application/json');
let webapp = {
manifestFile: file,
sourceDirectoryFile: file.parent,
sourceDirectoryName: file.parent.leafName,
buildDirectoryFile: buildDirectoryFile
};
let manifest = l10nManager.localizeManifest(webapp);
response.write(JSON.stringify(manifest));
}
}
}
}
var MarionetteHandler = {
/**
* Adding only test-agent for now.
* In the future individual apps may need
* access as well.
*/
crosDomains: [
'http://test-agent.gaiamobile.org',
'http://test-agent.gaiamobile.org:8080',
'http://test-agent.trunk.gaiamobile.org',
'http://test-agent.trunk.gaiamobile.org:8080'
],
// nsIHttpRequestHandler
handle: function mh_handle(request, response) {
try {
this.handleCrosHeaders(request, response);
switch (request.method) {
case 'GET':
this.onGet(request, response);
break;
case 'POST':
this.onPost(request, response);
break;
case 'OPTIONS':
this.onOptions(request, response);
break;
case 'PUT':
this.onPut(request, response);
break;
case 'DELETE':
this.onDelete(request, response);
break;
default:
this.onDefault(request, response);
break;
}
} catch (e) {
response.setStatusLine('1.1', 500, 'Internal Server Error');
response.write(e.toString() + e.stack == undefined ? '' : ' ' + e.stack);
}
},
onOptions: function mh_options(request, response) {
response.setStatusLine('1.1', 200, 'OK');
},
handleCrosHeaders: function mh_options(request, response) {
if(!request.hasHeader('Origin'))
return;
let methods = 'GET, POST, PUT, DELETE, OPTIONS';
let origin = request.getHeader('Origin');
if (!origin || this.crosDomains.indexOf(origin) === -1) {
return;
}
response.setHeader(
'Access-Control-Allow-Origin',
origin
);
response.setHeader(
'Access-Control-Allow-Credentials',
'true'
);
response.setHeader(
'Access-Control-Max-Age',
'2500'
);
response.setHeader(
'Access-Control-Allow-Methods',
methods
);
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, *');
},
onGet: function mh_get(request, response) {
debug('/marionette?' + request.queryString);
if (request.queryString.length === 0) {
response.setStatusLine('1.1', 404, 'Not Found');
response.write(JSON.stringify({ 'error': 'connection not found' }));
return;
}
response.setStatusLine('1.1', 200, 'OK');
response.setHeader('Content-Type', 'application/json');
let uid = request.queryString.split('=')[0];
let connection = Connections.get(uid);
if (!connection) {
debug('Could not get connection for ' + request.queryString);
return;
}
clearTimeout(connection.outstanding.timeout);
if (connection.buffer.length !== 0) {
connection.drain_queue(response);
return;
}
response.processAsync();
connection.outstanding.push = response;
connection.outstanding.noop = setTimeout(function() {
debug('sending noop');
connection.cast({ 'noop': true });
}, 25000);
},
onPost: function mh_post(request, response) {
response.setStatusLine('1.1', 200, 'OK');
response.setHeader('Content-Type', 'application/json');
let uid = getUID();
response.write(JSON.stringify({ 'id': uid }));
request.bodyInputStream.asyncWait(function(stream) {
let scriptable = new ScriptableInputStream(stream);
let json = scriptable.read(scriptable.available());
let { server: server, port: port } = JSON.parse(json);
let hostport = server + ':' + port;
if (hostport in transports) {
Connections.close(transports[hostport]);
}
debug('Opening a transport socket to the debugger...');
let transport = debuggerSocketConnect(server, parseInt(port));
let connection = new LongPoll(uid, transport);
Connections.add(uid, connection);
transports[hostport] = uid;
transport.hooks = {
onPacket: function onPacket(pack) {
debug('onpacket ' + JSON.stringify(pack));
connection.cast(pack);
},
onClosed: function onClosed(status) {
debug('onclosed ' + JSON.stringify(status));
}
};
transport.ready();
}, 0, 0, Services.tm.currentThread);
},
onPut: function mh_put(request, response) {
response.setStatusLine('1.1', 201, 'Accepted');
response.setHeader('Content-Type', 'text/plain', false);
response.write('');
let uid = request.queryString.split('=')[0];
let connection = Connections.get(uid);
if (!connection) {
debug('Could not get connection for ' + request.queryString);
return;
}
request.bodyInputStream.asyncWait(function(stream) {
let scriptable = new ScriptableInputStream(stream);
let json = scriptable.read(scriptable.available());
connection.send(JSON.parse(json));
}, 0, 0, Services.tm.currentThread);
},
onDelete: function mh_delete(request, response) {
Connections.close(request.queryString.split('=')[0]);
},
onDefault: function mh_default(request, response) {
response.setStatusLine('1.1', 405, 'Method Not Allowed');
response.write('');
}
};
startupHttpd(GAIA_DIR, GAIA_PORT);
}
function shutdown(data, reason) {
}
function install(data, reason) {
}
function uninstall(data, reason) {
}