aboutsummaryrefslogtreecommitdiff
path: root/chrome/code/redirector.js
blob: f4b209393e3931631dd1383ca9fce82fe56c98a4 (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
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
var EXPORTED_SYMBOLS = ['Redirector', 'rdump'];
Ci = Components.interfaces;
Cc = Components.classes;
Ci = Components.interfaces;
Cr = Components.results;

const FileInputStream = Components.Constructor("@mozilla.org/network/file-input-stream;1", "nsIFileInputStream", "init");
const ConverterInputStream = Components.Constructor("@mozilla.org/intl/converter-input-stream;1", "nsIConverterInputStream", "init");
const LocalFile = Components.Constructor("@mozilla.org/file/local;1", "nsILocalFile", "initWithPath");

Components.utils.import("chrome://redirector/content/code/redirect.js");
Components.utils.import("chrome://redirector/content/code/redirectorprefs.js");

function rdump(msg) {
	dump(msg + '\n');
}

Redirector = {
	
	get enabled() {
		return this._prefs && this._prefs.enabled;	
	},
	
	set enabled(value) {
		if (this._prefs) {
			this._prefs.enabled = value;
		}
	},

	get redirectCount() {
		return this._list.length;
	},
	
	toString : function() {
		return "Redirector";
	},
	
	addRedirect : function(redirect) {
		//This runaround is necessary because the redirect
		//that was created somewhere up in the GUI doesn't
		//have the Redirect function in scope.
		var rx = new Redirect();
		rx.copyValues(redirect);
		this._list.push(rx);
		this.save();
	},

	debug : function(msg) {
		if (this._prefs.debugEnabled) {
			this._cout.logStringMessage('REDIRECTOR: ' + msg);
		}
	},
	
	deleteRedirectAt : function(index) {
		this._list.splice(index, 1);
		this.save();
	},
	
	exportRedirects : function(file) {
		var fileStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
		const PR_WRONLY 	 = 0x02;
		const PR_CREATE_FILE = 0x08;
		const PR_TRUNCATE	 = 0x20;

		fileStream.init(file, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0644, 0);
		var stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
		stream.init(fileStream, "UTF-8", 16384, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
		var rjson = { globalExcludePattern : '', createdBy : 'Redirector v' + RedirectorPrefs.version, redirects :[]};
		for each (var re in this._list) {
			rjson.redirects.push(re.toObject());
		}
		stream.writeString(JSON.stringify(rjson, null, 4));
		stream.close();
	},
	
	getRedirectAt : function(index) {
		return this._list[index];	
	},
	
	//Get the redirect url for the given url. This will not check if we are enabled, and
	//not do any verification on the url, just assume that it is a good string url that is for http/s
	getRedirectUrl : function(url) {
		this.debug("Checking " + url);
		
		for each (var redirect in this._list) {
			var result = redirect.getMatch(url);
			if (result.isExcludeMatch) {
				this.debug(url + ' matched exclude pattern ' + redirect.excludePattern + ' so the redirect ' + redirect.includePattern + ' will not be used');
			} else if (result.isDisabledMatch) {
				this.debug(url + ' matched pattern ' + redirect.includePattern + ' but the redirect is disabled');
			} else if (result.isMatch) {
				redirectUrl = this._makeAbsoluteUrl(url, result.redirectTo);
				
				//check for loops...
				result = redirect.getMatch(redirectUrl);
				if (result.isMatch) {
					var title = this._getString('invalidRedirectTitle');
					var msg = this._getFormattedString('invalidRedirectText', [redirect.includePattern, url, redirectUrl]);
					this.debug(msg);
					redirect.disabled = true;
					this.save();					
					this._msgBox(title, msg);
				} else {
					this.debug('Redirecting ' + url + ' to ' + redirectUrl);
					return redirectUrl;
				}
			}
		}
		return null;
	},
	
	QueryInterface: function(iid) {
		if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIContentPolicy) || iid.equals(Ci.nsIChannelEventSink)) {
			return this;
		}
		throw Cr.NS_ERROR_NO_INTERFACE;
	},
	
	_getRedirectsFile : function() {
		var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
		file.append('redirector.rjson');
		return file;
	},	
	
	handleUpgrades : function(){
		var currentVersion = '2.6';

		//Here update checks are handled
		if (this._prefs.version != currentVersion) {
			var data = this._prefs.redirects;
			var arr;
			this._list = [];
			if (data != '') {
				for each (redirectString in data.split(':::')) {
					if (!redirectString || !redirectString.split) {
						continue;
						rdump('Invalid old redirect: ' + redirectString);
					}	
					var parts = redirectString.split(',,,');
					if (parts.length < 5) {
						throw Error("Invalid serialized redirect, too few fields: " + redirectString);
					}
					var redirect = new Redirect();
					redirect._init.apply(parts);
					this._list.push(redirect);
				}
				this.save();
				this._list = []; //Let the real loading start this properly
			}
		}
		this._prefs.version = currentVersion;
	},	
	
	importOldRedirects : function(file) {
		var fileStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
		fileStream.init(file, 0x01, 0444, 0); //TODO: Find the actual constants for these magic numbers

		var stream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
		stream.init(fileStream, "UTF-8", 16384, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
		stream = stream.QueryInterface(Ci.nsIUnicharLineInputStream);



		var importCount = 0, existsCount = 0;
		var lines = [];
		var line = {value: null};
		stream.readLine(line);
		while (line.value) {
			var redirect = new Redirect();
			redirect.deserialize(line.value.replace('\n', ''));
			if (this._containsRedirect(redirect)) {
				existsCount++;
			} else {
				this._list.push(redirect);
				importCount++;
			}
			stream.readLine(line);
		}
		stream.close();
		this.save();
		return importCount | (existsCount << 16);
	},

	importRedirects : function(file) {
		var fileStream = new FileInputStream(file, 0x01, 0444, 0);
		var stream = new ConverterInputStream(fileStream, "UTF-8", 16384, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
		var str = {};
		var rjson = '';
		while (stream.readString(4096, str) != 0) {
			rjson += str.value;
		}
		stream.close();
		var importCount = 0, existsCount = 0;
		rjson = JSON.parse(rjson);
		for each (var rd in rjson.redirects) {
			var redirect = new Redirect();
			redirect.fromObject(rd);
			if (this._containsRedirect(redirect)) {
				existsCount++;
			} else {
				this._list.push(redirect);
				importCount++;
			}
		}
		this.save();
		return importCount | (existsCount << 16);
	},

	save : function() {
		var file = this._getRedirectsFile();
		this.exportRedirects(file);
	},
	
	switchItems : function(index1, index2) {
		var item = this._list[index1];
		this._list[index1] = this._list[index2];
		this._list[index2] = item;
		this.save();
	},
	
	
	// nsIContentPolicy implementation
	shouldLoad: function(contentType, contentLocation, requestOrigin, aContext, mimeTypeGuess, extra) {
		if (contentLocation.scheme != "http" && contentLocation.scheme != "https") {
			return Ci.nsIContentPolicy.ACCEPT;
		} //Immediately, otherwise we will log all sorts of crap
			
		rdump('nsIContentPolicy::ShouldLoad ' + contentLocation.spec);
		try {
			//This is also done in getRedirectUrl, but we want to exit as quickly as possible for performance
			if (!this._prefs.enabled) {
				return Ci.nsIContentPolicy.ACCEPT;
			}
			
			if (contentType != Ci.nsIContentPolicy.TYPE_DOCUMENT) {
				return Ci.nsIContentPolicy.ACCEPT;
			}

			if (contentLocation.scheme != "http" && contentLocation.scheme != "https") {
				return Ci.nsIContentPolicy.ACCEPT;
			}
			
			if (!aContext || !aContext.loadURI) {
				return Ci.nsIContentPolicy.ACCEPT;
			}
			
			var redirectUrl = this.getRedirectUrl(contentLocation.spec);

			if (!redirectUrl) {
				return Ci.nsIContentPolicy.ACCEPT;
			}			

			aContext.loadURI(redirectUrl, requestOrigin, null);
			return Ci.nsIContentPolicy.REJECT_REQUEST;
		} catch(e) {
			this.debug(e);	 
		}
		
	},
	
	shouldProcess: function(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) {
		return Ci.nsIContentPolicy.ACCEPT;
	},
	//end nsIContentPolicy

	//nsIChannelEventSink implementation
	
	//For FF4.0. Got this from a thread about adblock plus, https://adblockplus.org/forum/viewtopic.php?t=5895
	asyncOnChannelRedirect: function(oldChannel, newChannel, flags, redirectCallback) {
		this.onChannelRedirect(oldChannel, newChannel, flags);
		redirectCallback.onRedirectVerifyCallback(0);
	},	
	
	onChannelRedirect: function(oldChannel, newChannel, flags)
	{
		try {
			let newLocation = newChannel.URI.spec;
			rdump('nsIChannelEventSink::onChannelRedirect ' + newLocation);

			if (!(newChannel.loadFlags & Ci.nsIChannel.LOAD_DOCUMENT_URI)) {
				//We only redirect documents...
				return; 
			}

			if (!this._prefs.enabled) {
				return;
			}
			
			if (!newLocation) {
				return;
			}
			let callbacks = [];
			if (newChannel.notificationCallbacks) {
				callbacks.push(newChannel.notificationCallbacks);
			}
			if (newChannel.loadGroup && newChannel.loadGroup.notificationCallbacks) {
				callbacks.push(newChannel.loadGroup.notificationCallbacks);
			}
			var win;
			var webNav;
			for each (let callback in callbacks)
			{
				try {
					win = callback.getInterface(Ci.nsILoadContext).associatedWindow;
					webNav = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation);
					break;
				} catch(e) {}
			}
			if (!webNav) {
				return; 
			}
			var redirectUrl = this.getRedirectUrl(newLocation);

			if (redirectUrl) {
				webNav.loadURI(redirectUrl,null,null,null,null);
				throw Cr.NS_BASE_STREAM_WOULD_BLOCK; //Throw this because the real error we should throw shows up in console...
			}			
			
		} catch (e if (e != Cr.NS_BASE_STREAM_WOULD_BLOCK)) {
			// We shouldn't throw exceptions here - this will prevent the redirect.
			rdump("Redirector: Unexpected error in onChannelRedirect: " + e + "\n");
		}
	},
	//end nsIChannelEventSink
	
	//Private members and methods
			
	_prefs : null,
	_list : null,
	_strings : null,
	_cout : Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService),

	init : function() {
		if (this._prefs) {
			this._prefs.dispose();
		}
		this._cout.logStringMessage('REDIRECTOR CREATED');
		this._prefs = new RedirectorPrefs();
		//Check if we need to update existing redirects
		var data = this._prefs.redirects;
		var version = this._prefs.version;
		this._loadStrings();
		this._list = [];
		this.handleUpgrades();
		var redirectsFile = this._getRedirectsFile();
		if (redirectsFile.exists()) {
			this.importRedirects(redirectsFile);
		}
	},
	
	_loadStrings : function() {
		var src = 'chrome://redirector/locale/redirector.properties';
		var localeService = Cc["@mozilla.org/intl/nslocaleservice;1"].getService(Ci.nsILocaleService);
		var appLocale = localeService.getApplicationLocale();
		var stringBundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
		this._strings = stringBundleService.createBundle(src, appLocale);	 
	},	  

	_redirectsAsString : function(seperator) {
		return [r.serialize() for each (r in this._list)].join(seperator);
	},
	
	
	_containsRedirect : function(redirect) {
		for each (var existing in this._list) {
			if (existing.equals(redirect)) {
				return true;
			}	
		}
		return false;
	},
	
	_getString : function(name) {
		return this._strings.GetStringFromName(name);
	},
	
	_getFormattedString : function(name, params) {
		return this._strings.formatStringFromName(name, params, params.length);
	},
	
	_msgBox : function(title, text) {
		Cc["@mozilla.org/embedcomp/prompt-service;1"]
			.getService(Ci.nsIPromptService)
				.alert(null, title, text);
	},

	_makeAbsoluteUrl : function(currentUrl, relativeUrl) {
		
		if (relativeUrl.match(/https?:/)) {
			return relativeUrl;
		} 
		
		var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
		var uri = ioService.newURI(currentUrl, null, null); 
		
		return uri.resolve(relativeUrl);
	}
};

Redirector.init();