2007-12-11 05:38:53 +00:00
|
|
|
/* ***** BEGIN LICENSE BLOCK *****
|
|
|
|
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
|
|
|
*
|
|
|
|
* The contents of this file are subject to the Mozilla Public License Version
|
|
|
|
* 1.1 (the "License"); you may not use this file except in compliance with
|
|
|
|
* the License. You may obtain a copy of the License at
|
|
|
|
* http://www.mozilla.org/MPL/
|
|
|
|
*
|
|
|
|
* Software distributed under the License is distributed on an "AS IS" basis,
|
|
|
|
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
|
|
|
* for the specific language governing rights and limitations under the
|
|
|
|
* License.
|
|
|
|
*
|
|
|
|
* The Original Code is Bookmarks Sync.
|
|
|
|
*
|
|
|
|
* The Initial Developer of the Original Code is Mozilla.
|
|
|
|
* Portions created by the Initial Developer are Copyright (C) 2007
|
|
|
|
* the Initial Developer. All Rights Reserved.
|
|
|
|
*
|
|
|
|
* Contributor(s):
|
|
|
|
* Dan Mills <thunder@mozilla.com>
|
2010-11-16 19:50:18 +00:00
|
|
|
* Richard Newman <rnewman@mozilla.com>
|
2007-12-11 05:38:53 +00:00
|
|
|
*
|
|
|
|
* Alternatively, the contents of this file may be used under the terms of
|
|
|
|
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
|
|
|
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
|
|
|
* in which case the provisions of the GPL or the LGPL are applicable instead
|
|
|
|
* of those above. If you wish to allow use of your version of this file only
|
|
|
|
* under the terms of either the GPL or the LGPL, and not to allow others to
|
|
|
|
* use your version of this file under the terms of the MPL, indicate your
|
|
|
|
* decision by deleting the provisions above and replace them with the notice
|
|
|
|
* and other provisions required by the GPL or the LGPL. If you do not delete
|
|
|
|
* the provisions above, a recipient may use your version of this file under
|
|
|
|
* the terms of any one of the MPL, the GPL or the LGPL.
|
|
|
|
*
|
|
|
|
* ***** END LICENSE BLOCK ***** */
|
|
|
|
|
2011-05-20 01:08:35 +00:00
|
|
|
const EXPORTED_SYMBOLS = ["XPCOMUtils", "Services", "NetUtil", "PlacesUtils",
|
2011-08-26 17:25:29 +00:00
|
|
|
"FileUtils", "Utils", "Async", "Svc", "Str"];
|
2007-12-11 05:38:53 +00:00
|
|
|
|
|
|
|
const Cc = Components.classes;
|
|
|
|
const Ci = Components.interfaces;
|
|
|
|
const Cr = Components.results;
|
|
|
|
const Cu = Components.utils;
|
|
|
|
|
2011-08-26 17:25:29 +00:00
|
|
|
Cu.import("resource://services-sync/async.js");
|
2010-06-16 21:30:08 +00:00
|
|
|
Cu.import("resource://services-sync/constants.js");
|
|
|
|
Cu.import("resource://services-sync/ext/Observers.js");
|
|
|
|
Cu.import("resource://services-sync/ext/Preferences.js");
|
|
|
|
Cu.import("resource://services-sync/ext/StringBundle.js");
|
|
|
|
Cu.import("resource://services-sync/log4moz.js");
|
2011-05-20 01:08:35 +00:00
|
|
|
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
|
2011-05-20 01:08:07 +00:00
|
|
|
Cu.import("resource://gre/modules/Services.jsm");
|
2011-05-20 01:08:22 +00:00
|
|
|
Cu.import("resource://gre/modules/PlacesUtils.jsm");
|
2011-04-07 22:31:11 +00:00
|
|
|
Cu.import("resource://gre/modules/NetUtil.jsm");
|
2011-05-20 01:08:51 +00:00
|
|
|
Cu.import("resource://gre/modules/FileUtils.jsm");
|
2011-01-27 05:43:33 +00:00
|
|
|
|
2007-12-11 05:38:53 +00:00
|
|
|
/*
|
|
|
|
* Utility functions
|
|
|
|
*/
|
|
|
|
|
2008-02-13 22:30:44 +00:00
|
|
|
let Utils = {
|
2009-06-06 05:21:14 +00:00
|
|
|
/**
|
|
|
|
* Wrap a function to catch all exceptions and log them
|
|
|
|
*
|
|
|
|
* @usage MyObj._catch = Utils.catch;
|
|
|
|
* MyObj.foo = function() { this._catch(func)(); }
|
2011-01-11 05:51:29 +00:00
|
|
|
*
|
|
|
|
* Optionally pass a function which will be called if an
|
|
|
|
* exception occurs.
|
2009-06-06 05:21:14 +00:00
|
|
|
*/
|
2011-01-11 05:51:29 +00:00
|
|
|
catch: function Utils_catch(func, exceptionCallback) {
|
2009-06-06 05:21:14 +00:00
|
|
|
let thisArg = this;
|
|
|
|
return function WrappedCatch() {
|
|
|
|
try {
|
|
|
|
return func.call(thisArg);
|
|
|
|
}
|
|
|
|
catch(ex) {
|
2009-07-24 22:28:42 +00:00
|
|
|
thisArg._log.debug("Exception: " + Utils.exceptionStr(ex));
|
2011-01-11 05:51:29 +00:00
|
|
|
if (exceptionCallback) {
|
|
|
|
return exceptionCallback.call(thisArg, ex);
|
|
|
|
}
|
|
|
|
return null;
|
2009-06-06 05:21:14 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
},
|
|
|
|
|
2009-06-06 18:52:49 +00:00
|
|
|
/**
|
|
|
|
* Wrap a function to call lock before calling the function then unlock.
|
|
|
|
*
|
|
|
|
* @usage MyObj._lock = Utils.lock;
|
|
|
|
* MyObj.foo = function() { this._lock(func)(); }
|
|
|
|
*/
|
2010-11-30 00:41:17 +00:00
|
|
|
lock: function lock(label, func) {
|
2009-06-06 18:52:49 +00:00
|
|
|
let thisArg = this;
|
|
|
|
return function WrappedLock() {
|
2010-11-30 00:41:17 +00:00
|
|
|
if (!thisArg.lock()) {
|
|
|
|
throw "Could not acquire lock. Label: \"" + label + "\".";
|
|
|
|
}
|
2009-06-06 18:52:49 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
return func.call(thisArg);
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
thisArg.unlock();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
},
|
2010-12-16 20:00:57 +00:00
|
|
|
|
|
|
|
isLockException: function isLockException(ex) {
|
2011-01-11 05:51:29 +00:00
|
|
|
return ex && ex.indexOf && ex.indexOf("Could not acquire lock.") == 0;
|
2010-12-16 20:00:57 +00:00
|
|
|
},
|
2009-06-06 18:52:49 +00:00
|
|
|
|
2009-06-05 22:34:23 +00:00
|
|
|
/**
|
2011-07-30 01:47:39 +00:00
|
|
|
* Wrap functions to notify when it starts and finishes executing or if it
|
|
|
|
* threw an error.
|
|
|
|
*
|
|
|
|
* The message is a combination of a provided prefix, the local name, and
|
|
|
|
* the event. Possible events are: "start", "finish", "error". The subject
|
|
|
|
* is the function's return value on "finish" or the caught exception on
|
|
|
|
* "error". The data argument is the predefined data value.
|
|
|
|
*
|
|
|
|
* Example:
|
|
|
|
*
|
|
|
|
* @usage function MyObj(name) {
|
|
|
|
* this.name = name;
|
|
|
|
* this._notify = Utils.notify("obj:");
|
|
|
|
* }
|
|
|
|
* MyObj.prototype = {
|
|
|
|
* foo: function() this._notify("func", "data-arg", function () {
|
|
|
|
* //...
|
|
|
|
* }(),
|
|
|
|
* };
|
2009-06-05 22:34:23 +00:00
|
|
|
*/
|
|
|
|
notify: function Utils_notify(prefix) {
|
2011-07-30 01:47:39 +00:00
|
|
|
return function NotifyMaker(name, data, func) {
|
2009-06-05 22:34:23 +00:00
|
|
|
let thisArg = this;
|
2011-07-30 01:47:39 +00:00
|
|
|
let notify = function(state, subject) {
|
2009-06-05 22:34:23 +00:00
|
|
|
let mesg = prefix + name + ":" + state;
|
2009-12-18 02:51:55 +00:00
|
|
|
thisArg._log.trace("Event: " + mesg);
|
2011-07-30 01:47:39 +00:00
|
|
|
Observers.notify(mesg, subject, data);
|
2009-06-05 22:34:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return function WrappedNotify() {
|
|
|
|
try {
|
2011-07-30 01:47:39 +00:00
|
|
|
notify("start", null);
|
2009-06-05 22:34:23 +00:00
|
|
|
let ret = func.call(thisArg);
|
2011-07-30 01:47:39 +00:00
|
|
|
notify("finish", ret);
|
2009-06-05 22:34:23 +00:00
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
catch(ex) {
|
2011-07-30 01:47:39 +00:00
|
|
|
notify("error", ex);
|
2009-06-05 22:34:23 +00:00
|
|
|
throw ex;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
},
|
2009-08-31 23:28:00 +00:00
|
|
|
|
2011-02-03 18:23:38 +00:00
|
|
|
runInTransaction: function(db, callback, thisObj) {
|
|
|
|
let hasTransaction = false;
|
|
|
|
try {
|
|
|
|
db.beginTransaction();
|
|
|
|
hasTransaction = true;
|
|
|
|
} catch(e) { /* om nom nom exceptions */ }
|
|
|
|
|
|
|
|
try {
|
|
|
|
return callback.call(thisObj);
|
|
|
|
} finally {
|
|
|
|
if (hasTransaction) {
|
|
|
|
db.commitTransaction();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2010-11-30 18:26:13 +00:00
|
|
|
byteArrayToString: function byteArrayToString(bytes) {
|
|
|
|
return [String.fromCharCode(byte) for each (byte in bytes)].join("");
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a string of random bytes.
|
|
|
|
*/
|
|
|
|
generateRandomBytes: function generateRandomBytes(length) {
|
|
|
|
let rng = Cc["@mozilla.org/security/random-generator;1"]
|
|
|
|
.createInstance(Ci.nsIRandomGenerator);
|
|
|
|
let bytes = rng.generateRandomBytes(length);
|
|
|
|
return Utils.byteArrayToString(bytes);
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Encode byte string as base64url (RFC 4648).
|
|
|
|
*/
|
|
|
|
encodeBase64url: function encodeBase64url(bytes) {
|
|
|
|
return btoa(bytes).replace('+', '-', 'g').replace('/', '_', 'g');
|
|
|
|
},
|
2009-09-24 22:54:47 +00:00
|
|
|
|
2010-11-30 18:26:13 +00:00
|
|
|
/**
|
|
|
|
* GUIDs are 9 random bytes encoded with base64url (RFC 4648).
|
|
|
|
* That makes them 12 characters long with 72 bits of entropy.
|
|
|
|
*/
|
|
|
|
makeGUID: function makeGUID() {
|
|
|
|
return Utils.encodeBase64url(Utils.generateRandomBytes(9));
|
2008-06-20 19:34:29 +00:00
|
|
|
},
|
|
|
|
|
2011-01-28 17:39:28 +00:00
|
|
|
_base64url_regex: /^[-abcdefghijklmnopqrstuvwxyz0123456789_]{12}$/i,
|
|
|
|
checkGUID: function checkGUID(guid) {
|
|
|
|
return !!guid && this._base64url_regex.test(guid);
|
|
|
|
},
|
|
|
|
|
2009-04-13 21:39:29 +00:00
|
|
|
/**
|
|
|
|
* Add a simple getter/setter to an object that defers access of a property
|
|
|
|
* to an inner property.
|
|
|
|
*
|
|
|
|
* @param obj
|
|
|
|
* Object to add properties to defer in its prototype
|
|
|
|
* @param defer
|
2011-02-25 22:43:10 +00:00
|
|
|
* Property of obj to defer to
|
2009-04-13 21:39:29 +00:00
|
|
|
* @param prop
|
|
|
|
* Property name to defer (or an array of property names)
|
|
|
|
*/
|
|
|
|
deferGetSet: function Utils_deferGetSet(obj, defer, prop) {
|
2011-08-26 17:26:11 +00:00
|
|
|
if (Array.isArray(prop))
|
2009-04-13 21:39:29 +00:00
|
|
|
return prop.map(function(prop) Utils.deferGetSet(obj, defer, prop));
|
|
|
|
|
|
|
|
let prot = obj.prototype;
|
|
|
|
|
|
|
|
// Create a getter if it doesn't exist yet
|
2010-11-30 00:41:17 +00:00
|
|
|
if (!prot.__lookupGetter__(prop)) {
|
2011-02-25 22:43:10 +00:00
|
|
|
prot.__defineGetter__(prop, function () {
|
|
|
|
return this[defer][prop];
|
|
|
|
});
|
2010-11-30 00:41:17 +00:00
|
|
|
}
|
2009-04-13 21:39:29 +00:00
|
|
|
|
|
|
|
// Create a setter if it doesn't exist yet
|
2011-02-25 22:43:10 +00:00
|
|
|
if (!prot.__lookupSetter__(prop)) {
|
|
|
|
prot.__defineSetter__(prop, function (val) {
|
|
|
|
this[defer][prop] = val;
|
|
|
|
});
|
|
|
|
}
|
2009-04-13 21:39:29 +00:00
|
|
|
},
|
|
|
|
|
2009-08-19 03:03:11 +00:00
|
|
|
lazyStrings: function Weave_lazyStrings(name) {
|
2010-06-10 00:03:31 +00:00
|
|
|
let bundle = "chrome://weave/locale/services/" + name + ".properties";
|
2009-08-19 03:03:11 +00:00
|
|
|
return function() new StringBundle(bundle);
|
|
|
|
},
|
|
|
|
|
2009-05-19 15:53:30 +00:00
|
|
|
deepEquals: function eq(a, b) {
|
|
|
|
// If they're triple equals, then it must be equals!
|
|
|
|
if (a === b)
|
2008-02-13 22:30:44 +00:00
|
|
|
return true;
|
2008-03-05 08:00:56 +00:00
|
|
|
|
2009-07-23 06:49:15 +00:00
|
|
|
// If they weren't equal, they must be objects to be different
|
|
|
|
if (typeof a != "object" || typeof b != "object")
|
2008-02-13 22:30:44 +00:00
|
|
|
return false;
|
|
|
|
|
2009-07-23 06:49:15 +00:00
|
|
|
// But null objects won't have properties to compare
|
|
|
|
if (a === null || b === null)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Make sure all of a's keys have a matching value in b
|
|
|
|
for (let k in a)
|
|
|
|
if (!eq(a[k], b[k]))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Do the same for b's keys but skip those that we already checked
|
|
|
|
for (let k in b)
|
|
|
|
if (!(k in a) && !eq(a[k], b[k]))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
return true;
|
2008-02-13 22:30:44 +00:00
|
|
|
},
|
2007-12-11 05:38:53 +00:00
|
|
|
|
2008-03-07 09:56:36 +00:00
|
|
|
exceptionStr: function Weave_exceptionStr(e) {
|
2008-06-26 18:15:02 +00:00
|
|
|
let message = e.message ? e.message : e;
|
2009-07-24 22:28:42 +00:00
|
|
|
return message + " " + Utils.stackTrace(e);
|
2010-11-16 19:42:17 +00:00
|
|
|
},
|
2012-03-12 18:12:47 +00:00
|
|
|
|
2009-07-24 22:28:42 +00:00
|
|
|
stackTrace: function Weave_stackTrace(e) {
|
|
|
|
// Wrapped nsIException
|
2012-03-12 18:12:47 +00:00
|
|
|
if (e.location){
|
|
|
|
let frame = e.location;
|
|
|
|
let output = [];
|
|
|
|
while (frame) {
|
|
|
|
// Works on frames or exceptions, munges file:// URIs to shorten the paths
|
|
|
|
// FIXME: filename munging is sort of hackish, might be confusing if
|
|
|
|
// there are multiple extensions with similar filenames
|
|
|
|
let str = "<file:unknown>";
|
|
|
|
|
|
|
|
let file = frame.filename || frame.fileName;
|
|
|
|
if (file){
|
|
|
|
str = file.replace(/^(?:chrome|file):.*?([^\/\.]+\.\w+)$/, "$1");
|
|
|
|
}
|
2009-07-24 22:28:42 +00:00
|
|
|
|
2012-03-12 18:12:47 +00:00
|
|
|
if (frame.lineNumber){
|
|
|
|
str += ":" + frame.lineNumber;
|
|
|
|
}
|
|
|
|
if (frame.name){
|
|
|
|
str = frame.name + "()@" + str;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (str){
|
|
|
|
output.push(str);
|
|
|
|
}
|
|
|
|
frame = frame.caller;
|
|
|
|
}
|
|
|
|
return "Stack trace: " + output.join(" < ");
|
|
|
|
}
|
2009-07-24 22:28:42 +00:00
|
|
|
// Standard JS exception
|
2012-03-12 18:12:47 +00:00
|
|
|
if (e.stack){
|
2009-07-24 22:28:42 +00:00
|
|
|
return "JS Stack trace: " + e.stack.trim().replace(/\n/g, " < ").
|
2010-06-22 23:29:47 +00:00
|
|
|
replace(/@[^@]*?([^\/\.]+\.\w+:)/g, "@$1");
|
2012-03-12 18:12:47 +00:00
|
|
|
}
|
2009-07-24 22:28:42 +00:00
|
|
|
|
|
|
|
return "No traceback available";
|
2008-03-07 09:56:36 +00:00
|
|
|
},
|
2010-12-09 18:32:03 +00:00
|
|
|
|
|
|
|
// Generator and discriminator for HMAC exceptions.
|
|
|
|
// Split these out in case we want to make them richer in future, and to
|
|
|
|
// avoid inevitable confusion if the message changes.
|
|
|
|
throwHMACMismatch: function throwHMACMismatch(shouldBe, is) {
|
|
|
|
throw "Record SHA256 HMAC mismatch: should be " + shouldBe + ", is " + is;
|
|
|
|
},
|
|
|
|
|
|
|
|
isHMACMismatch: function isHMACMismatch(ex) {
|
|
|
|
const hmacFail = "Record SHA256 HMAC mismatch: ";
|
|
|
|
return ex && ex.indexOf && (ex.indexOf(hmacFail) == 0);
|
|
|
|
},
|
|
|
|
|
2011-03-01 22:29:41 +00:00
|
|
|
/**
|
|
|
|
* UTF8-encode a message and hash it with the given hasher. Returns a
|
|
|
|
* string containing bytes. The hasher is reset if it's an HMAC hasher.
|
|
|
|
*/
|
|
|
|
digestUTF8: function digestUTF8(message, hasher) {
|
|
|
|
let data = this._utf8Converter.convertToByteArray(message, {});
|
2008-03-26 06:01:34 +00:00
|
|
|
hasher.update(data, data.length);
|
2011-03-01 22:29:41 +00:00
|
|
|
let result = hasher.finish(false);
|
|
|
|
if (hasher instanceof Ci.nsICryptoHMAC) {
|
|
|
|
hasher.reset();
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Treat the given message as a bytes string and hash it with the given
|
|
|
|
* hasher. Returns a string containing bytes. The hasher is reset if it's
|
|
|
|
* an HMAC hasher.
|
|
|
|
*/
|
|
|
|
digestBytes: function digestBytes(message, hasher) {
|
|
|
|
// No UTF-8 encoding for you, sunshine.
|
|
|
|
let bytes = [b.charCodeAt() for each (b in message)];
|
|
|
|
hasher.update(bytes, bytes.length);
|
|
|
|
let result = hasher.finish(false);
|
|
|
|
if (hasher instanceof Ci.nsICryptoHMAC) {
|
|
|
|
hasher.reset();
|
|
|
|
}
|
|
|
|
return result;
|
2010-09-13 15:17:37 +00:00
|
|
|
},
|
2008-03-26 06:01:34 +00:00
|
|
|
|
2010-09-13 15:17:37 +00:00
|
|
|
bytesAsHex: function bytesAsHex(bytes) {
|
2011-03-01 22:29:41 +00:00
|
|
|
let hex = "";
|
|
|
|
for (let i = 0; i < bytes.length; i++) {
|
|
|
|
hex += ("0" + bytes[i].charCodeAt().toString(16)).slice(-2);
|
|
|
|
}
|
|
|
|
return hex;
|
2010-03-16 23:31:56 +00:00
|
|
|
},
|
2008-03-26 06:01:34 +00:00
|
|
|
|
2010-09-13 15:17:37 +00:00
|
|
|
_sha1: function _sha1(message) {
|
2010-03-16 23:31:56 +00:00
|
|
|
let hasher = Cc["@mozilla.org/security/hash;1"].
|
|
|
|
createInstance(Ci.nsICryptoHash);
|
|
|
|
hasher.init(hasher.SHA1);
|
2011-03-01 22:29:41 +00:00
|
|
|
return Utils.digestUTF8(message, hasher);
|
2010-03-16 23:31:56 +00:00
|
|
|
},
|
|
|
|
|
2010-09-13 15:17:37 +00:00
|
|
|
sha1: function sha1(message) {
|
|
|
|
return Utils.bytesAsHex(Utils._sha1(message));
|
|
|
|
},
|
|
|
|
|
|
|
|
sha1Base32: function sha1Base32(message) {
|
|
|
|
return Utils.encodeBase32(Utils._sha1(message));
|
|
|
|
},
|
2010-11-16 19:42:17 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Produce an HMAC key object from a key string.
|
|
|
|
*/
|
|
|
|
makeHMACKey: function makeHMACKey(str) {
|
|
|
|
return Svc.KeyFactory.keyFromString(Ci.nsIKeyObject.HMAC, str);
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
2011-03-01 22:29:41 +00:00
|
|
|
* Produce an HMAC hasher and initialize it with the given HMAC key.
|
2010-11-16 19:42:17 +00:00
|
|
|
*/
|
2011-03-01 22:29:41 +00:00
|
|
|
makeHMACHasher: function makeHMACHasher(type, key) {
|
|
|
|
let hasher = Cc["@mozilla.org/security/hmac;1"]
|
|
|
|
.createInstance(Ci.nsICryptoHMAC);
|
|
|
|
hasher.init(type, key);
|
|
|
|
return hasher;
|
2010-11-30 00:41:17 +00:00
|
|
|
},
|
|
|
|
|
2010-12-09 20:14:08 +00:00
|
|
|
/**
|
|
|
|
* HMAC-based Key Derivation Step 2 according to RFC 5869.
|
|
|
|
*/
|
|
|
|
hkdfExpand: function hkdfExpand(prk, info, len) {
|
|
|
|
const BLOCKSIZE = 256 / 8;
|
2011-03-01 22:29:41 +00:00
|
|
|
let h = Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256,
|
|
|
|
Utils.makeHMACKey(prk));
|
2010-12-09 20:14:08 +00:00
|
|
|
let T = "";
|
|
|
|
let Tn = "";
|
|
|
|
let iterations = Math.ceil(len/BLOCKSIZE);
|
|
|
|
for (let i = 0; i < iterations; i++) {
|
2011-03-01 22:29:41 +00:00
|
|
|
Tn = Utils.digestBytes(Tn + info + String.fromCharCode(i + 1), h);
|
2010-12-09 20:14:08 +00:00
|
|
|
T += Tn;
|
|
|
|
}
|
|
|
|
return T.slice(0, len);
|
|
|
|
},
|
|
|
|
|
2010-11-16 19:42:17 +00:00
|
|
|
/**
|
|
|
|
* PBKDF2 implementation in Javascript.
|
2010-11-16 19:50:18 +00:00
|
|
|
*
|
|
|
|
* The arguments to this function correspond to items in
|
|
|
|
* PKCS #5, v2.0 pp. 9-10
|
|
|
|
*
|
|
|
|
* P: the passphrase, an octet string: e.g., "secret phrase"
|
|
|
|
* S: the salt, an octet string: e.g., "DNXPzPpiwn"
|
|
|
|
* c: the number of iterations, a positive integer: e.g., 4096
|
|
|
|
* dkLen: the length in octets of the destination
|
|
|
|
* key, a positive integer: e.g., 16
|
|
|
|
*
|
|
|
|
* The output is an octet string of length dkLen, which you
|
|
|
|
* can encode as you wish.
|
2010-11-16 19:42:17 +00:00
|
|
|
*/
|
2010-11-16 19:50:18 +00:00
|
|
|
pbkdf2Generate : function pbkdf2Generate(P, S, c, dkLen) {
|
2010-11-30 00:41:17 +00:00
|
|
|
// We don't have a default in the algo itself, as NSS does.
|
|
|
|
// Use the constant.
|
|
|
|
if (!dkLen)
|
|
|
|
dkLen = SYNC_KEY_DECODED_LENGTH;
|
|
|
|
|
2010-11-16 19:50:18 +00:00
|
|
|
/* For HMAC-SHA-1 */
|
|
|
|
const HLEN = 20;
|
|
|
|
|
2011-03-01 22:29:41 +00:00
|
|
|
function F(S, c, i, h) {
|
2010-11-16 19:50:18 +00:00
|
|
|
|
|
|
|
function XOR(a, b, isA) {
|
|
|
|
if (a.length != b.length) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
let val = [];
|
|
|
|
for (let i = 0; i < a.length; i++) {
|
|
|
|
if (isA) {
|
|
|
|
val[i] = a[i] ^ b[i];
|
|
|
|
} else {
|
|
|
|
val[i] = a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
|
|
}
|
|
|
|
}
|
2010-11-16 19:42:17 +00:00
|
|
|
|
2010-11-16 19:50:18 +00:00
|
|
|
return val;
|
|
|
|
}
|
|
|
|
|
|
|
|
let ret;
|
|
|
|
let U = [];
|
|
|
|
|
|
|
|
/* Encode i into 4 octets: _INT */
|
|
|
|
let I = [];
|
|
|
|
I[0] = String.fromCharCode((i >> 24) & 0xff);
|
|
|
|
I[1] = String.fromCharCode((i >> 16) & 0xff);
|
|
|
|
I[2] = String.fromCharCode((i >> 8) & 0xff);
|
|
|
|
I[3] = String.fromCharCode(i & 0xff);
|
|
|
|
|
2011-03-01 22:29:41 +00:00
|
|
|
U[0] = Utils.digestBytes(S + I.join(''), h);
|
2010-11-16 19:50:18 +00:00
|
|
|
for (let j = 1; j < c; j++) {
|
2011-03-01 22:29:41 +00:00
|
|
|
U[j] = Utils.digestBytes(U[j - 1], h);
|
2010-11-16 19:42:17 +00:00
|
|
|
}
|
|
|
|
|
2010-11-16 19:50:18 +00:00
|
|
|
ret = U[0];
|
|
|
|
for (j = 1; j < c; j++) {
|
2010-11-30 00:41:17 +00:00
|
|
|
ret = Utils.byteArrayToString(XOR(ret, U[j]));
|
2010-11-16 19:50:18 +00:00
|
|
|
}
|
2010-11-16 19:42:17 +00:00
|
|
|
|
2010-11-16 19:50:18 +00:00
|
|
|
return ret;
|
2010-11-16 19:42:17 +00:00
|
|
|
}
|
2010-11-16 19:50:18 +00:00
|
|
|
|
|
|
|
let l = Math.ceil(dkLen / HLEN);
|
|
|
|
let r = dkLen - ((l - 1) * HLEN);
|
2010-11-16 19:42:17 +00:00
|
|
|
|
|
|
|
// Reuse the key and the hasher. Remaking them 4096 times is 'spensive.
|
2011-03-01 22:29:41 +00:00
|
|
|
let h = Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA1, Utils.makeHMACKey(P));
|
2010-11-16 19:42:17 +00:00
|
|
|
|
|
|
|
T = [];
|
|
|
|
for (let i = 0; i < l;) {
|
2011-03-01 22:29:41 +00:00
|
|
|
T[i] = F(S, c, ++i, h);
|
2010-11-16 19:42:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let ret = '';
|
|
|
|
for (i = 0; i < l-1;) {
|
|
|
|
ret += T[i++];
|
|
|
|
}
|
|
|
|
ret += T[l - 1].substr(0, r);
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
},
|
|
|
|
|
2010-09-13 15:17:37 +00:00
|
|
|
|
2010-11-30 00:41:17 +00:00
|
|
|
/**
|
|
|
|
* Base32 decode (RFC 4648) a string.
|
|
|
|
*/
|
|
|
|
decodeBase32: function decodeBase32(str) {
|
|
|
|
const key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
|
|
|
|
|
|
let padChar = str.indexOf("=");
|
|
|
|
let chars = (padChar == -1) ? str.length : padChar;
|
|
|
|
let bytes = Math.floor(chars * 5 / 8);
|
|
|
|
let blocks = Math.ceil(chars / 8);
|
|
|
|
|
|
|
|
// Process a chunk of 5 bytes / 8 characters.
|
|
|
|
// The processing of this is known in advance,
|
|
|
|
// so avoid arithmetic!
|
|
|
|
function processBlock(ret, cOffset, rOffset) {
|
|
|
|
let c, val;
|
|
|
|
|
|
|
|
// N.B., this relies on
|
|
|
|
// undefined | foo == foo.
|
|
|
|
function accumulate(val) {
|
|
|
|
ret[rOffset] |= val;
|
|
|
|
}
|
|
|
|
|
|
|
|
function advance() {
|
|
|
|
c = str[cOffset++];
|
|
|
|
if (!c || c == "" || c == "=") // Easier than range checking.
|
|
|
|
throw "Done"; // Will be caught far away.
|
|
|
|
val = key.indexOf(c);
|
|
|
|
if (val == -1)
|
|
|
|
throw "Unknown character in base32: " + c;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle a left shift, restricted to bytes.
|
|
|
|
function left(octet, shift)
|
|
|
|
(octet << shift) & 0xff;
|
|
|
|
|
|
|
|
advance();
|
|
|
|
accumulate(left(val, 3));
|
|
|
|
advance();
|
|
|
|
accumulate(val >> 2);
|
|
|
|
++rOffset;
|
|
|
|
accumulate(left(val, 6));
|
|
|
|
advance();
|
|
|
|
accumulate(left(val, 1));
|
|
|
|
advance();
|
|
|
|
accumulate(val >> 4);
|
|
|
|
++rOffset;
|
|
|
|
accumulate(left(val, 4));
|
|
|
|
advance();
|
|
|
|
accumulate(val >> 1);
|
|
|
|
++rOffset;
|
|
|
|
accumulate(left(val, 7));
|
|
|
|
advance();
|
|
|
|
accumulate(left(val, 2));
|
|
|
|
advance();
|
|
|
|
accumulate(val >> 3);
|
|
|
|
++rOffset;
|
|
|
|
accumulate(left(val, 5));
|
|
|
|
advance();
|
|
|
|
accumulate(val);
|
|
|
|
++rOffset;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Our output. Define to be explicit (and maybe the compiler will be smart).
|
|
|
|
let ret = new Array(bytes);
|
|
|
|
let i = 0;
|
|
|
|
let cOff = 0;
|
|
|
|
let rOff = 0;
|
|
|
|
|
|
|
|
for (; i < blocks; ++i) {
|
|
|
|
try {
|
|
|
|
processBlock(ret, cOff, rOff);
|
|
|
|
} catch (ex) {
|
|
|
|
// Handle the detection of padding.
|
|
|
|
if (ex == "Done")
|
|
|
|
break;
|
|
|
|
throw ex;
|
|
|
|
}
|
|
|
|
cOff += 8;
|
|
|
|
rOff += 5;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Slice in case our shift overflowed to the right.
|
|
|
|
return Utils.byteArrayToString(ret.slice(0, bytes));
|
|
|
|
},
|
|
|
|
|
2010-09-13 15:17:37 +00:00
|
|
|
/**
|
|
|
|
* Base32 encode (RFC 4648) a string
|
|
|
|
*/
|
|
|
|
encodeBase32: function encodeBase32(bytes) {
|
|
|
|
const key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
|
|
let quanta = Math.floor(bytes.length / 5);
|
|
|
|
let leftover = bytes.length % 5;
|
|
|
|
|
|
|
|
// Pad the last quantum with zeros so the length is a multiple of 5.
|
|
|
|
if (leftover) {
|
|
|
|
quanta += 1;
|
|
|
|
for (let i = leftover; i < 5; i++)
|
|
|
|
bytes += "\0";
|
|
|
|
}
|
|
|
|
|
|
|
|
// Chop the string into quanta of 5 bytes (40 bits). Each quantum
|
|
|
|
// is turned into 8 characters from the 32 character base.
|
|
|
|
let ret = "";
|
|
|
|
for (let i = 0; i < bytes.length; i += 5) {
|
|
|
|
let c = [byte.charCodeAt() for each (byte in bytes.slice(i, i + 5))];
|
|
|
|
ret += key[c[0] >> 3]
|
|
|
|
+ key[((c[0] << 2) & 0x1f) | (c[1] >> 6)]
|
|
|
|
+ key[(c[1] >> 1) & 0x1f]
|
|
|
|
+ key[((c[1] << 4) & 0x1f) | (c[2] >> 4)]
|
|
|
|
+ key[((c[2] << 1) & 0x1f) | (c[3] >> 7)]
|
|
|
|
+ key[(c[3] >> 2) & 0x1f]
|
|
|
|
+ key[((c[3] << 3) & 0x1f) | (c[4] >> 5)]
|
|
|
|
+ key[c[4] & 0x1f];
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (leftover) {
|
|
|
|
case 1:
|
|
|
|
return ret.slice(0, -6) + "======";
|
|
|
|
case 2:
|
|
|
|
return ret.slice(0, -4) + "====";
|
|
|
|
case 3:
|
|
|
|
return ret.slice(0, -3) + "===";
|
|
|
|
case 4:
|
|
|
|
return ret.slice(0, -1) + "=";
|
|
|
|
default:
|
|
|
|
return ret;
|
|
|
|
}
|
2008-03-26 06:01:34 +00:00
|
|
|
},
|
|
|
|
|
2010-11-30 00:41:17 +00:00
|
|
|
/**
|
|
|
|
* Turn RFC 4648 base32 into our own user-friendly version.
|
|
|
|
* ABCDEFGHIJKLMNOPQRSTUVWXYZ234567
|
|
|
|
* becomes
|
|
|
|
* abcdefghijk8mn9pqrstuvwxyz234567
|
|
|
|
*/
|
|
|
|
base32ToFriendly: function base32ToFriendly(input) {
|
|
|
|
return input.toLowerCase()
|
|
|
|
.replace("l", '8', "g")
|
|
|
|
.replace("o", '9', "g");
|
|
|
|
},
|
|
|
|
|
|
|
|
base32FromFriendly: function base32FromFriendly(input) {
|
|
|
|
return input.toUpperCase()
|
|
|
|
.replace("8", 'L', "g")
|
|
|
|
.replace("9", 'O', "g");
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Key manipulation.
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Return an octet string in friendly base32 *with no trailing =*.
|
|
|
|
encodeKeyBase32: function encodeKeyBase32(keyData) {
|
|
|
|
return Utils.base32ToFriendly(
|
|
|
|
Utils.encodeBase32(keyData))
|
|
|
|
.slice(0, SYNC_KEY_ENCODED_LENGTH);
|
|
|
|
},
|
|
|
|
|
|
|
|
decodeKeyBase32: function decodeKeyBase32(encoded) {
|
|
|
|
return Utils.decodeBase32(
|
|
|
|
Utils.base32FromFriendly(
|
|
|
|
Utils.normalizePassphrase(encoded)))
|
|
|
|
.slice(0, SYNC_KEY_DECODED_LENGTH);
|
|
|
|
},
|
|
|
|
|
|
|
|
base64Key: function base64Key(keyData) {
|
|
|
|
return btoa(keyData);
|
|
|
|
},
|
|
|
|
|
|
|
|
deriveKeyFromPassphrase: function deriveKeyFromPassphrase(passphrase, salt, keyLength, forceJS) {
|
|
|
|
if (Svc.Crypto.deriveKeyFromPassphrase && !forceJS) {
|
|
|
|
return Svc.Crypto.deriveKeyFromPassphrase(passphrase, salt, keyLength);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
// Fall back to JS implementation.
|
|
|
|
// 4096 is hardcoded in WeaveCrypto, so do so here.
|
|
|
|
return Utils.pbkdf2Generate(passphrase, atob(salt), 4096, keyLength);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* N.B., salt should be base64 encoded, even though we have to decode
|
|
|
|
* it later!
|
|
|
|
*/
|
|
|
|
derivePresentableKeyFromPassphrase : function derivePresentableKeyFromPassphrase(passphrase, salt, keyLength, forceJS) {
|
|
|
|
let k = Utils.deriveKeyFromPassphrase(passphrase, salt, keyLength, forceJS);
|
|
|
|
return Utils.encodeKeyBase32(k);
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* N.B., salt should be base64 encoded, even though we have to decode
|
|
|
|
* it later!
|
|
|
|
*/
|
|
|
|
deriveEncodedKeyFromPassphrase : function deriveEncodedKeyFromPassphrase(passphrase, salt, keyLength, forceJS) {
|
|
|
|
let k = Utils.deriveKeyFromPassphrase(passphrase, salt, keyLength, forceJS);
|
|
|
|
return Utils.base64Key(k);
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Take a base64-encoded 128-bit AES key, returning it as five groups of five
|
|
|
|
* uppercase alphanumeric characters, separated by hyphens.
|
|
|
|
* A.K.A. base64-to-base32 encoding.
|
|
|
|
*/
|
|
|
|
presentEncodedKeyAsSyncKey : function presentEncodedKeyAsSyncKey(encodedKey) {
|
|
|
|
return Utils.encodeKeyBase32(atob(encodedKey));
|
|
|
|
},
|
|
|
|
|
2012-02-28 01:52:48 +00:00
|
|
|
/**
|
|
|
|
* Compute the HTTP MAC SHA-1 for an HTTP request.
|
|
|
|
*
|
|
|
|
* @param identifier
|
|
|
|
* (string) MAC Key Identifier.
|
|
|
|
* @param key
|
|
|
|
* (string) MAC Key.
|
|
|
|
* @param method
|
|
|
|
* (string) HTTP request method.
|
|
|
|
* @param URI
|
|
|
|
* (nsIURI) HTTP request URI.
|
|
|
|
* @param extra
|
|
|
|
* (object) Optional extra parameters. Valid keys are:
|
|
|
|
* nonce_bytes - How many bytes the nonce should be. This defaults
|
|
|
|
* to 8. Note that this many bytes are Base64 encoded, so the
|
|
|
|
* string length of the nonce will be longer than this value.
|
|
|
|
* ts - Timestamp to use. Should only be defined for testing.
|
|
|
|
* nonce - String nonce. Should only be defined for testing as this
|
|
|
|
* function will generate a cryptographically secure random one
|
|
|
|
* if not defined.
|
|
|
|
* ext - Extra string to be included in MAC. Per the HTTP MAC spec,
|
|
|
|
* the format is undefined and thus application specific.
|
|
|
|
* @returns
|
|
|
|
* (object) Contains results of operation and input arguments (for
|
|
|
|
* symmetry). The object has the following keys:
|
|
|
|
*
|
|
|
|
* identifier - (string) MAC Key Identifier (from arguments).
|
|
|
|
* key - (string) MAC Key (from arguments).
|
|
|
|
* method - (string) HTTP request method (from arguments).
|
|
|
|
* hostname - (string) HTTP hostname used (derived from arguments).
|
|
|
|
* port - (string) HTTP port number used (derived from arguments).
|
|
|
|
* mac - (string) Raw HMAC digest bytes.
|
|
|
|
* getHeader - (function) Call to obtain the string Authorization
|
|
|
|
* header value for this invocation.
|
|
|
|
* nonce - (string) Nonce value used.
|
|
|
|
* ts - (number) Integer seconds since Unix epoch that was used.
|
|
|
|
*/
|
|
|
|
computeHTTPMACSHA1: function computeHTTPMACSHA1(identifier, key, method,
|
|
|
|
uri, extra) {
|
|
|
|
let ts = (extra && extra.ts) ? extra.ts : Math.floor(Date.now() / 1000);
|
|
|
|
let nonce_bytes = (extra && extra.nonce_bytes > 0) ? extra.nonce_bytes : 8;
|
|
|
|
|
|
|
|
// We are allowed to use more than the Base64 alphabet if we want.
|
|
|
|
let nonce = (extra && extra.nonce)
|
|
|
|
? extra.nonce
|
|
|
|
: btoa(Utils.generateRandomBytes(nonce_bytes));
|
|
|
|
|
|
|
|
let host = uri.asciiHost;
|
|
|
|
let port;
|
|
|
|
let usedMethod = method.toUpperCase();
|
|
|
|
|
|
|
|
if (uri.port != -1) {
|
|
|
|
port = uri.port;
|
|
|
|
} else if (uri.scheme == "http") {
|
|
|
|
port = "80";
|
|
|
|
} else if (uri.scheme == "https") {
|
|
|
|
port = "443";
|
|
|
|
} else {
|
|
|
|
throw new Error("Unsupported URI scheme: " + uri.scheme);
|
|
|
|
}
|
|
|
|
|
|
|
|
let ext = (extra && extra.ext) ? extra.ext : "";
|
|
|
|
|
|
|
|
let requestString = ts.toString(10) + "\n" +
|
|
|
|
nonce + "\n" +
|
|
|
|
usedMethod + "\n" +
|
|
|
|
uri.path + "\n" +
|
|
|
|
host + "\n" +
|
|
|
|
port + "\n" +
|
|
|
|
ext + "\n";
|
|
|
|
|
|
|
|
let hasher = Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA1,
|
|
|
|
Utils.makeHMACKey(key));
|
|
|
|
let mac = Utils.digestBytes(requestString, hasher);
|
|
|
|
|
|
|
|
function getHeader() {
|
|
|
|
return Utils.getHTTPMACSHA1Header(this.identifier, this.ts, this.nonce,
|
|
|
|
this.mac, this.ext);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
identifier: identifier,
|
|
|
|
key: key,
|
|
|
|
method: usedMethod,
|
|
|
|
hostname: host,
|
|
|
|
port: port,
|
|
|
|
mac: mac,
|
|
|
|
nonce: nonce,
|
|
|
|
ts: ts,
|
|
|
|
ext: ext,
|
|
|
|
getHeader: getHeader
|
|
|
|
};
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Obtain the HTTP MAC Authorization header value from fields.
|
|
|
|
*
|
|
|
|
* @param identifier
|
|
|
|
* (string) MAC key identifier.
|
|
|
|
* @param ts
|
|
|
|
* (number) Integer seconds since Unix epoch.
|
|
|
|
* @param nonce
|
|
|
|
* (string) Nonce value.
|
|
|
|
* @param mac
|
|
|
|
* (string) Computed HMAC digest (raw bytes).
|
|
|
|
* @param ext
|
|
|
|
* (optional) (string) Extra string content.
|
|
|
|
* @returns
|
|
|
|
* (string) Value to put in Authorization header.
|
|
|
|
*/
|
|
|
|
getHTTPMACSHA1Header: function getHTTPMACSHA1Header(identifier, ts, nonce,
|
|
|
|
mac, ext) {
|
|
|
|
let header ='MAC id="' + identifier + '", ' +
|
|
|
|
'ts="' + ts + '", ' +
|
|
|
|
'nonce="' + nonce + '", ' +
|
|
|
|
'mac="' + btoa(mac) + '"';
|
|
|
|
|
|
|
|
if (!ext) {
|
|
|
|
return header;
|
|
|
|
}
|
|
|
|
|
|
|
|
return header += ', ext="' + ext +'"';
|
|
|
|
},
|
|
|
|
|
2008-02-13 22:30:44 +00:00
|
|
|
makeURI: function Weave_makeURI(URIString) {
|
2009-01-07 22:22:02 +00:00
|
|
|
if (!URIString)
|
2008-02-13 22:30:44 +00:00
|
|
|
return null;
|
2008-11-03 22:56:56 +00:00
|
|
|
try {
|
2011-05-20 01:08:07 +00:00
|
|
|
return Services.io.newURI(URIString, null, null);
|
2008-11-03 22:56:56 +00:00
|
|
|
} catch (e) {
|
2011-06-13 18:42:18 +00:00
|
|
|
let log = Log4Moz.repository.getLogger("Sync.Utils");
|
2009-07-24 22:28:42 +00:00
|
|
|
log.debug("Could not create URI: " + Utils.exceptionStr(e));
|
2008-11-03 22:56:56 +00:00
|
|
|
return null;
|
|
|
|
}
|
2008-02-13 22:30:44 +00:00
|
|
|
},
|
2007-12-11 05:38:53 +00:00
|
|
|
|
2009-04-01 00:52:16 +00:00
|
|
|
/**
|
|
|
|
* Load a json object from disk
|
|
|
|
*
|
|
|
|
* @param filePath
|
|
|
|
* Json file path load from weave/[filePath].json
|
|
|
|
* @param that
|
|
|
|
* Object to use for logging and "this" for callback
|
|
|
|
* @param callback
|
|
|
|
* Function to process json object as its first parameter
|
|
|
|
*/
|
|
|
|
jsonLoad: function Utils_jsonLoad(filePath, that, callback) {
|
|
|
|
filePath = "weave/" + filePath + ".json";
|
|
|
|
if (that._log)
|
2009-07-15 01:44:41 +00:00
|
|
|
that._log.trace("Loading json from disk: " + filePath);
|
2009-04-01 00:52:16 +00:00
|
|
|
|
2012-03-12 18:12:47 +00:00
|
|
|
let file = FileUtils.getFile("ProfD", filePath.split("/"), true);
|
2011-01-27 05:43:24 +00:00
|
|
|
if (!file.exists()) {
|
|
|
|
callback.call(that);
|
2009-04-01 00:52:16 +00:00
|
|
|
return;
|
2011-01-27 05:43:24 +00:00
|
|
|
}
|
2009-04-01 00:52:16 +00:00
|
|
|
|
2011-02-08 21:43:35 +00:00
|
|
|
let channel = NetUtil.newChannel(file);
|
|
|
|
channel.contentType = "application/json";
|
|
|
|
|
|
|
|
NetUtil.asyncFetch(channel, function (is, result) {
|
2011-01-27 05:43:33 +00:00
|
|
|
if (!Components.isSuccessCode(result)) {
|
|
|
|
callback.call(that);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let string = NetUtil.readInputStreamToString(is, is.available());
|
|
|
|
is.close();
|
|
|
|
let json;
|
|
|
|
try {
|
|
|
|
json = JSON.parse(string);
|
|
|
|
} catch (ex) {
|
|
|
|
if (that._log)
|
|
|
|
that._log.debug("Failed to load json: " + Utils.exceptionStr(ex));
|
|
|
|
}
|
|
|
|
callback.call(that, json);
|
|
|
|
});
|
2009-04-01 00:52:16 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Save a json-able object to disk
|
|
|
|
*
|
|
|
|
* @param filePath
|
|
|
|
* Json file path save to weave/[filePath].json
|
|
|
|
* @param that
|
|
|
|
* Object to use for logging and "this" for callback
|
2011-01-27 05:43:24 +00:00
|
|
|
* @param obj
|
2009-04-01 00:52:16 +00:00
|
|
|
* Function to provide json-able object to save. If this isn't a
|
|
|
|
* function, it'll be used as the object to make a json string.
|
2011-01-27 05:43:24 +00:00
|
|
|
* @param callback
|
|
|
|
* Function called when the write has been performed. Optional.
|
2009-04-01 00:52:16 +00:00
|
|
|
*/
|
2011-01-27 05:43:24 +00:00
|
|
|
jsonSave: function Utils_jsonSave(filePath, that, obj, callback) {
|
2009-04-01 00:52:16 +00:00
|
|
|
filePath = "weave/" + filePath + ".json";
|
|
|
|
if (that._log)
|
2009-07-15 01:44:41 +00:00
|
|
|
that._log.trace("Saving json to disk: " + filePath);
|
2009-04-01 00:52:16 +00:00
|
|
|
|
2012-03-12 18:12:47 +00:00
|
|
|
let file = FileUtils.getFile("ProfD", filePath.split("/"), true);
|
2011-01-27 05:43:24 +00:00
|
|
|
let json = typeof obj == "function" ? obj.call(that) : obj;
|
2009-04-01 00:52:16 +00:00
|
|
|
let out = JSON.stringify(json);
|
2011-01-27 05:43:33 +00:00
|
|
|
|
2011-05-20 01:08:51 +00:00
|
|
|
let fos = FileUtils.openSafeFileOutputStream(file);
|
2011-03-01 22:29:41 +00:00
|
|
|
let is = this._utf8Converter.convertToInputStream(out);
|
2011-01-27 05:43:33 +00:00
|
|
|
NetUtil.asyncCopy(is, fos, function (result) {
|
|
|
|
if (typeof callback == "function") {
|
|
|
|
callback.call(that);
|
|
|
|
}
|
|
|
|
});
|
2009-04-01 00:52:16 +00:00
|
|
|
},
|
|
|
|
|
2011-06-06 19:27:36 +00:00
|
|
|
/**
|
|
|
|
* Execute a function on the next event loop tick.
|
2011-06-08 16:12:12 +00:00
|
|
|
*
|
|
|
|
* @param callback
|
|
|
|
* Function to invoke.
|
|
|
|
* @param thisObj [optional]
|
|
|
|
* Object to bind the callback to.
|
2011-06-06 19:27:36 +00:00
|
|
|
*/
|
|
|
|
nextTick: function nextTick(callback, thisObj) {
|
|
|
|
if (thisObj) {
|
|
|
|
callback = callback.bind(thisObj);
|
|
|
|
}
|
2011-06-08 16:12:12 +00:00
|
|
|
Services.tm.currentThread.dispatch(callback, Ci.nsIThread.DISPATCH_NORMAL);
|
2011-06-06 19:27:36 +00:00
|
|
|
},
|
|
|
|
|
2009-09-25 05:51:38 +00:00
|
|
|
/**
|
|
|
|
* Return a timer that is scheduled to call the callback after waiting the
|
|
|
|
* provided time or as soon as possible. The timer will be set as a property
|
|
|
|
* of the provided object with the given timer name.
|
|
|
|
*/
|
2011-06-06 19:27:36 +00:00
|
|
|
namedTimer: function delay(callback, wait, thisObj, name) {
|
|
|
|
if (!thisObj || !name) {
|
|
|
|
throw "You must provide both an object and a property name for the timer!";
|
|
|
|
}
|
2009-09-25 05:51:38 +00:00
|
|
|
|
|
|
|
// Delay an existing timer if it exists
|
2010-02-23 21:10:32 +00:00
|
|
|
if (name in thisObj && thisObj[name] instanceof Ci.nsITimer) {
|
2009-09-25 05:51:38 +00:00
|
|
|
thisObj[name].delay = wait;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a special timer that we can add extra properties
|
|
|
|
let timer = {};
|
|
|
|
timer.__proto__ = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
|
|
|
|
|
|
|
|
// Provide an easy way to clear out the timer
|
|
|
|
timer.clear = function() {
|
|
|
|
thisObj[name] = null;
|
|
|
|
timer.cancel();
|
|
|
|
};
|
|
|
|
|
|
|
|
// Initialize the timer with a smart callback
|
|
|
|
timer.initWithCallback({
|
|
|
|
notify: function notify() {
|
|
|
|
// Clear out the timer once it's been triggered
|
|
|
|
timer.clear();
|
|
|
|
callback.call(thisObj, timer);
|
|
|
|
}
|
|
|
|
}, wait, timer.TYPE_ONE_SHOT);
|
|
|
|
|
|
|
|
return thisObj[name] = timer;
|
2008-06-10 02:30:11 +00:00
|
|
|
},
|
|
|
|
|
2009-11-26 00:59:02 +00:00
|
|
|
getIcon: function(iconUri, defaultIcon) {
|
|
|
|
try {
|
|
|
|
let iconURI = Utils.makeURI(iconUri);
|
2011-05-20 01:08:22 +00:00
|
|
|
return PlacesUtils.favicons.getFaviconLinkForIcon(iconURI).spec;
|
2009-11-26 00:59:02 +00:00
|
|
|
}
|
|
|
|
catch(ex) {}
|
|
|
|
|
|
|
|
// Just give the provided default icon or the system's default
|
2011-05-20 01:08:22 +00:00
|
|
|
return defaultIcon || PlacesUtils.favicons.defaultFavicon.spec;
|
2009-11-26 00:59:02 +00:00
|
|
|
},
|
|
|
|
|
2009-08-25 04:47:35 +00:00
|
|
|
getErrorString: function Utils_getErrorString(error, args) {
|
2009-09-16 01:38:52 +00:00
|
|
|
try {
|
2009-09-16 23:52:43 +00:00
|
|
|
return Str.errors.get(error, args || null);
|
2009-09-16 01:38:52 +00:00
|
|
|
} catch (e) {}
|
2009-11-20 22:34:20 +00:00
|
|
|
|
2009-09-16 01:38:52 +00:00
|
|
|
// basically returns "Unknown Error"
|
2009-09-16 23:52:43 +00:00
|
|
|
return Str.errors.get("error.reason.unknown");
|
2009-08-25 04:47:35 +00:00
|
|
|
},
|
|
|
|
|
2010-07-03 18:11:58 +00:00
|
|
|
encodeUTF8: function(str) {
|
|
|
|
try {
|
2011-03-01 22:29:41 +00:00
|
|
|
str = this._utf8Converter.ConvertFromUnicode(str);
|
|
|
|
return str + this._utf8Converter.Finish();
|
2010-07-03 18:11:58 +00:00
|
|
|
} catch(ex) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
decodeUTF8: function(str) {
|
|
|
|
try {
|
2011-03-01 22:29:41 +00:00
|
|
|
str = this._utf8Converter.ConvertToUnicode(str);
|
|
|
|
return str + this._utf8Converter.Finish();
|
2010-07-03 18:11:58 +00:00
|
|
|
} catch(ex) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2010-09-17 15:48:06 +00:00
|
|
|
/**
|
2010-11-30 00:41:17 +00:00
|
|
|
* Generate 26 characters.
|
2010-09-17 15:48:06 +00:00
|
|
|
*/
|
2010-11-30 00:41:17 +00:00
|
|
|
generatePassphrase: function generatePassphrase() {
|
|
|
|
// Note that this is a different base32 alphabet to the one we use for
|
|
|
|
// other tasks. It's lowercase, uses different letters, and needs to be
|
|
|
|
// decoded with decodeKeyBase32, not just decodeBase32.
|
2010-11-30 18:26:13 +00:00
|
|
|
return Utils.encodeKeyBase32(Utils.generateRandomBytes(16));
|
2010-09-17 15:48:06 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
2010-11-30 00:41:17 +00:00
|
|
|
* The following are the methods supported for UI use:
|
|
|
|
*
|
|
|
|
* * isPassphrase:
|
|
|
|
* determines whether a string is either a normalized or presentable
|
|
|
|
* passphrase.
|
|
|
|
* * hyphenatePassphrase:
|
|
|
|
* present a normalized passphrase for display. This might actually
|
|
|
|
* perform work beyond just hyphenation; sorry.
|
|
|
|
* * hyphenatePartialPassphrase:
|
|
|
|
* present a fragment of a normalized passphrase for display.
|
|
|
|
* * normalizePassphrase:
|
|
|
|
* take a presentable passphrase and reduce it to a normalized
|
|
|
|
* representation for storage. normalizePassphrase can safely be called
|
|
|
|
* on normalized input.
|
2010-12-21 23:32:58 +00:00
|
|
|
* * normalizeAccount:
|
|
|
|
* take user input for account/username, cleaning up appropriately.
|
2010-09-17 15:48:06 +00:00
|
|
|
*/
|
2010-11-30 00:41:17 +00:00
|
|
|
|
|
|
|
isPassphrase: function(s) {
|
|
|
|
if (s) {
|
|
|
|
return /^[abcdefghijkmnpqrstuvwxyz23456789]{26}$/.test(Utils.normalizePassphrase(s));
|
|
|
|
}
|
|
|
|
return false;
|
2010-09-17 15:48:06 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
2010-11-30 00:41:17 +00:00
|
|
|
* Hyphenate a passphrase (26 characters) into groups.
|
|
|
|
* abbbbccccddddeeeeffffggggh
|
|
|
|
* =>
|
|
|
|
* a-bbbbc-cccdd-ddeee-effff-ggggh
|
2010-09-17 15:48:06 +00:00
|
|
|
*/
|
2010-11-30 00:41:17 +00:00
|
|
|
hyphenatePassphrase: function hyphenatePassphrase(passphrase) {
|
|
|
|
// For now, these are the same.
|
|
|
|
return Utils.hyphenatePartialPassphrase(passphrase, true);
|
|
|
|
},
|
|
|
|
|
|
|
|
hyphenatePartialPassphrase: function hyphenatePartialPassphrase(passphrase, omitTrailingDash) {
|
|
|
|
if (!passphrase)
|
|
|
|
return null;
|
|
|
|
|
|
|
|
// Get the raw data input. Just base32.
|
|
|
|
let data = passphrase.toLowerCase().replace(/[^abcdefghijkmnpqrstuvwxyz23456789]/g, "");
|
|
|
|
|
|
|
|
// This is the neatest way to do this.
|
|
|
|
if ((data.length == 1) && !omitTrailingDash)
|
|
|
|
return data + "-";
|
|
|
|
|
|
|
|
// Hyphenate it.
|
|
|
|
let y = data.substr(0,1);
|
|
|
|
let z = data.substr(1).replace(/(.{1,5})/g, "-$1");
|
|
|
|
|
|
|
|
// Correct length? We're done.
|
|
|
|
if ((z.length == 30) || omitTrailingDash)
|
|
|
|
return y + z;
|
|
|
|
|
|
|
|
// Add a trailing dash if appropriate.
|
|
|
|
return (y + z.replace(/([^-]{5})$/, "$1-")).substr(0, SYNC_KEY_HYPHENATED_LENGTH);
|
|
|
|
},
|
|
|
|
|
|
|
|
normalizePassphrase: function normalizePassphrase(pp) {
|
|
|
|
// Short var name... have you seen the lines below?!
|
2010-12-20 22:46:16 +00:00
|
|
|
// Allow leading and trailing whitespace.
|
2010-12-28 18:33:23 +00:00
|
|
|
pp = pp.trim().toLowerCase();
|
2010-12-20 18:10:37 +00:00
|
|
|
|
|
|
|
// 20-char sync key.
|
|
|
|
if (pp.length == 23 &&
|
|
|
|
[5, 11, 17].every(function(i) pp[i] == '-')) {
|
|
|
|
|
|
|
|
return pp.slice(0, 5) + pp.slice(6, 11)
|
|
|
|
+ pp.slice(12, 17) + pp.slice(18, 23);
|
|
|
|
}
|
|
|
|
|
|
|
|
// "Modern" 26-char key.
|
|
|
|
if (pp.length == 31 &&
|
|
|
|
[1, 7, 13, 19, 25].every(function(i) pp[i] == '-')) {
|
|
|
|
|
2010-11-30 00:41:17 +00:00
|
|
|
return pp.slice(0, 1) + pp.slice(2, 7)
|
|
|
|
+ pp.slice(8, 13) + pp.slice(14, 19)
|
|
|
|
+ pp.slice(20, 25) + pp.slice(26, 31);
|
2010-12-20 18:10:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Something else -- just return.
|
2010-09-17 15:48:06 +00:00
|
|
|
return pp;
|
|
|
|
},
|
2010-12-21 23:32:58 +00:00
|
|
|
|
|
|
|
normalizeAccount: function normalizeAccount(acc) {
|
2010-12-28 18:33:23 +00:00
|
|
|
return acc.trim();
|
2010-12-21 23:32:58 +00:00
|
|
|
},
|
2010-09-17 15:48:06 +00:00
|
|
|
|
2010-11-30 00:41:17 +00:00
|
|
|
// WeaveCrypto returns bad base64 strings. Truncate excess padding
|
|
|
|
// and decode.
|
|
|
|
// See Bug 562431, comment 4.
|
|
|
|
safeAtoB: function safeAtoB(b64) {
|
|
|
|
let len = b64.length;
|
|
|
|
let over = len % 4;
|
|
|
|
return over ? atob(b64.substr(0, len - over)) : atob(b64);
|
|
|
|
},
|
|
|
|
|
2009-09-11 06:11:33 +00:00
|
|
|
/**
|
2011-05-30 22:57:33 +00:00
|
|
|
* Create an array like the first but without elements of the second. Reuse
|
|
|
|
* arrays if possible.
|
2009-09-11 06:11:33 +00:00
|
|
|
*/
|
|
|
|
arraySub: function arraySub(minuend, subtrahend) {
|
2011-05-30 22:57:33 +00:00
|
|
|
if (!minuend.length || !subtrahend.length)
|
|
|
|
return minuend;
|
2009-09-11 06:11:33 +00:00
|
|
|
return minuend.filter(function(i) subtrahend.indexOf(i) == -1);
|
|
|
|
},
|
|
|
|
|
2011-01-28 17:39:12 +00:00
|
|
|
/**
|
2011-05-30 22:57:33 +00:00
|
|
|
* Build the union of two arrays. Reuse arrays if possible.
|
2011-01-28 17:39:12 +00:00
|
|
|
*/
|
|
|
|
arrayUnion: function arrayUnion(foo, bar) {
|
2011-05-30 22:57:33 +00:00
|
|
|
if (!foo.length)
|
|
|
|
return bar;
|
|
|
|
if (!bar.length)
|
|
|
|
return foo;
|
2011-01-28 17:39:12 +00:00
|
|
|
return foo.concat(Utils.arraySub(bar, foo));
|
|
|
|
},
|
|
|
|
|
2008-03-07 09:56:36 +00:00
|
|
|
bind2: function Async_bind2(object, method) {
|
2008-05-23 18:05:42 +00:00
|
|
|
return function innerBind() { return method.apply(object, arguments); };
|
2008-03-07 09:56:36 +00:00
|
|
|
},
|
|
|
|
|
2010-04-08 21:03:10 +00:00
|
|
|
mpLocked: function mpLocked() {
|
2011-02-23 00:09:43 +00:00
|
|
|
let modules = Cc["@mozilla.org/security/pkcs11moduledb;1"]
|
|
|
|
.getService(Ci.nsIPKCS11ModuleDB);
|
2010-04-08 21:03:10 +00:00
|
|
|
let sdrSlot = modules.findSlotByName("");
|
|
|
|
let status = sdrSlot.status;
|
|
|
|
let slots = Ci.nsIPKCS11Slot;
|
|
|
|
|
2010-08-31 15:58:35 +00:00
|
|
|
if (status == slots.SLOT_READY || status == slots.SLOT_LOGGED_IN
|
|
|
|
|| status == slots.SLOT_UNINITIALIZED)
|
2010-04-08 21:03:10 +00:00
|
|
|
return false;
|
|
|
|
|
|
|
|
if (status == slots.SLOT_NOT_LOGGED_IN)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// something wacky happened, pretend MP is locked
|
|
|
|
return true;
|
|
|
|
},
|
|
|
|
|
2011-01-14 00:56:10 +00:00
|
|
|
// If Master Password is enabled and locked, present a dialog to unlock it.
|
|
|
|
// Return whether the system is unlocked.
|
|
|
|
ensureMPUnlocked: function ensureMPUnlocked() {
|
2011-10-26 20:46:40 +00:00
|
|
|
if (!Utils.mpLocked()) {
|
|
|
|
return true;
|
|
|
|
}
|
2011-02-23 00:09:43 +00:00
|
|
|
let sdr = Cc["@mozilla.org/security/sdr;1"]
|
|
|
|
.getService(Ci.nsISecretDecoderRing);
|
2011-01-14 00:56:10 +00:00
|
|
|
try {
|
|
|
|
sdr.encryptString("bacon");
|
2011-02-23 00:09:43 +00:00
|
|
|
return true;
|
2011-01-14 00:56:10 +00:00
|
|
|
} catch(e) {}
|
2011-02-23 00:09:43 +00:00
|
|
|
return false;
|
2011-01-14 00:56:10 +00:00
|
|
|
},
|
|
|
|
|
2011-06-27 13:22:49 +00:00
|
|
|
/**
|
|
|
|
* Return a value for a backoff interval. Maximum is eight hours, unless
|
|
|
|
* Status.backoffInterval is higher.
|
|
|
|
*
|
|
|
|
*/
|
2012-03-22 22:49:50 +00:00
|
|
|
calculateBackoff: function calculateBackoff(attempts, baseInterval,
|
|
|
|
statusInterval) {
|
2011-06-27 13:22:49 +00:00
|
|
|
let backoffInterval = attempts *
|
2012-03-22 22:49:50 +00:00
|
|
|
(Math.floor(Math.random() * baseInterval) +
|
|
|
|
baseInterval);
|
|
|
|
return Math.max(Math.min(backoffInterval, MAXIMUM_BACKOFF_INTERVAL),
|
|
|
|
statusInterval);
|
|
|
|
},
|
2009-01-06 21:54:18 +00:00
|
|
|
};
|
|
|
|
|
2011-05-20 01:08:35 +00:00
|
|
|
XPCOMUtils.defineLazyGetter(Utils, "_utf8Converter", function() {
|
2011-03-01 22:29:41 +00:00
|
|
|
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
|
|
|
|
.createInstance(Ci.nsIScriptableUnicodeConverter);
|
|
|
|
converter.charset = "UTF-8";
|
|
|
|
return converter;
|
|
|
|
});
|
2010-03-02 19:07:30 +00:00
|
|
|
|
2009-01-06 21:54:18 +00:00
|
|
|
/*
|
|
|
|
* Commonly-used services
|
|
|
|
*/
|
|
|
|
let Svc = {};
|
2009-02-10 08:52:05 +00:00
|
|
|
Svc.Prefs = new Preferences(PREFS_BRANCH);
|
2010-06-16 22:11:40 +00:00
|
|
|
Svc.DefaultPrefs = new Preferences({branch: PREFS_BRANCH, defaultBranch: true});
|
2009-12-15 22:21:12 +00:00
|
|
|
Svc.Obs = Observers;
|
2010-08-17 13:44:29 +00:00
|
|
|
|
2011-05-20 01:08:35 +00:00
|
|
|
let _sessionCID = Services.appinfo.ID == SEAMONKEY_ID ?
|
|
|
|
"@mozilla.org/suite/sessionstore;1" :
|
|
|
|
"@mozilla.org/browser/sessionstore;1";
|
|
|
|
|
|
|
|
[["Form", "@mozilla.org/satchel/form-history;1", "nsIFormHistory2"],
|
2009-07-17 23:55:15 +00:00
|
|
|
["Idle", "@mozilla.org/widget/idleservice;1", "nsIIdleService"],
|
2010-03-16 23:31:56 +00:00
|
|
|
["KeyFactory", "@mozilla.org/security/keyobjectfactory;1", "nsIKeyObjectFactory"],
|
2011-05-20 01:08:35 +00:00
|
|
|
["Session", _sessionCID, "nsISessionStore"]
|
|
|
|
].forEach(function([name, contract, iface]) {
|
|
|
|
XPCOMUtils.defineLazyServiceGetter(Svc, name, contract, iface);
|
|
|
|
});
|
2009-08-19 03:03:11 +00:00
|
|
|
|
2011-05-25 23:40:09 +00:00
|
|
|
// nsIPrivateBrowsingService is not implemented in mobile Firefox.
|
|
|
|
// Svc.Private should just return undefined in this case instead of throwing.
|
|
|
|
XPCOMUtils.defineLazyGetter(Svc, "Private", function() {
|
|
|
|
try {
|
|
|
|
return Cc["@mozilla.org/privatebrowsing;1"].getService(Ci["nsIPrivateBrowsingService"]);
|
|
|
|
} catch (e) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2010-10-14 19:17:35 +00:00
|
|
|
Svc.__defineGetter__("Crypto", function() {
|
|
|
|
let cryptoSvc;
|
2011-04-07 22:31:11 +00:00
|
|
|
let ns = {};
|
|
|
|
Cu.import("resource://services-crypto/WeaveCrypto.js", ns);
|
|
|
|
cryptoSvc = new ns.WeaveCrypto();
|
2010-10-14 19:17:35 +00:00
|
|
|
delete Svc.Crypto;
|
|
|
|
return Svc.Crypto = cryptoSvc;
|
|
|
|
});
|
|
|
|
|
2009-08-19 03:03:11 +00:00
|
|
|
let Str = {};
|
2011-05-20 01:08:35 +00:00
|
|
|
["errors", "sync"].forEach(function(lazy) {
|
|
|
|
XPCOMUtils.defineLazyGetter(Str, lazy, Utils.lazyStrings(lazy));
|
|
|
|
});
|
2010-08-10 23:54:46 +00:00
|
|
|
|
|
|
|
Svc.Obs.add("xpcom-shutdown", function () {
|
|
|
|
for (let name in Svc)
|
|
|
|
delete Svc[name];
|
|
|
|
});
|