--- a/.eslintignore
+++ b/.eslintignore
@@ -72,26 +72,24 @@ mail/app/profile/channel-prefs.js
mail/base/content/protovis-r2.6-modded.js
mail/branding/nightly/thunderbird-branding.js
mail/branding/thunderbird/thunderbird-branding.js
# This file is split into two in order to keep it as a valid json file
# for documentation purposes (policies.json) but to be accessed by the
# code as a .jsm (schema.jsm)
mail/components/enterprisepolicies/schemas/schema.jsm
mail/components/im/all-im.js
+mail/extensions/openpgp/prefs/openpgp-prefs.js
mail/locales/en-US/all-l10n.js
mail/components/compose/texzilla/**
mail/components/compose/composer.js
# exclude MailConstants.jsm because: #filter subtitution
mail/base/modules/MailConstants.jsm
-# openpgp exclusions, should get enabled, tracked in bug 1595319
-mail/extensions/openpgp/**
-
# calendar/ exclusions
# prefs files
calendar/lightning/content/lightning.js
calendar/providers/gdata/defaults/preferences.js
calendar/timezones/preferences.js
# third party library
--- a/mail/extensions/openpgp/content/BondOpenPGP.jsm
+++ b/mail/extensions/openpgp/content/BondOpenPGP.jsm
@@ -33,18 +33,16 @@ const getEnigmailPgpmimeHander = Enigmai
"EnigmailPgpmimeHander"
);
const getRNP = EnigmailLazy.loader("enigmail/rnp.jsm", "RNP");
const getEnigmailWindows = EnigmailLazy.loader(
"enigmail/windows.jsm",
"EnigmailWindows"
);
-/* global APP_SHUTDOWN: false */
-
var BondOpenPGP = {
logException(exc) {
try {
Services.console.logStringMessage(exc.toString() + "\n" + exc.stack);
} catch (x) {}
},
initDone: false,
--- a/mail/extensions/openpgp/content/am-enigprefs.xhtml
+++ b/mail/extensions/openpgp/content/am-enigprefs.xhtml
@@ -130,18 +130,16 @@
<checkbox id="openpgp.sendKeyWithMsg"
label="&enigmail.amPrefPgp.sendKeyWithMsg.label;"
checked="false"/>
</vbox>
<!-- Autocrypt tab -->
<vbox flex="1" align="start">
- <html:p id="enigmail_amPrefAutocryptDesc" onclick="Enigmail.edit.handleClick(event)"></html:p>
-
<checkbox id="enigmail_enableAutocrypt"
prefstring="mail.server.%serverkey%.enableAutocrypt"
preftype="bool" prefattribute="value"
observes="enigmail_bcEnablePgp"
oncommand="Enigmail.edit.enableAcSettings()"
label="&enigmail.enableAutocrypt.label;"/>
<checkbox id="enigmail_acPreferEncrypt"
--- a/mail/extensions/openpgp/content/modules/addrbook.jsm
+++ b/mail/extensions/openpgp/content/modules/addrbook.jsm
@@ -1,50 +1,46 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailAddrbook"];
/*
* Functionality related to the Thunderbird address book
*
*/
-
-
-
-
const ABMANAGER = "@mozilla.org/abmanager;1";
var EnigmailAddrbook = {
/**
* Look up the address book card for a given email address
*
* @param emailAddr: String - email address to find
*
* @return if found: Object:
* - card: nsIAbCard for found email address
* - directory: nsIAbDirectory of found card
* NULL if not found
*/
- lookupEmailAddress: function(emailAddr) {
+ lookupEmailAddress(emailAddr) {
let abm = Cc[ABMANAGER].getService(Ci.nsIAbManager);
for (let abd of abm.directories) {
try {
let crd = abd.cardForEmailAddress(emailAddr);
- if (crd) return {
- directory: abd,
- card: crd
- };
- }
- catch (x) {}
+ if (crd) {
+ return {
+ directory: abd,
+ card: crd,
+ };
+ }
+ } catch (x) {}
}
return null;
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/amPrefsService.jsm
+++ b/mail/extensions/openpgp/content/modules/amPrefsService.jsm
@@ -1,73 +1,74 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
"use strict";
-const {
- manager: Cm,
- results: Cr,
- Constructor: CC
-} = Components;
+const { manager: Cm } = Components;
Cm.QueryInterface(Ci.nsIComponentRegistrar);
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const EnigmailCompat = ChromeUtils.import(
+ "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
const CATEGORY = "mailnews-accountmanager-extensions";
const CATEGORY_ENTRY = "openpgp-account-manager-extension";
-const PREF_SERVICE_NAME = "@mozilla.org/accountmanager/extension;1?name=enigprefs";
+const PREF_SERVICE_NAME =
+ "@mozilla.org/accountmanager/extension;1?name=enigprefs";
var EXPORTED_SYMBOLS = ["EnigmailAmPrefsService"];
var EnigmailAmPrefsService = {
- startup: function(reason) {
+ startup(reason) {
try {
- var catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
- catMan.addCategoryEntry(CATEGORY,
+ Services.catMan.addCategoryEntry(
+ CATEGORY,
CATEGORY_ENTRY,
PREF_SERVICE_NAME,
- false, true);
+ false,
+ true
+ );
this.factory = new Factory(EnigmailPrefService);
- }
- catch (ex) {}
+ } catch (ex) {}
},
- shutdown: function(reason) {
- var catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
- catMan.deleteCategoryEntry(CATEGORY, CATEGORY_ENTRY, false);
+ shutdown(reason) {
+ Services.catMan.deleteCategoryEntry(CATEGORY, CATEGORY_ENTRY, false);
if (this.factory) {
this.factory.unregister();
}
- }
+ },
};
function EnigmailPrefService() {}
EnigmailPrefService.prototype = {
name: "enigprefs",
chromePackageName: "openpgp",
classID: Components.ID("{f2be6d32-ff3c-11e9-8e8b-00163e5e6c00}"),
classDescription: "OpenPGP Account Manager Extension Service",
contractID: PREF_SERVICE_NAME,
QueryInterface: EnigmailCompat.generateQI(["nsIMsgAccountManagerExtension"]),
- showPanel: function(server) {
+ showPanel(server) {
// show Enigmail panel for POP3, IMAP, NNTP and "movemail" (unix) account types
switch (server.type) {
case "nntp":
case "imap":
case "pop3":
case "movemail":
return true;
}
return false;
- }
+ },
};
class Factory {
constructor(component) {
this.component = component;
this.register();
Object.freeze(this);
}
@@ -75,18 +76,20 @@ class Factory {
createInstance(outer, iid) {
if (outer) {
throw Cr.NS_ERROR_NO_AGGREGATION;
}
return new this.component();
}
register() {
- Cm.registerFactory(this.component.prototype.classID,
+ Cm.registerFactory(
+ this.component.prototype.classID,
this.component.prototype.classDescription,
this.component.prototype.contractID,
- this);
+ this
+ );
}
unregister() {
Cm.unregisterFactory(this.component.prototype.classID, this);
}
}
--- a/mail/extensions/openpgp/content/modules/app.jsm
+++ b/mail/extensions/openpgp/content/modules/app.jsm
@@ -3,69 +3,71 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailApp"];
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const getEnigmailLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
-const DIR_SERV_CONTRACTID = "@mozilla.org/file/directory_service;1";
-const ENIG_EXTENSION_GUID = "{847b3a00-7ab1-11d4-8f02-006008948af5}";
-const XPCOM_APPINFO = "@mozilla.org/xre/app-info;1";
+const EnigmailLazy = ChromeUtils.import(
+ "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const getEnigmailLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
var EnigmailApp = {
/**
* Platform application name (e.g. Thunderbird)
*/
- getName: function() {
- return Cc[XPCOM_APPINFO].getService(Ci.nsIXULAppInfo).name;
+ getName() {
+ return Services.appinfo.name;
},
/**
* Platform (Gecko) version number (e.g. 42.0)
* The platform version for SeaMonkey and for Thunderbird are identical
* (unlike the application version numbers)
*/
- getPlatformVersion: function() {
- return Cc[XPCOM_APPINFO].getService(Ci.nsIXULAppInfo).platformVersion;
+ getPlatformVersion() {
+ return Services.appinfo.platformVersion;
},
/**
* Return the directory holding the current profile as nsIFile object
*/
- getProfileDirectory: function() {
- let ds = Cc[DIR_SERV_CONTRACTID].getService(Ci.nsIProperties);
- return ds.get("ProfD", Ci.nsIFile);
+ getProfileDirectory() {
+ return Services.dirsvc.get("ProfD", Ci.nsIFile);
},
/**
* Get Enigmail version
*/
- getVersion: function() {
+ getVersion() {
getEnigmailLog().DEBUG("app.jsm: getVersion\n");
- getEnigmailLog().DEBUG("app.jsm: installed version: " + EnigmailApp._version + "\n");
+ getEnigmailLog().DEBUG(
+ "app.jsm: installed version: " + EnigmailApp._version + "\n"
+ );
return EnigmailApp._version;
},
/**
* Get Enigmail installation directory
*/
- getInstallLocation: function() {
+ getInstallLocation() {
return EnigmailApp._installLocation;
},
- setVersion: function(version) {
+ setVersion(version) {
EnigmailApp._version = version;
},
- setInstallLocation: function(location) {
+ setInstallLocation(location) {
EnigmailApp._installLocation = location;
},
- initAddon: function() {
+ initAddon() {
EnigmailApp.setVersion(0);
EnigmailApp.setInstallLocation(0);
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/armor.jsm
+++ b/mail/extensions/openpgp/content/modules/armor.jsm
@@ -1,22 +1,24 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailArmor"];
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
// Locates STRing in TEXT occurring only at the beginning of a line
function indexOfArmorDelimiter(text, str, offset) {
let currentOffset = offset;
while (currentOffset < text.length) {
let loc = text.indexOf(str, currentOffset);
@@ -29,28 +31,26 @@ function indexOfArmorDelimiter(text, str
return -1;
}
function searchBlankLine(str, then) {
var offset = str.search(/\n\s*\r?\n/);
if (offset === -1) {
return "";
- } else {
- return then(offset);
}
+ return then(offset);
}
function indexOfNewline(str, off, then) {
var offset = str.indexOf("\n", off);
if (offset === -1) {
return "";
- } else {
- return then(offset);
}
+ return then(offset);
}
var EnigmailArmor = {
/**
* Locates offsets bracketing PGP armored block in text,
* starting from given offset, and returns block type string.
*
* @param text: String - ASCII armored text
@@ -58,72 +58,110 @@ var EnigmailArmor = {
* @param indentStr: String - prefix that is used for all lines (such as "> ")
* @param beginIndexObj: Object - o.value will contain offset of first character of block
* @param endIndexObj: Object - o.value will contain offset of last character of block (newline)
* @param indentStrObj: Object - o.value will contain indent of 1st line
*
* @return String - type of block found (e.g. MESSAGE, PUBLIC KEY)
* If no block is found, an empty String is returned;
*/
- locateArmoredBlock: function(text, offset, indentStr, beginIndexObj, endIndexObj, indentStrObj) {
- EnigmailLog.DEBUG("armor.jsm: Enigmail.locateArmoredBlock: " + offset + ", '" + indentStr + "'\n");
+ locateArmoredBlock(
+ text,
+ offset,
+ indentStr,
+ beginIndexObj,
+ endIndexObj,
+ indentStrObj
+ ) {
+ EnigmailLog.DEBUG(
+ "armor.jsm: Enigmail.locateArmoredBlock: " +
+ offset +
+ ", '" +
+ indentStr +
+ "'\n"
+ );
beginIndexObj.value = -1;
endIndexObj.value = -1;
- var beginIndex = indexOfArmorDelimiter(text, indentStr + "-----BEGIN PGP ", offset);
+ var beginIndex = indexOfArmorDelimiter(
+ text,
+ indentStr + "-----BEGIN PGP ",
+ offset
+ );
if (beginIndex == -1) {
var blockStart = text.indexOf("-----BEGIN PGP ");
if (blockStart >= 0) {
var indentStart = text.search(/\n.*-----BEGIN PGP /) + 1;
indentStrObj.value = text.substring(indentStart, blockStart);
indentStr = indentStrObj.value;
- beginIndex = indexOfArmorDelimiter(text, indentStr + "-----BEGIN PGP ", offset);
+ beginIndex = indexOfArmorDelimiter(
+ text,
+ indentStr + "-----BEGIN PGP ",
+ offset
+ );
}
}
- if (beginIndex == -1)
+ if (beginIndex == -1) {
return "";
+ }
// Locate newline at end of armor header
offset = text.indexOf("\n", beginIndex);
- if (offset == -1)
+ if (offset == -1) {
return "";
+ }
- var endIndex = indexOfArmorDelimiter(text, indentStr + "-----END PGP ", offset);
+ var endIndex = indexOfArmorDelimiter(
+ text,
+ indentStr + "-----END PGP ",
+ offset
+ );
- if (endIndex == -1)
+ if (endIndex == -1) {
return "";
+ }
// Locate newline at end of PGP block
endIndex = text.indexOf("\n", endIndex);
if (endIndex == -1) {
// No terminating newline
endIndex = text.length - 1;
}
var blockHeader = text.substr(beginIndex, offset - beginIndex + 1);
- var blockRegex = new RegExp("^" + indentStr +
- "-----BEGIN PGP (.{1,30})-----\\s*\\r?\\n");
+ var blockRegex = new RegExp(
+ "^" + indentStr + "-----BEGIN PGP (.{1,30})-----\\s*\\r?\\n"
+ );
var matches = blockHeader.match(blockRegex);
var blockType = "";
- if (matches && (matches.length > 1)) {
+ if (matches && matches.length > 1) {
blockType = matches[1];
- EnigmailLog.DEBUG("armor.jsm: Enigmail.locateArmoredBlock: blockType=" + blockType + "\n");
+ EnigmailLog.DEBUG(
+ "armor.jsm: Enigmail.locateArmoredBlock: blockType=" + blockType + "\n"
+ );
}
if (blockType == "UNVERIFIED MESSAGE") {
// Skip any unverified message block
- return EnigmailArmor.locateArmoredBlock(text, endIndex + 1, indentStr, beginIndexObj, endIndexObj, indentStrObj);
+ return EnigmailArmor.locateArmoredBlock(
+ text,
+ endIndex + 1,
+ indentStr,
+ beginIndexObj,
+ endIndexObj,
+ indentStrObj
+ );
}
beginIndexObj.value = beginIndex;
endIndexObj.value = endIndex;
return blockType;
},
@@ -135,131 +173,158 @@ var EnigmailArmor = {
* @return Array of objects with the following structure:
* obj.begin: Number
* obj.end: Number
* obj.indent: String
* obj.blocktype: String
*
* if no block was found, an empty array is returned
*/
- locateArmoredBlocks: function(text) {
+ locateArmoredBlocks(text) {
var beginObj = {};
var endObj = {};
var indentStrObj = {};
var blocks = [];
var i = 0;
var b;
- while ((b = EnigmailArmor.locateArmoredBlock(text, i, "", beginObj, endObj, indentStrObj)) !== "") {
+ while (
+ (b = EnigmailArmor.locateArmoredBlock(
+ text,
+ i,
+ "",
+ beginObj,
+ endObj,
+ indentStrObj
+ )) !== ""
+ ) {
blocks.push({
begin: beginObj.value,
end: endObj.value,
indent: indentStrObj.value ? indentStrObj.value : "",
- blocktype: b
+ blocktype: b,
});
i = endObj.value;
}
- EnigmailLog.DEBUG("armor.jsm: locateArmorBlocks: Found " + blocks.length + " Blocks\n");
+ EnigmailLog.DEBUG(
+ "armor.jsm: locateArmorBlocks: Found " + blocks.length + " Blocks\n"
+ );
return blocks;
},
- extractSignaturePart: function(signatureBlock, part) {
- EnigmailLog.DEBUG("armor.jsm: Enigmail.extractSignaturePart: part=" + part + "\n");
+ extractSignaturePart(signatureBlock, part) {
+ EnigmailLog.DEBUG(
+ "armor.jsm: Enigmail.extractSignaturePart: part=" + part + "\n"
+ );
return searchBlankLine(signatureBlock, function(offset) {
return indexOfNewline(signatureBlock, offset + 1, function(offset) {
- var beginIndex = signatureBlock.indexOf("-----BEGIN PGP SIGNATURE-----", offset + 1);
+ var beginIndex = signatureBlock.indexOf(
+ "-----BEGIN PGP SIGNATURE-----",
+ offset + 1
+ );
if (beginIndex == -1) {
return "";
}
if (part === EnigmailConstants.SIGNATURE_TEXT) {
- return signatureBlock.substr(offset + 1, beginIndex - offset - 1).
- replace(/^- -/, "-").
- replace(/\n- -/g, "\n-").
- replace(/\r- -/g, "\r-");
+ return signatureBlock
+ .substr(offset + 1, beginIndex - offset - 1)
+ .replace(/^- -/, "-")
+ .replace(/\n- -/g, "\n-")
+ .replace(/\r- -/g, "\r-");
}
return indexOfNewline(signatureBlock, beginIndex, function(offset) {
- var endIndex = signatureBlock.indexOf("-----END PGP SIGNATURE-----", offset);
+ var endIndex = signatureBlock.indexOf(
+ "-----END PGP SIGNATURE-----",
+ offset
+ );
if (endIndex == -1) {
return "";
}
var signBlock = signatureBlock.substr(offset, endIndex - offset);
return searchBlankLine(signBlock, function(armorIndex) {
if (part == EnigmailConstants.SIGNATURE_HEADERS) {
return signBlock.substr(1, armorIndex);
}
- return indexOfNewline(signBlock, armorIndex + 1, function(armorIndex) {
+ return indexOfNewline(signBlock, armorIndex + 1, function(
+ armorIndex
+ ) {
if (part == EnigmailConstants.SIGNATURE_ARMOR) {
- return signBlock.substr(armorIndex, endIndex - armorIndex).
- replace(/\s*/g, "");
- } else {
- return "";
+ return signBlock
+ .substr(armorIndex, endIndex - armorIndex)
+ .replace(/\s*/g, "");
}
+ return "";
});
});
});
});
});
},
/**
* Remove all headers from an OpenPGP Armored message and replace them
* with a set of new headers.
*
* @param armorText: String - ASCII armored message
* @param headers: Object - key/value pairs of new headers to insert
*
* @return String - new armored message
*/
- replaceArmorHeaders: function(armorText, headers) {
-
+ replaceArmorHeaders(armorText, headers) {
let text = armorText.replace(/\r\n/g, "\n");
let i = text.search(/\n/);
- if (i < 0) return armorText;
+ if (i < 0) {
+ return armorText;
+ }
let m = text.substr(0, i + 1);
for (let j in headers) {
m += j + ": " + headers[j] + "\n";
}
i = text.search(/\n\n/);
- if (i < 0) return armorText;
+ if (i < 0) {
+ return armorText;
+ }
m += text.substr(i + 1);
return m;
},
/**
* Get a list of all headers found in an armor message
*
* @param text String - ASCII armored message
*
* @return Object: key/value pairs of headers. All keys are in lowercase.
*/
- getArmorHeaders: function(text) {
+ getArmorHeaders(text) {
let headers = {};
let b = this.locateArmoredBlocks(text);
if (b.length === 0) {
return headers;
}
let msg = text.substr(b[0].begin);
let lx = new RegExp("\\n" + b[0].indent + "\\r?\\n");
let hdrEnd = msg.search(lx);
- if (hdrEnd < 0) return headers;
+ if (hdrEnd < 0) {
+ return headers;
+ }
let lines = msg.substr(0, hdrEnd).split(/\r?\n/);
let rx = new RegExp("^" + b[0].indent + "([^: ]+)(: )(.*)");
// skip 1st line (ARMOR-line)
for (let i = 1; i < lines.length; i++) {
let m = lines[i].match(rx);
if (m && m.length >= 4) {
@@ -268,26 +333,26 @@ var EnigmailArmor = {
}
return headers;
},
/**
* Split armored blocks into an array of strings
*/
- splitArmoredBlocks: function(keyBlockStr) {
+ splitArmoredBlocks(keyBlockStr) {
let myRe = /-----BEGIN PGP (PUBLIC|PRIVATE) KEY BLOCK-----/g;
let myArray;
let retArr = [];
let startIndex = -1;
while ((myArray = myRe.exec(keyBlockStr)) !== null) {
if (startIndex >= 0) {
let s = keyBlockStr.substring(startIndex, myArray.index);
retArr.push(s);
}
startIndex = myArray.index;
}
retArr.push(keyBlockStr.substring(startIndex));
return retArr;
- }
-};
\ No newline at end of file
+ },
+};
--- a/mail/extensions/openpgp/content/modules/attachment.jsm
+++ b/mail/extensions/openpgp/content/modules/attachment.jsm
@@ -1,19 +1,20 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailAttachment"];
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailCryptoAPI = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
var EnigmailAttachment = {
- getFileName: function(parent, byteData) {
+ getFileName(parent, byteData) {
const cApi = EnigmailCryptoAPI();
return cApi.sync(cApi.getFileName(parent, byteData));
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/autoSetup.jsm
+++ b/mail/extensions/openpgp/content/modules/autoSetup.jsm
@@ -8,171 +8,206 @@
/**
* Module to determine the type of setup of the user, based on existing emails
* found in the inbox
*/
var EXPORTED_SYMBOLS = ["EnigmailAutoSetup"];
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailAutocrypt = ChromeUtils.import("chrome://openpgp/content/modules/autocrypt.jsm").EnigmailAutocrypt;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailAutocrypt = ChromeUtils.import(
+ "chrome://openpgp/content/modules/autocrypt.jsm"
+).EnigmailAutocrypt;
+const EnigmailFuncs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailDialog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailKeyRing = ChromeUtils.import(
+ "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailMime = ChromeUtils.import(
+ "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const EnigmailWks = ChromeUtils.import("chrome://openpgp/content/modules/webKey.jsm").EnigmailWks;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
+const EnigmailWks = ChromeUtils.import(
+ "chrome://openpgp/content/modules/webKey.jsm"
+).EnigmailWks;
+const EnigmailTimer = ChromeUtils.import(
+ "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+const EnigmailStreams = ChromeUtils.import(
+ "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailGpg = ChromeUtils.import(
+ "chrome://openpgp/content/modules/gpg.jsm"
+).EnigmailGpg;
// Interfaces
-const nsIFolderLookupService = Ci.nsIFolderLookupService;
const nsIMsgAccountManager = Ci.nsIMsgAccountManager;
-const nsIMsgAccount = Ci.nsIMsgAccount;
-const nsIMsgDBHdr = Ci.nsIMsgDBHdr;
const nsIMessenger = Ci.nsIMessenger;
const nsIMsgMessageService = Ci.nsIMsgMessageService;
-const nsIMsgFolder = Ci.nsIMsgFolder;
/**
* the determined setup type
*/
var gDeterminedSetupType = {
- value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED
+ value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED,
};
var EnigmailAutoSetup = {
-
- getDeterminedSetupType: async function() {
- if (gDeterminedSetupType.value === EnigmailConstants.AUTOSETUP_NOT_INITIALIZED) {
- return await this.determinePreviousInstallType();
+ async getDeterminedSetupType() {
+ if (
+ gDeterminedSetupType.value === EnigmailConstants.AUTOSETUP_NOT_INITIALIZED
+ ) {
+ return this.determinePreviousInstallType();
}
- else
- return gDeterminedSetupType;
+ return gDeterminedSetupType;
},
/**
* Identify which type of setup the user had before Enigmail was (re-)installed
*
* @return Promise<Object> with:
* - value : For each case assigned value, see EnigmailConstants.AUTOSETUP_xxx values
* - acSetupMessage {nsIMsgDBHdr} in case value === 1
* - msgHeaders {Object} in case value === 2
*/
- determinePreviousInstallType: function() {
- let self = this;
+ determinePreviousInstallType() {
gDeterminedSetupType = {
- value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED
+ value: EnigmailConstants.AUTOSETUP_NOT_INITIALIZED,
};
return new Promise(async (resolve, reject) => {
EnigmailLog.DEBUG("autoSetup.jsm: determinePreviousInstallType()\n");
try {
- let msgAccountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(nsIMsgAccountManager);
- let folderService = Cc["@mozilla.org/mail/folder-lookup;1"].getService(nsIFolderLookupService);
+ let msgAccountManager = Cc[
+ "@mozilla.org/messenger/account-manager;1"
+ ].getService(nsIMsgAccountManager);
let returnMsgValue = {
- value: EnigmailConstants.AUTOSETUP_NO_HEADER
+ value: EnigmailConstants.AUTOSETUP_NO_HEADER,
};
var accounts = msgAccountManager.accounts;
let msgHeaders = [];
- let autocryptSetupMessage = {};
// If no account, except Local Folders is configured
if (accounts.length <= 1) {
gDeterminedSetupType.value = EnigmailConstants.AUTOSETUP_NO_ACCOUNT;
resolve(gDeterminedSetupType);
return;
}
// Iterate through each account
for (var i = 0; i < accounts.length; i++) {
var account = accounts.queryElementAt(i, Ci.nsIMsgAccount);
var accountMsgServer = account.incomingServer;
- EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: scanning account "${accountMsgServer.prettyName}"\n`);
+ EnigmailLog.DEBUG(
+ `autoSetup.jsm: determinePreviousInstallType: scanning account "${
+ accountMsgServer.prettyName
+ }"\n`
+ );
let msgFolderArr = [];
try {
getMsgFolders(account.incomingServer.rootFolder, msgFolderArr);
- }
- catch (e) {
- EnigmailLog.DEBUG("autoSetup.jsm: determinePreviousInstallType: Error: " + e + "\n");
+ } catch (e) {
+ EnigmailLog.DEBUG(
+ "autoSetup.jsm: determinePreviousInstallType: Error: " + e + "\n"
+ );
}
if (account.incomingServer.type.search(/^(none|nntp)$/) === 0) {
// ignore NNTP accounts and "Local Folders" accounts
continue;
}
// Iterating through each non empty Folder Database in the Account
for (var k = 0; k < msgFolderArr.length; k++) {
let msgFolder = msgFolderArr[k];
let msgDatabase = msgFolderArr[k].msgDatabase;
- if ((msgFolder.flags & Ci.nsMsgFolderFlags.Junk) ||
- (msgFolder.flags & Ci.nsMsgFolderFlags.Trash) ||
- (!account.defaultIdentity)) {
+ if (
+ msgFolder.flags & Ci.nsMsgFolderFlags.Junk ||
+ msgFolder.flags & Ci.nsMsgFolderFlags.Trash ||
+ !account.defaultIdentity
+ ) {
continue;
}
- EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: scanning folder "${msgFolder.name}"\n`);
+ EnigmailLog.DEBUG(
+ `autoSetup.jsm: determinePreviousInstallType: scanning folder "${
+ msgFolder.name
+ }"\n`
+ );
// Iterating through each message in the Folder
for (let msgHeader of msgDatabase.ReverseEnumerateMessages()) {
let msgURI = msgFolder.getUriForMsg(msgHeader);
let msgAuthor = "";
try {
msgAuthor = EnigmailFuncs.stripEmail(msgHeader.author);
- }
- catch (x) {}
+ } catch (x) {}
// Listing all the headers in the message
- let messenger = Components.classes["@mozilla.org/messenger;1"].createInstance(nsIMessenger);
- let mms = messenger.messageServiceFromURI(msgURI).QueryInterface(nsIMsgMessageService);
+ let messenger = Cc["@mozilla.org/messenger;1"].createInstance(
+ nsIMessenger
+ );
+ let mms = messenger
+ .messageServiceFromURI(msgURI)
+ .QueryInterface(nsIMsgMessageService);
let headerObj = await getStreamedHeaders(msgURI, mms);
- let checkHeaderValues = await checkHeaders(headerObj, msgHeader, msgAuthor, account.defaultIdentity.email, msgFolder, returnMsgValue, msgHeaders);
+ let checkHeaderValues = await checkHeaders(
+ headerObj,
+ msgHeader,
+ msgAuthor,
+ account.defaultIdentity.email,
+ msgFolder,
+ returnMsgValue,
+ msgHeaders
+ );
msgHeaders = checkHeaderValues.msgHeaders;
returnMsgValue = checkHeaderValues.returnMsgValue;
const currDateInSeconds = getCurrentTime();
const diffSecond = currDateInSeconds - msgHeader.dateInSeconds;
/**
2592000 = No. of Seconds in a Month.
This is to ignore 1 month old messages.
*/
if (diffSecond > 2592000.0) {
break;
}
}
-
}
-
}
if (returnMsgValue.acSetupMessage) {
- EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: found AC-Setup message\n`);
+ EnigmailLog.DEBUG(
+ `autoSetup.jsm: determinePreviousInstallType: found AC-Setup message\n`
+ );
gDeterminedSetupType = returnMsgValue;
resolve(gDeterminedSetupType);
- }
- else {
+ } else {
EnigmailLog.DEBUG(`msgHeaders.length: ${msgHeaders.length}\n`);
// find newest message to know the protocol
let latestMsg = null;
for (let i = 0; i < msgHeaders.length; i++) {
if (!latestMsg) {
latestMsg = msgHeaders[i];
}
@@ -181,63 +216,70 @@ var EnigmailAutoSetup = {
latestMsg = msgHeaders[i];
}
}
if (latestMsg) {
if (latestMsg.msgType === "Autocrypt") {
returnMsgValue.value = EnigmailConstants.AUTOSETUP_AC_HEADER;
returnMsgValue.msgHeaders = msgHeaders;
- }
- else {
+ } else {
returnMsgValue.value = EnigmailConstants.AUTOSETUP_ENCRYPTED_MSG;
returnMsgValue.msgHeaders = msgHeaders;
}
}
let defId = EnigmailFuncs.getDefaultIdentity();
if (defId) {
returnMsgValue.userName = defId.fullName;
returnMsgValue.userEmail = defId.email;
- }
- else {
+ } else {
returnMsgValue.userName = undefined;
returnMsgValue.userEmail = undefined;
}
gDeterminedSetupType = returnMsgValue;
- EnigmailLog.DEBUG(`autoSetup.jsm: determinePreviousInstallType: found type: ${returnMsgValue.value}\n`);
+ EnigmailLog.DEBUG(
+ `autoSetup.jsm: determinePreviousInstallType: found type: ${
+ returnMsgValue.value
+ }\n`
+ );
resolve(returnMsgValue);
}
- }
- catch (x) {
+ } catch (x) {
reject(x);
}
});
-
},
/**
* Process the Autocrypt Setup Message
*
* @param {Object} headerValue: contains header and attachment of an Autocrypt Setup Message
* @param {nsIWindow} passwordWindow: parent window for password dialog
* @param {nsIWindow} confirmWindow: parent window for confirmation dialog
* (note: split into 2 parent windows for unit tests)
*
* @return {Promise<Number>}: Import result.
* 1: imported OK
* 0: no Autocrypt setup message
* -1: import not OK (wrong password, canceled etc.)
*/
- performAutocryptSetup: async function(headerValue, passwordWindow = null, confirmWindow = null) {
+ async performAutocryptSetup(
+ headerValue,
+ passwordWindow = null,
+ confirmWindow = null
+ ) {
EnigmailLog.DEBUG("autoSetup.jsm: performAutocryptSetup()\n");
- EnigmailDialog.alert(window, "EnigmailAutocrypt.handleBackupMessage not implemented");
+ EnigmailDialog.alert(
+ confirmWindow,
+ "EnigmailAutocrypt.handleBackupMessage not implemented"
+ );
let imported = 0;
/*
if (headerValue.attachment.contentType.search(/^application\/autocrypt-setup$/i) === 0) {
try {
let res = await EnigmailAutocrypt.getSetupMessageData(headerValue.attachment.url);
let passwd = EnigmailWindows.autocryptSetupPasswd(passwordWindow, "input", res.passphraseFormat, res.passphraseHint);
@@ -279,42 +321,45 @@ var EnigmailAutoSetup = {
/**
* Process accounts with Autocrypt headers
*
* @param {Object} setupType: containing Autocrypt headers from accounts
*
* @return {Promise<Number>}: Result: 0: OK / 1: failure
*/
- processAutocryptHeader: function(setupType) {
+ processAutocryptHeader(setupType) {
EnigmailLog.DEBUG("autoSetup.jsm: processAutocryptHeader()\n");
return new Promise(async (resolve, reject) => {
-
// find newest message to know the protocol
let latestMsg = null;
for (let i = 0; i < setupType.msgHeaders.length; i++) {
if (!latestMsg) {
latestMsg = setupType.msgHeaders[i];
}
if (setupType.msgHeaders[i].dateTime > latestMsg) {
latestMsg = setupType.msgHeaders[i];
}
}
let sysType = latestMsg.msgType;
- EnigmailLog.DEBUG(`autoSetup.jsm: processAutocryptHeader: got type: ${sysType}\n`);
-
+ EnigmailLog.DEBUG(
+ `autoSetup.jsm: processAutocryptHeader: got type: ${sysType}\n`
+ );
for (let i = 0; i < setupType.msgHeaders.length; i++) {
if (setupType.msgHeaders[i].msgType === "Autocrypt") {
// FIXME
- let success = await EnigmailAutocrypt.processAutocryptHeader(setupType.msgHeaders[i].fromAddr, [setupType.msgHeaders[i].msgData],
- setupType.msgHeaders[i].date);
+ let success = await EnigmailAutocrypt.processAutocryptHeader(
+ setupType.msgHeaders[i].fromAddr,
+ [setupType.msgHeaders[i].msgData],
+ setupType.msgHeaders[i].date
+ );
if (success !== 0) {
resolve(1);
}
}
}
resolve(0);
});
},
@@ -322,35 +367,41 @@ var EnigmailAutoSetup = {
/**
* Create a new autocrypt key for every configured account and configure the account
* to use that key. The keys are not protected by a password.
*
* The creation is done in the background after waiting timeoutValue ms
* @param {Number} timeoutValue: number of miliseconds to wait before starting
* the process
*/
- createKeyForAllAccounts: function(timeoutValue = 1000) {
+ createKeyForAllAccounts(timeoutValue = 1000) {
EnigmailLog.DEBUG("autoSetup.jsm: createKeyForAllAccounts()\n");
let self = this;
- EnigmailTimer.setTimeout(async function _f() {
- let msgAccountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(nsIMsgAccountManager);
+ EnigmailTimer.setTimeout(async function() {
+ let msgAccountManager = Cc[
+ "@mozilla.org/messenger/account-manager;1"
+ ].getService(nsIMsgAccountManager);
let accounts = msgAccountManager.accounts;
let createdKeys = [];
for (let i = 0; i < accounts.length; i++) {
let account = accounts.queryElementAt(i, Ci.nsIMsgAccount);
let id = account.defaultIdentity;
if (id && id.email) {
let keyId = await self.createAutocryptKey(id.fullName, id.email);
- EnigmailLog.DEBUG(`autoSetup.jsm: createKeyForAllAccounts: created key ${keyId}\n`);
+ EnigmailLog.DEBUG(
+ `autoSetup.jsm: createKeyForAllAccounts: created key ${keyId}\n`
+ );
if (keyId) {
let keyObj = EnigmailKeyRing.getKeyById(keyId);
- if (keyObj) createdKeys.push(keyObj);
+ if (keyObj) {
+ createdKeys.push(keyObj);
+ }
id.setBoolAttribute("enablePgp", true);
id.setCharAttribute("pgpkeyId", keyId);
id.setIntAttribute("pgpKeyMode", 1);
id.setBoolAttribute("pgpMimeMode", true);
id.setBoolAttribute("pgpSignEncrypted", true);
}
}
}
@@ -364,17 +415,17 @@ var EnigmailAutoSetup = {
* Create a new autocrypt-complinant key
* The keys will not be protected by passwords.
*
* @param {String} userName: Display name
* @param {String} userEmail: Email address
*
* @return {Promise<Boolean>}: Success (true = successful)
*/
- createAutocryptKey: function(userName, userEmail) {
+ createAutocryptKey(userName, userEmail) {
return new Promise((resolve, reject) => {
EnigmailLog.DEBUG("autoSetup.jsm: createAutocryptKey()\n");
let keyType = "ECC",
keyLength = 0;
if (!EnigmailGpg.getGpgFeature("supports-ecc-keys")) {
// fallback for gpg < 2.1
@@ -384,59 +435,74 @@ var EnigmailAutoSetup = {
let expiry = 1825, // 5 years
passphrase = "",
generateObserver = {
keyId: null,
backupLocation: null,
_state: 0,
- onDataAvailable: function(data) {},
- onStopRequest: function(exitCode) {
- EnigmailLog.DEBUG("autoSetup.jsm: createAutocryptKey(): key generation complete\n");
+ onDataAvailable(data) {},
+ onStopRequest(exitCode) {
+ EnigmailLog.DEBUG(
+ "autoSetup.jsm: createAutocryptKey(): key generation complete\n"
+ );
resolve(generateObserver.keyId);
- }
+ },
};
try {
- let keygenRequest = EnigmailKeyRing.generateKey(userName, "", userEmail, expiry, keyLength, keyType, passphrase, generateObserver);
- }
- catch (ex) {
- EnigmailLog.DEBUG("autoSetup.jsm: createAutocryptKey: error: " + ex.message);
+ EnigmailKeyRing.generateKey(
+ userName,
+ "",
+ userEmail,
+ expiry,
+ keyLength,
+ keyType,
+ passphrase,
+ generateObserver
+ );
+ } catch (ex) {
+ EnigmailLog.DEBUG(
+ "autoSetup.jsm: createAutocryptKey: error: " + ex.message
+ );
resolve(null);
}
});
},
/**
* Configure Enigmail to use existing keys
*/
- applyExistingKeys: function() {
- let msgAccountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(nsIMsgAccountManager);
+ applyExistingKeys() {
+ let msgAccountManager = Cc[
+ "@mozilla.org/messenger/account-manager;1"
+ ].getService(nsIMsgAccountManager);
let identities = msgAccountManager.allIdentities;
for (let i = 0; i < identities.length; i++) {
let id = identities.queryElementAt(i, Ci.nsIMsgIdentity);
if (id && id.email) {
let keyObj = EnigmailKeyRing.getSecretKeyByEmail(id.email);
if (keyObj) {
- EnigmailLog.DEBUG(`autoSetup.jsm: applyExistingKeys: found key ${keyObj.keyId}\n`);
+ EnigmailLog.DEBUG(
+ `autoSetup.jsm: applyExistingKeys: found key ${keyObj.keyId}\n`
+ );
id.setBoolAttribute("enablePgp", true);
id.setCharAttribute("pgpkeyId", "0x" + keyObj.fpr);
id.setIntAttribute("pgpKeyMode", 1);
id.setBoolAttribute("pgpMimeMode", true);
id.setBoolAttribute("pgpSignEncrypted", true);
}
}
}
- }
+ },
};
-
/**
* Recusrively go through all folders to get a flat array of all sub-folders
* starting with a parent folder.
*
* @param {nsIMsgFolder} folder: the folder to scan
* @param {nsIMsgFolder} msgFolderArr: An array to be filled with all folders that contain messages
*/
@@ -455,199 +521,218 @@ function getMsgFolders(folder, msgFolder
// Util Function for Extracting manually added Headers
function streamListener(callback) {
let streamListener = {
mAttachments: [],
mHeaders: [],
mBusy: true,
- onStartRequest: function(aRequest) {
+ onStartRequest(aRequest) {
this.mAttachments = [];
this.mHeaders = [];
this.mBusy = true;
- var channel = aRequest.QueryInterface(Components.interfaces.nsIChannel);
- channel.URI.QueryInterface(Components.interfaces.nsIMsgMailNewsUrl);
+ var channel = aRequest.QueryInterface(Ci.nsIChannel);
+ channel.URI.QueryInterface(Ci.nsIMsgMailNewsUrl);
channel.URI.msgHeaderSink = this; // adds this header sink interface to the channel
},
- onStopRequest: function(aRequest, aStatusCode) {
+ onStopRequest(aRequest, aStatusCode) {
callback();
this.mBusy = false; // if needed, you can poll this var to see if we are done collecting attachment details
},
- onDataAvailable: function(aRequest, aInputStream, aOffset, aCount) {},
- onStartHeaders: function() {},
- onEndHeaders: function() {},
- processHeaders: function(aHeaderNameEnumerator, aHeaderValueEnumerator, aDontCollectAddress) {
+ onDataAvailable(aRequest, aInputStream, aOffset, aCount) {},
+ onStartHeaders() {},
+ onEndHeaders() {},
+ processHeaders(
+ aHeaderNameEnumerator,
+ aHeaderValueEnumerator,
+ aDontCollectAddress
+ ) {
for (let headerName of aHeaderNameEnumerator) {
this.mHeaders.push({
name: headerName.toLowerCase(),
- value: aHeaderValueEnumerator.getNext()
+ value: aHeaderValueEnumerator.getNext(),
});
}
},
- handleAttachment: function(aContentType, aUrl, aDisplayName, aUri, aIsExternalAttachment) {
+ handleAttachment(
+ aContentType,
+ aUrl,
+ aDisplayName,
+ aUri,
+ aIsExternalAttachment
+ ) {
if (aContentType == "text/html") {
return;
}
this.mAttachments.push({
contentType: aContentType,
url: aUrl,
displayName: aDisplayName,
uri: aUri,
- isExternal: aIsExternalAttachment
+ isExternal: aIsExternalAttachment,
});
},
- onEndAllAttachments: function() {},
- onEndMsgDownload: function(aUrl) {},
- onEndMsgHeaders: function(aUrl) {},
- onMsgHasRemoteContent: function(aMsgHdr) {},
- getSecurityInfo: function() {},
- setSecurityInfo: function(aSecurityInfo) {},
- getDummyMsgHeader: function() {},
+ onEndAllAttachments() {},
+ onEndMsgDownload(aUrl) {},
+ onEndMsgHeaders(aUrl) {},
+ onMsgHasRemoteContent(aMsgHdr) {},
+ getSecurityInfo() {},
+ setSecurityInfo(aSecurityInfo) {},
+ getDummyMsgHeader() {},
- QueryInterface: function(aIID) {
- if (aIID.equals(Components.interfaces.nsIStreamListener) ||
- aIID.equals(Components.interfaces.nsIMsgHeaderSink) ||
- aIID.equals(Components.interfaces.nsISupports)) {
- return this;
- }
-
- throw Components.results.NS_NOINTERFACE;
- }
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIStreamListener",
+ "nsIMsgHeaderSink",
+ ]),
};
return streamListener;
}
function getStreamedMessage(msgFolder, msgHeader) {
return new Promise((resolve, reject) => {
let msgURI = msgFolder.getUriForMsg(msgHeader);
var listener = streamListener(() => {
resolve(listener.mAttachments[0]);
});
- let messenger = Components.classes["@mozilla.org/messenger;1"].createInstance(nsIMessenger);
- let mms = messenger.messageServiceFromURI(msgURI).QueryInterface(nsIMsgMessageService);
+ let messenger = Cc["@mozilla.org/messenger;1"].createInstance(nsIMessenger);
+ let mms = messenger
+ .messageServiceFromURI(msgURI)
+ .QueryInterface(nsIMsgMessageService);
mms.streamMessage(msgURI, listener, null, null, true, "filter");
});
}
-function checkHeaders(headerObj, msgHeader, msgAuthor, accountEmail, msgFolder, returnMsgValue, msgHeaders) {
+function checkHeaders(
+ headerObj,
+ msgHeader,
+ msgAuthor,
+ accountEmail,
+ msgFolder,
+ returnMsgValue,
+ msgHeaders
+) {
return new Promise(async (resolve, reject) => {
- if (headerObj['autocrypt-setup-message'] && msgHeader.author == msgHeader.recipients) {
-
+ if (
+ headerObj["autocrypt-setup-message"] &&
+ msgHeader.author == msgHeader.recipients
+ ) {
// To extract Attachement for Autocrypt Setup Message
- returnMsgValue.attachment = await getStreamedMessage(msgFolder, msgHeader);
+ returnMsgValue.attachment = await getStreamedMessage(
+ msgFolder,
+ msgHeader
+ );
if (!returnMsgValue.acSetupMessage) {
returnMsgValue.value = 1;
returnMsgValue.acSetupMessage = msgHeader;
- }
- else if (returnMsgValue.acSetupMessage.date < msgHeader.date) {
+ } else if (returnMsgValue.acSetupMessage.date < msgHeader.date) {
returnMsgValue.acSetupMessage = msgHeader;
}
-
- }
- else if (msgAuthor == accountEmail &&
- ("autocrypt" in headerObj)) {
-
+ } else if (msgAuthor == accountEmail && "autocrypt" in headerObj) {
let msgType = "Autocrypt";
let fromHeaderExist = null;
for (let j = 0; j < msgHeaders.length; j++) {
if (msgHeaders[j].fromAddr == msgAuthor) {
fromHeaderExist = msgHeaders[j];
break;
}
}
if (fromHeaderExist === null) {
let dateTime = new Date(0);
try {
dateTime = jsmime.headerparser.parseDateHeader(headerObj.date);
- }
- catch (x) {}
+ } catch (x) {}
let addHeader = {
fromAddr: msgAuthor,
- msgType: msgType,
+ msgType,
msgData: headerObj.autocrypt,
date: headerObj.date,
- dateTime: dateTime
+ dateTime,
};
msgHeaders.push(addHeader);
- }
- else {
+ } else {
let dateTime = new Date(0);
try {
dateTime = jsmime.headerparser.parseDateHeader(headerObj.date);
- }
- catch (x) {}
+ } catch (x) {}
if (dateTime > fromHeaderExist.dateTime) {
fromHeaderExist.msgData = headerObj.autocrypt;
fromHeaderExist.date = headerObj.date;
fromHeaderExist.msgType = msgType;
fromHeaderExist.dateTime = dateTime;
}
}
}
resolve({
- 'returnMsgValue': returnMsgValue,
- 'msgHeaders': msgHeaders
+ returnMsgValue,
+ msgHeaders,
});
});
}
function getStreamedHeaders(msgURI, mms) {
-
return new Promise((resolve, reject) => {
- let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
+ let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(
+ Ci.nsIMimeHeaders
+ );
let headerObj = {};
try {
- mms.streamHeaders(msgURI, EnigmailStreams.newStringStreamListener(aRawString => {
- try {
- //EnigmailLog.DEBUG(`getStreamedHeaders: ${aRawString}\n`);
- headers.initialize(aRawString);
+ mms.streamHeaders(
+ msgURI,
+ EnigmailStreams.newStringStreamListener(aRawString => {
+ try {
+ //EnigmailLog.DEBUG(`getStreamedHeaders: ${aRawString}\n`);
+ headers.initialize(aRawString);
- let i = headers.headerNames;
- for (let hdr of headers.headerNames) {
- let hdrName = hdr.toLowerCase();
+ let i = headers.headerNames;
+ for (let hdr of headers.headerNames) {
+ let hdrName = hdr.toLowerCase();
- let hdrValue = headers.extractHeader(hdrName, true);
- headerObj[hdrName] = hdrValue;
- }
+ let hdrValue = headers.extractHeader(hdrName, true);
+ headerObj[hdrName] = hdrValue;
+ }
- if ("autocrypt" in headerObj) {
- let acHeader = headers.extractHeader("autocrypt", false);
- acHeader = acHeader.replace(/keydata=/i, 'keydata="') + '"';
+ if ("autocrypt" in headerObj) {
+ let acHeader = headers.extractHeader("autocrypt", false);
+ acHeader = acHeader.replace(/keydata=/i, 'keydata="') + '"';
- let paramArr = EnigmailMime.getAllParameters(acHeader);
- paramArr.keydata = paramArr.keydata.replace(/[\r\n\t ]/g, "");
+ let paramArr = EnigmailMime.getAllParameters(acHeader);
+ paramArr.keydata = paramArr.keydata.replace(/[\r\n\t ]/g, "");
- headerObj.autocrypt = "";
- for (i in paramArr) {
- if (headerObj.autocrypt.length > 0) {
- headerObj.autocrypt += "; ";
+ headerObj.autocrypt = "";
+ for (i in paramArr) {
+ if (headerObj.autocrypt.length > 0) {
+ headerObj.autocrypt += "; ";
+ }
+ headerObj.autocrypt += `${i}="${paramArr[i]}"`;
}
- headerObj.autocrypt += `${i}="${paramArr[i]}"`;
}
+ } catch (e) {
+ reject({});
+ EnigmailLog.DEBUG(
+ "autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n"
+ );
}
- }
- catch (e) {
- reject({});
- EnigmailLog.DEBUG("autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n");
- }
- resolve(headerObj);
- }), null, false);
- }
- catch (e) {
+ resolve(headerObj);
+ }),
+ null,
+ false
+ );
+ } catch (e) {
reject({});
- EnigmailLog.DEBUG("autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n");
+ EnigmailLog.DEBUG(
+ "autoSetup.jsm: getStreamedHeaders: Error: " + e + "\n"
+ );
}
});
}
-
function getCurrentTime() {
return new Date().getTime() / 1000;
}
--- a/mail/extensions/openpgp/content/modules/autocrypt.jsm
+++ b/mail/extensions/openpgp/content/modules/autocrypt.jsm
@@ -6,139 +6,180 @@
/**
* Module for dealing with received Autocrypt headers, level 0
* See details at https://github.com/mailencrypt/autocrypt
*/
var EXPORTED_SYMBOLS = ["EnigmailAutocrypt"];
-const Cr = Components.results;
-
-Components.utils.importGlobalProperties(["crypto"]);
+//Cu.importGlobalProperties(["crypto"]);
const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailSqliteDb = ChromeUtils.import("chrome://openpgp/content/modules/sqliteDb.jsm").EnigmailSqliteDb;
-const PromiseUtils = ChromeUtils.import("resource://gre/modules/PromiseUtils.jsm").PromiseUtils;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailOpenPGP = ChromeUtils.import("chrome://openpgp/content/modules/openpgp.jsm").EnigmailOpenPGP;
-const EnigmailRNG = ChromeUtils.import("chrome://openpgp/content/modules/rng.jsm").EnigmailRNG;
-const EnigmailSend = ChromeUtils.import("chrome://openpgp/content/modules/send.jsm").EnigmailSend;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailRules = ChromeUtils.import("chrome://openpgp/content/modules/rules.jsm").EnigmailRules;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailFuncs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailMime = ChromeUtils.import(
+ "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailSqliteDb = ChromeUtils.import(
+ "chrome://openpgp/content/modules/sqliteDb.jsm"
+).EnigmailSqliteDb;
+const PromiseUtils = ChromeUtils.import(
+ "resource://gre/modules/PromiseUtils.jsm"
+).PromiseUtils;
+const EnigmailKeyRing = ChromeUtils.import(
+ "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailStreams = ChromeUtils.import(
+ "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailArmor = ChromeUtils.import(
+ "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+const EnigmailRules = ChromeUtils.import(
+ "chrome://openpgp/content/modules/rules.jsm"
+).EnigmailRules;
+const EnigmailStdlib = ChromeUtils.import(
+ "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailCryptoAPI = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
var gCreatedSetupIds = [];
var EnigmailAutocrypt = {
/**
* Process the "Autocrypt:" header and if successful store the update in the database
*
* @param {String} fromAddr: Address of sender (From: header)
* @param {Array of String} headerDataArr: all instances of the Autocrypt: header found in the message
* @param {String or Number} dateSent: "Date:" field of the message as readable string or in seconds after 1970-01-01
* @param {Boolean} autoCryptEnabled: if true, autocrypt is enabled for the context of the message
*
* @return {Promise<Number>}: success: 0 = success, 1+ = failure
*/
- processAutocryptHeader: async function(fromAddr, headerDataArr, dateSent, autoCryptEnabled = false, isGossip = false) {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader(): from=" + fromAddr + "\n");
+ async processAutocryptHeader(
+ fromAddr,
+ headerDataArr,
+ dateSent,
+ autoCryptEnabled = false,
+ isGossip = false
+ ) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader(): from=" + fromAddr + "\n"
+ );
let conn;
try {
// critical parameters: {param: mandatory}
const CRITICAL = {
addr: true,
keydata: true,
type: false, // That's actually oboslete according to the Level 1 spec.
- "prefer-encrypt": false
+ "prefer-encrypt": false,
};
try {
fromAddr = EnigmailFuncs.stripEmail(fromAddr).toLowerCase();
- }
- catch (ex) {
+ } catch (ex) {
throw new Error("processAutocryptHeader error " + ex);
}
let foundTypes = {};
let paramArr = [];
for (let hdrNum = 0; hdrNum < headerDataArr.length; hdrNum++) {
-
let hdr = headerDataArr[hdrNum].replace(/[\r\n \t]/g, "");
let k = hdr.search(/keydata=/);
if (k > 0) {
let d = hdr.substr(k);
if (d.search(/"/) < 0) {
hdr = hdr.replace(/keydata=/, 'keydata="') + '"';
}
}
paramArr = EnigmailMime.getAllParameters(hdr);
for (let i in CRITICAL) {
if (CRITICAL[i]) {
// found mandatory parameter
if (!(i in paramArr)) {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: cannot find param '" + i + "'\n");
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader: cannot find param '" +
+ i +
+ "'\n"
+ );
return 1; // do nothing if not all mandatory parts are present
}
}
}
for (let i in paramArr) {
if (i.substr(0, 1) !== "_") {
if (!(i in CRITICAL)) {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: unknown critical param " + i + "\n");
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader: unknown critical param " +
+ i +
+ "\n"
+ );
return 2; // do nothing if an unknown critical parameter is found
}
}
}
paramArr.addr = paramArr.addr.toLowerCase();
if (fromAddr !== paramArr.addr) {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: from Addr " + fromAddr + " != " + paramArr.addr.toLowerCase() + "\n");
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader: from Addr " +
+ fromAddr +
+ " != " +
+ paramArr.addr.toLowerCase() +
+ "\n"
+ );
return 3;
}
if (!("type" in paramArr)) {
- paramArr.type = (isGossip ? "1g" : "1");
- }
- else {
+ paramArr.type = isGossip ? "1g" : "1";
+ } else {
paramArr.type = paramArr.type.toLowerCase();
if (paramArr.type !== "1") {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: unknown type " + paramArr.type + "\n");
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader: unknown type " +
+ paramArr.type +
+ "\n"
+ );
return 4; // we currently only support 1 (=OpenPGP)
}
}
try {
- let keyData = atob(paramArr.keydata);
- }
- catch (ex) {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: key is not base64-encoded\n");
+ atob(paramArr.keydata); // don't need result
+ } catch (ex) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader: key is not base64-encoded\n"
+ );
return 5;
}
if (paramArr.type in foundTypes) {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: duplicate header for type=" + paramArr.type + "\n");
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader: duplicate header for type=" +
+ paramArr.type +
+ "\n"
+ );
return 6; // do not process anything if more than one Autocrypt header for the same type is found
}
foundTypes[paramArr.type] = 1;
}
if (isGossip) {
paramArr["prefer-encrypt"] = "nopreference";
@@ -146,104 +187,125 @@ var EnigmailAutocrypt = {
if (!("prefer-encrypt" in paramArr)) {
paramArr["prefer-encrypt"] = "nopreference";
}
let lastDate;
if (typeof dateSent === "string") {
lastDate = jsmime.headerparser.parseDateHeader(dateSent);
- }
- else {
+ } else {
lastDate = new Date(dateSent * 1000);
}
let now = new Date();
if (lastDate > now) {
lastDate = now;
}
paramArr.dateSent = lastDate;
- if (("_enigmail_artificial" in paramArr) && (paramArr._enigmail_artificial === "yes")) {
+ if (
+ "_enigmail_artificial" in paramArr &&
+ paramArr._enigmail_artificial === "yes"
+ ) {
if ("_enigmail_fpr" in paramArr) {
paramArr.fpr = paramArr._enigmail_fpr;
}
paramArr.keydata = "";
paramArr.autocryptDate = 0;
- }
- else {
+ } else {
paramArr.autocryptDate = lastDate;
}
try {
conn = await EnigmailSqliteDb.openDatabase();
- }
- catch (ex) {
- EnigmailLog.DEBUG("autocrypt.jsm: processAutocryptHeader: could not open database\n");
+ } catch (ex) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: processAutocryptHeader: could not open database\n"
+ );
return 7;
}
let resultObj = await findUserRecord(conn, [fromAddr], paramArr.type);
EnigmailLog.DEBUG("autocrypt.jsm: got " + resultObj.numRows + " rows\n");
if (resultObj.data.length === 0) {
await appendUser(conn, paramArr);
- }
- else {
+ } else {
await updateUser(conn, paramArr, resultObj.data, autoCryptEnabled);
}
EnigmailLog.DEBUG("autocrypt.jsm: OK - closing connection\n");
conn.close();
return 0;
- }
- catch (err) {
- EnigmailLog.DEBUG("autocrypt.jsm: error - closing connection: " + err + "\n");
+ } catch (err) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: error - closing connection: " + err + "\n"
+ );
conn.close();
return 8;
}
},
/**
* Import autocrypt OpenPGP keys into regular keyring for a given list of email addresses
* @param {Array of String} emailAddr: email addresses
* @param {Boolean} acceptGossipKeys: import keys received via gossip
*
* @return {Promise<Array of keyObj>}
*/
- importAutocryptKeys: async function(emailAddr, acceptGossipKeys = false) {
+ async importAutocryptKeys(emailAddr, acceptGossipKeys = false) {
EnigmailLog.DEBUG("autocrypt.jsm: importAutocryptKeys()\n");
let keyArr = await this.getOpenPGPKeyForEmail(emailAddr);
- if (!keyArr) return [];
+ if (!keyArr) {
+ return [];
+ }
let importedKeys = [];
let now = new Date();
let prev = null;
for (let i = 0; i < keyArr.length; i++) {
- if (prev && prev.email === keyArr[i].email && prev.type === "1" && keyArr[i].type === "1g") {
+ if (
+ prev &&
+ prev.email === keyArr[i].email &&
+ prev.type === "1" &&
+ keyArr[i].type === "1g"
+ ) {
// skip if we have "gossip" key preceeded by a "regular" key
continue;
}
if (!acceptGossipKeys && keyArr[i].type === "1g") {
- EnigmailLog.DEBUG(`autocrypt.jsm: importAutocryptKeys: skipping gossip key for ${keyArr[i].email}\n`);
+ EnigmailLog.DEBUG(
+ `autocrypt.jsm: importAutocryptKeys: skipping gossip key for ${
+ keyArr[i].email
+ }\n`
+ );
continue;
}
prev = keyArr[i];
if ((now - keyArr[i].lastAutocrypt) / (1000 * 60 * 60 * 24) < 366) {
// only import keys received less than 12 months ago
try {
let keyData = atob(keyArr[i].keyData);
if (keyData.length > 1) {
- importedKeys = await this.applyKeyFromKeydata(keyData, keyArr[i].email, keyArr[i].state, keyArr[i].type);
+ importedKeys = await this.applyKeyFromKeydata(
+ keyData,
+ keyArr[i].email,
+ keyArr[i].state,
+ keyArr[i].type
+ );
}
- }
- catch (ex) {
- EnigmailLog.DEBUG("autocrypt.jsm importAutocryptKeys: exception " + ex.toString() + "\n");
+ } catch (ex) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm importAutocryptKeys: exception " +
+ ex.toString() +
+ "\n"
+ );
}
}
}
return importedKeys;
},
/**
@@ -251,170 +313,198 @@ var EnigmailAutocrypt = {
*
* @param {String} keyData - String key data (BLOB, binary form)
* @param {String} email - email address associated with key
* @param {String} autocryptState - mutual or nopreference
* @param {String} type - autocrypt header type (1 / 1g)
*
* @return {Promise<Array of keys>} list of imported keys
*/
- applyKeyFromKeydata: async function(keyData, email, autocryptState, type) {
+ async applyKeyFromKeydata(keyData, email, autocryptState, type) {
+ throw new Error("Not implemented");
+
+ /*
let keysObj = {};
let importedKeys = [];
- let pubkey = EnigmailOpenPGP.enigmailFuncs.bytesToArmor(EnigmailOpenPGP.armor.public_key, keyData);
+ // TODO: need a MPL version of bytesToArmor
+ let pubkey = EnigmailOpenPGP.enigmailFuncs.bytesToArmor(
+ EnigmailOpenPGP.armor.public_key,
+ keyData
+ );
await EnigmailKeyRing.importKeyAsync(null, false, pubkey, "", {}, keysObj);
if (keysObj.value) {
importedKeys = importedKeys.concat(keysObj.value);
if (keysObj.value.length > 0) {
let key = EnigmailKeyRing.getKeyById(keysObj.value[0]);
// enable encryption if state (prefer-encrypt) is "mutual";
// otherwise, disable it explicitely
- let signEncrypt = (autocryptState === "mutual" ? 1 : 0);
+ let signEncrypt = autocryptState === "mutual" ? 1 : 0;
if (key && key.fpr) {
let ruleObj = {
email: `{${EnigmailConstants.AC_RULE_PREFIX}${email}}`,
keyList: `0x${key.fpr}`,
sign: signEncrypt,
encrypt: signEncrypt,
pgpMime: 2,
- flags: 0
+ flags: 0,
};
EnigmailRules.insertOrUpdateRule(ruleObj);
await this.setKeyImported(null, email);
}
}
}
return importedKeys;
+ */
},
/**
* Update key in the Autocrypt database to mark it "imported in keyring"
*/
- setKeyImported: async function(connection, email) {
+ async setKeyImported(connection, email) {
EnigmailLog.DEBUG(`autocrypt.jsm: setKeyImported(${email})\n`);
try {
let conn = connection;
if (!conn) {
conn = await EnigmailSqliteDb.openDatabase();
}
- let updateStr = "update autocrypt_keydata set keyring_inserted = '1' where email = :email;";
+ let updateStr =
+ "update autocrypt_keydata set keyring_inserted = '1' where email = :email;";
let updateObj = {
- email: email.toLowerCase()
+ email: email.toLowerCase(),
};
await new Promise((resolve, reject) =>
- conn.executeTransaction(function _trx() {
- conn.execute(updateStr, updateObj).then(r => {
- resolve(r);
- }).catch(err => {
- EnigmailLog.DEBUG(`autocrypt.jsm: setKeyImported: error ${err}\n`);
- reject(err);
- });
- }));
+ conn.executeTransaction(function() {
+ conn
+ .execute(updateStr, updateObj)
+ .then(r => {
+ resolve(r);
+ })
+ .catch(err => {
+ EnigmailLog.DEBUG(
+ `autocrypt.jsm: setKeyImported: error ${err}\n`
+ );
+ reject(err);
+ });
+ })
+ );
- if (!connection) conn.close();
- }
- catch (err) {
+ if (!connection) {
+ conn.close();
+ }
+ } catch (err) {
EnigmailLog.DEBUG(`autocrypt.jsm: setKeyImported: error ${err}\n`);
throw err;
}
},
/**
* Go through all emails in the autocrypt store and determine which keys already
* have a per-recipient rule
*/
- updateAllImportedKeys: async function() {
+ async updateAllImportedKeys() {
EnigmailLog.DEBUG(`autocrypt.jsm: updateAllImportedKeys()\n`);
try {
let conn = await EnigmailSqliteDb.openDatabase();
let rows = [];
- await conn.execute("select email, type from autocrypt_keydata where type = '1';", {},
- function _onRow(record) {
+ await conn.execute(
+ "select email, type from autocrypt_keydata where type = '1';",
+ {},
+ function(record) {
rows.push(record.getResultByName("email"));
- });
+ }
+ );
for (let i in rows) {
- let r = EnigmailRules.getRuleByEmail(`${EnigmailConstants.AC_RULE_PREFIX}${rows[i]}`);
+ let r = EnigmailRules.getRuleByEmail(
+ `${EnigmailConstants.AC_RULE_PREFIX}${rows[i]}`
+ );
if (r) {
await this.setKeyImported(conn, rows[i], "1");
}
-
}
EnigmailLog.DEBUG(`autocrypt.jsm: updateAllImportedKeys done\n`);
conn.close();
- }
- catch (err) {
+ } catch (err) {
EnigmailLog.DEBUG(`autocrypt.jsm: updateAllImportedKeys: error ${err}\n`);
throw err;
}
},
/**
* Find an autocrypt OpenPGP key for a given list of email addresses
* @param emailAddr: Array of String - email addresses
*
* @return Promise(<Array of Object>)
* Object: {fpr, keyData, lastAutocrypt}
*/
- getOpenPGPKeyForEmail: function(emailAddr) {
- EnigmailLog.DEBUG("autocrypt.jsm: getOpenPGPKeyForEmail(" + emailAddr.join(",") + ")\n");
+ getOpenPGPKeyForEmail(emailAddr) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: getOpenPGPKeyForEmail(" + emailAddr.join(",") + ")\n"
+ );
let conn;
return new Promise((resolve, reject) => {
- EnigmailSqliteDb.openDatabase().then(
- function onConnection(connection) {
- conn = connection;
- return findUserRecord(conn, emailAddr, "1,1g");
- },
- function onError(error) {
- EnigmailLog.DEBUG("autocrypt.jsm: getOpenPGPKeyForEmail: could not open database\n");
- reject("getOpenPGPKeyForEmail1 error " + error);
- }
- ).then(
- function gotData(resultObj) {
- EnigmailLog.DEBUG("autocrypt.jsm: getOpenPGPKeyForEmail got " + resultObj.numRows + " rows\n");
+ EnigmailSqliteDb.openDatabase()
+ .then(
+ function(connection) {
+ conn = connection;
+ return findUserRecord(conn, emailAddr, "1,1g");
+ },
+ function(error) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: getOpenPGPKeyForEmail: could not open database\n"
+ );
+ reject("getOpenPGPKeyForEmail1 error " + error);
+ }
+ )
+ .then(function(resultObj) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: getOpenPGPKeyForEmail got " +
+ resultObj.numRows +
+ " rows\n"
+ );
conn.close();
if (resultObj.data.length === 0) {
resolve(null);
- }
- else {
+ } else {
let retArr = [];
for (let i in resultObj.data) {
let record = resultObj.data[i];
retArr.push({
email: record.getResultByName("email"),
fpr: record.getResultByName("fpr"),
keyData: record.getResultByName("keydata"),
state: record.getResultByName("state"),
type: record.getResultByName("type"),
- lastAutocrypt: new Date(record.getResultByName("last_seen_autocrypt"))
+ lastAutocrypt: new Date(
+ record.getResultByName("last_seen_autocrypt")
+ ),
});
}
resolve(retArr);
}
- }
- ).
- catch((err) => {
- conn.close();
- reject("getOpenPGPKeyForEmail: error " + err);
- });
+ })
+ .catch(err => {
+ conn.close();
+ reject("getOpenPGPKeyForEmail: error " + err);
+ });
});
},
/**
* Create Autocrypt Setup Message
*
* @param identity: Object - nsIMsgIdentity
*
@@ -535,56 +625,63 @@ var EnigmailAutocrypt = {
else {
reject(99);
}
});
});
},
*/
-
/**
* get the data of the attachment of a setup message
*
* @param attachmentUrl: String - URL of the attachment
*
* @return Promise(Object):
* attachmentData: String - complete attachment data
* passphraseFormat: String - extracted format from the header (e.g. numeric9x4) [optional]
* passphraseHint: String - 1st two digits of the password [optional]
*/
- getSetupMessageData: function(attachmentUrl) {
+ getSetupMessageData(attachmentUrl) {
EnigmailLog.DEBUG("autocrypt.jsm: getSetupMessageData()\n");
return new Promise((resolve, reject) => {
let s = EnigmailStreams.newStringStreamListener(data => {
let start = {},
end = {};
- let msgType = EnigmailArmor.locateArmoredBlock(data, 0, "", start, end, {});
+ let msgType = EnigmailArmor.locateArmoredBlock(
+ data,
+ 0,
+ "",
+ start,
+ end,
+ {}
+ );
if (msgType === "MESSAGE") {
- EnigmailLog.DEBUG("autocrypt.jsm: getSetupMessageData: got backup key\n");
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: getSetupMessageData: got backup key\n"
+ );
let armorHdr = EnigmailArmor.getArmorHeaders(data);
let passphraseFormat = "generic";
if ("passphrase-format" in armorHdr) {
passphraseFormat = armorHdr["passphrase-format"];
}
let passphraseHint = "";
if ("passphrase-begin" in armorHdr) {
passphraseHint = armorHdr["passphrase-begin"];
}
resolve({
attachmentData: data,
- passphraseFormat: passphraseFormat,
- passphraseHint: passphraseHint
+ passphraseFormat,
+ passphraseHint,
});
- }
- else {
+ } else {
reject("getSetupMessageData");
}
});
let channel = EnigmailStreams.createChannel(attachmentUrl);
channel.asyncOpen(s, null);
});
},
@@ -645,82 +742,98 @@ var EnigmailAutocrypt = {
});
});
},
*/
/**
* Determine if a message id was self-created (only during same TB session)
*/
- isSelfCreatedSetupMessage: function(messageId) {
- return (gCreatedSetupIds.indexOf(messageId) >= 0);
+ isSelfCreatedSetupMessage(messageId) {
+ return gCreatedSetupIds.includes(messageId);
},
/**
* Check if an account is set up with OpenPGP and if the configured key is valid
*
* @param emailAddr: String - email address identifying the account
*
* @return Boolean: true: account is valid / false: OpenPGP not configured or key not valid
*/
- isAccountSetupForPgp: function(emailAddr) {
- let id = EnigmailStdlib.getIdentityForEmail(EnigmailFuncs.stripEmail(emailAddr).toLowerCase());
+ isAccountSetupForPgp(emailAddr) {
+ let id = EnigmailStdlib.getIdentityForEmail(
+ EnigmailFuncs.stripEmail(emailAddr).toLowerCase()
+ );
let keyObj = null;
- if (!(id && id.identity)) return false;
- if (!id.identity.getBoolAttribute("enablePgp")) return false;
+ if (!(id && id.identity)) {
+ return false;
+ }
+ if (!id.identity.getBoolAttribute("enablePgp")) {
+ return false;
+ }
if (id.identity.getIntAttribute("pgpKeyMode") === 1) {
- keyObj = EnigmailKeyRing.getKeyById(id.identity.getCharAttribute("pgpkeyId"));
- }
- else {
+ keyObj = EnigmailKeyRing.getKeyById(
+ id.identity.getCharAttribute("pgpkeyId")
+ );
+ } else {
keyObj = EnigmailKeyRing.getSecretKeyByUserId(emailAddr);
}
- if (!keyObj) return false;
- if (!keyObj.secretAvailable) return false;
+ if (!keyObj) {
+ return false;
+ }
+ if (!keyObj.secretAvailable) {
+ return false;
+ }
let o = keyObj.getEncryptionValidity();
- if (!o.keyValid) return false;
+ if (!o.keyValid) {
+ return false;
+ }
o = keyObj.getSigningValidity();
- if (!o.keyValid) return false;
+ if (!o.keyValid) {
+ return false;
+ }
return true;
},
/**
* Delete the record for a user from the autocrypt keystore
* The record with the highest precedence is deleted (i.e. type=1 before type=1g)
*/
- deleteUser: async function(email, type) {
+ async deleteUser(email, type) {
EnigmailLog.DEBUG(`autocrypt.jsm: deleteUser(${email})\n`);
let conn = await EnigmailSqliteDb.openDatabase();
- let updateStr = "delete from autocrypt_keydata where email = :email and type = :type";
+ let updateStr =
+ "delete from autocrypt_keydata where email = :email and type = :type";
let updateObj = {
- email: email,
- type: type
+ email,
+ type,
};
await new Promise((resolve, reject) => {
- conn.executeTransaction(function _trx() {
- conn.execute(updateStr, updateObj).then(
- function _ok() {
+ conn.executeTransaction(function() {
+ conn
+ .execute(updateStr, updateObj)
+ .then(function() {
resolve();
- }
- ).catch(function _err() {
- reject("update failed");
- });
+ })
+ .catch(function() {
+ reject("update failed");
+ });
});
});
EnigmailLog.DEBUG(" deletion complete\n");
conn.close();
- }
-
+ },
};
/**
* Find the database record for a given email address and type
*
* @param connection: Object - SQLite connection
* @param emails Array of String - Email addresses to search
* @param type: String - types to search (in lowercase), separated by comma
@@ -732,17 +845,17 @@ var EnigmailAutocrypt = {
async function findUserRecord(connection, emails, type) {
EnigmailLog.DEBUG("autocrypt.jsm: findUserRecord\n");
let data = [];
let t = type.split(/[ ,]+/);
let queryParam = {
e0: emails[0],
- t0: t[0]
+ t0: t[0],
};
let numRows = 0;
let search = ":e0";
for (let i = 1; i < emails.length; i++) {
search += ", :e" + i;
queryParam["e" + i] = emails[i].toLowerCase();
@@ -751,31 +864,36 @@ async function findUserRecord(connection
let typeParam = ":t0";
for (let i = 1; i < t.length; i++) {
typeParam += ", :t" + i;
queryParam["t" + i] = t[i];
}
try {
await connection.execute(
- "select * from autocrypt_keydata where email in (" + search + ") and type in (" + typeParam + ") order by email, type", queryParam,
- function _onRow(row) {
+ "select * from autocrypt_keydata where email in (" +
+ search +
+ ") and type in (" +
+ typeParam +
+ ") order by email, type",
+ queryParam,
+ function(row) {
EnigmailLog.DEBUG("autocrypt.jsm: findUserRecord - got row\n");
data.push(row);
++numRows;
- });
- }
- catch (x) {
+ }
+ );
+ } catch (x) {
EnigmailLog.DEBUG(`autocrypt.jsm: findUserRecord: error ${x}\n`);
throw x;
}
return {
- data: data,
- numRows: numRows
+ data,
+ numRows,
};
}
/**
* Create new database record for an Autorypt header
*
* @param connection: Object - SQLite connection
* @param paramsArr: Object - the Autocrypt header parameters
@@ -785,41 +903,44 @@ async function findUserRecord(connection
async function appendUser(connection, paramsArr) {
EnigmailLog.DEBUG("autocrypt.jsm: appendUser(" + paramsArr.addr + ")\n");
if (!("fpr" in paramsArr)) {
await getFprForKey(paramsArr);
}
return new Promise((resolve, reject) => {
-
if (paramsArr.autocryptDate == 0) {
// do not insert record for non-autocrypt mail
resolve();
return;
}
- connection.executeTransaction(function _trx() {
- connection.execute("insert into autocrypt_keydata (email, keydata, fpr, type, last_seen_autocrypt, last_seen, state) values " +
- "(:email, :keyData, :fpr, :type, :lastAutocrypt, :lastSeen, :state)", {
- email: paramsArr.addr.toLowerCase(),
- keyData: paramsArr.keydata,
- fpr: ("fpr" in paramsArr ? paramsArr.fpr : ""),
- type: paramsArr.type,
- lastAutocrypt: paramsArr.dateSent.toJSON(),
- lastSeen: paramsArr.dateSent.toJSON(),
- state: paramsArr["prefer-encrypt"]
- }).then(
- function _ok() {
+ connection.executeTransaction(function() {
+ connection
+ .execute(
+ "insert into autocrypt_keydata (email, keydata, fpr, type, last_seen_autocrypt, last_seen, state) values " +
+ "(:email, :keyData, :fpr, :type, :lastAutocrypt, :lastSeen, :state)",
+ {
+ email: paramsArr.addr.toLowerCase(),
+ keyData: paramsArr.keydata,
+ fpr: "fpr" in paramsArr ? paramsArr.fpr : "",
+ type: paramsArr.type,
+ lastAutocrypt: paramsArr.dateSent.toJSON(),
+ lastSeen: paramsArr.dateSent.toJSON(),
+ state: paramsArr["prefer-encrypt"],
+ }
+ )
+ .then(function() {
EnigmailLog.DEBUG("autocrypt.jsm: appendUser - OK\n");
resolve();
- }
- ).catch(function _err() {
- reject("appendUser");
- });
+ })
+ .catch(function() {
+ reject("appendUser");
+ });
});
});
}
/**
* Update the record for an email address and type, if the email we got is newer
* than the latest record we already stored
*
@@ -829,121 +950,142 @@ async function appendUser(connection, pa
* @param autoCryptEnabled: Boolean: is autocrypt enabled for this transaction
*
* @return Promise
*/
async function updateUser(connection, paramsArr, resultRows, autoCryptEnabled) {
EnigmailLog.DEBUG("autocrypt.jsm: updateUser\n");
let currData = resultRows[0];
- let deferred = PromiseUtils.defer();
+ PromiseUtils.defer();
let lastSeen = new Date(currData.getResultByName("last_seen"));
let lastAutocrypt = new Date(currData.getResultByName("last_seen_autocrypt"));
- let notGossip = (currData.getResultByName("state") !== "gossip");
+ let notGossip = currData.getResultByName("state") !== "gossip";
let currentKeyData = currData.getResultByName("keydata");
- let isKeyInKeyring = (currData.getResultByName("keyring_inserted") === "1");
+ let isKeyInKeyring = currData.getResultByName("keyring_inserted") === "1";
- if (lastSeen >= paramsArr.dateSent ||
- (paramsArr["prefer-encrypt"] === "gossip" && notGossip)) {
- EnigmailLog.DEBUG("autocrypt.jsm: updateUser: not a relevant new latest message\n");
+ if (
+ lastSeen >= paramsArr.dateSent ||
+ (paramsArr["prefer-encrypt"] === "gossip" && notGossip)
+ ) {
+ EnigmailLog.DEBUG(
+ "autocrypt.jsm: updateUser: not a relevant new latest message\n"
+ );
return;
}
EnigmailLog.DEBUG("autocrypt.jsm: updateUser: updating latest message\n");
let updateStr;
let updateObj;
if (paramsArr.autocryptDate > 0) {
lastAutocrypt = paramsArr.autocryptDate;
if (!("fpr" in paramsArr)) {
await getFprForKey(paramsArr);
}
- updateStr = "update autocrypt_keydata set state = :state, keydata = :keyData, last_seen_autocrypt = :lastAutocrypt, " +
+ updateStr =
+ "update autocrypt_keydata set state = :state, keydata = :keyData, last_seen_autocrypt = :lastAutocrypt, " +
"fpr = :fpr, last_seen = :lastSeen where email = :email and type = :type";
updateObj = {
email: paramsArr.addr.toLowerCase(),
state: paramsArr["prefer-encrypt"],
keyData: paramsArr.keydata,
- fpr: ("fpr" in paramsArr ? paramsArr.fpr : ""),
+ fpr: "fpr" in paramsArr ? paramsArr.fpr : "",
type: paramsArr.type,
lastAutocrypt: lastAutocrypt.toJSON(),
- lastSeen: paramsArr.dateSent.toJSON()
+ lastSeen: paramsArr.dateSent.toJSON(),
};
- }
- else {
- updateStr = "update autocrypt_keydata set state = :state, last_seen = :lastSeen where email = :email and type = :type";
+ } else {
+ updateStr =
+ "update autocrypt_keydata set state = :state, last_seen = :lastSeen where email = :email and type = :type";
updateObj = {
email: paramsArr.addr.toLowerCase(),
state: paramsArr["prefer-encrypt"],
type: paramsArr.type,
- lastSeen: paramsArr.dateSent.toJSON()
+ lastSeen: paramsArr.dateSent.toJSON(),
};
}
if (!("fpr" in paramsArr)) {
await getFprForKey(paramsArr);
}
await new Promise((resolve, reject) => {
- connection.executeTransaction(function _trx() {
- connection.execute(updateStr, updateObj).then(
- function _ok() {
+ connection.executeTransaction(function() {
+ connection
+ .execute(updateStr, updateObj)
+ .then(function() {
resolve();
- }
- ).catch(function _err() {
- reject("update failed");
- });
+ })
+ .catch(function() {
+ reject("update failed");
+ });
});
});
- if (autoCryptEnabled && isKeyInKeyring && (currentKeyData !== paramsArr.keydata)) {
- await updateKeyIfNeeded(paramsArr.addr.toLowerCase(), paramsArr.keydata, paramsArr.fpr, paramsArr.type, paramsArr["prefer-encrypt"]);
+ if (
+ autoCryptEnabled &&
+ isKeyInKeyring &&
+ currentKeyData !== paramsArr.keydata
+ ) {
+ await updateKeyIfNeeded(
+ paramsArr.addr.toLowerCase(),
+ paramsArr.keydata,
+ paramsArr.fpr,
+ paramsArr.type,
+ paramsArr["prefer-encrypt"]
+ );
}
-
- return;
}
-
/**
* Determine if a key in the keyring should be replaced by a new (or updated) key
* @param {String} email - Email address
* @param {String} keydata - new keydata to import
* @param {String} fpr - fingerprint of new key
* @param {String} keyType - key type (1 / 1g)
* @param {String} autocryptState - mutual or nopreference
*
* @return {Promise<Boolean>} - key updated
*/
async function updateKeyIfNeeded(email, keydata, fpr, keyType, autocryptState) {
- let ruleNode = EnigmailRules.getRuleByEmail(EnigmailConstants.AC_RULE_PREFIX + email);
- if (!ruleNode) return false;
+ let ruleNode = EnigmailRules.getRuleByEmail(
+ EnigmailConstants.AC_RULE_PREFIX + email
+ );
+ if (!ruleNode) {
+ return false;
+ }
let doImport = false;
let currentKeyId = ruleNode.getAttribute("keyList");
if (`0x${fpr}` === currentKeyId || keyType === "1") {
doImport = true;
- }
- else {
+ } else {
// Gossip keys
let keyObj = EnigmailKeyRing.getKeyById(currentKeyId);
let encOk = keyObj.getEncryptionValidity().keyValid;
if (!encOk) {
// current key is not valid anymore
doImport = true;
}
}
if (doImport) {
- await EnigmailAutocrypt.applyKeyFromKeydata(atob(keydata), email, autocryptState, keyType);
+ await EnigmailAutocrypt.applyKeyFromKeydata(
+ atob(keydata),
+ email,
+ autocryptState,
+ keyType
+ );
}
return doImport;
}
/**
* Set the fpr attribute for a given key parameter object
*/
@@ -960,117 +1102,144 @@ async function getFprForKey(paramsArr) {
for (let k in keyInfo) {
keyArr.push(keyInfo[k]);
}
if (keyArr.length === 1) {
paramsArr.fpr = keyArr[0].fpr;
}
- }
- catch (x) {}
+ } catch (x) {}
}
-
/**
* Create the 9x4 digits backup code as defined in the Autocrypt spec
*
* @return String: xxxx-xxxx-...
*/
-
+/*
function createBackupCode() {
let bkpCode = "";
for (let i = 0; i < 9; i++) {
- if (i > 0) bkpCode += "-";
+ if (i > 0) {
+ bkpCode += "-";
+ }
let a = new Uint8Array(4);
crypto.getRandomValues(a);
for (let j = 0; j < 4; j++) {
bkpCode += String(a[j] % 10);
}
}
return bkpCode;
}
-
function createBackupOuterMsg(toEmail, encryptedMsg) {
-
let boundary = EnigmailMime.createBoundary();
- let msgStr = 'To: ' + toEmail + '\r\n' +
- 'From: ' + toEmail + '\r\n' +
- 'Autocrypt-Setup-Message: v1\r\n' +
- 'Subject: ' + EnigmailLocale.getString("autocrypt.setupMsg.subject") + '\r\n' +
- 'Content-type: multipart/mixed; boundary="' + boundary + '"\r\n\r\n' +
- '--' + boundary + '\r\n' +
- 'Content-Type: text/plain\r\n\r\n' +
- EnigmailLocale.getString("autocryptSetupReq.setupMsg.desc") + '\r\n\r\n' +
- EnigmailLocale.getString("autocrypt.setupMsg.msgBody") + '\r\n\r\n' +
- EnigmailLocale.getString("autocryptSetupReq.setupMsg.backup") + '\r\n' +
- '--' + boundary + '\r\n' +
- 'Content-Type: application/autocrypt-setup\r\n' +
+ let msgStr =
+ "To: " +
+ toEmail +
+ "\r\n" +
+ "From: " +
+ toEmail +
+ "\r\n" +
+ "Autocrypt-Setup-Message: v1\r\n" +
+ "Subject: " +
+ EnigmailLocale.getString("autocrypt.setupMsg.subject") +
+ "\r\n" +
+ 'Content-type: multipart/mixed; boundary="' +
+ boundary +
+ '"\r\n\r\n' +
+ "--" +
+ boundary +
+ "\r\n" +
+ "Content-Type: text/plain\r\n\r\n" +
+ EnigmailLocale.getString("autocryptSetupReq.setupMsg.desc") +
+ "\r\n\r\n" +
+ EnigmailLocale.getString("autocrypt.setupMsg.msgBody") +
+ "\r\n\r\n" +
+ EnigmailLocale.getString("autocryptSetupReq.setupMsg.backup") +
+ "\r\n" +
+ "--" +
+ boundary +
+ "\r\n" +
+ "Content-Type: application/autocrypt-setup\r\n" +
'Content-Disposition: attachment; filename="autocrypt-setup-message.html"\r\n\r\n' +
- '<html><body>\r\n' +
- '<p>' + EnigmailLocale.getString("autocrypt.setupMsg.fileTxt") + '</p>\r\n' +
- '<pre>\r\n' +
+ "<html><body>\r\n" +
+ "<p>" +
+ EnigmailLocale.getString("autocrypt.setupMsg.fileTxt") +
+ "</p>\r\n" +
+ "<pre>\r\n" +
encryptedMsg +
- '</pre></body></html>\r\n' +
- '--' + boundary + '--\r\n';
+ "</pre></body></html>\r\n" +
+ "--" +
+ boundary +
+ "--\r\n";
return msgStr;
}
-
+*/
/**
* @return Object:
* fpr: String - FPR of the imported key
* preferEncrypt: String - Autocrypt preferEncrypt value (e.g. mutual)
*/
+/*
function importSetupKey(keyData) {
-
EnigmailLog.DEBUG("autocrypt.jsm: importSetupKey()\n");
let preferEncrypt = "nopreference"; // Autocrypt default according spec
let start = {},
end = {},
keyObj = {};
- let msgType = EnigmailArmor.locateArmoredBlock(keyData, 0, "", start, end, {});
+ let msgType = EnigmailArmor.locateArmoredBlock(
+ keyData,
+ 0,
+ "",
+ start,
+ end,
+ {}
+ );
if (msgType === "PRIVATE KEY BLOCK") {
-
let headers = EnigmailArmor.getArmorHeaders(keyData);
if ("autocrypt-prefer-encrypt" in headers) {
preferEncrypt = headers["autocrypt-prefer-encrypt"];
}
let r = EnigmailKeyRing.importKey(null, false, keyData, "", {}, keyObj);
if (r === 0 && keyObj.value && keyObj.value.length > 0) {
return {
fpr: keyObj.value[0],
- preferEncrypt: preferEncrypt
+ preferEncrypt,
};
}
}
return null;
}
-
function updateRuleForEmail(email, preferEncrypt, fpr = null) {
- let node = EnigmailRules.getRuleByEmail(EnigmailConstants.AC_RULE_PREFIX + email);
+ let node = EnigmailRules.getRuleByEmail(
+ EnigmailConstants.AC_RULE_PREFIX + email
+ );
if (node) {
- let signEncrypt = (preferEncrypt === "mutual" ? "1" : "0");
+ let signEncrypt = preferEncrypt === "mutual" ? "1" : "0";
- if (node.getAttribute("sign") !== signEncrypt ||
- node.getAttribute("encrypt") !== signEncrypt) {
-
+ if (
+ node.getAttribute("sign") !== signEncrypt ||
+ node.getAttribute("encrypt") !== signEncrypt
+ ) {
node.setAttribute("sign", signEncrypt);
node.setAttribute("encrypt", signEncrypt);
if (fpr) {
node.setAttribute("keyList", `0x${fpr}`);
}
EnigmailRules.saveRulesFile();
}
}
}
+*/
--- a/mail/extensions/openpgp/content/modules/clipboard.jsm
+++ b/mail/extensions/openpgp/content/modules/clipboard.jsm
@@ -5,102 +5,104 @@
*/
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailClipboard"];
// Import the Services module for future use, if we're not in
// a browser window where it's already loaded.
-const Services = ChromeUtils.import('resource://gre/modules/Services.jsm').Services;
-
-
-// Create a constructor for the built-in supports-string class.
-const nsSupportsString = Components.Constructor("@mozilla.org/supports-string;1", "nsISupportsString");
-
-function SupportsString(str) {
- // Create an instance of the supports-string class
- var res = nsSupportsString();
-
- // Store the JavaScript string that we want to wrap in the new nsISupportsString object
- res.data = str;
- return res;
-}
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
// Create a constructor for the built-in transferable class
-const nsTransferable = Components.Constructor("@mozilla.org/widget/transferable;1", "nsITransferable");
+const nsTransferable = Components.Constructor(
+ "@mozilla.org/widget/transferable;1",
+ "nsITransferable"
+);
// Create a wrapper to construct an nsITransferable instance and set its source to the given window, when necessary
function Transferable(source) {
let res = nsTransferable();
- if ('init' in res) {
+ if ("init" in res) {
// When passed a Window object, find a suitable privacy context for it.
- if (source instanceof Ci.nsIDOMWindow)
- source = source.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation);
+ if (source instanceof Ci.nsIDOMWindow) {
+ source = source
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebNavigation);
+ }
res.init(source);
}
return res;
}
var EnigmailClipboard = {
-
/**
* Get the content string of a clipboard
*
* @param window : nsIWindow or nsIDOMWindow of caller
* @param clipBoardType: Number - clipboard type according to nsIClipboard
*
* @return String - content of clipBoard
*/
- getClipboardContent: function(window, clipBoardType) {
+ getClipboardContent(window, clipBoardType) {
if (!window) {
throw new Error("window is a required parameter");
}
- let clipBoard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
+ let clipBoard = Services.clipboard;
let data = {};
let cBoardContent = "";
- if (clipBoardType !== clipBoard.kSelectionClipboard || clipBoard.supportsSelectionClipboard()) {
+ if (
+ clipBoardType !== clipBoard.kSelectionClipboard ||
+ clipBoard.supportsSelectionClipboard()
+ ) {
try {
let transferable = Transferable(window);
transferable.addDataFlavor("text/unicode");
clipBoard.getData(transferable, clipBoardType);
let flavour = {};
transferable.getAnyTransferData(flavour, data);
cBoardContent = data.value.QueryInterface(Ci.nsISupportsString).data;
- }
- catch (ex) {}
+ } catch (ex) {}
}
return cBoardContent;
},
/**
* Set the global (and if available, the selection clipboard)
*
* @param str: String - data to set
* @param clipBoardType: Number - clipboard type according to nsIClipboard.
* If not provided, the global plus the selection clipboard will be used
*
* @return Boolean: true - success / false - failure
*/
- setClipboardContent: function(str, clipBoardType) {
+ setClipboardContent(str, clipBoardType) {
let useClipboard = clipBoardType;
if (clipBoardType === undefined) {
useClipboard = Ci.nsIClipboard.kGlobalClipboard;
}
try {
- let clipBoard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
- let clipBoardHlp = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
+ let clipBoard = Services.clipboard;
+ let clipBoardHlp = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(
+ Ci.nsIClipboardHelper
+ );
clipBoardHlp.copyStringToClipboard(str, useClipboard);
- if (clipBoard.supportsSelectionClipboard() &&
- (useClipboard === Ci.nsIClipboard.kSelectionClipboard || clipBoardType === undefined)) {
- clipBoardHlp.copyStringToClipboard(str, Ci.nsIClipboard.kSelectionClipboard);
+ if (
+ clipBoard.supportsSelectionClipboard() &&
+ (useClipboard === Ci.nsIClipboard.kSelectionClipboard ||
+ clipBoardType === undefined)
+ ) {
+ clipBoardHlp.copyStringToClipboard(
+ str,
+ Ci.nsIClipboard.kSelectionClipboard
+ );
}
- }
- catch (ex) {
+ } catch (ex) {
return false;
}
return true;
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/commandLine.jsm
+++ b/mail/extensions/openpgp/content/modules/commandLine.jsm
@@ -1,47 +1,60 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailCommandLine"];
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
+const EnigmailCompat = ChromeUtils.import(
+ "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
-const NS_ENIGCLINE_SERVICE_CID = Components.ID("{847b3ab1-7ab1-11d4-8f02-006008948af5}");
+const NS_ENIGCLINE_SERVICE_CID = Components.ID(
+ "{847b3ab1-7ab1-11d4-8f02-006008948af5}"
+);
const NS_CLINE_SERVICE_CONTRACTID = "@mozilla.org/enigmail/cline-handler;1";
function Handler() {}
Handler.prototype = {
classDescription: "Enigmail Key Management CommandLine Service",
classID: NS_ENIGCLINE_SERVICE_CID,
contractID: NS_CLINE_SERVICE_CONTRACTID,
- QueryInterface: EnigmailCompat.generateQI(["nsICommandLineHandler", "nsIFactory"]),
+ QueryInterface: EnigmailCompat.generateQI([
+ "nsICommandLineHandler",
+ "nsIFactory",
+ ]),
// nsICommandLineHandler
- handle: function(cmdLine) {
+ handle(cmdLine) {
if (cmdLine.handleFlag("pgpkeyman", false)) {
cmdLine.preventDefault = true; // do not open main app window
- const wwatch = Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher);
- wwatch.openWindow(null, "chrome://openpgp/content/ui/enigmailKeyManager.xhtml", "_blank", "chrome,dialog=no,all", cmdLine);
+ Services.ww.openWindow(
+ null,
+ "chrome://openpgp/content/ui/enigmailKeyManager.xhtml",
+ "_blank",
+ "chrome,dialog=no,all",
+ cmdLine
+ );
}
},
helpInfo: " -pgpkeyman Open the OpenPGP key management.\n",
- lockFactory: function(lock) {}
+ lockFactory(lock) {},
};
var EnigmailCommandLine = {
- Handler: Handler,
+ Handler,
categoryRegistry: {
category: "command-line-handler",
entry: "m-cline-enigmail",
- serviceName: NS_CLINE_SERVICE_CONTRACTID
- }
+ serviceName: NS_CLINE_SERVICE_CONTRACTID,
+ },
};
--- a/mail/extensions/openpgp/content/modules/compat.jsm
+++ b/mail/extensions/openpgp/content/modules/compat.jsm
@@ -5,99 +5,113 @@
"use strict";
/**
* compatibility Module
*/
var EXPORTED_SYMBOLS = ["EnigmailCompat"];
-const XPCOM_APPINFO = "@mozilla.org/xre/app-info;1";
-
var MailUtils;
MailUtils = ChromeUtils.import("resource:///modules/MailUtils.jsm").MailUtils;
-var gCompFields, gPgpMimeObj;
-
var EnigmailCompat = {
- generateQI: function(aCid) {
+ generateQI(aCid) {
return ChromeUtils.generateQI(aCid);
},
- getExistingFolder: function(folderUri) {
+ getExistingFolder(folderUri) {
return MailUtils.getExistingFolder(folderUri);
},
/**
* Get a mail URL from a uriSpec
*
* @param uriSpec: String - URI of the desired message
*
* @return Object: nsIURL or nsIMsgMailNewsUrl object
*/
- getUrlFromUriSpec: function(uriSpec) {
+ getUrlFromUriSpec(uriSpec) {
try {
- if (!uriSpec)
+ if (!uriSpec) {
return null;
+ }
- let messenger = Cc["@mozilla.org/messenger;1"].getService(Ci.nsIMessenger);
+ let messenger = Cc["@mozilla.org/messenger;1"].getService(
+ Ci.nsIMessenger
+ );
let msgService = messenger.messageServiceFromURI(uriSpec);
let url;
// TB
let urlObj = {};
msgService.GetUrlForUri(uriSpec, urlObj, null);
url = urlObj.value;
if (url.scheme == "file") {
return url;
}
- else {
- return url.QueryInterface(Ci.nsIMsgMailNewsUrl);
- }
- }
- catch (ex) {
+ return url.QueryInterface(Ci.nsIMsgMailNewsUrl);
+ } catch (ex) {
return null;
}
},
/**
* Copy a file to a mail folder.
* in nsIFile aFile,
* in nsIMsgFolder dstFolder,
* in unsigned long aMsgFlags,
* in ACString aMsgKeywords,
* in nsIMsgCopyServiceListener listener,
* in nsIMsgWindow msgWindow
*/
- copyFileToMailFolder: function(file, destFolder, msgFlags, msgKeywords, listener, msgWindow) {
- let copySvc = Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(Ci.nsIMsgCopyService);
+ copyFileToMailFolder(
+ file,
+ destFolder,
+ msgFlags,
+ msgKeywords,
+ listener,
+ msgWindow
+ ) {
+ let copySvc = Cc["@mozilla.org/messenger/messagecopyservice;1"].getService(
+ Ci.nsIMsgCopyService
+ );
- return copySvc.CopyFileMessage(file, destFolder, null, false, msgFlags, msgKeywords, listener, msgWindow);
+ return copySvc.CopyFileMessage(
+ file,
+ destFolder,
+ null,
+ false,
+ msgFlags,
+ msgKeywords,
+ listener,
+ msgWindow
+ );
},
/**
* Get functions that wrap the changes on nsITreeView between TB 60 and TB 68
*
* @param treeObj
* @param listViewHolder
*
* @return {Object}
*/
- getTreeCompatibleFuncs: function(treeObj, listViewHolder) {
+ getTreeCompatibleFuncs(treeObj, listViewHolder) {
return {
- getCellAt: function(x,y) {
+ getCellAt(x, y) {
return treeObj.getCellAt(x, y);
},
- rowCountChanged: function(a, b) {
+ rowCountChanged(a, b) {
return treeObj.rowCountChanged(a, b);
},
- invalidate: function() {
+ invalidate() {
return treeObj.invalidate();
},
- invalidateRow: function(r) {
+ invalidateRow(r) {
return treeObj.invalidateRow(r);
- }
+ },
};
},
};
--- a/mail/extensions/openpgp/content/modules/configBackup.jsm
+++ b/mail/extensions/openpgp/content/modules/configBackup.jsm
@@ -1,99 +1,106 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailConfigBackup"];
-
-
-
-
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailRules = ChromeUtils.import("chrome://openpgp/content/modules/rules.jsm").EnigmailRules;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailRules = ChromeUtils.import(
+ "chrome://openpgp/content/modules/rules.jsm"
+).EnigmailRules;
+const EnigmailFiles = ChromeUtils.import(
+ "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailPrefs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
const TYPE_BOOL = 1;
const TYPE_CHAR = 2;
const TYPE_INT = 3;
const IdentityPref = {
enablePgp: TYPE_BOOL,
pgpkeyId: TYPE_CHAR,
pgpKeyMode: TYPE_INT,
pgpSignPlain: TYPE_BOOL,
pgpSignEncrypted: TYPE_BOOL,
defaultSigningPolicy: TYPE_INT,
defaultEncryptionPolicy: TYPE_INT,
openPgpUrlName: TYPE_CHAR,
pgpMimeMode: TYPE_BOOL,
attachPgpKey: TYPE_BOOL,
- autoEncryptDrafts: TYPE_BOOL
+ autoEncryptDrafts: TYPE_BOOL,
};
var EnigmailConfigBackup = {
-
- getAccountManager: function() {
- let amService = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+ getAccountManager() {
+ let amService = Cc["@mozilla.org/messenger/account-manager;1"].getService(
+ Ci.nsIMsgAccountManager
+ );
return amService;
},
/**
* itereate over all identities and execute a callback function for each found element
*
* @param callbackFunc function - the callback for each identity
* The function takes the identity as 1st argument, i.e.
* callbackFunc(nsIMsgIdentity)
* @return - undefined
*/
- forAllIdentitites: function(callbackFunc) {
-
+ forAllIdentitites(callbackFunc) {
let amService = this.getAccountManager();
amService.LoadAccounts(); // ensure accounts are really loaded
let a = amService.allIdentities;
for (let i = 0; i < a.length; i++) {
let id = a.queryElementAt(i, Ci.nsIMsgIdentity);
try {
callbackFunc(id);
- }
- catch (ex) {
- EnigmailLog.DEBUG("configBackup.jsm: forAllIdentitites: exception " + ex.toString() + "\n");
+ } catch (ex) {
+ EnigmailLog.DEBUG(
+ "configBackup.jsm: forAllIdentitites: exception " +
+ ex.toString() +
+ "\n"
+ );
}
}
},
/**
* backup Enigmail preferences to a file
*
* @param outputFile nsIFile - handle to file to be saved
*
* @return 0: success, other values: failure
*/
- backupPrefs: function(outputFile) {
+ backupPrefs(outputFile) {
EnigmailLog.DEBUG("configBackup.jsm: backupPrefs\n");
// user preference
let prefObj = {
enigmailPrefs: EnigmailPrefs.getAllPrefs(),
- mailIdentities: {}
+ mailIdentities: {},
};
function getIdentityPrefs(identity) {
-
- if (!identity.getBoolAttribute("enablePgp")) return; // do nothing if Enigmail disabled
+ if (!identity.getBoolAttribute("enablePgp")) {
+ return;
+ } // do nothing if Enigmail disabled
let keyObj = {
emailAddress: identity.email.toLowerCase(),
- identityName: identity.identityName
+ identityName: identity.identityName,
};
for (let pref in IdentityPref) {
switch (IdentityPref[pref]) {
case TYPE_BOOL:
keyObj[pref] = identity.getBoolAttribute(pref);
break;
case TYPE_INT:
@@ -131,28 +138,35 @@ var EnigmailConfigBackup = {
*
* @param inputFile nsIFile - handle to file to be saved
*
* @return Object: {
* retVal: Number - 0: success, other values: failure
* unmatchedIds: Array (String): keys of identities
* }
*/
- restorePrefs: function(inputFile) {
+ restorePrefs(inputFile) {
EnigmailLog.DEBUG("configBackup.jsm: restorePrefs\n");
var prefObj;
var returnObj = {
retVal: -1,
- unmatchedIds: []
+ unmatchedIds: [],
};
function setIdentityPref(identity) {
for (let k in prefObj.mailIdentities) {
- if (prefObj.mailIdentities[k].emailAddress === identity.email.toLowerCase()) {
- EnigmailLog.DEBUG("configBackup.jsm: setIdentityPref: restoring values for " + identity.email + "\n");
+ if (
+ prefObj.mailIdentities[k].emailAddress ===
+ identity.email.toLowerCase()
+ ) {
+ EnigmailLog.DEBUG(
+ "configBackup.jsm: setIdentityPref: restoring values for " +
+ identity.email +
+ "\n"
+ );
prefObj.mailIdentities[k].foundMatchingEmail = true;
let keyObj = prefObj.mailIdentities[k];
for (let pref in IdentityPref) {
switch (IdentityPref[pref]) {
case TYPE_BOOL:
identity.setBoolAttribute(pref, keyObj[pref]);
break;
case TYPE_INT:
@@ -162,27 +176,28 @@ var EnigmailConfigBackup = {
identity.setCharAttribute(pref, keyObj[pref]);
break;
}
}
return;
}
}
- EnigmailLog.DEBUG("configBackup.jsm: setIdentityPref: no matching data for " + identity.email + "\n");
+ EnigmailLog.DEBUG(
+ "configBackup.jsm: setIdentityPref: no matching data for " +
+ identity.email +
+ "\n"
+ );
}
// Profile must be a single UTF-8 encoded JSON object.
try {
let jsonStr = EnigmailFiles.readFile(inputFile);
prefObj = JSON.parse(jsonStr);
- var nsIPB = Ci.nsIPrefBranch;
- var branch = EnigmailPrefs.getPrefBranch();
-
// Set all options recorded in the JSON file.
for (let name in prefObj.enigmailPrefs) {
EnigmailPrefs.setPref(name, prefObj.enigmailPrefs[name]);
}
this.forAllIdentitites(setIdentityPref);
for (let i in prefObj.mailIdentities) {
@@ -194,20 +209,19 @@ var EnigmailConfigBackup = {
let am = this.getAccountManager();
am.saveAccountInfo();
EnigmailPrefs.savePrefs();
if ("rules" in prefObj) {
EnigmailRules.loadRulesFromString(prefObj.rules);
EnigmailRules.saveRulesFile();
}
-
- }
- catch (ex) {
- EnigmailLog.ERROR("configBackup.jsm: restorePrefs - exception " + ex.toString() + "\n");
+ } catch (ex) {
+ EnigmailLog.ERROR(
+ "configBackup.jsm: restorePrefs - exception " + ex.toString() + "\n"
+ );
return returnObj;
}
returnObj.retVal = 0;
return returnObj;
- }
-
+ },
};
--- a/mail/extensions/openpgp/content/modules/configure.jsm
+++ b/mail/extensions/openpgp/content/modules/configure.jsm
@@ -3,45 +3,75 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailConfigure"];
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailStdlib = ChromeUtils.import("chrome://openpgp/content/modules/stdlib.jsm").EnigmailStdlib;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailAutoSetup = ChromeUtils.import("chrome://openpgp/content/modules/autoSetup.jsm").EnigmailAutoSetup;
-const EnigmailSqliteDb = ChromeUtils.import("chrome://openpgp/content/modules/sqliteDb.jsm").EnigmailSqliteDb;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
-// Interfaces
-const nsIFolderLookupService = Ci.nsIFolderLookupService;
-const nsIMsgAccountManager = Ci.nsIMsgAccountManager;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailPrefs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailTimer = ChromeUtils.import(
+ "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
+const EnigmailApp = ChromeUtils.import(
+ "chrome://openpgp/content/modules/app.jsm"
+).EnigmailApp;
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailDialog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailWindows = ChromeUtils.import(
+ "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailCore = ChromeUtils.import(
+ "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailStdlib = ChromeUtils.import(
+ "chrome://openpgp/content/modules/stdlib.jsm"
+).EnigmailStdlib;
+const EnigmailLazy = ChromeUtils.import(
+ "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const EnigmailAutoSetup = ChromeUtils.import(
+ "chrome://openpgp/content/modules/autoSetup.jsm"
+).EnigmailAutoSetup;
/**
* Upgrade sending prefs
* (v1.6.x -> v1.7 )
*/
function upgradePrefsSending() {
EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending()\n");
var cbs = EnigmailPrefs.getPref("confirmBeforeSend");
var ats = EnigmailPrefs.getPref("alwaysTrustSend");
var ksfr = EnigmailPrefs.getPref("keepSettingsForReply");
- EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending cbs=" + cbs + " ats=" + ats + " ksfr=" + ksfr + "\n");
+ EnigmailLog.DEBUG(
+ "enigmailCommon.jsm: upgradePrefsSending cbs=" +
+ cbs +
+ " ats=" +
+ ats +
+ " ksfr=" +
+ ksfr +
+ "\n"
+ );
// Upgrade confirmBeforeSend (bool) to confirmBeforeSending (int)
switch (cbs) {
case false:
EnigmailPrefs.setPref("confirmBeforeSending", 0); // never
break;
case true:
EnigmailPrefs.setPref("confirmBeforeSending", 1); // always
@@ -56,246 +86,260 @@ function upgradePrefsSending() {
case true:
EnigmailPrefs.setPref("acceptedKeys", 1); // all
break;
}
// if all settings are default settings, use convenient encryption
if (cbs === false && ats === true && ksfr === true) {
EnigmailPrefs.setPref("encryptionModel", 0); // convenient
- EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending() encryptionModel=0 (convenient)\n");
- }
- else {
+ EnigmailLog.DEBUG(
+ "enigmailCommon.jsm: upgradePrefsSending() encryptionModel=0 (convenient)\n"
+ );
+ } else {
EnigmailPrefs.setPref("encryptionModel", 1); // manually
- EnigmailLog.DEBUG("enigmailCommon.jsm: upgradePrefsSending() encryptionModel=1 (manually)\n");
+ EnigmailLog.DEBUG(
+ "enigmailCommon.jsm: upgradePrefsSending() encryptionModel=1 (manually)\n"
+ );
}
// clear old prefs
EnigmailPrefs.getPrefBranch().clearUserPref("confirmBeforeSend");
EnigmailPrefs.getPrefBranch().clearUserPref("alwaysTrustSend");
}
/**
* Replace short key IDs with FPR in identity settings
* (v1.9 -> v2.0)
*/
function replaceKeyIdWithFpr() {
try {
- const GetKeyRing = EnigmailLazy.loader("enigmail/keyRing.jsm", "EnigmailKeyRing");
+ const GetKeyRing = EnigmailLazy.loader(
+ "enigmail/keyRing.jsm",
+ "EnigmailKeyRing"
+ );
- var accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+ var accountManager = Cc[
+ "@mozilla.org/messenger/account-manager;1"
+ ].getService(Ci.nsIMsgAccountManager);
for (var i = 0; i < accountManager.allIdentities.length; i++) {
- var id = accountManager.allIdentities.queryElementAt(i, Ci.nsIMsgIdentity);
+ var id = accountManager.allIdentities.queryElementAt(
+ i,
+ Ci.nsIMsgIdentity
+ );
if (id.getBoolAttribute("enablePgp")) {
let keyId = id.getCharAttribute("pgpkeyId");
if (keyId.search(/^(0x)?[a-fA-F0-9]{8}$/) === 0) {
-
EnigmailCore.getService();
let k = GetKeyRing().getKeyById(keyId);
if (k) {
id.setCharAttribute("pgpkeyId", "0x" + k.fpr);
- }
- else {
+ } else {
id.setCharAttribute("pgpkeyId", "");
}
}
}
}
- }
- catch (ex) {
+ } catch (ex) {
EnigmailDialog.alert("config upgrade: error" + ex.toString());
}
}
-
/**
* Change the default to PGP/MIME for all accounts, except nntp
* (v1.8.x -> v1.9)
*/
function defaultPgpMime() {
- let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+ let accountManager = Cc[
+ "@mozilla.org/messenger/account-manager;1"
+ ].getService(Ci.nsIMsgAccountManager);
let changedSomething = false;
for (let acct = 0; acct < accountManager.accounts.length; acct++) {
let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);
if (ac.incomingServer.type.search(/(pop3|imap|movemail)/) >= 0) {
-
for (let i = 0; i < ac.identities.length; i++) {
let id = ac.identities.queryElementAt(i, Ci.nsIMsgIdentity);
- if (id.getBoolAttribute("enablePgp") && !id.getBoolAttribute("pgpMimeMode")) {
+ if (
+ id.getBoolAttribute("enablePgp") &&
+ !id.getBoolAttribute("pgpMimeMode")
+ ) {
changedSomething = true;
}
id.setBoolAttribute("pgpMimeMode", true);
}
}
}
if (EnigmailPrefs.getPref("advancedUser") && changedSomething) {
- EnigmailDialog.alert(null,
- EnigmailLocale.getString("preferences.defaultToPgpMime"));
+ EnigmailDialog.alert(
+ null,
+ EnigmailLocale.getString("preferences.defaultToPgpMime")
+ );
}
}
/**
* set the Autocrypt prefer-encrypt option to "mutual" for all existing
* accounts
*/
function setAutocryptForOldAccounts() {
try {
- let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
- let changedSomething = false;
+ let accountManager = Cc[
+ "@mozilla.org/messenger/account-manager;1"
+ ].getService(Ci.nsIMsgAccountManager);
for (let acct = 0; acct < accountManager.accounts.length; acct++) {
let ac = accountManager.accounts.queryElementAt(acct, Ci.nsIMsgAccount);
if (ac.incomingServer.type.search(/(pop3|imap|movemail)/) >= 0) {
ac.incomingServer.setIntValue("acPreferEncrypt", 1);
}
}
- }
- catch (ex) {}
+ } catch (ex) {}
}
function setDefaultKeyServer() {
EnigmailLog.DEBUG("configure.jsm: setDefaultKeyServer()\n");
let ks = EnigmailPrefs.getPref("keyserver");
if (ks.search(/^ldaps?:\/\//) < 0) {
ks = "vks://keys.openpgp.org, " + ks;
}
ks = ks.replace(/hkps:\/\/keys.openpgp.org/g, "vks://keys.openpgp.org");
EnigmailPrefs.setPref("keyserver", ks);
}
-
-
function displayUpgradeInfo() {
EnigmailLog.DEBUG("configure.jsm: displayUpgradeInfo()\n");
try {
EnigmailWindows.openMailTab("chrome://openpgp/content/ui/upgradeInfo.html");
- }
- catch (ex) {}
+ } catch (ex) {}
}
-
var EnigmailConfigure = {
/**
* configureEnigmail: main function for configuring Enigmail during the first run
* this method is called from core.jsm if Enigmail has not been set up before
* (determined via checking the configuredVersion in the preferences)
*
* @param {nsIWindow} win: The parent window. Null if no parent window available
* @param {Boolean} startingPreferences: if true, called while switching to new preferences
* (to avoid re-check for preferences)
*
* @return {Promise<null>}
*/
- configureEnigmail: async function(win, startingPreferences) {
+ async configureEnigmail(win, startingPreferences) {
EnigmailLog.DEBUG("configure.jsm: configureEnigmail()\n");
if (!EnigmailStdlib.hasConfiguredAccounts()) {
- EnigmailLog.DEBUG("configure.jsm: configureEnigmail: no account configured. Waiting 60 seconds.\n");
+ EnigmailLog.DEBUG(
+ "configure.jsm: configureEnigmail: no account configured. Waiting 60 seconds.\n"
+ );
// try again in 60 seconds
- EnigmailTimer.setTimeout(
- function _f() {
- EnigmailConfigure.configureEnigmail(win, startingPreferences);
- },
- 60000);
+ EnigmailTimer.setTimeout(function() {
+ EnigmailConfigure.configureEnigmail(win, startingPreferences);
+ }, 60000);
return;
}
let oldVer = EnigmailPrefs.getPref("configuredVersion");
- let vc = Cc["@mozilla.org/xpcom/version-comparator;1"].getService(Ci.nsIVersionComparator);
-
if (oldVer === "") {
try {
- let setupResult = await EnigmailAutoSetup.determinePreviousInstallType();
+ await EnigmailAutoSetup.determinePreviousInstallType();
switch (EnigmailAutoSetup.value) {
case EnigmailConstants.AUTOSETUP_NOT_INITIALIZED:
case EnigmailConstants.AUTOSETUP_NO_ACCOUNT:
break;
default:
- EnigmailPrefs.setPref("configuredVersion", EnigmailApp.getVersion());
+ EnigmailPrefs.setPref(
+ "configuredVersion",
+ EnigmailApp.getVersion()
+ );
EnigmailWindows.openSetupWizard(win);
}
- }
- catch(x) {
+ } catch (x) {
// ignore exceptions and proceed without setup wizard
}
- }
- else {
- if (vc.compare(oldVer, "1.7a1pre") < 0) {
+ } else {
+ if (Services.vc.compare(oldVer, "1.7a1pre") < 0) {
// 1: rules only
// => assignKeysByRules true; rest false
// 2: rules & email addresses (normal)
// => assignKeysByRules/assignKeysByEmailAddr/assignKeysManuallyIfMissing true
// 3: email address only (no rules)
// => assignKeysByEmailAddr/assignKeysManuallyIfMissing true
// 4: manually (always prompt, no rules)
// => assignKeysManuallyAlways true
// 5: no rules, no key selection
// => assignKeysByRules/assignKeysByEmailAddr true
upgradePrefsSending();
}
- if (vc.compare(oldVer, "1.7") < 0) {
+ if (Services.vc.compare(oldVer, "1.7") < 0) {
// open a modal dialog. Since this might happen during the opening of another
// window, we have to do this asynchronously
- EnigmailTimer.setTimeout(
- function _cb() {
- var doIt = EnigmailDialog.confirmDlg(win,
- EnigmailLocale.getString("enigmailCommon.versionSignificantlyChanged"),
- EnigmailLocale.getString("enigmailCommon.checkPreferences"),
- EnigmailLocale.getString("dlg.button.close"));
- if (!startingPreferences && doIt) {
- // same as:
- // - EnigmailWindows.openPrefWindow(window, true, 'sendingTab');
- // but
- // - without starting the service again because we do that right now
- // - and modal (waiting for its end)
- win.openDialog("chrome://openpgp/content/ui/pref-enigmail.xhtml",
- "_blank", "chrome,resizable=yes,modal", {
- 'showBasic': true,
- 'clientType': 'thunderbird',
- 'selectTab': 'sendingTab'
- });
- }
- }, 100);
+ EnigmailTimer.setTimeout(function() {
+ var doIt = EnigmailDialog.confirmDlg(
+ win,
+ EnigmailLocale.getString(
+ "enigmailCommon.versionSignificantlyChanged"
+ ),
+ EnigmailLocale.getString("enigmailCommon.checkPreferences"),
+ EnigmailLocale.getString("dlg.button.close")
+ );
+ if (!startingPreferences && doIt) {
+ // same as:
+ // - EnigmailWindows.openPrefWindow(window, true, 'sendingTab');
+ // but
+ // - without starting the service again because we do that right now
+ // - and modal (waiting for its end)
+ win.openDialog(
+ "chrome://openpgp/content/ui/pref-enigmail.xhtml",
+ "_blank",
+ "chrome,resizable=yes,modal",
+ {
+ showBasic: true,
+ clientType: "thunderbird",
+ selectTab: "sendingTab",
+ }
+ );
+ }
+ }, 100);
}
- if (vc.compare(oldVer, "1.9a2pre") < 0) {
+ if (Services.vc.compare(oldVer, "1.9a2pre") < 0) {
defaultPgpMime();
}
- if (vc.compare(oldVer, "2.0a1pre") < 0) {
+ if (Services.vc.compare(oldVer, "2.0a1pre") < 0) {
this.upgradeTo20();
}
- if (vc.compare(oldVer, "2.0.1a2pre") < 0) {
+ if (Services.vc.compare(oldVer, "2.0.1a2pre") < 0) {
this.upgradeTo201();
}
- if (vc.compare(oldVer, "2.1b2") < 0) {
+ if (Services.vc.compare(oldVer, "2.1b2") < 0) {
this.upgradeTo21();
}
-
}
EnigmailPrefs.setPref("configuredVersion", EnigmailApp.getVersion());
EnigmailPrefs.savePrefs();
},
- upgradeTo20: function() {
+ upgradeTo20() {
replaceKeyIdWithFpr();
displayUpgradeInfo();
},
- upgradeTo201: function() {
+ upgradeTo201() {
setAutocryptForOldAccounts();
},
- upgradeTo21: function() {
+ upgradeTo21() {
setDefaultKeyServer();
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/constants.jsm
+++ b/mail/extensions/openpgp/content/modules/constants.jsm
@@ -1,15 +1,14 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailConstants"];
var EnigmailConstants = {
POSSIBLE_PGPMIME: -2081,
// possible values for
@@ -157,10 +156,10 @@ var EnigmailConstants = {
/* Bootstrapped Addon constants */
APP_STARTUP: 1, // The application is starting up.
APP_SHUTDOWN: 2, // The application is shutting down.
ADDON_ENABLE: 3, // The add-on is being enabled.
ADDON_DISABLE: 4, // The add-on is being disabled. (Also sent during uninstallation)
ADDON_INSTALL: 5, // The add-on is being installed.
ADDON_UNINSTALL: 6, // The add-on is being uninstalled.
ADDON_UPGRADE: 7, // The add-on is being upgraded.
- ADDON_DOWNGRADE: 8 // The add-on is being downgraded.
+ ADDON_DOWNGRADE: 8, // The add-on is being downgraded.
};
--- a/mail/extensions/openpgp/content/modules/core.jsm
+++ b/mail/extensions/openpgp/content/modules/core.jsm
@@ -1,74 +1,109 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
-const {
- manager: Cm,
- Constructor: CC
-} = Components;
+const { manager: Cm } = Components;
Cm.QueryInterface(Ci.nsIComponentRegistrar);
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
+const EnigmailLazy = ChromeUtils.import(
+ "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
// load all modules lazily to avoid possible cross-reference errors
-const getEnigmailConsole = EnigmailLazy.loader("enigmail/pipeConsole.jsm", "EnigmailConsole");
-const getEnigmailMimeEncrypt = EnigmailLazy.loader("enigmail/mimeEncrypt.jsm", "EnigmailMimeEncrypt");
-const getEnigmailProtocolHandler = EnigmailLazy.loader("enigmail/protocolHandler.jsm", "EnigmailProtocolHandler");
-const getEnigmailFiltersWrapper = EnigmailLazy.loader("enigmail/filtersWrapper.jsm", "EnigmailFiltersWrapper");
+const getEnigmailConsole = EnigmailLazy.loader(
+ "enigmail/pipeConsole.jsm",
+ "EnigmailConsole"
+);
+const getEnigmailMimeEncrypt = EnigmailLazy.loader(
+ "enigmail/mimeEncrypt.jsm",
+ "EnigmailMimeEncrypt"
+);
+const getEnigmailProtocolHandler = EnigmailLazy.loader(
+ "enigmail/protocolHandler.jsm",
+ "EnigmailProtocolHandler"
+);
+const getEnigmailFiltersWrapper = EnigmailLazy.loader(
+ "enigmail/filtersWrapper.jsm",
+ "EnigmailFiltersWrapper"
+);
const getEnigmailLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
-const getEnigmailOS = EnigmailLazy.loader("enigmail/os.jsm", "EnigmailOS");
-const getEnigmailLocale = EnigmailLazy.loader("enigmail/locale.jsm", "EnigmailLocale");
-const getEnigmailCommandLine = EnigmailLazy.loader("enigmail/commandLine.jsm", "EnigmailCommandLine");
-const getEnigmailPrefs = EnigmailLazy.loader("enigmail/prefs.jsm", "EnigmailPrefs");
-const getEnigmailVerify = EnigmailLazy.loader("enigmail/mimeVerify.jsm", "EnigmailVerify");
-const getEnigmailWindows = EnigmailLazy.loader("enigmail/windows.jsm", "EnigmailWindows");
-const getEnigmailDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
-const getEnigmailConfigure = EnigmailLazy.loader("enigmail/configure.jsm", "EnigmailConfigure");
+const getEnigmailLocale = EnigmailLazy.loader(
+ "enigmail/locale.jsm",
+ "EnigmailLocale"
+);
+const getEnigmailCommandLine = EnigmailLazy.loader(
+ "enigmail/commandLine.jsm",
+ "EnigmailCommandLine"
+);
+const getEnigmailPrefs = EnigmailLazy.loader(
+ "enigmail/prefs.jsm",
+ "EnigmailPrefs"
+);
+const getEnigmailVerify = EnigmailLazy.loader(
+ "enigmail/mimeVerify.jsm",
+ "EnigmailVerify"
+);
+const getEnigmailWindows = EnigmailLazy.loader(
+ "enigmail/windows.jsm",
+ "EnigmailWindows"
+);
+const getEnigmailDialog = EnigmailLazy.loader(
+ "enigmail/dialog.jsm",
+ "EnigmailDialog"
+);
+const getEnigmailConfigure = EnigmailLazy.loader(
+ "enigmail/configure.jsm",
+ "EnigmailConfigure"
+);
const getEnigmailApp = EnigmailLazy.loader("enigmail/app.jsm", "EnigmailApp");
-const getEnigmailKeyRefreshService = EnigmailLazy.loader("enigmail/keyRefreshService.jsm", "EnigmailKeyRefreshService");
-const getEnigmailKeyServer = EnigmailLazy.loader("enigmail/keyserver.jsm", "EnigmailKeyServer");
-const getEnigmailWksMimeHandler = EnigmailLazy.loader("enigmail/wksMimeHandler.jsm", "EnigmailWksMimeHandler");
+const getEnigmailWksMimeHandler = EnigmailLazy.loader(
+ "enigmail/wksMimeHandler.jsm",
+ "EnigmailWksMimeHandler"
+);
//const getEnigmailOverlays = EnigmailLazy.loader("enigmail/enigmailOverlays.jsm", "EnigmailOverlays");
-const getEnigmailSqlite = EnigmailLazy.loader("enigmail/sqliteDb.jsm", "EnigmailSqliteDb");
-const getEnigmailTimer = EnigmailLazy.loader("enigmail/timer.jsm", "EnigmailTimer");
-const getOpenPGPMasterpass = EnigmailLazy.loader("enigmail/masterpass.jsm", "OpenPGPMasterpass");
-const Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
+const getEnigmailSqlite = EnigmailLazy.loader(
+ "enigmail/sqliteDb.jsm",
+ "EnigmailSqliteDb"
+);
+const getOpenPGPMasterpass = EnigmailLazy.loader(
+ "enigmail/masterpass.jsm",
+ "OpenPGPMasterpass"
+);
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
var EXPORTED_SYMBOLS = ["EnigmailCore"];
// Interfaces
const nsIEnvironment = Ci.nsIEnvironment;
-var gPreferredGpgPath = null;
var gOverwriteEnvVar = [];
var gEnigmailService = null; // Global Enigmail Service
var gEnvList = null; // currently filled from enigmail.js
var EnigmailCore = {
/**
* Create a new instance of Enigmail, or return the already existing one
*/
- createInstance: function() {
+ createInstance() {
if (!gEnigmailService) {
gEnigmailService = new Enigmail();
}
return gEnigmailService;
},
- startup: function(reason) {
+ startup(reason) {
let self = this;
let env = getEnvironment();
initializeLogDirectory();
initializeLogging(env);
const logger = getEnigmailLog();
@@ -85,36 +120,51 @@ var EnigmailCore = {
try {
let mimeEncrypt = getEnigmailMimeEncrypt();
mimeEncrypt.startup(reason);
//getEnigmailOverlays().startup();
self.factories.push(new Factory(getEnigmailProtocolHandler()));
self.factories.push(new Factory(mimeEncrypt.Handler));
getOpenPGPMasterpass().ensureMasterPassword();
} catch (ex) {
- Services.console.logStringMessage("core.jsm: startup.continueStartup: error " + ex.message + "\n" + ex.stack + "\n");
- logger.DEBUG("core.jsm: startup.continueStartup: error " + ex.message + "\n" + ex.stack + "\n");
+ Services.console.logStringMessage(
+ "core.jsm: startup.continueStartup: error " +
+ ex.message +
+ "\n" +
+ ex.stack +
+ "\n"
+ );
+ logger.DEBUG(
+ "core.jsm: startup.continueStartup: error " +
+ ex.message +
+ "\n" +
+ ex.stack +
+ "\n"
+ );
}
}
getEnigmailVerify().registerContentTypeHandler();
getEnigmailWksMimeHandler().registerContentTypeHandler();
getEnigmailFiltersWrapper().onStartup();
continueStartup(1);
let myName = getEnigmailLocale().getString("Enigmail");
console.log("core.jsm: loaded string from properties " + myName);
},
- shutdown: function(reason) {
+ shutdown(reason) {
getEnigmailLog().DEBUG("core.jsm: shutdown():\n");
let cLineReg = getEnigmailCommandLine().categoryRegistry;
- let catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
- catMan.deleteCategoryEntry(cLineReg.category, cLineReg.entry, false);
+ Services.catMan.deleteCategoryEntry(
+ cLineReg.category,
+ cLineReg.entry,
+ false
+ );
if (this.factories) {
for (let fct of this.factories) {
fct.unregister();
}
}
getEnigmailFiltersWrapper().onShutdown();
@@ -124,138 +174,183 @@ var EnigmailCore = {
getEnigmailLog().onShutdown();
getEnigmailLog().setLogLevel(3);
gEnigmailService = null;
},
version: "",
- init: function(enigmailVersion) {
+ init(enigmailVersion) {
this.version = enigmailVersion;
},
/**
* get and or initialize the Enigmail service,
* including the handling for upgrading old preferences to new versions
*
* @win: - nsIWindow: parent window (optional)
* @startingPreferences - Boolean: true - called while switching to new preferences
* (to avoid re-check for preferences)
*/
- getService: function(win, startingPreferences) {
+ getService(win, startingPreferences) {
// Lazy initialization of Enigmail JS component (for efficiency)
if (gEnigmailService) {
return gEnigmailService.initialized ? gEnigmailService : null;
}
try {
this.createInstance();
return gEnigmailService.getService(win, startingPreferences);
} catch (ex) {
return null;
}
-
},
- getEnigmailService: function() {
+ getEnigmailService() {
return gEnigmailService;
},
- setEnigmailService: function(v) {
+ setEnigmailService(v) {
gEnigmailService = v;
},
/**
* obtain a list of all environment variables
*
* @return: Array of Strings with the following structrue
* variable_name=variable_content
*/
- getEnvList: function() {
+ getEnvList() {
return gEnvList;
},
- addToEnvList: function(str) {
+ addToEnvList(str) {
gEnvList.push(str);
},
- setEnvVariable: function(varname, value) {
+ setEnvVariable(varname, value) {
for (let i = 0; i < gEnvList.length; i++) {
if (gEnvList[i].startsWith(varname + "=")) {
gEnvList[i] = varname + "=" + value;
break;
}
}
- }
+ },
};
///////////////////////////////////////////////////////////////////////////////
// Enigmail encryption/decryption service
///////////////////////////////////////////////////////////////////////////////
function getLogDirectoryPrefix() {
try {
- return getEnigmailPrefs().getPrefBranch().getCharPref("logDirectory") || "";
+ return (
+ getEnigmailPrefs()
+ .getPrefBranch()
+ .getCharPref("logDirectory") || ""
+ );
} catch (ex) {
return "";
}
}
function initializeLogDirectory() {
const prefix = getLogDirectoryPrefix();
if (prefix) {
getEnigmailLog().setLogLevel(5);
getEnigmailLog().setLogDirectory(prefix);
- getEnigmailLog().DEBUG("core.jsm: Logging debug output to " + prefix + "/enigdbug.txt\n");
+ getEnigmailLog().DEBUG(
+ "core.jsm: Logging debug output to " + prefix + "/enigdbug.txt\n"
+ );
}
}
function initializeLogging(env) {
const nspr_log_modules = env.get("NSPR_LOG_MODULES");
const matches = nspr_log_modules.match(/enigmail.js:(\d+)/);
- if (matches && (matches.length > 1)) {
+ if (matches && matches.length > 1) {
getEnigmailLog().setLogLevel(Number(matches[1]));
- getEnigmailLog().WARNING("core.jsm: Enigmail: LogLevel=" + matches[1] + "\n");
+ getEnigmailLog().WARNING(
+ "core.jsm: Enigmail: LogLevel=" + matches[1] + "\n"
+ );
}
}
function failureOn(ex, status) {
- status.initializationError = getEnigmailLocale().getString("enigmailNotAvailable");
- getEnigmailLog().ERROR("core.jsm: Enigmail.initialize: Error - " + status.initializationError + "\n");
- getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: exception=" + ex.toString() + "\n");
- throw Components.results.NS_ERROR_FAILURE;
+ status.initializationError = getEnigmailLocale().getString(
+ "enigmailNotAvailable"
+ );
+ getEnigmailLog().ERROR(
+ "core.jsm: Enigmail.initialize: Error - " +
+ status.initializationError +
+ "\n"
+ );
+ getEnigmailLog().DEBUG(
+ "core.jsm: Enigmail.initialize: exception=" + ex.toString() + "\n"
+ );
+ throw Cr.NS_ERROR_FAILURE;
}
function getEnvironment(status) {
try {
return Cc["@mozilla.org/process/environment;1"].getService(nsIEnvironment);
} catch (ex) {
failureOn(ex, status);
}
return null;
}
function initializeEnvironment(env) {
// Initialize global environment variables list
- let passEnv = ["GNUPGHOME", "GPGDIR", "ETC",
- "ALLUSERSPROFILE", "APPDATA", "LOCALAPPDATA", "BEGINLIBPATH",
- "COMMONPROGRAMFILES", "COMSPEC", "DBUS_SESSION_BUS_ADDRESS", "DISPLAY",
- "ENIGMAIL_PASS_ENV", "ENDLIBPATH",
+ let passEnv = [
+ "GNUPGHOME",
+ "GPGDIR",
+ "ETC",
+ "ALLUSERSPROFILE",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "BEGINLIBPATH",
+ "COMMONPROGRAMFILES",
+ "COMSPEC",
+ "DBUS_SESSION_BUS_ADDRESS",
+ "DISPLAY",
+ "ENIGMAIL_PASS_ENV",
+ "ENDLIBPATH",
"GTK_IM_MODULE",
- "HOME", "HOMEDRIVE", "HOMEPATH",
- "LOCPATH", "LOGNAME", "LD_LIBRARY_PATH", "MOZILLA_FIVE_HOME",
- "NLSPATH", "PATH", "PATHEXT", "PINENTRY_USER_DATA", "PROGRAMFILES", "PWD",
+ "HOME",
+ "HOMEDRIVE",
+ "HOMEPATH",
+ "LOCPATH",
+ "LOGNAME",
+ "LD_LIBRARY_PATH",
+ "MOZILLA_FIVE_HOME",
+ "NLSPATH",
+ "PATH",
+ "PATHEXT",
+ "PINENTRY_USER_DATA",
+ "PROGRAMFILES",
+ "PWD",
"QT_IM_MODULE",
- "SHELL", "SYSTEMDRIVE", "SYSTEMROOT",
- "TEMP", "TMP", "TMPDIR", "TZ", "TZDIR", "UNIXROOT",
- "USER", "USERPROFILE", "WINDIR", "XAUTHORITY",
- "XMODIFIERS"
+ "SHELL",
+ "SYSTEMDRIVE",
+ "SYSTEMROOT",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "TZ",
+ "TZDIR",
+ "UNIXROOT",
+ "USER",
+ "USERPROFILE",
+ "WINDIR",
+ "XAUTHORITY",
+ "XMODIFIERS",
];
gEnvList = [];
// if (!getEnigmailPrefs().getPref("gpgLocaleEn")) {
// passEnv = passEnv.concat([
// "LANG", "LANGUAGE", "LC_ALL", "LC_COLLATE", "LC_CTYPE",
// "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME"
@@ -287,35 +382,38 @@ function initializeEnvironment(env) {
} else {
envValue = env.get(envName);
}
if (envValue) {
EnigmailCore.addToEnvList(envName + "=" + envValue);
}
}
- getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: Ec.envList = " + gEnvList + "\n");
+ getEnigmailLog().DEBUG(
+ "core.jsm: Enigmail.initialize: Ec.envList = " + gEnvList + "\n"
+ );
}
-
function Enigmail() {
this.wrappedJSObject = this;
}
Enigmail.prototype = {
initialized: false,
initializationAttempted: false,
initializationError: "",
- initialize: function(domWindow, version) {
+ initialize(domWindow, version) {
this.initializationAttempted = true;
getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: START\n");
- if (this.initialized) return;
+ if (this.initialized) {
+ return;
+ }
this.environment = getEnvironment(this);
initializeEnvironment(this.environment);
try {
getEnigmailConsole().write("Initializing Enigmail service ...\n");
} catch (ex) {
@@ -324,76 +422,82 @@ Enigmail.prototype = {
//getEnigmailKeyRefreshService().start(getEnigmailKeyServer());
this.initialized = true;
getEnigmailLog().DEBUG("core.jsm: Enigmail.initialize: END\n");
},
- reinitialize: function() {
+ reinitialize() {
getEnigmailLog().DEBUG("core.jsm: Enigmail.reinitialize:\n");
this.initialized = false;
this.initializationAttempted = true;
getEnigmailConsole().write("Reinitializing Enigmail service ...\n");
initializeEnvironment(this.environment);
this.initialized = true;
},
- perferGpgPath: function(gpgPath) {
- getEnigmailLog().DEBUG("core.jsm: Enigmail.perferGpgPath = " + gpgPath + "\n");
- gPreferredGpgPath = gpgPath;
- },
-
- overwriteEnvVar: function(envVar) {
+ overwriteEnvVar(envVar) {
let envLines = envVar.split(/\n/);
gOverwriteEnvVar = [];
for (let i = 0; i < envLines.length; i++) {
let j = envLines[i].indexOf("=");
if (j > 0) {
gOverwriteEnvVar[envLines[i].substr(0, j)] = envLines[i].substr(j + 1);
}
}
},
- getService: function(win, startingPreferences) {
+ getService(win, startingPreferences) {
if (!win) {
win = getEnigmailWindows().getBestParentWin();
}
getEnigmailLog().DEBUG("core.jsm: svc = " + this + "\n");
if (!this.initialized) {
const firstInitialization = !this.initializationAttempted;
try {
// Initialize enigmail
EnigmailCore.init(getEnigmailApp().getVersion());
this.initialize(win, getEnigmailApp().getVersion());
try {
// Reset alert count to default value
- getEnigmailPrefs().getPrefBranch().clearUserPref("initAlert");
+ getEnigmailPrefs()
+ .getPrefBranch()
+ .clearUserPref("initAlert");
} catch (ex) {}
} catch (ex) {
if (firstInitialization) {
// Display initialization error alert
- const errMsg = (this.initializationError ? this.initializationError : getEnigmailLocale().getString("accessError")) +
- "\n\n" + getEnigmailLocale().getString("initErr.howToFixIt");
+ const errMsg =
+ (this.initializationError
+ ? this.initializationError
+ : getEnigmailLocale().getString("accessError")) +
+ "\n\n" +
+ getEnigmailLocale().getString("initErr.howToFixIt");
const checkedObj = {
- value: false
+ value: false,
};
if (getEnigmailPrefs().getPref("initAlert")) {
- const r = getEnigmailDialog().longAlert(win, "Enigmail: " + errMsg,
+ const r = getEnigmailDialog().longAlert(
+ win,
+ "Enigmail: " + errMsg,
getEnigmailLocale().getString("dlgNoPrompt"),
- null, getEnigmailLocale().getString("initErr.setupWizard.button"),
- null, checkedObj);
+ null,
+ getEnigmailLocale().getString("initErr.setupWizard.button"),
+ null,
+ checkedObj
+ );
if (r >= 0 && checkedObj.value) {
getEnigmailPrefs().setPref("initAlert", false);
}
if (r == 1) {
// start setup wizard
getEnigmailWindows().openSetupWizard(win, false);
return Enigmail.getService(win);
}
@@ -404,45 +508,51 @@ Enigmail.prototype = {
}
}
return null;
}
const configuredVersion = getEnigmailPrefs().getPref("configuredVersion");
- getEnigmailLog().DEBUG("core.jsm: getService: last used version: " + configuredVersion + "\n");
+ getEnigmailLog().DEBUG(
+ "core.jsm: getService: last used version: " + configuredVersion + "\n"
+ );
- if (this.initialized && (getEnigmailApp().getVersion() != configuredVersion)) {
+ if (
+ this.initialized &&
+ getEnigmailApp().getVersion() != configuredVersion
+ ) {
getEnigmailConfigure().configureEnigmail(win, startingPreferences);
}
}
return this.initialized ? this : null;
- }
+ },
}; // Enigmail.prototype
-
class Factory {
constructor(component) {
this.component = component;
this.register();
Object.freeze(this);
}
createInstance(outer, iid) {
if (outer) {
throw Cr.NS_ERROR_NO_AGGREGATION;
}
return new this.component();
}
register() {
- Cm.registerFactory(this.component.prototype.classID,
+ Cm.registerFactory(
+ this.component.prototype.classID,
this.component.prototype.classDescription,
this.component.prototype.contractID,
- this);
+ this
+ );
}
unregister() {
Cm.unregisterFactory(this.component.prototype.classID, this);
}
}
--- a/mail/extensions/openpgp/content/modules/cryptoAPI.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI.jsm
@@ -1,33 +1,32 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
"use strict";
-var EXPORTED_SYMBOLS = ["EnigmailCryptoAPI"];
+var EXPORTED_SYMBOLS = ["EnigmailCryptoAPI", "EnigmailGnuPGAPI"];
var gCurrentApi = null;
var gGnuPGApi = null;
-var Services = ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
function EnigmailCryptoAPI() {
if (!gCurrentApi) {
- const {
- getRNPAPI
- } = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm");
+ const { getRNPAPI } = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm"
+ );
gCurrentApi = getRNPAPI();
}
return gCurrentApi;
}
function EnigmailGnuPGAPI() {
if (!gGnuPGApi) {
- const {
- getGnuPGAPI
- } = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm");
+ const { getGnuPGAPI } = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm"
+ );
gGnuPGApi = getGnuPGAPI();
}
return gGnuPGApi;
}
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/GnuPGCryptoAPI.jsm
@@ -1,47 +1,48 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["getGnuPGAPI"];
-var Services = Components.utils.import("resource://gre/modules/Services.jsm").Services;
+var Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
-Services.scriptloader.loadSubScript("chrome://openpgp/content/modules/cryptoAPI/interface.js",
- null, "UTF-8"); /* global CryptoAPI */
-
-/* global getOpenPGP: false, EnigmailLog: false */
+Services.scriptloader.loadSubScript(
+ "chrome://openpgp/content/modules/cryptoAPI/interface.js",
+ null,
+ "UTF-8"
+); /* global CryptoAPI */
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailErrorHandling = ChromeUtils.import("chrome://openpgp/content/modules/errorHandling.jsm").EnigmailErrorHandling;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
const {
obtainKeyList,
getPhotoFileFromGnuPG,
- extractSignatures,
- getGpgKeyData
-} = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm");
+ getGpgKeyData,
+} = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm"
+);
-const {
- GnuPG_importKeyFromFile,
- GnuPG_extractSecretKey
-} = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI/gnupg-key.jsm");
+const { GnuPG_importKeyFromFile, GnuPG_extractSecretKey } = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI/gnupg-key.jsm"
+);
/**
* GnuPG implementation of CryptoAPI
*/
class GnuPGCryptoAPI extends CryptoAPI {
constructor() {
super();
@@ -67,17 +68,16 @@ class GnuPGCryptoAPI extends CryptoAPI {
*
* @return {Promise<Array of Object>} - see extractSignatures()
*/
async getKeySignatures(keyId, ignoreUnknownUid = false) {
EnigmailLog.DEBUG(`gnupg.js: getKeySignatures: ${keyId}\n`);
throw new Error("Not implemented");
}
-
/**
* Export the minimum key for the public key object:
* public key, primary user ID, newest encryption subkey
*
* @param {String} fpr: a single FPR
* @param {String} email: [optional] the email address of the desired user ID.
* If the desired user ID cannot be found or is not valid, use the primary UID instead
* @param {Array<Number>} subkeyDates: [optional] remove subkeys with sepcific creation Dates
@@ -137,17 +137,18 @@ class GnuPGCryptoAPI extends CryptoAPI {
* - {String} keyData: ASCII armored key data material
* - {String} errorMsg: error message in case exitCode !== 0
*/
async extractSecretKey(keyId, minimalKey) {
let ret = await GnuPG_extractSecretKey(keyId, minimalKey);
if (ret.exitCode !== 0) {
- ret.errorMsg = EnigmailLocale.getString("failKeyExtract") + "\n" + ret.errorMsg;
+ ret.errorMsg =
+ EnigmailLocale.getString("failKeyExtract") + "\n" + ret.errorMsg;
}
return ret;
}
/**
*
* @param {byte} byteData The encrypted data
*
@@ -170,34 +171,32 @@ class GnuPGCryptoAPI extends CryptoAPI {
* The message will be an error message in this case.
*/
async verifyAttachment(filePath, sigPath) {
EnigmailLog.DEBUG(`gnupg.js: verifyAttachment()\n`);
throw new Error("Not implemented");
}
-
/**
*
* @param {Bytes} encrypted The encrypted data
*
* @return {Promise<Object>} - Return object with decryptedData and
* status information
*
* Use Promise.catch to handle failed decryption.
* retObj.errorMsg will be an error message in this case.
*/
async decryptAttachment(encrypted) {
EnigmailLog.DEBUG(`gnupg.js: decryptAttachment()\n`);
throw new Error("Not implemented");
}
-
/**
*
* @param {String} encrypted The encrypted data
* @param {Object} options Decryption options
*
* @return {Promise<Object>} - Return object with decryptedData and
* status information
*
@@ -262,17 +261,16 @@ class GnuPGCryptoAPI extends CryptoAPI {
async getKeyListFromKeyBlock(keyBlockStr) {
let res;
res = await getGpgKeyData(keyBlockStr);
return res;
}
async genKey(userId, keyType, keySize, expiryTime, passphrase) {
throw new Error("GnuPG genKey() not implemented");
- return null;
}
async deleteKey(keyFingerprint, deleteSecret) {
return null;
}
async encryptAndOrSign(plaintext, args, resultStatus) {
return null;
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/RNPCryptoAPI.jsm
@@ -11,39 +11,24 @@ var EXPORTED_SYMBOLS = ["getRNPAPI"];
const RNP = ChromeUtils.import("chrome://openpgp/content/modules/rnp.jsm").RNP;
var Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
.Services;
Services.scriptloader.loadSubScript(
"chrome://openpgp/content/modules/cryptoAPI/interface.js",
null,
"UTF-8"
-);
-
-/* Globals loaded from openpgp-js.js: */
-/* global getOpenPGP: false, EnigmailLog: false */
+); /* global CryptoAPI */
const EnigmailLog = ChromeUtils.import(
"chrome://openpgp/content/modules/log.jsm"
).EnigmailLog;
-const EnigmailFiles = ChromeUtils.import(
- "chrome://openpgp/content/modules/files.jsm"
-).EnigmailFiles;
const EnigmailConstants = ChromeUtils.import(
"chrome://openpgp/content/modules/constants.jsm"
).EnigmailConstants;
-const EnigmailTime = ChromeUtils.import(
- "chrome://openpgp/content/modules/time.jsm"
-).EnigmailTime;
-const EnigmailData = ChromeUtils.import(
- "chrome://openpgp/content/modules/data.jsm"
-).EnigmailData;
-const EnigmailLocale = ChromeUtils.import(
- "chrome://openpgp/content/modules/locale.jsm"
-).EnigmailLocale;
/**
* RNP implementation of CryptoAPI
*/
class RNPCryptoAPI extends CryptoAPI {
constructor() {
super();
@@ -259,25 +244,25 @@ class RNPCryptoAPI extends CryptoAPI {
return RNP.getKeyListFromKeyBlock(keyBlockStr);
}
async genKey(userId, keyType, keySize, expiryTime, passphrase) {
let id = RNP.genKey(userId, keyType, keySize, expiryTime, passphrase);
RNP.saveKeyRings();
return id;
}
-
+
async deleteKey(keyFingerprint, deleteSecret) {
- return RNP.deleteKey(keyId, deleteSecret);
+ return RNP.deleteKey(keyFingerprint, deleteSecret);
}
async encryptAndOrSign(plaintext, args, resultStatus) {
return RNP.encryptAndOrSign(plaintext, args, resultStatus);
}
-
+
async getPublicKey(id) {
return RNP.getPublicKey(id);
}
}
function getRNPAPI() {
return new RNPCryptoAPI();
}
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-key.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-key.jsm
@@ -7,20 +7,22 @@
/****
Private sub-module to GnuPGCryptoAPI.jsm for handling key import/export
****/
"use strict";
var EXPORTED_SYMBOLS = ["GnuPG_importKeyFromFile", "GnuPG_extractSecretKey"];
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
async function GnuPG_importKeyFromFile(inputFile) {
- EnigmailLog.DEBUG("gnupg-key.jsm: importKeysFromFile: fileName=" + inputFile.path + "\n");
+ EnigmailLog.DEBUG(
+ "gnupg-key.jsm: importKeysFromFile: fileName=" + inputFile.path + "\n"
+ );
throw new Error("Not implemented");
}
-
async function GnuPG_extractSecretKey(userId, minimalKey) {
throw new Error("Not implemented");
}
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/gnupg-keylist.jsm
@@ -5,28 +5,38 @@
*/
/****
Private sub-module to GnuPGCryptoAPI.jsm for handling key lists from GnuPG
****/
"use strict";
-var EXPORTED_SYMBOLS = ["obtainKeyList",
- "getPhotoFileFromGnuPG", "extractSignatures", "getGpgKeyData"
+var EXPORTED_SYMBOLS = [
+ "obtainKeyList",
+ "getPhotoFileFromGnuPG",
+ "extractSignatures",
+ "getGpgKeyData",
];
-const EnigmailTime = ChromeUtils.import("chrome://openpgp/content/modules/time.jsm").EnigmailTime;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailTrust = ChromeUtils.import("chrome://openpgp/content/modules/trust.jsm").EnigmailTrust;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
+const EnigmailTime = ChromeUtils.import(
+ "chrome://openpgp/content/modules/time.jsm"
+).EnigmailTime;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailTrust = ChromeUtils.import(
+ "chrome://openpgp/content/modules/trust.jsm"
+).EnigmailTrust;
+const EnigmailData = ChromeUtils.import(
+ "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
// field ID's of key list (as described in the doc/DETAILS file in the GnuPG distribution)
const ENTRY_ID = 0;
const KEY_TRUST_ID = 1;
const KEY_SIZE_ID = 2;
const KEY_ALGO_ID = 3;
const KEY_ID = 4;
const CREATED_ID = 5;
@@ -41,43 +51,34 @@ const ALGO_SYMBOL = {
1: "RSA",
2: "RSA",
3: "RSA",
16: "ELG",
17: "DSA",
18: "ECDH",
19: "ECDSA",
20: "ELG",
- 22: "EDDSA"
+ 22: "EDDSA",
};
const UNKNOWN_SIGNATURE = "[User ID not found]";
-const NS_RDONLY = 0x01;
-const NS_WRONLY = 0x02;
-const NS_CREATE_FILE = 0x08;
-const NS_TRUNCATE = 0x20;
-const STANDARD_FILE_PERMS = 0o600;
-
-const NS_LOCALFILEOUTPUTSTREAM_CONTRACTID = "@mozilla.org/network/file-output-stream;1";
-
/**
* Get key list from GnuPG.
*
* @param {Array of String} onlyKeys: only load data for specified key IDs
*
* @return {Promise<Array Object>}:
* key objects as specified in EnigmailKeyObj.constructor
*/
async function obtainKeyList(onlyKeys = null) {
EnigmailLog.DEBUG("gnupg-keylist.jsm: obtainKeyList()\n");
throw new Error("Not implemented");
}
-
/**
* Append key objects to a given key cache
*
* @param keyListString: array of |string| formatted output from GnuPG for key listing
* @param keyList: |object| holding the resulting key list
* obj.keyList: Array holding key objects
* obj.keySortList: Array holding values to make sorting easier
*
@@ -87,17 +88,19 @@ function appendKeyItems(keyListString, k
EnigmailLog.DEBUG("gnupg-keylist.jsm: appendKeyItems()\n");
let keyObj = {};
let uatNum = 0; // counter for photos (counts per key)
const TRUSTLEVELS_SORTED = EnigmailTrust.trustLevelsSorted();
for (let i = 0; i < keyListString.length; i++) {
let listRow = keyListString[i].split(/:/);
- if (listRow.length === 0) continue;
+ if (listRow.length === 0) {
+ continue;
+ }
switch (listRow[ENTRY_ID]) {
case "pub":
keyObj = createKeyObj(listRow);
uatNum = 0;
keyList.keys.push(keyObj);
keyList.index[keyObj.keyId] = keyObj;
break;
@@ -118,55 +121,58 @@ function appendKeyItems(keyListString, k
if (keyObj.fpr === "") {
keyObj.fpr = listRow[USERID_ID];
}
break;
case "uid":
if (listRow[USERID_ID].length === 0) {
listRow[USERID_ID] = "-";
}
- if (typeof(keyObj.userId) !== "string") {
+ if (typeof keyObj.userId !== "string") {
keyObj.userId = EnigmailData.convertGpgToUnicode(listRow[USERID_ID]);
- if (TRUSTLEVELS_SORTED.indexOf(listRow[KEY_TRUST_ID]) < TRUSTLEVELS_SORTED.indexOf(keyObj.keyTrust)) {
+ if (
+ TRUSTLEVELS_SORTED.indexOf(listRow[KEY_TRUST_ID]) <
+ TRUSTLEVELS_SORTED.indexOf(keyObj.keyTrust)
+ ) {
// reduce key trust if primary UID is less trusted than public key
keyObj.keyTrust = listRow[KEY_TRUST_ID];
}
}
keyObj.userIds.push({
userId: EnigmailData.convertGpgToUnicode(listRow[USERID_ID]),
keyTrust: listRow[KEY_TRUST_ID],
uidFpr: listRow[UID_ID],
- type: "uid"
+ type: "uid",
});
break;
case "sub":
keyObj.subKeys.push({
keyId: listRow[KEY_ID],
expiry: EnigmailTime.getDateTime(listRow[EXPIRY_ID], true, false),
expiryTime: Number(listRow[EXPIRY_ID]),
keyTrust: listRow[KEY_TRUST_ID],
keyUseFor: listRow[KEY_USE_FOR_ID],
keySize: listRow[KEY_SIZE_ID],
algoSym: ALGO_SYMBOL[listRow[KEY_ALGO_ID]],
created: EnigmailTime.getDateTime(listRow[CREATED_ID], true, false),
keyCreated: Number(listRow[CREATED_ID]),
- type: "sub"
+ type: "sub",
});
break;
case "uat":
if (listRow[USERID_ID].indexOf("1 ") === 0) {
const userId = EnigmailLocale.getString("userAtt.photo");
keyObj.userIds.push({
- userId: userId,
+ userId,
keyTrust: listRow[KEY_TRUST_ID],
uidFpr: listRow[UID_ID],
type: "uat",
- uatNum: uatNum
+ uatNum,
});
keyObj.photoAvailable = true;
++uatNum;
}
break;
}
}
}
@@ -193,50 +199,56 @@ function createKeyObj(lineArr) {
keyObj.userIds = [];
keyObj.subKeys = [];
}
keyObj.type = lineArr[ENTRY_ID];
return keyObj;
}
-
/**
* Handle secret keys for which gpg 2.0 does not create a public key record
*/
function appendUnkownSecretKey(keyId, aKeyList, startIndex, keyList) {
- EnigmailLog.DEBUG(`gnupg-keylist.jsm: appendUnkownSecretKey: keyId: ${keyId}\n`);
+ EnigmailLog.DEBUG(
+ `gnupg-keylist.jsm: appendUnkownSecretKey: keyId: ${keyId}\n`
+ );
let keyListStr = [];
- for (let j = startIndex; j < aKeyList.length && (j === startIndex || aKeyList[j].substr(0, 4) !== "sec:"); j++) {
+ for (
+ let j = startIndex;
+ j < aKeyList.length &&
+ (j === startIndex || aKeyList[j].substr(0, 4) !== "sec:");
+ j++
+ ) {
keyListStr.push(aKeyList[j]);
}
// make the listing a "public" key
keyListStr[0] = keyListStr[0].replace(/^sec:/, "pub:");
appendKeyItems(keyListStr, keyList);
}
-
/**
* Extract a photo ID from a key, store it as file and return the file object.
* @param {String} keyId: Key ID / fingerprint
* @param {Number} photoNumber: number of the photo on the key, starting with 0
*
* @return {Promise<nsIFile>} object or null in case no data / error.
*/
async function getPhotoFileFromGnuPG(keyId, photoNumber) {
- EnigmailLog.DEBUG(`gnupg-keylist.jsm: getPhotoFileFromGnuPG, keyId=${keyId} photoNumber=${photoNumber}\n`);
+ EnigmailLog.DEBUG(
+ `gnupg-keylist.jsm: getPhotoFileFromGnuPG, keyId=${keyId} photoNumber=${photoNumber}\n`
+ );
throw new Error("Not implemented");
}
-
/**
* Return signatures for a given key list
*
* @param {String} gpgKeyList Output from gpg such as produced by getKeySig()
* Only the first public key is processed!
* @param {Boolean} ignoreUnknownUid true if unknown signer's UIDs should be filtered out
*
* @return {Array of Object}:
@@ -271,41 +283,53 @@ function extractSignatures(gpgKeyList, i
case "pub":
if (havePub) {
return listObj;
}
havePub = true;
keyId = lineTokens[KEY_ID];
break;
case "fpr":
- if (fpr === "")
+ if (fpr === "") {
fpr = lineTokens[USERID_ID];
+ }
break;
case "uid":
case "uat":
currUid = lineTokens[UID_ID];
listObj[currUid] = {
- userId: lineTokens[ENTRY_ID] == "uat" ? EnigmailLocale.getString("keyring.photo") : EnigmailData.convertGpgToUnicode(lineTokens[USERID_ID]),
+ userId:
+ lineTokens[ENTRY_ID] == "uat"
+ ? EnigmailLocale.getString("keyring.photo")
+ : EnigmailData.convertGpgToUnicode(lineTokens[USERID_ID]),
rawUserId: lineTokens[USERID_ID],
- keyId: keyId,
- fpr: fpr,
- created: EnigmailTime.getDateTime(lineTokens[CREATED_ID], true, false),
- sigList: []
+ keyId,
+ fpr,
+ created: EnigmailTime.getDateTime(
+ lineTokens[CREATED_ID],
+ true,
+ false
+ ),
+ sigList: [],
};
break;
case "sig":
if (lineTokens[SIG_TYPE_ID].substr(0, 2).toLowerCase() !== "1f") {
// ignrore revoked signature
let sig = {
userId: EnigmailData.convertGpgToUnicode(lineTokens[USERID_ID]),
- created: EnigmailTime.getDateTime(lineTokens[CREATED_ID], true, false),
+ created: EnigmailTime.getDateTime(
+ lineTokens[CREATED_ID],
+ true,
+ false
+ ),
signerKeyId: lineTokens[KEY_ID],
sigType: lineTokens[SIG_TYPE_ID],
- sigKnown: lineTokens[USERID_ID] != UNKNOWN_SIGNATURE
+ sigKnown: lineTokens[USERID_ID] != UNKNOWN_SIGNATURE,
};
if (!ignoreUnknownUid || sig.userId != UNKNOWN_SIGNATURE) {
listObj[currUid].sigList.push(sig);
}
}
break;
}
--- a/mail/extensions/openpgp/content/modules/cryptoAPI/interface.js
+++ b/mail/extensions/openpgp/content/modules/cryptoAPI/interface.js
@@ -28,31 +28,35 @@ class CryptoAPI {
* @param {Promise} promise: the promise to wait for
*
* @return {Variant} whatever the promise returns
*/
sync(promise) {
console.log("CryptoAPI.sync() starting");
if (!inspector) {
- inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+ inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+ Ci.nsIJSInspector
+ );
}
let res = null;
- let p = promise.then(gotResult => {
- console.log("CryptoAPI.sync() good result:");
- console.log(gotResult);
- res = gotResult;
- inspector.exitNestedEventLoop();
- }).catch(gotResult => {
- console.log("CryptoAPI.sync() failed result:");
- console.log(gotResult);
- res = gotResult;
- inspector.exitNestedEventLoop();
- });
+ promise
+ .then(gotResult => {
+ console.log("CryptoAPI.sync() good result:");
+ console.log(gotResult);
+ res = gotResult;
+ inspector.exitNestedEventLoop();
+ })
+ .catch(gotResult => {
+ console.log("CryptoAPI.sync() failed result:");
+ console.log(gotResult);
+ res = gotResult;
+ inspector.exitNestedEventLoop();
+ });
inspector.enterNestedEventLoop(0);
console.log("CryptoAPI.sync() leaving");
return res;
}
/**
@@ -79,17 +83,17 @@ class CryptoAPI {
* - exitCode (0 = success)
* - errorMsg (if exitCode != 0)
* - keyData: BASE64-encded string of key data
*/
async getMinimalPubKey(fpr, email) {
return {
exitCode: -1,
errorMsg: "",
- keyData: ""
+ keyData: "",
};
}
/**
* Get the list of all konwn keys (including their secret keys)
* @param {Array of String} onlyKeys: [optional] only load data for specified key IDs
*
* @return {Promise<Array of Object>}
--- a/mail/extensions/openpgp/content/modules/data.jsm
+++ b/mail/extensions/openpgp/content/modules/data.jsm
@@ -1,168 +1,181 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailData"];
-const SCRIPTABLEUNICODECONVERTER_CONTRACTID = "@mozilla.org/intl/scriptableunicodeconverter";
+const SCRIPTABLEUNICODECONVERTER_CONTRACTID =
+ "@mozilla.org/intl/scriptableunicodeconverter";
const HEX_TABLE = "0123456789abcdef";
function converter(charset) {
- let unicodeConv = Cc[SCRIPTABLEUNICODECONVERTER_CONTRACTID].getService(Ci.nsIScriptableUnicodeConverter);
+ let unicodeConv = Cc[SCRIPTABLEUNICODECONVERTER_CONTRACTID].getService(
+ Ci.nsIScriptableUnicodeConverter
+ );
unicodeConv.charset = charset || "utf-8";
return unicodeConv;
}
var EnigmailData = {
- getUnicodeData: function(data) {
+ getUnicodeData(data) {
// convert output to Unicode
- var tmpStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
+ var tmpStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
+ Ci.nsIStringInputStream
+ );
tmpStream.setData(data, data.length);
- var inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
+ var inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
+ Ci.nsIScriptableInputStream
+ );
inStream.init(tmpStream);
return inStream.read(tmpStream.available());
},
- extractMessageId: function(uri) {
+ extractMessageId(uri) {
var messageId = "";
var matches = uri.match(/^enigmail:message\/(.+)/);
- if (matches && (matches.length > 1)) {
+ if (matches && matches.length > 1) {
messageId = matches[1];
}
return messageId;
},
- extractMimeMessageId: function(uri) {
+ extractMimeMessageId(uri) {
var messageId = "";
var matches = uri.match(/^enigmail:mime-message\/(.+)/);
- if (matches && (matches.length > 1)) {
+ if (matches && matches.length > 1) {
messageId = matches[1];
}
return messageId;
},
- decodeQuotedPrintable: function(str) {
- return unescape(str.replace(/%/g, "=25").replace(new RegExp('=', 'g'), '%'));
+ decodeQuotedPrintable(str) {
+ return unescape(
+ str.replace(/%/g, "=25").replace(new RegExp("=", "g"), "%")
+ );
},
- decodeBase64: function(str) {
+ decodeBase64(str) {
return atob(str.replace(/[\s\r\n]*/g, ""));
},
/***
* Encode a string in base64, with a max. line length of 72 characters
*/
- encodeBase64: function(str) {
+ encodeBase64(str) {
return btoa(str).replace(/(.{72})/g, "$1\r\n");
},
- convertToUnicode: function(text, charset) {
- if (!text || (charset && (charset.toLowerCase() == "iso-8859-1"))) {
+ convertToUnicode(text, charset) {
+ if (!text || (charset && charset.toLowerCase() == "iso-8859-1")) {
return text;
}
// Encode plaintext
try {
return converter(charset).ConvertToUnicode(text);
- }
- catch (ex) {
+ } catch (ex) {
return text;
}
},
- convertFromUnicode: function(text, charset) {
+ convertFromUnicode(text, charset) {
if (!text) {
return "";
}
try {
return converter(charset).ConvertFromUnicode(text);
- }
- catch (ex) {
+ } catch (ex) {
return text;
}
},
- convertGpgToUnicode: function(text) {
- if (typeof(text) === "string") {
- text = text.replace(/\\x3a/ig, "\\e3A");
+ convertGpgToUnicode(text) {
+ if (typeof text === "string") {
+ text = text.replace(/\\x3a/gi, "\\e3A");
var a = text.search(/\\x[0-9a-fA-F]{2}/);
while (a >= 0) {
- var ch = unescape('%' + text.substr(a + 2, 2));
+ var ch = unescape("%" + text.substr(a + 2, 2));
var r = new RegExp("\\" + text.substr(a, 4));
text = text.replace(r, ch);
a = text.search(/\\x[0-9a-fA-F]{2}/);
}
- text = EnigmailData.convertToUnicode(text, "utf-8").replace(/\\e3A/g, ":");
+ text = EnigmailData.convertToUnicode(text, "utf-8").replace(
+ /\\e3A/g,
+ ":"
+ );
}
return text;
},
- pack: function(value, bytes) {
- let str = '';
+ pack(value, bytes) {
+ let str = "";
let mask = 0xff;
for (let j = 0; j < bytes; j++) {
- str = String.fromCharCode((value & mask) >> j * 8) + str;
+ str = String.fromCharCode((value & mask) >> (j * 8)) + str;
mask <<= 8;
}
return str;
},
- unpack: function(str) {
+ unpack(str) {
let len = str.length;
let value = 0;
for (let j = 0; j < len; j++) {
value <<= 8;
value |= str.charCodeAt(j);
}
return value;
},
- bytesToHex: function(str) {
+ bytesToHex(str) {
let len = str.length;
- let hex = '';
+ let hex = "";
for (let j = 0; j < len; j++) {
let charCode = str.charCodeAt(j);
- hex += HEX_TABLE.charAt((charCode & 0xf0) >> 4) +
- HEX_TABLE.charAt((charCode & 0x0f));
+ hex +=
+ HEX_TABLE.charAt((charCode & 0xf0) >> 4) +
+ HEX_TABLE.charAt(charCode & 0x0f);
}
return hex;
},
/**
* Convert an ArrayBuffer (or Uint8Array) object into a string
*/
- arrayBufferToString: function(buffer) {
+ arrayBufferToString(buffer) {
const MAXLEN = 102400;
let uArr = new Uint8Array(buffer);
let ret = "";
let len = buffer.byteLength;
for (let j = 0; j < Math.floor(len / MAXLEN) + 1; j++) {
- ret += String.fromCharCode.apply(null, uArr.subarray(j * MAXLEN, ((j + 1) * MAXLEN)));
+ ret += String.fromCharCode.apply(
+ null,
+ uArr.subarray(j * MAXLEN, (j + 1) * MAXLEN)
+ );
}
return ret;
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/decryption.jsm
+++ b/mail/extensions/openpgp/content/modules/decryption.jsm
@@ -1,78 +1,119 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
+/* eslint-disable complexity */
+
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailDecryption"];
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailArmor = ChromeUtils.import("chrome://openpgp/content/modules/armor.jsm").EnigmailArmor;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailHttpProxy = ChromeUtils.import("chrome://openpgp/content/modules/httpProxy.jsm").EnigmailHttpProxy;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailErrorHandling = ChromeUtils.import("chrome://openpgp/content/modules/errorHandling.jsm").EnigmailErrorHandling;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailKey = ChromeUtils.import("chrome://openpgp/content/modules/key.jsm").EnigmailKey;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailCore = ChromeUtils.import(
+ "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailPrefs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailArmor = ChromeUtils.import(
+ "chrome://openpgp/content/modules/armor.jsm"
+).EnigmailArmor;
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailData = ChromeUtils.import(
+ "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailDialog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailHttpProxy = ChromeUtils.import(
+ "chrome://openpgp/content/modules/httpProxy.jsm"
+).EnigmailHttpProxy;
+const EnigmailFiles = ChromeUtils.import(
+ "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailKeyRing = ChromeUtils.import(
+ "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailKey = ChromeUtils.import(
+ "chrome://openpgp/content/modules/key.jsm"
+).EnigmailKey;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailFuncs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailCryptoAPI = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
-const STATUS_ERROR = EnigmailConstants.BAD_SIGNATURE | EnigmailConstants.DECRYPTION_FAILED;
-const STATUS_DECRYPTION_OK = EnigmailConstants.DECRYPTION_OKAY;
-const STATUS_GOODSIG = EnigmailConstants.GOOD_SIGNATURE;
-
-const NS_WRONLY = 0x02;
-
-function statusObjectFrom(signatureObj, exitCodeObj, statusFlagsObj, keyIdObj, userIdObj, sigDetailsObj, errorMsgObj, blockSeparationObj, encToDetailsObj) {
+function statusObjectFrom(
+ signatureObj,
+ exitCodeObj,
+ statusFlagsObj,
+ keyIdObj,
+ userIdObj,
+ sigDetailsObj,
+ errorMsgObj,
+ blockSeparationObj,
+ encToDetailsObj
+) {
return {
signature: signatureObj,
exitCode: exitCodeObj,
statusFlags: statusFlagsObj,
keyId: keyIdObj,
userId: userIdObj,
sigDetails: sigDetailsObj,
message: errorMsgObj,
blockSeparation: blockSeparationObj,
- encToDetails: encToDetailsObj
+ encToDetails: encToDetailsObj,
};
}
function newStatusObject() {
- return statusObjectFrom({
- value: ""
- }, {}, {}, {}, {}, {}, {}, {}, {});
+ return statusObjectFrom(
+ {
+ value: "",
+ },
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {}
+ );
}
var EnigmailDecryption = {
- isReady: function(win) {
+ isReady(win) {
// this used to return false while generating a key. still necessary?
return EnigmailCore.getService(win);
},
- getFromAddr: function(win) {
+ getFromAddr(win) {
var fromAddr;
if (win && win.gFolderDisplay && win.gFolderDisplay.selectedMessage) {
fromAddr = win.gFolderDisplay.selectedMessage.author;
try {
fromAddr = EnigmailFuncs.stripEmail(fromAddr);
if (fromAddr.search(/[a-zA-Z0-9]@.*[\(\)]/) >= 0) {
fromAddr = false;
}
- }
- catch (ex) {
+ } catch (ex) {
fromAddr = false;
}
}
return fromAddr;
},
/**
* Decrypts a PGP ciphertext and returns the the plaintext
@@ -88,332 +129,457 @@ var EnigmailDecryption = {
*out @sigDetailsObj
*out @errorMsgObj error string
*out @blockSeparationObj
*out @encToDetailsObj returns in details, which keys the mesage was encrypted for (ENC_TO entries)
*
* @return string plaintext ("" if error)
*
*/
- decryptMessage: function(parent, uiFlags, cipherText,
- signatureObj, exitCodeObj,
- statusFlagsObj, keyIdObj, userIdObj, sigDetailsObj, errorMsgObj,
- blockSeparationObj, encToDetailsObj) {
- const esvc = EnigmailCore.getEnigmailService();
+ decryptMessage(
+ parent,
+ uiFlags,
+ cipherText,
+ signatureObj,
+ exitCodeObj,
+ statusFlagsObj,
+ keyIdObj,
+ userIdObj,
+ sigDetailsObj,
+ errorMsgObj,
+ blockSeparationObj,
+ encToDetailsObj
+ ) {
+ EnigmailLog.DEBUG(
+ "decryption.jsm: decryptMessage(" +
+ cipherText.length +
+ " bytes, " +
+ uiFlags +
+ ")\n"
+ );
- EnigmailLog.DEBUG("decryption.jsm: decryptMessage(" + cipherText.length + " bytes, " + uiFlags + ")\n");
-
- if (!cipherText)
+ if (!cipherText) {
return "";
+ }
var interactive = uiFlags & EnigmailConstants.UI_INTERACTIVE;
var allowImport = uiFlags & EnigmailConstants.UI_ALLOW_KEY_IMPORT;
- var unverifiedEncryptedOK = uiFlags & EnigmailConstants.UI_UNVERIFIED_ENC_OK;
+ var unverifiedEncryptedOK =
+ uiFlags & EnigmailConstants.UI_UNVERIFIED_ENC_OK;
var oldSignature = signatureObj.value;
- EnigmailLog.DEBUG("decryption.jsm: decryptMessage: oldSignature=" + oldSignature + "\n");
+ EnigmailLog.DEBUG(
+ "decryption.jsm: decryptMessage: oldSignature=" + oldSignature + "\n"
+ );
signatureObj.value = "";
exitCodeObj.value = -1;
statusFlagsObj.value = 0;
keyIdObj.value = "";
userIdObj.value = "";
errorMsgObj.value = "";
var beginIndexObj = {};
var endIndexObj = {};
var indentStrObj = {};
- var blockType = EnigmailArmor.locateArmoredBlock(cipherText, 0, "", beginIndexObj, endIndexObj, indentStrObj);
+ var blockType = EnigmailArmor.locateArmoredBlock(
+ cipherText,
+ 0,
+ "",
+ beginIndexObj,
+ endIndexObj,
+ indentStrObj
+ );
if (!blockType || blockType == "SIGNATURE") {
// return without displaying a message
return "";
}
- var publicKey = (blockType == "PUBLIC KEY BLOCK");
+ var publicKey = blockType == "PUBLIC KEY BLOCK";
+
+ var verifyOnly = blockType == "SIGNED MESSAGE";
- var verifyOnly = (blockType == "SIGNED MESSAGE");
-
- var pgpBlock = cipherText.substr(beginIndexObj.value,
- endIndexObj.value - beginIndexObj.value + 1);
+ var pgpBlock = cipherText.substr(
+ beginIndexObj.value,
+ endIndexObj.value - beginIndexObj.value + 1
+ );
if (indentStrObj.value) {
var indentRegexp = new RegExp("^" + indentStrObj.value, "gm");
pgpBlock = pgpBlock.replace(indentRegexp, "");
if (indentStrObj.value.substr(-1) == " ") {
var indentRegexpStr = "^" + indentStrObj.value.replace(/ $/m, "$");
indentRegexp = new RegExp(indentRegexpStr, "gm");
pgpBlock = pgpBlock.replace(indentRegexp, "");
}
}
// HACK to better support messages from Outlook: if there are empty lines, drop them
if (pgpBlock.search(/MESSAGE-----\r?\n\r?\nVersion/) >= 0) {
- EnigmailLog.DEBUG("decryption.jsm: decryptMessage: apply Outlook empty line workaround\n");
+ EnigmailLog.DEBUG(
+ "decryption.jsm: decryptMessage: apply Outlook empty line workaround\n"
+ );
pgpBlock = pgpBlock.replace(/\r?\n\r?\n/g, "\n");
}
- const head = "";
- var tail = cipherText.substr(endIndexObj.value + 1,
- cipherText.length - endIndexObj.value - 1);
+ var tail = cipherText.substr(
+ endIndexObj.value + 1,
+ cipherText.length - endIndexObj.value - 1
+ );
if (publicKey) {
if (!allowImport) {
errorMsgObj.value = EnigmailLocale.getString("keyInMessageBody");
statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
statusFlagsObj.value |= EnigmailConstants.INLINE_KEY;
return "";
}
// Import public key
- exitCodeObj.value = EnigmailKeyRing.importKey(parent, true, pgpBlock, "",
- errorMsgObj);
+ exitCodeObj.value = EnigmailKeyRing.importKey(
+ parent,
+ true,
+ pgpBlock,
+ "",
+ errorMsgObj
+ );
if (exitCodeObj.value === 0) {
statusFlagsObj.value |= EnigmailConstants.IMPORTED_KEY;
}
return "";
}
var newSignature = "";
if (verifyOnly) {
- newSignature = EnigmailArmor.extractSignaturePart(pgpBlock, EnigmailConstants.SIGNATURE_ARMOR);
- if (oldSignature && (newSignature != oldSignature)) {
- EnigmailLog.ERROR("enigmail.js: Enigmail.decryptMessage: Error - signature mismatch " + newSignature + "\n");
+ newSignature = EnigmailArmor.extractSignaturePart(
+ pgpBlock,
+ EnigmailConstants.SIGNATURE_ARMOR
+ );
+ if (oldSignature && newSignature != oldSignature) {
+ EnigmailLog.ERROR(
+ "enigmail.js: Enigmail.decryptMessage: Error - signature mismatch " +
+ newSignature +
+ "\n"
+ );
errorMsgObj.value = EnigmailLocale.getString("sigMismatch");
statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
return "";
}
}
if (!EnigmailCore.getService(parent)) {
- EnigmailLog.ERROR("decryption.jsm: decryptMessage: not yet initialized\n");
+ EnigmailLog.ERROR(
+ "decryption.jsm: decryptMessage: not yet initialized\n"
+ );
errorMsgObj.value = EnigmailLocale.getString("notInit");
statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
return "";
}
if (EnigmailKeyRing.isGeneratingKey()) {
errorMsgObj.value = EnigmailLocale.getString("notComplete");
statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
return "";
}
// limit output to 100 times message size to avoid DoS attack
var maxOutput = pgpBlock.length * 100;
let keyserver = EnigmailPrefs.getPref("autoKeyRetrieve");
let options = {
- keyserver: keyserver,
+ keyserver,
keyserverProxy: EnigmailHttpProxy.getHttpProxy(keyserver),
fromAddr: EnigmailDecryption.getFromAddr(parent),
- verifyOnly: verifyOnly,
+ verifyOnly,
noOutput: false,
maxOutputLength: maxOutput,
- uiFlags: uiFlags
+ uiFlags,
};
const cApi = EnigmailCryptoAPI();
let result = cApi.sync(cApi.decrypt(pgpBlock, options));
EnigmailLog.DEBUG("decryption.jsm: decryptMessage: decryption finished\n");
- if (! result) {
+ if (!result) {
return "";
}
var plainText = EnigmailData.getUnicodeData(result.decryptedData);
exitCodeObj.value = result.exitCode;
statusFlagsObj.value = result.statusFlags;
errorMsgObj.value = result.errorMsg;
// do not return anything if gpg signales DECRYPTION_FAILED
// (which could be possible in case of MDC errors)
- if ((uiFlags & EnigmailConstants.UI_IGNORE_MDC_ERROR) &&
- (result.statusFlags & EnigmailConstants.MISSING_MDC)) {
+ if (
+ uiFlags & EnigmailConstants.UI_IGNORE_MDC_ERROR &&
+ result.statusFlags & EnigmailConstants.MISSING_MDC
+ ) {
EnigmailLog.DEBUG("decryption.jsm: decryptMessage: ignoring MDC error\n");
- }
- else if (result.statusFlags & EnigmailConstants.DECRYPTION_FAILED) {
+ } else if (result.statusFlags & EnigmailConstants.DECRYPTION_FAILED) {
EnigmailLog.DEBUG("decryption.jsm: decryptMessage: failed\n");
plainText = "";
}
userIdObj.value = result.userId;
keyIdObj.value = result.keyId;
sigDetailsObj.value = result.sigDetails;
if (encToDetailsObj) {
encToDetailsObj.value = result.encToDetails;
}
blockSeparationObj.value = result.blockSeparation;
if (tail.search(/\S/) >= 0) {
statusFlagsObj.value |= EnigmailConstants.PARTIALLY_PGP;
}
-
if (exitCodeObj.value === 0) {
// Normal return
- var doubleDashSeparator = false;
- try {
- doubleDashSeparator = EnigmailPrefs.getPrefBranch().getBoolPref("doubleDashSeparator");
- }
- catch (ex) {}
+ let doubleDashSeparator = EnigmailPrefs.getPrefBranch().getBoolPref(
+ "doubleDashSeparator",
+ false
+ );
- if (doubleDashSeparator && (plainText.search(/(\r|\n)-- +(\r|\n)/) < 0)) {
+ if (doubleDashSeparator && plainText.search(/(\r|\n)-- +(\r|\n)/) < 0) {
// Workaround for MsgCompose stripping trailing spaces from sig separator
plainText = plainText.replace(/(\r|\n)--(\r|\n)/, "$1-- $2");
}
statusFlagsObj.value |= EnigmailConstants.DISPLAY_MESSAGE;
if (verifyOnly && indentStrObj.value) {
plainText = plainText.replace(/^/gm, indentStrObj.value);
}
- return EnigmailDecryption.inlineInnerVerification(parent, uiFlags, plainText,
- statusObjectFrom(signatureObj, exitCodeObj, statusFlagsObj, keyIdObj, userIdObj,
- sigDetailsObj, errorMsgObj, blockSeparationObj, encToDetailsObj));
+ return EnigmailDecryption.inlineInnerVerification(
+ parent,
+ uiFlags,
+ plainText,
+ statusObjectFrom(
+ signatureObj,
+ exitCodeObj,
+ statusFlagsObj,
+ keyIdObj,
+ userIdObj,
+ sigDetailsObj,
+ errorMsgObj,
+ blockSeparationObj,
+ encToDetailsObj
+ )
+ );
}
var pubKeyId = keyIdObj.value;
if (statusFlagsObj.value & EnigmailConstants.BAD_SIGNATURE) {
if (verifyOnly && indentStrObj.value) {
// Probably replied message that could not be verified
- errorMsgObj.value = EnigmailLocale.getString("unverifiedReply") + "\n\n" + errorMsgObj.value;
+ errorMsgObj.value =
+ EnigmailLocale.getString("unverifiedReply") +
+ "\n\n" +
+ errorMsgObj.value;
return "";
}
// Return bad signature (for checking later)
signatureObj.value = newSignature;
-
- }
- else if (pubKeyId &&
- (statusFlagsObj.value & EnigmailConstants.UNVERIFIED_SIGNATURE)) {
-
+ } else if (
+ pubKeyId &&
+ statusFlagsObj.value & EnigmailConstants.UNVERIFIED_SIGNATURE
+ ) {
var innerKeyBlock;
if (verifyOnly) {
// Search for indented public key block in signed message
- var innerBlockType = EnigmailArmor.locateArmoredBlock(pgpBlock, 0, "- ", beginIndexObj, endIndexObj, indentStrObj);
+ var innerBlockType = EnigmailArmor.locateArmoredBlock(
+ pgpBlock,
+ 0,
+ "- ",
+ beginIndexObj,
+ endIndexObj,
+ indentStrObj
+ );
if (innerBlockType == "PUBLIC KEY BLOCK") {
-
- innerKeyBlock = pgpBlock.substr(beginIndexObj.value,
- endIndexObj.value - beginIndexObj.value + 1);
+ innerKeyBlock = pgpBlock.substr(
+ beginIndexObj.value,
+ endIndexObj.value - beginIndexObj.value + 1
+ );
innerKeyBlock = innerKeyBlock.replace(/- -----/g, "-----");
statusFlagsObj.value |= EnigmailConstants.INLINE_KEY;
- EnigmailLog.DEBUG("decryption.jsm: decryptMessage: innerKeyBlock found\n");
+ EnigmailLog.DEBUG(
+ "decryption.jsm: decryptMessage: innerKeyBlock found\n"
+ );
}
}
if (allowImport) {
-
var importedKey = false;
if (innerKeyBlock) {
var importErrorMsgObj = {};
- var exitStatus = EnigmailKeyRing.importKey(parent, true, innerKeyBlock,
- pubKeyId, importErrorMsgObj);
+ var exitStatus = EnigmailKeyRing.importKey(
+ parent,
+ true,
+ innerKeyBlock,
+ pubKeyId,
+ importErrorMsgObj
+ );
- importedKey = (exitStatus === 0);
+ importedKey = exitStatus === 0;
if (exitStatus > 0) {
- EnigmailDialog.alert(parent, EnigmailLocale.getString("cantImport") + importErrorMsgObj.value);
+ EnigmailDialog.alert(
+ parent,
+ EnigmailLocale.getString("cantImport") + importErrorMsgObj.value
+ );
}
}
if (importedKey) {
// Recursive call; note that EnigmailConstants.UI_ALLOW_KEY_IMPORT is unset
// to break the recursion
var uiFlagsDeep = interactive ? EnigmailConstants.UI_INTERACTIVE : 0;
signatureObj.value = "";
- return EnigmailDecryption.decryptMessage(parent, uiFlagsDeep, pgpBlock,
- signatureObj, exitCodeObj, statusFlagsObj,
- keyIdObj, userIdObj, sigDetailsObj, errorMsgObj);
+ return EnigmailDecryption.decryptMessage(
+ parent,
+ uiFlagsDeep,
+ pgpBlock,
+ signatureObj,
+ exitCodeObj,
+ statusFlagsObj,
+ keyIdObj,
+ userIdObj,
+ sigDetailsObj,
+ errorMsgObj
+ );
}
-
}
if (plainText && !unverifiedEncryptedOK) {
// Append original PGP block to unverified message
- plainText = "-----BEGIN PGP UNVERIFIED MESSAGE-----\r\n" + plainText +
- "-----END PGP UNVERIFIED MESSAGE-----\r\n\r\n" + pgpBlock;
+ plainText =
+ "-----BEGIN PGP UNVERIFIED MESSAGE-----\r\n" +
+ plainText +
+ "-----END PGP UNVERIFIED MESSAGE-----\r\n\r\n" +
+ pgpBlock;
}
-
}
return verifyOnly ? "" : plainText;
},
- inlineInnerVerification: function(parent, uiFlags, text, statusObject) {
+ inlineInnerVerification(parent, uiFlags, text, statusObject) {
EnigmailLog.DEBUG("decryption.jsm: inlineInnerVerification()\n");
if (text && text.indexOf("-----BEGIN PGP SIGNED MESSAGE-----") === 0) {
var status = newStatusObject();
- var newText = EnigmailDecryption.decryptMessage(parent, uiFlags, text,
- status.signature, status.exitCode, status.statusFlags, status.keyId, status.userId,
- status.sigDetails, status.message, status.blockSeparation, status.encToDetails);
+ var newText = EnigmailDecryption.decryptMessage(
+ parent,
+ uiFlags,
+ text,
+ status.signature,
+ status.exitCode,
+ status.statusFlags,
+ status.keyId,
+ status.userId,
+ status.sigDetails,
+ status.message,
+ status.blockSeparation,
+ status.encToDetails
+ );
if (status.exitCode.value === 0) {
text = newText;
// merge status into status object:
- statusObject.statusFlags.value = statusObject.statusFlags.value | status.statusFlags.value;
+ statusObject.statusFlags.value =
+ statusObject.statusFlags.value | status.statusFlags.value;
statusObject.keyId.value = status.keyId.value;
statusObject.userId.value = status.userId.value;
statusObject.sigDetails.value = status.sigDetails.value;
statusObject.message.value = status.message.value;
// we don't merge encToDetails
}
}
return text;
},
- decryptAttachment: function(parent, outFile, displayName, byteData,
- exitCodeObj, statusFlagsObj, errorMsgObj) {
- const esvc = EnigmailCore.getEnigmailService();
-
- EnigmailLog.DEBUG("decryption.jsm: decryptAttachment(parent=" + parent + ", outFileName=" + outFile.path + ")\n");
+ decryptAttachment(
+ parent,
+ outFile,
+ displayName,
+ byteData,
+ exitCodeObj,
+ statusFlagsObj,
+ errorMsgObj
+ ) {
+ EnigmailLog.DEBUG(
+ "decryption.jsm: decryptAttachment(parent=" +
+ parent +
+ ", outFileName=" +
+ outFile.path +
+ ")\n"
+ );
let attachmentHead = byteData.substr(0, 200);
if (attachmentHead.match(/-----BEGIN PGP \w{5,10} KEY BLOCK-----/)) {
// attachment appears to be a PGP key file
- if (EnigmailDialog.confirmDlg(parent, EnigmailLocale.getString("attachmentPgpKey", [displayName]),
- EnigmailLocale.getString("keyMan.button.import"), EnigmailLocale.getString("dlg.button.view"))) {
-
+ if (
+ EnigmailDialog.confirmDlg(
+ parent,
+ EnigmailLocale.getString("attachmentPgpKey", [displayName]),
+ EnigmailLocale.getString("keyMan.button.import"),
+ EnigmailLocale.getString("dlg.button.view")
+ )
+ ) {
let preview = EnigmailKey.getKeyListFromKeyBlock(byteData, errorMsgObj);
exitCodeObj.keyList = preview;
let exitStatus = 0;
if (errorMsgObj.value === "") {
if (preview.length > 0) {
if (preview.length == 1) {
- exitStatus = EnigmailDialog.confirmDlg(parent, EnigmailLocale.getString("doImportOne", [preview[0].name, preview[0].id]));
- }
- else {
- exitStatus = EnigmailDialog.confirmDlg(parent,
+ exitStatus = EnigmailDialog.confirmDlg(
+ parent,
+ EnigmailLocale.getString("doImportOne", [
+ preview[0].name,
+ preview[0].id,
+ ])
+ );
+ } else {
+ exitStatus = EnigmailDialog.confirmDlg(
+ parent,
EnigmailLocale.getString("doImportMultiple", [
- preview.map(function(a) {
- return "\t" + a.name + " (" + a.id + ")";
- }).
- join("\n")
- ]));
+ preview
+ .map(function(a) {
+ return "\t" + a.name + " (" + a.id + ")";
+ })
+ .join("\n"),
+ ])
+ );
}
if (exitStatus) {
- exitCodeObj.value = EnigmailKeyRing.importKey(parent, false, byteData, "", errorMsgObj);
+ exitCodeObj.value = EnigmailKeyRing.importKey(
+ parent,
+ false,
+ byteData,
+ "",
+ errorMsgObj
+ );
statusFlagsObj.value = EnigmailConstants.IMPORTED_KEY;
- }
- else {
+ } else {
exitCodeObj.value = 0;
statusFlagsObj.value = EnigmailConstants.DISPLAY_MESSAGE;
}
}
}
- }
- else {
+ } else {
exitCodeObj.value = 0;
statusFlagsObj.value = EnigmailConstants.DISPLAY_MESSAGE;
}
return true;
}
//var outFileName = EnigmailFiles.getEscapedFilename(EnigmailFiles.getFilePathReadonly(outFile.QueryInterface(Ci.nsIFile), NS_WRONLY));
@@ -422,10 +588,10 @@ var EnigmailDecryption = {
exitCodeObj.value = result.exitCode;
statusFlagsObj.value = result.statusFlags;
if (result.stdoutData.length > 0) {
return EnigmailFiles.writeFileContents(outFile, result.stdoutData);
}
return false;
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/dialog.jsm
+++ b/mail/extensions/openpgp/content/modules/dialog.jsm
@@ -1,93 +1,108 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailDialog"];
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailWindows = ChromeUtils.import("chrome://openpgp/content/modules/windows.jsm").EnigmailWindows;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
-const BUTTON_POS_0 = 1;
-const BUTTON_POS_1 = 1 << 8;
-const BUTTON_POS_2 = 1 << 16;
-
-const gPromptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailWindows = ChromeUtils.import(
+ "chrome://openpgp/content/modules/windows.jsm"
+).EnigmailWindows;
+const EnigmailPrefs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
const LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";
var EnigmailDialog = {
-
/***
* Confirmation dialog with OK / Cancel buttons (both customizable)
*
* @win: nsIWindow - parent window to display modal dialog; can be null
* @mesg: String - message text
* @okLabel: String - OPTIONAL label for OK button
* @cancelLabel: String - OPTIONAL label for cancel button
*
* @return: Boolean - true: OK pressed / false: Cancel or ESC pressed
*/
- confirmDlg: function(win, mesg, okLabel, cancelLabel) {
-
- let buttonPressed = EnigmailDialog.msgBox(win, {
+ confirmDlg(win, mesg, okLabel, cancelLabel) {
+ let buttonPressed = EnigmailDialog.msgBox(
+ win,
+ {
msgtext: mesg,
button1: okLabel ? okLabel : EnigmailLocale.getString("dlg.button.ok"),
- cancelButton: cancelLabel ? cancelLabel : EnigmailLocale.getString("dlg.button.cancel"),
+ cancelButton: cancelLabel
+ ? cancelLabel
+ : EnigmailLocale.getString("dlg.button.cancel"),
iconType: EnigmailConstants.ICONTYPE_QUESTION,
- dialogTitle: EnigmailLocale.getString("enigConfirm")
+ dialogTitle: EnigmailLocale.getString("enigConfirm"),
},
- null);
+ null
+ );
- return (buttonPressed === 0);
+ return buttonPressed === 0;
},
/**
* Displays an alert dialog.
*
* @win: nsIWindow - parent window to display modal dialog; can be null
* @mesg: String - message text
*
* no return value
*/
- alert: function(win, mesg) {
- EnigmailDialog.msgBox(win, {
+ alert(win, mesg) {
+ EnigmailDialog.msgBox(
+ win,
+ {
msgtext: mesg,
button1: EnigmailLocale.getString("dlg.button.close"),
iconType: EnigmailConstants.ICONTYPE_ALERT,
- dialogTitle: EnigmailLocale.getString("enigAlert")
+ dialogTitle: EnigmailLocale.getString("enigAlert"),
},
- null);
+ null
+ );
},
/**
* Displays an information dialog.
*
* @win: nsIWindow - parent window to display modal dialog; can be null
* @mesg: String - message text
*
* no return value
*/
- info: function(win, mesg) {
- EnigmailDialog.msgBox(win, {
+ info(win, mesg) {
+ EnigmailDialog.msgBox(
+ win,
+ {
msgtext: mesg,
button1: EnigmailLocale.getString("dlg.button.close"),
iconType: EnigmailConstants.ICONTYPE_INFO,
- dialogTitle: EnigmailLocale.getString("enigInfo")
+ dialogTitle: EnigmailLocale.getString("enigInfo"),
},
- null);
+ null
+ );
},
/**
* Displays an alert dialog with 1-3 optional buttons.
*
* @win: nsIWindow - parent window to display modal dialog; can be null
* @mesg: String - message text
* @checkboxLabel: String - if not null, display checkbox with text; the
@@ -96,36 +111,48 @@ var EnigmailDialog = {
* use "buttonType:label" or ":buttonType" to indicate special button types
* (buttonType is one of cancel, help, extra1, extra2)
* @checkedObj: Object - holding the checkbox value
*
* @return: 0-2: button Number pressed
* -1: ESC or close window button pressed
*
*/
- longAlert: function(win, mesg, checkboxLabel, okLabel, labelButton2, labelButton3, checkedObj) {
+ longAlert(
+ win,
+ mesg,
+ checkboxLabel,
+ okLabel,
+ labelButton2,
+ labelButton3,
+ checkedObj
+ ) {
var result = {
value: -1,
- checked: false
+ checked: false,
};
if (!win) {
win = EnigmailWindows.getBestParentWin();
}
- win.openDialog("chrome://openpgp/content/ui/enigmailMsgBox.xhtml", "_blank",
- "chrome,dialog,modal,centerscreen,resizable,titlebar", {
+ win.openDialog(
+ "chrome://openpgp/content/ui/enigmailMsgBox.xhtml",
+ "_blank",
+ "chrome,dialog,modal,centerscreen,resizable,titlebar",
+ {
msgtext: mesg,
- checkboxLabel: checkboxLabel,
+ checkboxLabel,
iconType: EnigmailConstants.ICONTYPE_ALERT,
button1: okLabel,
button2: labelButton2,
- button3: labelButton3
+ button3: labelButton3,
},
- result);
+ result
+ );
if (checkboxLabel) {
checkedObj.value = result.checked;
}
return result.value;
},
/**
@@ -147,76 +174,90 @@ var EnigmailDialog = {
* if no button is provided, OK will be displayed
*
* @checkedObj: Object - holding the checkbox value
*
* @return: 0-2: button Number pressed
* -1: cancel button, ESC or close window button pressed
*
*/
- msgBox: function(win, argsObj, checkedObj) {
+ msgBox(win, argsObj, checkedObj) {
var result = {
value: -1,
- checked: false
+ checked: false,
};
if (!win) {
win = EnigmailWindows.getBestParentWin();
}
- win.openDialog("chrome://openpgp/content/ui/enigmailMsgBox.xhtml", "",
- "chrome,dialog,modal,centerscreen,resizable", argsObj, result);
+ win.openDialog(
+ "chrome://openpgp/content/ui/enigmailMsgBox.xhtml",
+ "",
+ "chrome,dialog,modal,centerscreen,resizable",
+ argsObj,
+ result
+ );
if (argsObj.checkboxLabel) {
checkedObj.value = result.checked;
}
return result.value;
},
/**
* Display a dialog with a message and a text entry field
*
* @win: nsIWindow - parent window to display modal dialog; can be null
* @mesg: String - message text
* @valueObj: Object - object to hold the entered text in .value
*
* @return: Boolean - true if OK was pressed / false otherwise
*/
- promptValue: function(win, mesg, valueObj) {
- return gPromptSvc.prompt(win, EnigmailLocale.getString("enigPrompt"),
- mesg, valueObj, "", {});
+ promptValue(win, mesg, valueObj) {
+ return Services.prompt(
+ win,
+ EnigmailLocale.getString("enigPrompt"),
+ mesg,
+ valueObj,
+ "",
+ {}
+ );
},
/**
* Display an alert message with an OK button and a checkbox to hide
* the message in the future.
* In case the checkbox was pressed in the past, the dialog is skipped
*
* @win: nsIWindow - the parent window to hold the modal dialog
* @mesg: String - the localized message to display
* @prefText: String - the name of the Enigmail preference to read/store the
* the future display status
*/
- alertPref: function(win, mesg, prefText) {
+ alertPref(win, mesg, prefText) {
const display = true;
const dontDisplay = false;
let prefValue = EnigmailPrefs.getPref(prefText);
if (prefValue === display) {
let checkBoxObj = {
- value: false
+ value: false,
};
- let buttonPressed = EnigmailDialog.msgBox(win, {
+ let buttonPressed = EnigmailDialog.msgBox(
+ win,
+ {
msgtext: mesg,
dialogTitle: EnigmailLocale.getString("enigInfo"),
iconType: EnigmailConstants.ICONTYPE_INFO,
- checkboxLabel: EnigmailLocale.getString("dlgNoPrompt")
+ checkboxLabel: EnigmailLocale.getString("dlgNoPrompt"),
},
- checkBoxObj);
+ checkBoxObj
+ );
if (checkBoxObj.value && buttonPressed === 0) {
EnigmailPrefs.setPref(prefText, dontDisplay);
}
}
},
/**
@@ -225,30 +266,33 @@ var EnigmailDialog = {
* If |counter| is 0, the dialog is not displayed.
*
* @win: nsIWindow - the parent window to hold the modal dialog
* @countPrefName: String - the name of the Enigmail preference to read/store the
* the |counter| value
* @mesg: String - the localized message to display
*
*/
- alertCount: function(win, countPrefName, mesg) {
+ alertCount(win, countPrefName, mesg) {
let alertCount = EnigmailPrefs.getPref(countPrefName);
- if (alertCount <= 0)
+ if (alertCount <= 0) {
return;
+ }
alertCount--;
EnigmailPrefs.setPref(countPrefName, alertCount);
if (alertCount > 0) {
mesg += EnigmailLocale.getString("repeatPrefix", [alertCount]) + " ";
- mesg += (alertCount == 1) ? EnigmailLocale.getString("repeatSuffixSingular") : EnigmailLocale.getString("repeatSuffixPlural");
- }
- else {
+ mesg +=
+ alertCount == 1
+ ? EnigmailLocale.getString("repeatSuffixSingular")
+ : EnigmailLocale.getString("repeatSuffixPlural");
+ } else {
mesg += EnigmailLocale.getString("noRepeat");
}
EnigmailDialog.alert(win, mesg);
},
/**
* Display a confirmation dialog with OK / Cancel buttons (both customizable) and
@@ -264,77 +308,90 @@ var EnigmailDialog = {
* @cancelLabel: String - OPTIONAL label for cancel button
*
* @return: Boolean - true: 1 pressed / 0: Cancel pressed / -1: ESC pressed
*
* If the dialog is not displayed:
* - if @prefText is type Boolean: return 1
* - if @prefText is type Number: return the last choice of the user
*/
- confirmPref: function(win, mesg, prefText, okLabel, cancelLabel) {
+ confirmPref(win, mesg, prefText, okLabel, cancelLabel) {
const notSet = 0;
const yes = 1;
const no = 2;
const display = true;
const dontDisplay = false;
var prefValue = EnigmailPrefs.getPref(prefText);
- if (typeof(prefValue) != "boolean") {
+ if (typeof prefValue != "boolean") {
// number: remember user's choice
switch (prefValue) {
- case notSet:
- {
- let checkBoxObj = {
- value: false
- };
- let buttonPressed = EnigmailDialog.msgBox(win, {
+ case notSet: {
+ let checkBoxObj = {
+ value: false,
+ };
+ let buttonPressed = EnigmailDialog.msgBox(
+ win,
+ {
msgtext: mesg,
- button1: okLabel ? okLabel : EnigmailLocale.getString("dlg.button.ok"),
- cancelButton: cancelLabel ? cancelLabel : EnigmailLocale.getString("dlg.button.cancel"),
+ button1: okLabel
+ ? okLabel
+ : EnigmailLocale.getString("dlg.button.ok"),
+ cancelButton: cancelLabel
+ ? cancelLabel
+ : EnigmailLocale.getString("dlg.button.cancel"),
checkboxLabel: EnigmailLocale.getString("dlgKeepSetting"),
iconType: EnigmailConstants.ICONTYPE_QUESTION,
- dialogTitle: EnigmailLocale.getString("enigConfirm")
- }, checkBoxObj);
+ dialogTitle: EnigmailLocale.getString("enigConfirm"),
+ },
+ checkBoxObj
+ );
- if (checkBoxObj.value) {
- EnigmailPrefs.setPref(prefText, (buttonPressed === 0 ? yes : no));
- }
- return (buttonPressed === 0 ? 1 : 0);
+ if (checkBoxObj.value) {
+ EnigmailPrefs.setPref(prefText, buttonPressed === 0 ? yes : no);
}
+ return buttonPressed === 0 ? 1 : 0;
+ }
case yes:
return 1;
case no:
return 0;
default:
return -1;
}
- }
- else {
+ } else {
// boolean: "do not show this dialog anymore" (and return default)
switch (prefValue) {
- case display:
- {
- let checkBoxObj = {
- value: false
- };
- let buttonPressed = EnigmailDialog.msgBox(win, {
+ case display: {
+ let checkBoxObj = {
+ value: false,
+ };
+ let buttonPressed = EnigmailDialog.msgBox(
+ win,
+ {
msgtext: mesg,
- button1: okLabel ? okLabel : EnigmailLocale.getString("dlg.button.ok"),
- cancelButton: cancelLabel ? cancelLabel : EnigmailLocale.getString("dlg.button.cancel"),
+ button1: okLabel
+ ? okLabel
+ : EnigmailLocale.getString("dlg.button.ok"),
+ cancelButton: cancelLabel
+ ? cancelLabel
+ : EnigmailLocale.getString("dlg.button.cancel"),
checkboxLabel: EnigmailLocale.getString("dlgNoPrompt"),
iconType: EnigmailConstants.ICONTYPE_QUESTION,
- dialogTitle: EnigmailLocale.getString("enigConfirm")
- }, checkBoxObj);
+ dialogTitle: EnigmailLocale.getString("enigConfirm"),
+ },
+ checkBoxObj
+ );
- if (checkBoxObj.value) {
- EnigmailPrefs.setPref(prefText, false);
- }
- return (buttonPressed === 0 ? 1 : 0);
+ if (checkBoxObj.value) {
+ EnigmailPrefs.setPref(prefText, false);
}
+ return buttonPressed === 0 ? 1 : 0;
+ }
case dontDisplay:
return 1;
default:
return -1;
}
}
},
@@ -347,59 +404,74 @@ var EnigmailDialog = {
* save: Boolean - true = Save file / false = Open file
* defaultExtension: String - optional: extension for the type of files to work with, e.g. "asc"
* defaultName: String - optional: filename, incl. extension, that should be suggested to
* the user as default, e.g. "keys.asc"
* filterPairs: Array - optional: [title, extension], e.g. ["Pictures", "*.jpg; *.png"]
*
* return value: nsIFile object representing the file to load or save
*/
- filePicker: function(win, title, displayDir, save, defaultExtension, defaultName, filterPairs) {
+ filePicker(
+ win,
+ title,
+ displayDir,
+ save,
+ defaultExtension,
+ defaultName,
+ filterPairs
+ ) {
EnigmailLog.DEBUG("enigmailCommon.jsm: filePicker: " + save + "\n");
let filePicker = Cc["@mozilla.org/filepicker;1"].createInstance();
filePicker = filePicker.QueryInterface(Ci.nsIFilePicker);
let mode = save ? Ci.nsIFilePicker.modeSave : Ci.nsIFilePicker.modeOpen;
filePicker.init(win, title, mode);
if (displayDir) {
var localFile = Cc[LOCAL_FILE_CONTRACTID].createInstance(Ci.nsIFile);
try {
localFile.initWithPath(displayDir);
filePicker.displayDirectory = localFile;
- }
- catch (ex) {}
+ } catch (ex) {}
}
if (defaultExtension) {
filePicker.defaultExtension = defaultExtension;
}
if (defaultName) {
filePicker.defaultString = defaultName;
}
let nfilters = 0;
if (filterPairs && filterPairs.length) {
nfilters = filterPairs.length / 2;
}
for (let index = 0; index < nfilters; index++) {
- filePicker.appendFilter(filterPairs[2 * index], filterPairs[2 * index + 1]);
+ filePicker.appendFilter(
+ filterPairs[2 * index],
+ filterPairs[2 * index + 1]
+ );
}
filePicker.appendFilters(Ci.nsIFilePicker.filterAll);
- let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+ let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+ Ci.nsIJSInspector
+ );
let gotFile = null;
filePicker.open(res => {
- if (res != Ci.nsIFilePicker.returnOK && res != Ci.nsIFilePicker.returnReplace) {
+ if (
+ res != Ci.nsIFilePicker.returnOK &&
+ res != Ci.nsIFilePicker.returnReplace
+ ) {
inspector.exitNestedEventLoop();
return;
}
gotFile = filePicker.file.QueryInterface(Ci.nsIFile);
inspector.exitNestedEventLoop();
});
@@ -414,35 +486,39 @@ var EnigmailDialog = {
*
* @param win: nsIWindow - parent window to display modal dialog; can be null
* @param keyList: Array of String - imported keyIDs
*
* @return: 0-2: button Number pressed
* -1: ESC or close window button pressed
*
*/
- keyImportDlg: function(win, keyList) {
+ keyImportDlg(win, keyList) {
var result = {
value: -1,
- checked: false
+ checked: false,
};
if (!win) {
win = EnigmailWindows.getBestParentWin();
}
- win.openDialog("chrome://openpgp/content/ui/enigmailKeyImportInfo.xhtml", "",
- "chrome,dialog,modal,centerscreen,resizable", {
- keyList: keyList
+ win.openDialog(
+ "chrome://openpgp/content/ui/enigmailKeyImportInfo.xhtml",
+ "",
+ "chrome,dialog,modal,centerscreen,resizable",
+ {
+ keyList,
},
- result);
+ result
+ );
return result.value;
},
/**
* return a pre-initialized prompt service
*/
- getPromptSvc: function() {
- return gPromptSvc;
- }
+ getPromptSvc() {
+ return Services.prompt;
+ },
};
EnigmailWindows.alert = EnigmailDialog.alert;
--- a/mail/extensions/openpgp/content/modules/encryption.jsm
+++ b/mail/extensions/openpgp/content/modules/encryption.jsm
@@ -1,204 +1,275 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailEncryption"];
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailPrefs = ChromeUtils.import("chrome://openpgp/content/modules/prefs.jsm").EnigmailPrefs;
-const EnigmailApp = ChromeUtils.import("chrome://openpgp/content/modules/app.jsm").EnigmailApp;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailDialog = ChromeUtils.import("chrome://openpgp/content/modules/dialog.jsm").EnigmailDialog;
-const EnigmailGpg = ChromeUtils.import("chrome://openpgp/content/modules/gpg.jsm").EnigmailGpg;
-const EnigmailErrorHandling = ChromeUtils.import("chrome://openpgp/content/modules/errorHandling.jsm").EnigmailErrorHandling;
-const EnigmailFiles = ChromeUtils.import("chrome://openpgp/content/modules/files.jsm").EnigmailFiles;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailCryptoAPI = ChromeUtils.import("chrome://openpgp/content/modules/cryptoAPI.jsm").EnigmailCryptoAPI;
+const EnigmailCore = ChromeUtils.import(
+ "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailData = ChromeUtils.import(
+ "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailPrefs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/prefs.jsm"
+).EnigmailPrefs;
+const EnigmailApp = ChromeUtils.import(
+ "chrome://openpgp/content/modules/app.jsm"
+).EnigmailApp;
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailDialog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/dialog.jsm"
+).EnigmailDialog;
+const EnigmailGpg = ChromeUtils.import(
+ "chrome://openpgp/content/modules/gpg.jsm"
+).EnigmailGpg;
+const EnigmailErrorHandling = ChromeUtils.import(
+ "chrome://openpgp/content/modules/errorHandling.jsm"
+).EnigmailErrorHandling;
+const EnigmailFiles = ChromeUtils.import(
+ "chrome://openpgp/content/modules/files.jsm"
+).EnigmailFiles;
+const EnigmailFuncs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailKeyRing = ChromeUtils.import(
+ "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailCryptoAPI = ChromeUtils.import(
+ "chrome://openpgp/content/modules/cryptoAPI.jsm"
+).EnigmailCryptoAPI;
-const gMimeHashAlgorithms = [null, "sha1", "ripemd160", "sha256", "sha384", "sha512", "sha224", "md5"];
+const gMimeHashAlgorithms = [
+ null,
+ "sha1",
+ "ripemd160",
+ "sha256",
+ "sha384",
+ "sha512",
+ "sha224",
+ "md5",
+];
const ENC_TYPE_MSG = 0;
const ENC_TYPE_ATTACH_BINARY = 1;
const ENC_TYPE_ATTACH_ASCII = 2;
-const GPG_COMMENT_OPT = "Using GnuPG with %s - https://doesnotexist-openpgp-integration.thunderbird/";
-
+const GPG_COMMENT_OPT =
+ "Using GnuPG with %s - https://doesnotexist-openpgp-integration.thunderbird/";
var EnigmailEncryption = {
- getEncryptCommand: function(fromMailAddr, toMailAddr, bccMailAddr, hashAlgorithm, sendFlags, isAscii, errorMsgObj,
- logFileObj) {
- EnigmailLog.DEBUG("encryption.jsm: getEncryptCommand: hashAlgorithm=" + hashAlgorithm + "\n");
+ getEncryptCommand(
+ fromMailAddr,
+ toMailAddr,
+ bccMailAddr,
+ hashAlgorithm,
+ sendFlags,
+ isAscii,
+ errorMsgObj,
+ logFileObj
+ ) {
+ EnigmailLog.DEBUG(
+ "encryption.jsm: getEncryptCommand: hashAlgorithm=" + hashAlgorithm + "\n"
+ );
try {
fromMailAddr = EnigmailFuncs.stripEmail(fromMailAddr);
toMailAddr = EnigmailFuncs.stripEmail(toMailAddr);
bccMailAddr = EnigmailFuncs.stripEmail(bccMailAddr);
-
- }
- catch (ex) {
+ } catch (ex) {
errorMsgObj.value = EnigmailLocale.getString("invalidEmail");
return null;
}
- var defaultSend = sendFlags & EnigmailConstants.SEND_DEFAULT;
var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
var encryptMsg = sendFlags & EnigmailConstants.SEND_ENCRYPTED;
var usePgpMime = sendFlags & EnigmailConstants.SEND_PGP_MIME;
var useDefaultComment = false;
try {
useDefaultComment = EnigmailPrefs.getPref("useDefaultComment");
- }
- catch (ex) {}
+ } catch (ex) {}
var hushMailSupport = false;
try {
hushMailSupport = EnigmailPrefs.getPref("hushMailSupport");
- }
- catch (ex) {}
+ } catch (ex) {}
- var detachedSig = (usePgpMime || (sendFlags & EnigmailConstants.SEND_ATTACHMENT)) && signMsg && !encryptMsg;
+ var detachedSig =
+ (usePgpMime || sendFlags & EnigmailConstants.SEND_ATTACHMENT) &&
+ signMsg &&
+ !encryptMsg;
var toAddrList = toMailAddr.split(/\s*,\s*/);
var bccAddrList = bccMailAddr.split(/\s*,\s*/);
var k;
var encryptArgs = EnigmailGpg.getStandardArgs(true);
- if (!useDefaultComment)
- encryptArgs = encryptArgs.concat(["--comment", GPG_COMMENT_OPT.replace(/%s/, EnigmailApp.getName())]);
+ if (!useDefaultComment) {
+ encryptArgs = encryptArgs.concat([
+ "--comment",
+ GPG_COMMENT_OPT.replace(/%s/, EnigmailApp.getName()),
+ ]);
+ }
- var angledFromMailAddr = ((fromMailAddr.search(/^0x/) === 0) || hushMailSupport) ?
- fromMailAddr : "<" + fromMailAddr + ">";
+ var angledFromMailAddr =
+ fromMailAddr.search(/^0x/) === 0 || hushMailSupport
+ ? fromMailAddr
+ : "<" + fromMailAddr + ">";
angledFromMailAddr = angledFromMailAddr.replace(/(["'`])/g, "\\$1");
if (signMsg && hashAlgorithm) {
encryptArgs = encryptArgs.concat(["--digest-algo", hashAlgorithm]);
}
if (logFileObj) {
logFileObj.value = EnigmailErrorHandling.getTempLogFile();
encryptArgs.push("--log-file");
- encryptArgs.push(EnigmailFiles.getEscapedFilename(EnigmailFiles.getFilePath(logFileObj.value)));
+ encryptArgs.push(
+ EnigmailFiles.getEscapedFilename(
+ EnigmailFiles.getFilePath(logFileObj.value)
+ )
+ );
}
if (encryptMsg) {
switch (isAscii) {
case ENC_TYPE_MSG:
encryptArgs.push("-a");
encryptArgs.push("-t");
break;
case ENC_TYPE_ATTACH_ASCII:
encryptArgs.push("-a");
}
encryptArgs.push("--encrypt");
- if (signMsg)
+ if (signMsg) {
encryptArgs.push("--sign");
+ }
if (sendFlags & EnigmailConstants.SEND_ALWAYS_TRUST) {
encryptArgs.push("--trust-model");
encryptArgs.push("always");
}
- if ((sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF) && fromMailAddr)
+ if (sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF && fromMailAddr) {
encryptArgs = encryptArgs.concat(["--encrypt-to", angledFromMailAddr]);
+ }
for (k = 0; k < toAddrList.length; k++) {
toAddrList[k] = toAddrList[k].replace(/'/g, "\\'");
if (toAddrList[k].length > 0) {
encryptArgs.push("-r");
if (toAddrList[k].search(/^GROUP:/) === 0) {
// groups from gpg.conf file
encryptArgs.push(toAddrList[k].substr(6));
- }
- else {
- encryptArgs.push((hushMailSupport || (toAddrList[k].search(/^0x/) === 0)) ? toAddrList[k] : "<" + toAddrList[k] + ">");
+ } else {
+ encryptArgs.push(
+ hushMailSupport || toAddrList[k].search(/^0x/) === 0
+ ? toAddrList[k]
+ : "<" + toAddrList[k] + ">"
+ );
}
}
}
for (k = 0; k < bccAddrList.length; k++) {
bccAddrList[k] = bccAddrList[k].replace(/'/g, "\\'");
if (bccAddrList[k].length > 0) {
encryptArgs.push("--hidden-recipient");
- encryptArgs.push((hushMailSupport || (bccAddrList[k].search(/^0x/) === 0)) ? bccAddrList[k] : "<" + bccAddrList[k] + ">");
+ encryptArgs.push(
+ hushMailSupport || bccAddrList[k].search(/^0x/) === 0
+ ? bccAddrList[k]
+ : "<" + bccAddrList[k] + ">"
+ );
}
}
-
- }
- else if (detachedSig) {
+ } else if (detachedSig) {
encryptArgs = encryptArgs.concat(["-s", "-b"]);
switch (isAscii) {
case ENC_TYPE_MSG:
encryptArgs = encryptArgs.concat(["-a", "-t"]);
break;
case ENC_TYPE_ATTACH_ASCII:
encryptArgs.push("-a");
}
-
- }
- else if (signMsg) {
+ } else if (signMsg) {
encryptArgs = encryptArgs.concat(["-t", "--clearsign"]);
}
if (fromMailAddr) {
encryptArgs = encryptArgs.concat(["-u", angledFromMailAddr]);
}
return encryptArgs;
},
-
- getCryptParams: function(fromMailAddr, toMailAddr, bccMailAddr, hashAlgorithm, sendFlags, isAscii, errorMsgObj,
- logFileObj) {
-
+ getCryptParams(
+ fromMailAddr,
+ toMailAddr,
+ bccMailAddr,
+ hashAlgorithm,
+ sendFlags,
+ isAscii,
+ errorMsgObj,
+ logFileObj
+ ) {
let result = {};
result.sender = "";
result.sign = false;
result.signatureHash = "";
result.sigTypeClear = false;
result.sigTypeDetached = false;
result.encrypt = false;
result.encryptToSender = false;
result.armor = false;
-
- EnigmailLog.DEBUG("encryption.jsm: getCryptParams: hashAlgorithm=" + hashAlgorithm + "\n");
+
+ EnigmailLog.DEBUG(
+ "encryption.jsm: getCryptParams: hashAlgorithm=" + hashAlgorithm + "\n"
+ );
- console.debug(`getCryptParams parameters: from=${fromMailAddr}, to=${toMailAddr}, bcc=${bccMailAddr}, hash=${hashAlgorithm}, flags=${sendFlags}, ascii=${isAscii}, errorObj=%o, logObj=%o`,
- errorMsgObj, logFileObj);
+ console.debug(
+ `getCryptParams parameters: from=${fromMailAddr}, to=${toMailAddr}, bcc=${bccMailAddr}, hash=${hashAlgorithm}, flags=${sendFlags}, ascii=${isAscii}, errorObj=%o, logObj=%o`,
+ errorMsgObj,
+ logFileObj
+ );
try {
fromMailAddr = EnigmailFuncs.stripEmail(fromMailAddr);
toMailAddr = EnigmailFuncs.stripEmail(toMailAddr);
bccMailAddr = EnigmailFuncs.stripEmail(bccMailAddr);
- }
- catch (ex) {
+ } catch (ex) {
errorMsgObj.value = EnigmailLocale.getString("invalidEmail");
return null;
}
- var defaultSend = sendFlags & EnigmailConstants.SEND_DEFAULT;
var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
var encryptMsg = sendFlags & EnigmailConstants.SEND_ENCRYPTED;
var usePgpMime = sendFlags & EnigmailConstants.SEND_PGP_MIME;
- var detachedSig = (usePgpMime || (sendFlags & EnigmailConstants.SEND_ATTACHMENT)) && signMsg && !encryptMsg;
+ var detachedSig =
+ (usePgpMime || sendFlags & EnigmailConstants.SEND_ATTACHMENT) &&
+ signMsg &&
+ !encryptMsg;
result.to = toMailAddr.split(/\s*,\s*/);
result.bcc = bccMailAddr.split(/\s*,\s*/);
if (result.to.length == 1 && result.to[0].length == 0) {
result.to.splice(0, 1); // remove the single empty entry
}
@@ -224,17 +295,17 @@ var EnigmailEncryption = {
result.armor = true;
}
result.encrypt = true;
if (signMsg) {
result.sign = true;
}
- if ((sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF) && fromMailAddr) {
+ if (sendFlags & EnigmailConstants.SEND_ENCRYPT_TO_SELF && fromMailAddr) {
result.encryptToSender = true;
}
var k;
for (k = 0; k < result.to.length; k++) {
//result.to[k] = result.to[k].replace(/'/g, "\\'");
if (result.to[k].length > 0 && result.to[k].search(/^0x/) !== 0) {
result.to[k] = "<" + result.to[k] + ">";
@@ -242,148 +313,198 @@ var EnigmailEncryption = {
}
for (k = 0; k < result.bcc.length; k++) {
//result.bcc[k] = result.bcc[k].replace(/'/g, "\\'");
if (result.bcc[k].length > 0 && result.bcc[k].search(/^0x/) !== 0) {
result.bcc[k] = "<" + result.bcc[k] + ">";
}
}
-
- }
- else if (detachedSig) {
+ } else if (detachedSig) {
result.sigTypeDetached = true;
if (isAscii != ENC_TYPE_ATTACH_BINARY) {
result.armor = true;
}
- }
- else if (signMsg) {
+ } else if (signMsg) {
result.sigTypeClear = true;
}
console.debug(`getCryptParams returning:`);
console.debug(result);
return result;
},
-
/**
* Determine if the sender key ID or user ID can be used for signing and/or encryption
*
* @param sendFlags: Number - the send Flags; need to contain SEND_SIGNED and/or SEND_ENCRYPTED
* @param fromMailAddr: String - the sender email address or key ID
*
* @return Object:
* - keyId: String - the found key ID, or null if fromMailAddr is not valid
* - errorMsg: String - the erorr message if key not valid, or null if key is valid
*/
- determineOwnKeyUsability: function(sendFlags, fromMailAddr) {
- EnigmailLog.DEBUG("encryption.jsm: determineOwnKeyUsability: sendFlags=" + sendFlags + ", sender=" + fromMailAddr + "\n");
+ determineOwnKeyUsability(sendFlags, fromMailAddr) {
+ EnigmailLog.DEBUG(
+ "encryption.jsm: determineOwnKeyUsability: sendFlags=" +
+ sendFlags +
+ ", sender=" +
+ fromMailAddr +
+ "\n"
+ );
let keyList = [];
let ret = {
keyId: null,
- errorMsg: null
+ errorMsg: null,
};
- let sign = (sendFlags & EnigmailConstants.SEND_SIGNED ? true : false);
- let encrypt = (sendFlags & EnigmailConstants.SEND_ENCRYPTED ? true : false);
+ let sign = !!(sendFlags & EnigmailConstants.SEND_SIGNED);
+ let encrypt = !!(sendFlags & EnigmailConstants.SEND_ENCRYPTED);
if (fromMailAddr.search(/^(0x)?[A-Z0-9]+$/) === 0) {
// key ID specified
let key = EnigmailKeyRing.getKeyById(fromMailAddr);
keyList.push(key);
- }
- else {
+ } else {
// email address specified
keyList = EnigmailKeyRing.getKeysByUserId(fromMailAddr);
}
if (keyList.length === 0) {
- ret.errorMsg = EnigmailLocale.getString("errorOwnKeyUnusable", fromMailAddr);
+ ret.errorMsg = EnigmailLocale.getString(
+ "errorOwnKeyUnusable",
+ fromMailAddr
+ );
return ret;
}
if (sign) {
- keyList = keyList.reduce(function _f(p, keyObj) {
- if (keyObj && keyObj.getSigningValidity().keyValid) p.push(keyObj);
+ keyList = keyList.reduce(function(p, keyObj) {
+ if (keyObj && keyObj.getSigningValidity().keyValid) {
+ p.push(keyObj);
+ }
return p;
}, []);
}
if (encrypt) {
- keyList = keyList.reduce(function _f(p, keyObj) {
- if (keyObj && keyObj.getEncryptionValidity().keyValid) p.push(keyObj);
+ keyList = keyList.reduce(function(p, keyObj) {
+ if (keyObj && keyObj.getEncryptionValidity().keyValid) {
+ p.push(keyObj);
+ }
return p;
}, []);
}
if (keyList.length === 0) {
if (sign) {
- ret.errorMsg = EnigmailErrorHandling.determineInvSignReason(fromMailAddr);
+ ret.errorMsg = EnigmailErrorHandling.determineInvSignReason(
+ fromMailAddr
+ );
+ } else {
+ ret.errorMsg = EnigmailErrorHandling.determineInvRcptReason(
+ fromMailAddr
+ );
}
- else {
- ret.errorMsg = EnigmailErrorHandling.determineInvRcptReason(fromMailAddr);
- }
- }
- else {
+ } else {
ret.keyId = keyList[0].fpr;
}
return ret;
},
- encryptMessageStart: function(win, uiFlags, fromMailAddr, toMailAddr, bccMailAddr,
- hashAlgorithm, sendFlags, listener, statusFlagsObj, errorMsgObj) {
- EnigmailLog.DEBUG("encryption.jsm: encryptMessageStart: uiFlags=" + uiFlags + ", from " + fromMailAddr + " to " + toMailAddr + ", hashAlgorithm=" + hashAlgorithm + " (" + EnigmailData.bytesToHex(
- EnigmailData.pack(sendFlags, 4)) + ")\n");
+ encryptMessageStart(
+ win,
+ uiFlags,
+ fromMailAddr,
+ toMailAddr,
+ bccMailAddr,
+ hashAlgorithm,
+ sendFlags,
+ listener,
+ statusFlagsObj,
+ errorMsgObj
+ ) {
+ EnigmailLog.DEBUG(
+ "encryption.jsm: encryptMessageStart: uiFlags=" +
+ uiFlags +
+ ", from " +
+ fromMailAddr +
+ " to " +
+ toMailAddr +
+ ", hashAlgorithm=" +
+ hashAlgorithm +
+ " (" +
+ EnigmailData.bytesToHex(EnigmailData.pack(sendFlags, 4)) +
+ ")\n"
+ );
let keyUseability = this.determineOwnKeyUsability(sendFlags, fromMailAddr);
if (!keyUseability.keyId) {
- EnigmailLog.DEBUG("encryption.jsm: encryptMessageStart: own key invalid\n");
+ EnigmailLog.DEBUG(
+ "encryption.jsm: encryptMessageStart: own key invalid\n"
+ );
errorMsgObj.value = keyUseability.errorMsg;
- statusFlagsObj.value = EnigmailConstants.INVALID_RECIPIENT | EnigmailConstants.NO_SECKEY | EnigmailConstants.DISPLAY_MESSAGE;
+ statusFlagsObj.value =
+ EnigmailConstants.INVALID_RECIPIENT |
+ EnigmailConstants.NO_SECKEY |
+ EnigmailConstants.DISPLAY_MESSAGE;
return null;
}
var pgpMime = uiFlags & EnigmailConstants.UI_PGP_MIME;
- var hashAlgo = gMimeHashAlgorithms[EnigmailPrefs.getPref("mimeHashAlgorithm")];
+ var hashAlgo =
+ gMimeHashAlgorithms[EnigmailPrefs.getPref("mimeHashAlgorithm")];
if (hashAlgorithm) {
hashAlgo = hashAlgorithm;
}
errorMsgObj.value = "";
if (!sendFlags) {
- EnigmailLog.DEBUG("encryption.jsm: encryptMessageStart: NO ENCRYPTION!\n");
+ EnigmailLog.DEBUG(
+ "encryption.jsm: encryptMessageStart: NO ENCRYPTION!\n"
+ );
errorMsgObj.value = EnigmailLocale.getString("notRequired");
return null;
}
if (!EnigmailCore.getService(win)) {
- EnigmailLog.ERROR("encryption.jsm: encryptMessageStart: not yet initialized\n");
+ EnigmailLog.ERROR(
+ "encryption.jsm: encryptMessageStart: not yet initialized\n"
+ );
errorMsgObj.value = EnigmailLocale.getString("notInit");
return null;
}
let logFileObj = {};
// GnuPG
// let encryptArgs = EnigmailEncryption.getEncryptCommand(fromMailAddr, toMailAddr, bccMailAddr, hashAlgo, sendFlags, ENC_TYPE_MSG, errorMsgObj, logFileObj);
- let encryptArgs = EnigmailEncryption.getCryptParams(fromMailAddr, toMailAddr, bccMailAddr, hashAlgo, sendFlags, ENC_TYPE_MSG, errorMsgObj, logFileObj);
+ let encryptArgs = EnigmailEncryption.getCryptParams(
+ fromMailAddr,
+ toMailAddr,
+ bccMailAddr,
+ hashAlgo,
+ sendFlags,
+ ENC_TYPE_MSG,
+ errorMsgObj,
+ logFileObj
+ );
- if (!encryptArgs)
+ if (!encryptArgs) {
return null;
+ }
- var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
if (!listener) {
listener = {};
}
if ("done" in listener) {
listener.outerDone = listener.done;
}
listener.done = function(exitCode) {
@@ -391,106 +512,158 @@ var EnigmailEncryption = {
if (this.outerDone) {
this.outerDone(exitCode);
}
};
let resultStatus = {};
const cApi = EnigmailCryptoAPI();
console.debug("listener: %o", listener);
- let encrypted = cApi.sync(cApi.encryptAndOrSign(listener.getInputForEncryption(), encryptArgs, resultStatus));
+ let encrypted = cApi.sync(
+ cApi.encryptAndOrSign(
+ listener.getInputForEncryption(),
+ encryptArgs,
+ resultStatus
+ )
+ );
console.debug(`encryptAndOrSign returned: ${encrypted}`);
listener.addEncryptedOutput(encrypted);
if (pgpMime && errorMsgObj.value) {
EnigmailDialog.alert(win, errorMsgObj.value);
}
listener.done(resultStatus.exitCode);
//return proc;
return null;
},
- encryptMessageEnd: function(fromMailAddr, stderrStr, exitCode, uiFlags, sendFlags, outputLen, retStatusObj) {
- EnigmailLog.DEBUG("encryption.jsm: encryptMessageEnd: uiFlags=" + uiFlags + ", sendFlags=" + EnigmailData.bytesToHex(EnigmailData.pack(sendFlags, 4)) + ", outputLen=" + outputLen + "\n");
+ encryptMessageEnd(
+ fromMailAddr,
+ stderrStr,
+ exitCode,
+ uiFlags,
+ sendFlags,
+ outputLen,
+ retStatusObj
+ ) {
+ EnigmailLog.DEBUG(
+ "encryption.jsm: encryptMessageEnd: uiFlags=" +
+ uiFlags +
+ ", sendFlags=" +
+ EnigmailData.bytesToHex(EnigmailData.pack(sendFlags, 4)) +
+ ", outputLen=" +
+ outputLen +
+ "\n"
+ );
- var pgpMime = uiFlags & EnigmailConstants.UI_PGP_MIME;
- var defaultSend = sendFlags & EnigmailConstants.SEND_DEFAULT;
var signMsg = sendFlags & EnigmailConstants.SEND_SIGNED;
var encryptMsg = sendFlags & EnigmailConstants.SEND_ENCRYPTED;
retStatusObj.statusFlags = 0;
retStatusObj.errorMsg = "";
retStatusObj.blockSeparation = "";
if (!EnigmailCore.getService().initialized) {
- EnigmailLog.ERROR("encryption.jsm: encryptMessageEnd: not yet initialized\n");
+ EnigmailLog.ERROR(
+ "encryption.jsm: encryptMessageEnd: not yet initialized\n"
+ );
retStatusObj.errorMsg = EnigmailLocale.getString("notInit");
return -1;
}
//EnigmailErrorHandling.parseErrorOutput(stderrStr, retStatusObj);
//exitCode = EnigmailExecution.fixExitCode(exitCode, retStatusObj);
- if ((exitCode === 0) && !outputLen) {
+ if (exitCode === 0 && !outputLen) {
exitCode = -1;
}
if (exitCode !== 0 && (signMsg || encryptMsg)) {
// GnuPG might return a non-zero exit code, even though the message was correctly
// signed or encryped -> try to fix the exit code
var correctedExitCode = 0;
if (signMsg) {
- if (!(retStatusObj.statusFlags & EnigmailConstants.SIG_CREATED)) correctedExitCode = exitCode;
+ if (!(retStatusObj.statusFlags & EnigmailConstants.SIG_CREATED)) {
+ correctedExitCode = exitCode;
+ }
}
if (encryptMsg) {
- if (!(retStatusObj.statusFlags & EnigmailConstants.END_ENCRYPTION)) correctedExitCode = exitCode;
+ if (!(retStatusObj.statusFlags & EnigmailConstants.END_ENCRYPTION)) {
+ correctedExitCode = exitCode;
+ }
}
exitCode = correctedExitCode;
}
- EnigmailLog.DEBUG("encryption.jsm: encryptMessageEnd: command execution exit code: " + exitCode + "\n");
+ EnigmailLog.DEBUG(
+ "encryption.jsm: encryptMessageEnd: command execution exit code: " +
+ exitCode +
+ "\n"
+ );
if (retStatusObj.statusFlags & EnigmailConstants.DISPLAY_MESSAGE) {
if (retStatusObj.extendedStatus.search(/\bdisp:/) >= 0) {
retStatusObj.errorMsg = retStatusObj.statusMsg;
- }
- else {
+ } else {
if (fromMailAddr.search(/^0x/) === 0) {
fromMailAddr = fromMailAddr.substr(2);
}
if (fromMailAddr.search(/^[A-F0-9]{8,40}$/i) === 0) {
fromMailAddr = "[A-F0-9]+" + fromMailAddr;
}
- let s = new RegExp("^(\\[GNUPG:\\] )?INV_(RECP|SGNR) [0-9]+ (\\<|0x)?" + fromMailAddr + "\\>?", "m");
+ let s = new RegExp(
+ "^(\\[GNUPG:\\] )?INV_(RECP|SGNR) [0-9]+ (\\<|0x)?" +
+ fromMailAddr +
+ "\\>?",
+ "m"
+ );
if (retStatusObj.statusMsg.search(s) >= 0) {
- retStatusObj.errorMsg += "\n\n" + EnigmailLocale.getString("keyError.resolutionAction");
- }
- else if (retStatusObj.statusMsg.length > 0) {
+ retStatusObj.errorMsg +=
+ "\n\n" + EnigmailLocale.getString("keyError.resolutionAction");
+ } else if (retStatusObj.statusMsg.length > 0) {
retStatusObj.errorMsg = retStatusObj.statusMsg;
}
}
- }
- else if (retStatusObj.statusFlags & EnigmailConstants.INVALID_RECIPIENT) {
+ } else if (retStatusObj.statusFlags & EnigmailConstants.INVALID_RECIPIENT) {
retStatusObj.errorMsg = retStatusObj.statusMsg;
- }
- else if (exitCode !== 0) {
+ } else if (exitCode !== 0) {
retStatusObj.errorMsg = EnigmailLocale.getString("badCommand");
}
return exitCode;
},
- encryptMessage: function(parent, uiFlags, plainText, fromMailAddr, toMailAddr, bccMailAddr, sendFlags,
- exitCodeObj, statusFlagsObj, errorMsgObj) {
- EnigmailLog.DEBUG("enigmail.js: Enigmail.encryptMessage: " + plainText.length + " bytes from " + fromMailAddr + " to " + toMailAddr + " (" + sendFlags + ")\n");
+ encryptMessage(
+ parent,
+ uiFlags,
+ plainText,
+ fromMailAddr,
+ toMailAddr,
+ bccMailAddr,
+ sendFlags,
+ exitCodeObj,
+ statusFlagsObj,
+ errorMsgObj
+ ) {
+ EnigmailLog.DEBUG(
+ "enigmail.js: Enigmail.encryptMessage: " +
+ plainText.length +
+ " bytes from " +
+ fromMailAddr +
+ " to " +
+ toMailAddr +
+ " (" +
+ sendFlags +
+ ")\n"
+ );
throw new Error("Not implemented");
/*
exitCodeObj.value = -1;
statusFlagsObj.value = 0;
errorMsgObj.value = "";
if (!plainText) {
--- a/mail/extensions/openpgp/content/modules/errorHandling.jsm
+++ b/mail/extensions/openpgp/content/modules/errorHandling.jsm
@@ -3,584 +3,150 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailErrorHandling"];
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-
-const getEnigmailKeyRing = EnigmailLazy.loader("enigmail/keyRing.jsm", "EnigmailKeyRing");
-const getEnigmailGpg = EnigmailLazy.loader("enigmail/gpg.jsm", "EnigmailGpg");
-const getEnigmailFiles = EnigmailLazy.loader("enigmail/files.jsm", "EnigmailFiles");
-const getEnigmailRNG = EnigmailLazy.loader("enigmail/rng.jsm", "EnigmailRNG");
-
-
-const gStatusFlags = {
- GOODSIG: EnigmailConstants.GOOD_SIGNATURE,
- BADSIG: EnigmailConstants.BAD_SIGNATURE,
- ERRSIG: EnigmailConstants.UNVERIFIED_SIGNATURE,
- EXPSIG: EnigmailConstants.EXPIRED_SIGNATURE,
- REVKEYSIG: EnigmailConstants.GOOD_SIGNATURE,
- EXPKEYSIG: EnigmailConstants.EXPIRED_KEY_SIGNATURE,
- KEYEXPIRED: EnigmailConstants.EXPIRED_KEY,
- KEYREVOKED: EnigmailConstants.REVOKED_KEY,
- NO_PUBKEY: EnigmailConstants.NO_PUBKEY,
- NO_SECKEY: EnigmailConstants.NO_SECKEY,
- IMPORTED: EnigmailConstants.IMPORTED_KEY,
- INV_RECP: EnigmailConstants.INVALID_RECIPIENT,
- MISSING_PASSPHRASE: EnigmailConstants.MISSING_PASSPHRASE,
- BAD_PASSPHRASE: EnigmailConstants.BAD_PASSPHRASE,
- BADARMOR: EnigmailConstants.BAD_ARMOR,
- NODATA: EnigmailConstants.NODATA,
- ERROR: EnigmailConstants.BAD_SIGNATURE | EnigmailConstants.DECRYPTION_FAILED,
- DECRYPTION_FAILED: EnigmailConstants.DECRYPTION_FAILED,
- DECRYPTION_OKAY: EnigmailConstants.DECRYPTION_OKAY,
- CARDCTRL: EnigmailConstants.CARDCTRL,
- SC_OP_FAILURE: EnigmailConstants.SC_OP_FAILURE,
- UNKNOWN_ALGO: EnigmailConstants.UNKNOWN_ALGO,
- SIG_CREATED: EnigmailConstants.SIG_CREATED,
- END_ENCRYPTION: EnigmailConstants.END_ENCRYPTION,
- INV_SGNR: 0x100000000,
- IMPORT_OK: 0x200000000,
- FAILURE: 0x400000000,
- DECRYPTION_INFO: 0x800000000
-};
-
-// taken from libgpg-error: gpg-error.h
-const GPG_SOURCE_SYSTEM = {
- GPG_ERR_SOURCE_UNKNOWN: 0,
- GPG_ERR_SOURCE_GCRYPT: 1,
- GPG_ERR_SOURCE_GPG: 2,
- GPG_ERR_SOURCE_GPGSM: 3,
- GPG_ERR_SOURCE_GPGAGENT: 4,
- GPG_ERR_SOURCE_PINENTRY: 5,
- GPG_ERR_SOURCE_SCD: 6,
- GPG_ERR_SOURCE_GPGME: 7,
- GPG_ERR_SOURCE_KEYBOX: 8,
- GPG_ERR_SOURCE_KSBA: 9,
- GPG_ERR_SOURCE_DIRMNGR: 10,
- GPG_ERR_SOURCE_GSTI: 11,
- GPG_ERR_SOURCE_GPA: 12,
- GPG_ERR_SOURCE_KLEO: 13,
- GPG_ERR_SOURCE_G13: 14,
- GPG_ERR_SOURCE_ASSUAN: 15,
- GPG_ERR_SOURCE_TLS: 17,
- GPG_ERR_SOURCE_ANY: 31
-};
-
-/**
- * Handling of specific error codes from GnuPG
- *
- * @param c Object - the retStatusObj
- * @param errorNumber String - the error number as printed by GnuPG
- */
-function handleErrorCode(c, errorNumber) {
- if (errorNumber && errorNumber.search(/^[0-9]+$/) === 0) {
- let errNum = Number(errorNumber);
- let sourceSystem = errNum >> 24;
- let errorCode = errNum & 0xFFFFFF;
-
- switch (errorCode) {
- case 32870: // error no tty
- if (sourceSystem === GPG_SOURCE_SYSTEM.GPG_ERR_SOURCE_PINENTRY) {
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.retStatusObj.extendedStatus += "disp:get_passphrase ";
- c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.pinentryCursesError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
- c.isError = true;
- }
- break;
- case 11: // bad Passphrase
- case 87: // bad PIN
- badPassphrase(c);
- break;
- case 177: // no passphrase
- case 178: // no PIN
- missingPassphrase(c);
- break;
- case 99: // operation canceled
- if (sourceSystem === GPG_SOURCE_SYSTEM.GPG_ERR_SOURCE_PINENTRY) {
- missingPassphrase(c);
- }
- break;
- case 77: // no agent
- case 78: // agent error
- case 80: // assuan server fault
- case 81: // assuan error
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.retStatusObj.extendedStatus += "disp:get_passphrase ";
- c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.gpgAgentError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
- c.isError = true;
- break;
- case 85: // no pinentry
- case 86: // pinentry error
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.retStatusObj.extendedStatus += "disp:get_passphrase ";
- c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.pinentryError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
- c.isError = true;
- break;
- case 92: // no dirmngr
- case 93: // dirmngr error
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.retStatusObj.extendedStatus += "disp:get_passphrase ";
- c.retStatusObj.statusMsg = "";
- c.isError = true;
- break;
- case 2:
- case 3:
- case 149:
- case 188:
- c.statusFlags |= EnigmailConstants.UNKNOWN_ALGO;
- break;
- case 15:
- c.statusFlags |= EnigmailConstants.BAD_ARMOR;
- break;
- case 58:
- c.statusFlags |= EnigmailConstants.NODATA;
- break;
- }
- }
-}
-
-/**
- * Special treatment for some ERROR messages from GnuPG
- *
- * extendedStatus are preceeded by "disp:" if an error message is set in statusMsg
- *
- * isError is set to true if this is a hard error that makes further processing of
- * the status codes useless
- */
-function handleError(c) {
- /*
- check_hijacking: gpg-agent was hijacked by some other process (like gnome-keyring)
- proc_pkt.plaintext: multiple plaintexts seen
- pkdecrypt_failed: public key decryption failed
- keyedit.passwd: error changing the passphrase
- card_key_generate: key generation failed (card)
- key_generate: key generation failed
- keyserver_send: keyserver send failed
- get_passphrase: gpg-agent cannot query the passphrase from pinentry (GnuPG 2.0.x)
- */
-
- var lineSplit = c.statusLine.split(/ +/);
- if (lineSplit.length > 0) {
-
- if (lineSplit.length >= 3) {
- // first check if the error code is a specifically treated hard failure
- handleErrorCode(c, lineSplit[2]);
- if (c.isError) return true;
- }
-
- switch (lineSplit[1]) {
- case "check_hijacking":
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.retStatusObj.extendedStatus += "disp:invalid_gpg_agent ";
- c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.gpgAgentInvalid") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
- c.isError = true;
- break;
- case "get_passphrase":
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.retStatusObj.extendedStatus += "disp:get_passphrase ";
- c.retStatusObj.statusMsg = EnigmailLocale.getString("errorHandling.pinentryError") + "\n\n" + EnigmailLocale.getString("errorHandling.readFaq");
- c.isError = true;
- break;
- case "proc_pkt.plaintext":
- c.retStatusObj.extendedStatus += "multiple_plaintexts ";
- c.isError = true;
- break;
- case "pkdecrypt_failed":
- c.retStatusObj.extendedStatus += "pubkey_decrypt ";
- handleErrorCode(c, lineSplit[2]);
- break;
- case "keyedit.passwd":
- c.retStatusObj.extendedStatus += "passwd_change_failed ";
- break;
- case "card_key_generate":
- case "key_generate":
- c.retStatusObj.extendedStatus += "key_generate_failure ";
- break;
- case "keyserver_send":
- c.retStatusObj.extendedStatus += "keyserver_send_failed ";
- c.isError = true;
- break;
- default:
- return false;
- }
- return true;
- } else {
- return false;
- }
-}
-
-// handle GnuPG FAILURE message (GnuPG 2.1.10 and newer)
-function failureMessage(c) {
- let lineSplit = c.statusLine.split(/ +/);
- if (lineSplit.length >= 3) {
- handleErrorCode(c, lineSplit[2]);
- }
-}
-
-function missingPassphrase(c) {
- c.statusFlags |= EnigmailConstants.MISSING_PASSPHRASE;
- if (c.retStatusObj.statusMsg.indexOf(EnigmailLocale.getString("missingPassphrase")) < 0) {
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.flag = 0;
- EnigmailLog.DEBUG("errorHandling.jsm: missingPassphrase: missing passphrase\n");
- c.retStatusObj.statusMsg += EnigmailLocale.getString("missingPassphrase") + "\n";
- }
-}
-
-function badPassphrase(c) {
- c.statusFlags |= EnigmailConstants.MISSING_PASSPHRASE;
- if (!(c.statusFlags & EnigmailConstants.BAD_PASSPHRASE)) {
- c.statusFlags |= EnigmailConstants.BAD_PASSPHRASE;
- c.flag = 0;
- EnigmailLog.DEBUG("errorHandling.jsm: badPassphrase: bad passphrase\n");
- c.retStatusObj.statusMsg += EnigmailLocale.getString("badPhrase") + "\n";
- }
-}
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailLazy = ChromeUtils.import(
+ "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
-
-function invalidSignature(c) {
- if (c.isError) return;
- var lineSplit = c.statusLine.split(/ +/);
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.flag = 0;
-
- let keySpec = lineSplit[2];
-
- if (keySpec) {
- EnigmailLog.DEBUG("errorHandling.jsm: invalidRecipient: detected invalid sender " + keySpec + " / code: " + lineSplit[1] + "\n");
- c.retStatusObj.errorMsg += EnigmailErrorHandling.determineInvSignReason(keySpec);
- }
-}
-
-function invalidRecipient(c) {
- if (c.isError) return;
- var lineSplit = c.statusLine.split(/ +/);
- c.statusFlags |= EnigmailConstants.DISPLAY_MESSAGE;
- c.flag = 0;
-
- let keySpec = lineSplit[2];
-
- if (keySpec) {
- EnigmailLog.DEBUG("errorHandling.jsm: invalidRecipient: detected invalid recipient " + keySpec + " / code: " + lineSplit[1] + "\n");
- c.retStatusObj.errorMsg += EnigmailErrorHandling.determineInvRcptReason(keySpec);
- }
-}
-
-function importOk(c) {
- var lineSplit = c.statusLine.split(/ +/);
- if (lineSplit.length > 1) {
- EnigmailLog.DEBUG("errorHandling.jsm: importOk: key imported: " + lineSplit[2] + "\n");
- } else {
- EnigmailLog.DEBUG("errorHandling.jsm: importOk: key without FPR imported\n");
- }
-}
-
-function unverifiedSignature(c) {
- var lineSplit = c.statusLine.split(/ +/);
- if (lineSplit.length > 7 && lineSplit[7] == "4") {
- c.flag = EnigmailConstants.UNKNOWN_ALGO;
- }
-}
-
-function noData(c) {
- // Recognize only "NODATA 1"
- if (c.statusLine.search(/NODATA 1\b/) < 0) {
- c.flag = 0;
- }
-}
-
-function decryptionInfo(c) {
- // Recognize "DECRYPTION_INFO 0 1 2"
- if (c.statusLine.search(/DECRYPTION_INFO /) >= 0) {
- let lineSplit = c.statusLine.split(/ +/);
-
- let mdcMethod = lineSplit[1];
- let aeadAlgo = lineSplit.length > 3 ? lineSplit[3] : "0";
-
- if (mdcMethod === "0" && aeadAlgo === "0") {
- c.statusFlags |= EnigmailConstants.MISSING_MDC;
- c.statusFlags |= EnigmailConstants.DECRYPTION_FAILED; // be sure to fail
- c.flag = EnigmailConstants.MISSING_MDC;
- EnigmailLog.DEBUG("errorHandling.jsm: missing MDC!\n");
- c.retStatusObj.statusMsg += EnigmailLocale.getString("missingMdcError") + "\n";
- }
- }
-}
-
-
-function decryptionFailed(c) {
- c.inDecryptionFailed = true;
-}
-
-function cardControl(c) {
- var lineSplit = c.statusLine.split(/ +/);
- if (lineSplit[1] == "3") {
- c.detectedCard = lineSplit[2];
- } else {
- c.errCode = Number(lineSplit[1]);
- if (c.errCode == 1) c.requestedCard = lineSplit[2];
- }
-}
-
-function setupFailureLookup() {
- var result = {};
- result[EnigmailConstants.DECRYPTION_FAILED] = decryptionFailed;
- result[EnigmailConstants.NODATA] = noData;
- result[EnigmailConstants.CARDCTRL] = cardControl;
- result[EnigmailConstants.UNVERIFIED_SIGNATURE] = unverifiedSignature;
- result[EnigmailConstants.MISSING_PASSPHRASE] = missingPassphrase;
- result[EnigmailConstants.BAD_PASSPHRASE] = badPassphrase;
- result[gStatusFlags.INV_RECP] = invalidRecipient;
- result[gStatusFlags.INV_SGNR] = invalidSignature;
- result[gStatusFlags.IMPORT_OK] = importOk;
- result[gStatusFlags.FAILURE] = failureMessage;
- result[gStatusFlags.DECRYPTION_INFO] = decryptionInfo;
- return result;
-}
-
-function ignore() {}
-
-const failureLookup = setupFailureLookup();
-
-function handleFailure(c, errorFlag) {
- c.flag = gStatusFlags[errorFlag]; // yields known flag or undefined
-
- (failureLookup[c.flag] || ignore)(c);
-
- // if known flag, story it in our status
- if (c.flag) {
- c.statusFlags |= c.flag;
- }
-}
-
-function newContext(errOutput, retStatusObj) {
- retStatusObj.statusMsg = "";
- retStatusObj.errorMsg = "";
- retStatusObj.extendedStatus = "";
- retStatusObj.blockSeparation = "";
- retStatusObj.encryptedFileName = null;
-
- return {
- errOutput: errOutput,
- retStatusObj: retStatusObj,
- errArray: [],
- statusArray: [],
- errCode: 0,
- detectedCard: null,
- requestedCard: null,
- errorMsg: "",
- statusPat: /^\[GNUPG:\] /,
- statusFlags: 0,
- plaintextCount: 0,
- withinCryptoMsg: false,
- cryptoStartPat: /^BEGIN_DECRYPTION/,
- cryptoEndPat: /^END_DECRYPTION/,
- plaintextPat: /^PLAINTEXT /,
- plaintextLengthPat: /^PLAINTEXT_LENGTH /
- };
-}
-
-function splitErrorOutput(errOutput) {
- var errLines = errOutput.split(/\r?\n/);
-
- // Discard last null string, if any
- if ((errLines.length > 1) && !errLines[errLines.length - 1]) {
- errLines.pop();
- }
-
- return errLines;
-}
-
-function parseErrorLine(errLine, c) {
- if (errLine.search(c.statusPat) === 0) {
- // status line
- c.statusLine = errLine.replace(c.statusPat, "");
- c.statusArray.push(c.statusLine);
-
- // extract first word as flag
- var matches = c.statusLine.match(/^((\w+)\b)/);
-
- if (matches && (matches.length > 1)) {
- let isError = (matches[1] == "ERROR");
- (isError ? handleError : handleFailure)(c, matches[1]);
- }
- } else {
- // non-status line (details of previous status command)
- if (!getEnigmailGpg().getGpgFeature("decryption-info")) {
- if (errLine == "gpg: WARNING: message was not integrity protected") {
- // workaround for Gpg < 2.0.19 that don't print DECRYPTION_INFO
- c.statusFlags |= EnigmailConstants.DECRYPTION_FAILED;
- c.inDecryptionFailed = true;
- }
- }
-
- c.errArray.push(errLine);
- // save details of DECRYPTION_FAILED message ass error message
- if (c.inDecryptionFailed) {
- c.errorMsg += errLine;
- }
- }
-}
-
-function detectForgedInsets(c) {
- // detect forged message insets
- let hasUnencryptedText = false;
- let hasEncryptedPart = false;
- for (var j = 0; j < c.statusArray.length; j++) {
- if (c.statusArray[j].search(c.cryptoStartPat) === 0) {
- c.withinCryptoMsg = true;
- hasEncryptedPart = true;
- } else if (c.withinCryptoMsg && c.statusArray[j].search(c.cryptoEndPat) === 0) {
- c.withinCryptoMsg = false;
- } else if (c.statusArray[j].search(c.plaintextPat) === 0) {
- if (!c.withinCryptoMsg) hasUnencryptedText = true;
-
- ++c.plaintextCount;
- if ((c.statusArray.length > j + 1) && (c.statusArray[j + 1].search(c.plaintextLengthPat) === 0)) {
- var matches = c.statusArray[j + 1].match(/(\w+) (\d+)/);
- if (matches.length >= 3) {
- c.retStatusObj.blockSeparation += (c.withinCryptoMsg ? "1" : "0") + ":" + matches[2] + " ";
- }
- } else {
- // strange: we got PLAINTEXT XX, but not PLAINTEXT_LENGTH XX
- c.retStatusObj.blockSeparation += (c.withinCryptoMsg ? "1" : "0") + ":0 ";
- }
- }
- }
- if (c.plaintextCount > 1 || (hasEncryptedPart && hasUnencryptedText)) {
- c.statusFlags |= (EnigmailConstants.DECRYPTION_FAILED | EnigmailConstants.BAD_SIGNATURE);
- }
-}
-
-function buildErrorMessageForCardCtrl(c, errCode, detectedCard) {
- var errorMsg = "";
- switch (errCode) {
- case 1:
- if (detectedCard) {
- errorMsg = EnigmailLocale.getString("sc.wrongCardAvailable", [c.detectedCard, c.requestedCard]);
- } else {
- errorMsg = EnigmailLocale.getString("sc.insertCard", [c.requestedCard]);
- }
- break;
- case 2:
- errorMsg = EnigmailLocale.getString("sc.removeCard");
- break;
- case 4:
- errorMsg = EnigmailLocale.getString("sc.noCardAvailable");
- break;
- case 5:
- errorMsg = EnigmailLocale.getString("sc.noReaderAvailable");
- break;
- }
- return errorMsg;
-}
+const getEnigmailKeyRing = EnigmailLazy.loader(
+ "enigmail/keyRing.jsm",
+ "EnigmailKeyRing"
+);
+const getEnigmailFiles = EnigmailLazy.loader(
+ "enigmail/files.jsm",
+ "EnigmailFiles"
+);
+const getEnigmailRNG = EnigmailLazy.loader("enigmail/rng.jsm", "EnigmailRNG");
var EnigmailErrorHandling = {
/**
* Determin why a given key or userID cannot be used for signing
*
* @param keySpec String - key ID or user ID
*
* @return String - the reason(s) as message to display to the user
* "" in case the key is valid
*/
- determineInvSignReason: function(keySpec) {
- EnigmailLog.DEBUG("errorHandling.jsm: determineInvSignReason: keySpec: " + keySpec + "\n");
+ determineInvSignReason(keySpec) {
+ EnigmailLog.DEBUG(
+ "errorHandling.jsm: determineInvSignReason: keySpec: " + keySpec + "\n"
+ );
let reasonMsg = "";
if (keySpec.search(/^(0x)?[0-9A-F]+$/) === 0) {
let key = getEnigmailKeyRing().getKeyById(keySpec);
if (!key) {
reasonMsg = EnigmailLocale.getString("keyError.keyIdNotFound", keySpec);
} else {
let r = key.getSigningValidity();
- if (!r.keyValid) reasonMsg = r.reason;
+ if (!r.keyValid) {
+ reasonMsg = r.reason;
+ }
}
} else {
let keys = getEnigmailKeyRing().getKeysByUserId(keySpec);
if (!keys || keys.length === 0) {
- reasonMsg = EnigmailLocale.getString("keyError.keySpecNotFound", keySpec);
+ reasonMsg = EnigmailLocale.getString(
+ "keyError.keySpecNotFound",
+ keySpec
+ );
} else {
for (let i in keys) {
let r = keys[i].getSigningValidity();
- if (!r.keyValid) reasonMsg += r.reason + "\n";
+ if (!r.keyValid) {
+ reasonMsg += r.reason + "\n";
+ }
}
}
}
return reasonMsg;
},
/**
* Determin why a given key or userID cannot be used for encryption
*
* @param keySpec String - key ID or user ID
*
* @return String - the reason(s) as message to display to the user
* "" in case the key is valid
*/
- determineInvRcptReason: function(keySpec) {
- EnigmailLog.DEBUG("errorHandling.jsm: determineInvRcptReason: keySpec: " + keySpec + "\n");
+ determineInvRcptReason(keySpec) {
+ EnigmailLog.DEBUG(
+ "errorHandling.jsm: determineInvRcptReason: keySpec: " + keySpec + "\n"
+ );
let reasonMsg = "";
if (keySpec.search(/^(0x)?[0-9A-F]+$/) === 0) {
let key = getEnigmailKeyRing().getKeyById(keySpec);
if (!key) {
reasonMsg = EnigmailLocale.getString("keyError.keyIdNotFound", keySpec);
} else {
let r = key.getEncryptionValidity();
- if (!r.keyValid) reasonMsg = r.reason;
+ if (!r.keyValid) {
+ reasonMsg = r.reason;
+ }
}
} else {
let keys = getEnigmailKeyRing().getKeysByUserId(keySpec);
if (!keys || keys.length === 0) {
- reasonMsg = EnigmailLocale.getString("keyError.keySpecNotFound", keySpec);
+ reasonMsg = EnigmailLocale.getString(
+ "keyError.keySpecNotFound",
+ keySpec
+ );
} else {
for (let i in keys) {
let r = keys[i].getEncryptionValidity();
- if (!r.keyValid) reasonMsg += r.reason + "\n";
+ if (!r.keyValid) {
+ reasonMsg += r.reason + "\n";
+ }
}
}
}
return reasonMsg;
},
/**
* Get a unique file to use for logging with --log-file
*/
- getTempLogFile: function() {
- let logFile = getEnigmailFiles().getTempDirObj().clone();
+ getTempLogFile() {
+ let logFile = getEnigmailFiles()
+ .getTempDirObj()
+ .clone();
logFile.normalize();
logFile.append("gpgOutput." + getEnigmailRNG().generateRandomString(6));
return logFile;
},
-
/**
* Append the content of a file (such as created via --log-file) to the
* debug log, and delete the file afterwards
*
* @param logFile: nsIFile object
*/
- appendLogFileToDebug: function(logFile) {
+ appendLogFileToDebug(logFile) {
if (logFile && logFile.exists() && logFile.isFile()) {
let logData = getEnigmailFiles().readFile(logFile);
- EnigmailLog.DEBUG(`errorHandling.jsm: Process terminated. Human-readable output from gpg:\n-----\n${logData}-----\n`);
+ EnigmailLog.DEBUG(
+ `errorHandling.jsm: Process terminated. Human-readable output from gpg:\n-----\n${logData}-----\n`
+ );
try {
logFile.remove(false);
} catch (ex) {}
}
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/events.jsm
+++ b/mail/extensions/openpgp/content/modules/events.jsm
@@ -1,33 +1,38 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailEvents"];
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailTimer = ChromeUtils.import("chrome://openpgp/content/modules/timer.jsm").EnigmailTimer;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailTimer = ChromeUtils.import(
+ "chrome://openpgp/content/modules/timer.jsm"
+).EnigmailTimer;
/**** DEPRECATED - use EnigmailTimer instead *****/
var EnigmailEvents = {
/**
* dispatch event aynchronously to the main thread
*
* @callbackFunction: Function - any function specification
* @sleepTimeMs: Number - optional number of miliseconds to delay
* (0 if not specified)
* @arrayOfArgs: Array - arguments to pass to callbackFunction
*/
- dispatchEvent: function(callbackFunction, sleepTimeMs, arrayOfArgs) {
- EnigmailLog.DEBUG("enigmailCommon.jsm: dispatchEvent f=" + callbackFunction.name + "\n");
+ dispatchEvent(callbackFunction, sleepTimeMs, arrayOfArgs) {
+ EnigmailLog.DEBUG(
+ "enigmailCommon.jsm: dispatchEvent f=" + callbackFunction.name + "\n"
+ );
return EnigmailTimer.setTimeout(() => {
callbackFunction(arrayOfArgs);
}, sleepTimeMs);
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/files.jsm
+++ b/mail/extensions/openpgp/content/modules/files.jsm
@@ -1,36 +1,40 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
const EXPORTED_SYMBOLS = ["EnigmailFiles"];
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
-const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm").EnigmailOS;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-Components.utils.importGlobalProperties(["TextDecoder"]);
+const EnigmailData = ChromeUtils.import(
+ "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
+const EnigmailOS = ChromeUtils.import("chrome://openpgp/content/modules/os.jsm")
+ .EnigmailOS;
+const EnigmailLazy = ChromeUtils.import(
+ "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
-const {
- OS
-} = ChromeUtils.import("resource://gre/modules/osfile.jsm", {});
+const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm", {});
+const Services = ChromeUtils.import("resource://gre/modules/Services.jsm")
+ .Services;
-const lazyStream = EnigmailLazy.loader("enigmail/streams.jsm", "EnigmailStreams");
+const lazyStream = EnigmailLazy.loader(
+ "enigmail/streams.jsm",
+ "EnigmailStreams"
+);
const lazyLog = EnigmailLazy.loader("enigmail/log.jsm", "EnigmailLog");
const NS_FILE_CONTRACTID = "@mozilla.org/file/local;1";
-const NS_LOCALFILEOUTPUTSTREAM_CONTRACTID = "@mozilla.org/network/file-output-stream;1";
-const NS_IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
-const NS_SCRIPTABLEINPUTSTREAM_CONTRACTID = "@mozilla.org/scriptableinputstream;1";
+const NS_LOCALFILEOUTPUTSTREAM_CONTRACTID =
+ "@mozilla.org/network/file-output-stream;1";
const DIRSERVICE_CONTRACTID = "@mozilla.org/file/directory_service;1";
const NS_RDONLY = 0x01;
const NS_WRONLY = 0x02;
const NS_CREATE_FILE = 0x08;
const NS_TRUNCATE = 0x20;
const DEFAULT_FILE_PERMS = 0o600;
@@ -44,223 +48,251 @@ function potentialWindowsExecutable(file
var EnigmailFiles = {
/**
* potentialWindowsExecutable appends .exe to a file
*
* @param String file - file path or executable name to append .exe to
*
* @return String file - modified file path or executable name
*/
- potentialWindowsExecutable: potentialWindowsExecutable,
+ potentialWindowsExecutable,
- isAbsolutePath: function(filePath, isDosLike) {
+ isAbsolutePath(filePath, isDosLike) {
// Check if absolute path
if (isDosLike) {
- return ((filePath.search(/^\w+:\\/) === 0) || (filePath.search(/^\\\\/) === 0) ||
- (filePath.search(/^\/\//) === 0));
+ return (
+ filePath.search(/^\w+:\\/) === 0 ||
+ filePath.search(/^\\\\/) === 0 ||
+ filePath.search(/^\/\//) === 0
+ );
}
- else {
- return (filePath.search(/^\//) === 0);
- }
+
+ return filePath.search(/^\//) === 0;
},
/**
* resolvePathWithEnv tries to resolve an file's path with the environment PATH variable.
*
* @param String file - file to be resolved
*
* @return String foundPath - Returns found path. If no path is found, returns null.
*/
- resolvePathWithEnv: function(executable) {
- let envSvc = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
- const foundPath = EnigmailFiles.resolvePath(potentialWindowsExecutable(executable), envSvc.get("PATH"), EnigmailOS.isDosLike);
+ resolvePathWithEnv(executable) {
+ let envSvc = Cc["@mozilla.org/process/environment;1"].getService(
+ Ci.nsIEnvironment
+ );
+ const foundPath = EnigmailFiles.resolvePath(
+ potentialWindowsExecutable(executable),
+ envSvc.get("PATH"),
+ EnigmailOS.isDosLike
+ );
if (foundPath !== null) {
foundPath.normalize();
}
return foundPath;
},
- resolvePath: function(filePath, envPath, isDosLike) {
+ resolvePath(filePath, envPath, isDosLike) {
lazyLog().DEBUG("files.jsm: resolvePath: filePath=" + filePath + "\n");
- if (EnigmailFiles.isAbsolutePath(filePath, isDosLike))
+ if (EnigmailFiles.isAbsolutePath(filePath, isDosLike)) {
return filePath;
+ }
- if (!envPath)
+ if (!envPath) {
return null;
+ }
const fileNames = filePath.split(";");
const pathDirs = envPath.split(isDosLike ? ";" : ":");
for (let i = 0; i < fileNames.length; i++) {
for (let j = 0; j < pathDirs.length; j++) {
try {
const pathDir = Cc[NS_FILE_CONTRACTID].createInstance(Ci.nsIFile);
- lazyLog().DEBUG("files.jsm: resolvePath: checking for " + pathDirs[j] + "/" + fileNames[i] + "\n");
+ lazyLog().DEBUG(
+ "files.jsm: resolvePath: checking for " +
+ pathDirs[j] +
+ "/" +
+ fileNames[i] +
+ "\n"
+ );
EnigmailFiles.initPath(pathDir, pathDirs[j]);
try {
if (pathDir.exists() && pathDir.isDirectory()) {
pathDir.appendRelativePath(fileNames[i]);
if (pathDir.exists() && !pathDir.isDirectory()) {
return pathDir;
}
}
- }
- catch (ex) {}
- }
- catch (ex) {}
+ } catch (ex) {}
+ } catch (ex) {}
}
}
return null;
},
- createFileStream: function(filePath, permissions) {
+ createFileStream(filePath, permissions) {
try {
let localFile;
if (typeof filePath == "string") {
localFile = Cc[NS_FILE_CONTRACTID].createInstance(Ci.nsIFile);
EnigmailFiles.initPath(localFile, filePath);
- }
- else {
+ } else {
localFile = filePath.QueryInterface(Ci.nsIFile);
}
if (localFile.exists()) {
+ if (localFile.isDirectory() || !localFile.isWritable()) {
+ throw Cr.NS_ERROR_FAILURE;
+ }
- if (localFile.isDirectory() || !localFile.isWritable())
- throw Components.results.NS_ERROR_FAILURE;
-
- if (!permissions)
+ if (!permissions) {
permissions = localFile.permissions;
+ }
}
- if (!permissions)
+ if (!permissions) {
permissions = DEFAULT_FILE_PERMS;
+ }
const flags = NS_WRONLY | NS_CREATE_FILE | NS_TRUNCATE;
- const fileStream = Cc[NS_LOCALFILEOUTPUTSTREAM_CONTRACTID].createInstance(Ci.nsIFileOutputStream);
+ const fileStream = Cc[NS_LOCALFILEOUTPUTSTREAM_CONTRACTID].createInstance(
+ Ci.nsIFileOutputStream
+ );
fileStream.init(localFile, flags, permissions, 0);
return fileStream;
-
- }
- catch (ex) {
- lazyLog().ERROR("files.jsm: createFileStream: Failed to create " + filePath + "\n");
+ } catch (ex) {
+ lazyLog().ERROR(
+ "files.jsm: createFileStream: Failed to create " + filePath + "\n"
+ );
return null;
}
},
// path initialization function
// uses persistentDescriptor in case that initWithPath fails
// (seems to happen frequently with UTF-8 characters in path names)
- initPath: function(localFileObj, pathStr) {
+ initPath(localFileObj, pathStr) {
localFileObj.initWithPath(pathStr);
if (!localFileObj.exists()) {
localFileObj.persistentDescriptor = pathStr;
}
},
/**
* Read the contents of a text file into a string
*
* @param fileObj: Object (nsIFile)
*
* @return String (file contents)
*/
- readFile: function(fileObj) {
+ readFile(fileObj) {
let fileContents = "";
if (fileObj.exists()) {
- let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+ let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+ Ci.nsIJSInspector
+ );
- let decoder = new TextDecoder();
- OS.File.read(fileObj.path).then(arr => {
- fileContents = EnigmailData.arrayBufferToString(arr); // Convert the array to a text
- inspector.exitNestedEventLoop();
- }).catch(err => {
- inspector.exitNestedEventLoop();
- });
+ OS.File.read(fileObj.path)
+ .then(arr => {
+ fileContents = EnigmailData.arrayBufferToString(arr); // Convert the array to a text
+ inspector.exitNestedEventLoop();
+ })
+ .catch(err => {
+ inspector.exitNestedEventLoop();
+ });
inspector.enterNestedEventLoop(0); // wait for async process to terminate
}
return fileContents;
},
/** Read the contents of a file with binary data into a string
* @param fileObj: Object (nsIFile)
*
* @return String (file contents)
*/
- readBinaryFile: function(fileObj) {
+ readBinaryFile(fileObj) {
let fileContents = "";
if (fileObj.exists()) {
- let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(Ci.nsIJSInspector);
+ let inspector = Cc["@mozilla.org/jsinspector;1"].createInstance(
+ Ci.nsIJSInspector
+ );
- OS.File.read(fileObj.path).then(arr => {
- for (let i = 0; i < arr.length; i++) {
- fileContents += String.fromCharCode(arr[i]);
- }
+ OS.File.read(fileObj.path)
+ .then(arr => {
+ for (let i = 0; i < arr.length; i++) {
+ fileContents += String.fromCharCode(arr[i]);
+ }
- inspector.exitNestedEventLoop();
- }).catch(err => {
- inspector.exitNestedEventLoop();
- });
+ inspector.exitNestedEventLoop();
+ })
+ .catch(err => {
+ inspector.exitNestedEventLoop();
+ });
inspector.enterNestedEventLoop(0); // wait for async process to terminate
}
return fileContents;
},
- formatCmdLine: function(command, args) {
+ formatCmdLine(command, args) {
function getQuoted(str) {
str = str.toString();
let i = str.indexOf(" ");
if (i >= 0) {
return '"' + str + '"';
}
- else {
- return str;
- }
+
+ return str;
}
if (command instanceof Ci.nsIFile) {
command = EnigmailFiles.getFilePathDesc(command);
}
const cmdStr = getQuoted(command) + " ";
- const argStr = args.map(getQuoted).join(" ").replace(/\\\\/g, '\\');
+ const argStr = args
+ .map(getQuoted)
+ .join(" ")
+ .replace(/\\\\/g, "\\");
return cmdStr + argStr;
},
- getFilePathDesc: function(nsFileObj) {
+ getFilePathDesc(nsFileObj) {
if (EnigmailOS.getOS() == "WINNT") {
return nsFileObj.persistentDescriptor;
}
- else {
- return nsFileObj.path;
- }
+
+ return nsFileObj.path;
},
- getFilePath: function(nsFileObj) {
- return EnigmailData.convertToUnicode(EnigmailFiles.getFilePathDesc(nsFileObj), "utf-8");
+ getFilePath(nsFileObj) {
+ return EnigmailData.convertToUnicode(
+ EnigmailFiles.getFilePathDesc(nsFileObj),
+ "utf-8"
+ );
},
- getEscapedFilename: function(fileNameStr) {
+ getEscapedFilename(fileNameStr) {
if (EnigmailOS.isDosLike) {
// escape the backslashes and the " character (for Windows and OS/2)
fileNameStr = fileNameStr.replace(/([\\"])/g, "\\$1");
}
if (EnigmailOS.getOS() == "WINNT") {
// replace leading "\\" with "//"
fileNameStr = fileNameStr.replace(/^\\\\*/, "//");
@@ -268,63 +300,61 @@ var EnigmailFiles = {
return fileNameStr;
},
/**
* get the temporary folder
*
* @return nsIFile object holding a reference to the temp directory
*/
- getTempDirObj: function() {
+ getTempDirObj() {
const TEMPDIR_PROP = "TmpD";
try {
- const dsprops = Cc[DIRSERVICE_CONTRACTID].getService().
- QueryInterface(Ci.nsIProperties);
+ const dsprops = Cc[DIRSERVICE_CONTRACTID].getService().QueryInterface(
+ Ci.nsIProperties
+ );
return dsprops.get(TEMPDIR_PROP, Ci.nsIFile);
- }
- catch (ex) {
+ } catch (ex) {
// let's guess ...
const tmpDirObj = Cc[NS_FILE_CONTRACTID].createInstance(Ci.nsIFile);
if (EnigmailOS.getOS() == "WINNT") {
tmpDirObj.initWithPath("C:/TEMP");
- }
- else {
+ } else {
tmpDirObj.initWithPath("/tmp");
}
return tmpDirObj;
}
},
/**
* get the temporary folder as string
*
* @return String containing the temp directory name
*/
- getTempDir: function() {
+ getTempDir() {
return EnigmailFiles.getTempDirObj().path;
},
/**
* create a new folder as subfolder of the temporary directory
*
* @param dirName String - name of subfolder
* @param unique Boolean - if true, the directory is guaranteed to be unique
*
* @return nsIFile object holding a reference to the created directory
*/
- createTempSubDir: function(dirName, unique = false) {
+ createTempSubDir(dirName, unique = false) {
const localFile = EnigmailFiles.getTempDirObj().clone();
localFile.append(dirName);
if (unique) {
- localFile.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */ );
- }
- else {
- localFile.create(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */ );
+ localFile.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */);
+ } else {
+ localFile.create(Ci.nsIFile.DIRECTORY_TYPE, 509 /* = 0775 */);
}
return localFile;
},
/**
* Ensure that a directory exists and is writeable.
*
@@ -332,165 +362,170 @@ var EnigmailFiles = {
* @param permissions Number - file permissions in Unix style (e.g. 0700)
*
* @return Number:
* 0 - OK: directory exists (or was created) and is writeable
* 1 - NOK: Directory does not exist (and cannot be created)
* 2 - NOK: Directory exists but is readonly (and cannot be modified)
* 3 - NOK: File object with required name exists but is not a directory
*/
- ensureWritableDirectory: function(dirObj, permissions) {
+ ensureWritableDirectory(dirObj, permissions) {
let retVal = -1;
try {
if (dirObj.isDirectory()) {
try {
if (dirObj.isWritable()) {
retVal = 0;
- }
- else {
+ } else {
dirObj.permissions = permissions;
retVal = 0;
}
- }
- catch (x) {
+ } catch (x) {
retVal = 2;
}
- }
- else {
+ } else {
retVal = 3;
}
- }
- catch (x) {
+ } catch (x) {
// directory doesn't exist
try {
dirObj.create(Ci.nsIFile.DIRECTORY_TYPE, permissions);
retVal = 0;
- }
- catch (x2) {
+ } catch (x2) {
retVal = 1;
}
}
return retVal;
},
-
/**
* Write data to a file
* @filePath |string| or |nsIFile| object - the file to be created
* @data |string| - the data to write to the file
* @permissions |number| - file permissions according to Unix spec (0600 by default)
*
* @return true if data was written successfully, false otherwise
*/
- writeFileContents: function(filePath, data, permissions) {
+ writeFileContents(filePath, data, permissions) {
try {
- const fileOutStream = EnigmailFiles.createFileStream(filePath, permissions);
+ const fileOutStream = EnigmailFiles.createFileStream(
+ filePath,
+ permissions
+ );
if (data.length) {
if (fileOutStream.write(data, data.length) != data.length) {
- throw Components.results.NS_ERROR_FAILURE;
+ throw Cr.NS_ERROR_FAILURE;
}
fileOutStream.flush();
}
fileOutStream.close();
- }
- catch (ex) {
- lazyLog().ERROR("files.jsm: writeFileContents: Failed to write to " + filePath + "\n");
+ } catch (ex) {
+ lazyLog().ERROR(
+ "files.jsm: writeFileContents: Failed to write to " + filePath + "\n"
+ );
return false;
}
return true;
},
/**
* Create a text file from the contents of a given URL
*
* @param srcUrl: String - the URL to download
* @param outFile: nsIFile object - the file to create
*
* no return value
*/
- writeUrlToFile: function(srcUrl, outFile) {
+ writeUrlToFile(srcUrl, outFile) {
lazyLog().DEBUG("files.jsm: writeUrlToFile(" + outFile.path + ")\n");
- var ioServ = Cc[NS_IOSERVICE_CONTRACTID].getService(Ci.nsIIOService);
- var msgUri = ioServ.newURI(srcUrl, null, null);
+ var msgUri = Services.io.newURI(srcUrl);
var channel = lazyStream().createChannel(msgUri);
var istream = channel.open();
- var fstream = Cc["@mozilla.org/network/safe-file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
- var buffer = Cc["@mozilla.org/network/buffered-output-stream;1"].createInstance(Ci.nsIBufferedOutputStream);
+ var fstream = Cc[
+ "@mozilla.org/network/safe-file-output-stream;1"
+ ].createInstance(Ci.nsIFileOutputStream);
+ var buffer = Cc[
+ "@mozilla.org/network/buffered-output-stream;1"
+ ].createInstance(Ci.nsIBufferedOutputStream);
fstream.init(outFile, 0x04 | 0x08 | 0x20, 0x180, 0); // write, create, truncate
buffer.init(fstream, 8192);
while (istream.available() > 0) {
buffer.writeFrom(istream, istream.available());
}
// Close the output streams
- if (buffer instanceof Ci.nsISafeOutputStream)
+ if (buffer instanceof Ci.nsISafeOutputStream) {
buffer.finish();
- else
+ } else {
buffer.close();
+ }
- if (fstream instanceof Ci.nsISafeOutputStream)
+ if (fstream instanceof Ci.nsISafeOutputStream) {
fstream.finish();
- else
+ } else {
fstream.close();
+ }
// Close the input stream
istream.close();
},
// return the useable path (for gpg) of a file object
- getFilePathReadonly: function(nsFileObj, creationMode) {
- if (creationMode === null) creationMode = NS_RDONLY;
+ getFilePathReadonly(nsFileObj, creationMode) {
+ if (creationMode === null) {
+ creationMode = NS_RDONLY;
+ }
return nsFileObj.path;
},
/**
* Create an empty ZIP file
*
* @param nsFileObj - nsIFile object: reference to the file to be created
*
* @return nsIZipWriter object allow to perform write operations on the ZIP file
*/
- createZipFile: function(nsFileObj) {
- const zipW = Cc['@mozilla.org/zipwriter;1'].createInstance(Ci.nsIZipWriter);
+ createZipFile(nsFileObj) {
+ const zipW = Cc["@mozilla.org/zipwriter;1"].createInstance(Ci.nsIZipWriter);
zipW.open(nsFileObj, NS_WRONLY | NS_CREATE_FILE | NS_TRUNCATE);
return zipW;
},
/**
* Open a ZIP file for reading
*
* @param nsFileObj - nsIFile object: reference to the file to be created
*
* @return nsIZipReader object allow to perform read operations on the ZIP file
*/
- openZipFile: function(nsFileObj) {
- const zipR = Cc['@mozilla.org/libjar/zip-reader;1'].createInstance(Ci.nsIZipReader);
+ openZipFile(nsFileObj) {
+ const zipR = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(
+ Ci.nsIZipReader
+ );
zipR.open(nsFileObj);
return zipR;
},
-
/**
* Unpack a ZIP file to a directory
*
* @param zipFile - nsIZipReader object: file to be extracted
* @param targetDir - nsIFile object: target directory
*
* @return Boolean: true if extraction successfull, false otherwise
*/
- extractZipFile: function(zipFile, targetDir) {
-
+ extractZipFile(zipFile, targetDir) {
// create missing parent directories
function createDirWithParents(dirObj) {
if (!dirObj.parent.exists()) {
createDirWithParents(dirObj.parent);
}
dirObj.create(dirObj.DIRECTORY_TYPE, 493);
}
@@ -499,33 +534,33 @@ var EnigmailFiles = {
let f = zipReader.findEntries("*");
for (let i of f) {
let t = targetDir.clone();
let entry = zipReader.getEntry(i);
if (!EnigmailOS.isDosLike) {
t.initWithPath(t.path + "/" + i);
- }
- else {
+ } else {
i = i.replace(/\//g, "\\");
t.initWithPath(t.path + "\\" + i);
}
if (!t.parent.exists()) {
createDirWithParents(t.parent);
}
if (!(entry.isDirectory || i.search(/[\/\\]$/) >= 0)) {
zipReader.extract(i, t);
}
}
zipReader.close();
return true;
- }
- catch (ex) {
- lazyLog().ERROR("files.jsm: extractZipFile: Failed to create ZIP: " + ex + "\n");
+ } catch (ex) {
+ lazyLog().ERROR(
+ "files.jsm: extractZipFile: Failed to create ZIP: " + ex + "\n"
+ );
return false;
}
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/filters.jsm
+++ b/mail/extensions/openpgp/content/modules/filters.jsm
@@ -3,449 +3,514 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailFilters"];
-const EnigmailLazy = ChromeUtils.import("chrome://openpgp/content/modules/lazy.jsm").EnigmailLazy;
-const EnigmailLocale = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm").EnigmailLocale;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailPersistentCrypto = ChromeUtils.import("chrome://openpgp/content/modules/persistentCrypto.jsm").EnigmailPersistentCrypto;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailKeyRing = ChromeUtils.import("chrome://openpgp/content/modules/keyRing.jsm").EnigmailKeyRing;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").EnigmailStreams;
-const EnigmailConstants = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm").EnigmailConstants;
-const EnigmailData = ChromeUtils.import("chrome://openpgp/content/modules/data.jsm").EnigmailData;
+const EnigmailLazy = ChromeUtils.import(
+ "chrome://openpgp/content/modules/lazy.jsm"
+).EnigmailLazy;
+const EnigmailLocale = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+).EnigmailLocale;
+const EnigmailCore = ChromeUtils.import(
+ "chrome://openpgp/content/modules/core.jsm"
+).EnigmailCore;
+const EnigmailPersistentCrypto = ChromeUtils.import(
+ "chrome://openpgp/content/modules/persistentCrypto.jsm"
+).EnigmailPersistentCrypto;
+const EnigmailLog = ChromeUtils.import(
+ "chrome://openpgp/content/modules/log.jsm"
+).EnigmailLog;
+const EnigmailFuncs = ChromeUtils.import(
+ "chrome://openpgp/content/modules/funcs.jsm"
+).EnigmailFuncs;
+const EnigmailKeyRing = ChromeUtils.import(
+ "chrome://openpgp/content/modules/keyRing.jsm"
+).EnigmailKeyRing;
+const EnigmailStreams = ChromeUtils.import(
+ "chrome://openpgp/content/modules/streams.jsm"
+).EnigmailStreams;
+const EnigmailConstants = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+).EnigmailConstants;
+const EnigmailData = ChromeUtils.import(
+ "chrome://openpgp/content/modules/data.jsm"
+).EnigmailData;
const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
-const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm").NetUtil;
-const EnigmailMime = ChromeUtils.import("chrome://openpgp/content/modules/mime.jsm").EnigmailMime;
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
+const NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm")
+ .NetUtil;
+const EnigmailMime = ChromeUtils.import(
+ "chrome://openpgp/content/modules/mime.jsm"
+).EnigmailMime;
+const EnigmailCompat = ChromeUtils.import(
+ "chrome://openpgp/content/modules/compat.jsm"
+).EnigmailCompat;
const getDialog = EnigmailLazy.loader("enigmail/dialog.jsm", "EnigmailDialog");
var gNewMailListenerInitiated = false;
/**
* filter action for creating a decrypted version of the mail and
* deleting the original mail at the same time
*/
const filterActionMoveDecrypt = {
- apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
-
- EnigmailLog.DEBUG("filters.jsm: filterActionMoveDecrypt: Move to: " + aActionValue + "\n");
+ apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: filterActionMoveDecrypt: Move to: " + aActionValue + "\n"
+ );
var msgHdrs = [];
for (var i = 0; i < aMsgHdrs.length; i++) {
msgHdrs.push(aMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr));
}
- EnigmailPersistentCrypto.dispatchMessages(msgHdrs, aActionValue, aListener, true);
+ EnigmailPersistentCrypto.dispatchMessages(
+ msgHdrs,
+ aActionValue,
+ aListener,
+ true
+ );
},
- isValidForType: function(type, scope) {
+ isValidForType(type, scope) {
return true;
},
- validateActionValue: function(value, folder, type) {
- getDialog().alert(null, EnigmailLocale.getString("filter.decryptMove.warnExperimental"));
+ validateActionValue(value, folder, type) {
+ getDialog().alert(
+ null,
+ EnigmailLocale.getString("filter.decryptMove.warnExperimental")
+ );
if (value === "") {
return EnigmailLocale.getString("filter.folderRequired");
}
return null;
- }
+ },
};
/**
* filter action for creating a decrypted copy of the mail, leaving the original
* message untouched
*/
const filterActionCopyDecrypt = {
- apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
- EnigmailLog.DEBUG("filters.jsm: filterActionCopyDecrypt: Copy to: " + aActionValue + "\n");
+ apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: filterActionCopyDecrypt: Copy to: " + aActionValue + "\n"
+ );
var msgHdrs = [];
for (var i = 0; i < aMsgHdrs.length; i++) {
msgHdrs.push(aMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr));
}
- EnigmailPersistentCrypto.dispatchMessages(msgHdrs, aActionValue, aListener, false);
+ EnigmailPersistentCrypto.dispatchMessages(
+ msgHdrs,
+ aActionValue,
+ aListener,
+ false
+ );
},
- isValidForType: function(type, scope) {
- EnigmailLog.DEBUG("filters.jsm: filterActionCopyDecrypt.isValidForType(" + type + ")\n");
+ isValidForType(type, scope) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: filterActionCopyDecrypt.isValidForType(" + type + ")\n"
+ );
let r = true;
return r;
},
- validateActionValue: function(value, folder, type) {
- EnigmailLog.DEBUG("filters.jsm: filterActionCopyDecrypt.validateActionValue(" + value + ")\n");
+ validateActionValue(value, folder, type) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: filterActionCopyDecrypt.validateActionValue(" +
+ value +
+ ")\n"
+ );
if (value === "") {
return EnigmailLocale.getString("filter.folderRequired");
}
return null;
- }
+ },
};
/**
* filter action for to encrypt a mail to a specific key
*/
const filterActionEncrypt = {
- apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+ apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
// Ensure KeyRing is loaded.
if (aMsgWindow) {
EnigmailCore.getService(aMsgWindow.domWindow);
- }
- else {
+ } else {
EnigmailCore.getService();
}
EnigmailKeyRing.getAllKeys();
- EnigmailLog.DEBUG("filters.jsm: filterActionEncrypt: Encrypt to: " + aActionValue + "\n");
+ EnigmailLog.DEBUG(
+ "filters.jsm: filterActionEncrypt: Encrypt to: " + aActionValue + "\n"
+ );
let keyObj = EnigmailKeyRing.getKeyById(aActionValue);
if (keyObj === null) {
- EnigmailLog.DEBUG("filters.jsm: failed to find key by id: " + aActionValue + "\n");
+ EnigmailLog.DEBUG(
+ "filters.jsm: failed to find key by id: " + aActionValue + "\n"
+ );
let keyId = EnigmailKeyRing.getValidKeyForRecipient(aActionValue);
if (keyId) {
keyObj = EnigmailKeyRing.getKeyById(keyId);
}
}
if (keyObj === null && aListener) {
EnigmailLog.DEBUG("filters.jsm: no valid key - aborting\n");
aListener.OnStartCopy();
aListener.OnStopCopy(1);
return;
}
- EnigmailLog.DEBUG("filters.jsm: key to encrypt to: " + JSON.stringify(keyObj) + ", userId: " + keyObj.userId + "\n");
+ EnigmailLog.DEBUG(
+ "filters.jsm: key to encrypt to: " +
+ JSON.stringify(keyObj) +
+ ", userId: " +
+ keyObj.userId +
+ "\n"
+ );
var msgHdrs = [];
for (let i = 0; i < aMsgHdrs.length; i++) {
let msg = aMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr);
// Maybe skip messages here if they are already encrypted to
// the target key? There might be some use case for unconditionally
// encrypting here. E.g. to use the local preferences and remove all
// other recipients.
// Also not encrypting to already encrypted messages would make the
// behavior less transparent as it's not obvious.
msgHdrs.push(msg);
}
if (msgHdrs.length) {
- EnigmailPersistentCrypto.dispatchMessages(msgHdrs, null /* same folder */ , aListener,
- true /* move */ , keyObj /* target key */ );
+ EnigmailPersistentCrypto.dispatchMessages(
+ msgHdrs,
+ null /* same folder */,
+ aListener,
+ true /* move */,
+ keyObj /* target key */
+ );
}
},
- isValidForType: function(type, scope) {
+ isValidForType(type, scope) {
return true;
},
- validateActionValue: function(value, folder, type) {
+ validateActionValue(value, folder, type) {
// Initialize KeyRing. Ugly as it blocks the GUI but
// we need it.
EnigmailCore.getService();
EnigmailKeyRing.getAllKeys();
- EnigmailLog.DEBUG("filters.jsm: validateActionValue: Encrypt to: " + value + "\n");
+ EnigmailLog.DEBUG(
+ "filters.jsm: validateActionValue: Encrypt to: " + value + "\n"
+ );
if (value === "") {
return EnigmailLocale.getString("filter.keyRequired");
}
let keyObj = EnigmailKeyRing.getKeyById(value);
if (keyObj === null) {
- EnigmailLog.DEBUG("filters.jsm: failed to find key by id. Looking for uid.\n");
+ EnigmailLog.DEBUG(
+ "filters.jsm: failed to find key by id. Looking for uid.\n"
+ );
let keyId = EnigmailKeyRing.getValidKeyForRecipient(value);
if (keyId) {
keyObj = EnigmailKeyRing.getKeyById(keyId);
}
}
if (keyObj === null) {
return EnigmailLocale.getString("filter.keyNotFound", [value]);
}
if (!keyObj.secretAvailable) {
// We warn but we allow it. There might be use cases where
// thunderbird + enigmail is used as a gateway filter with
// the secret not available on one machine and the decryption
// is intended to happen on different systems.
- getDialog().alert(null, EnigmailLocale.getString("filter.warn.keyNotSecret", [value]));
+ getDialog().alert(
+ null,
+ EnigmailLocale.getString("filter.warn.keyNotSecret", [value])
+ );
}
return null;
- }
+ },
};
function isPGPEncrypted(data) {
// We only check the first mime subpart for application/pgp-encrypted.
// If it is text/plain or text/html we look into that for the
// message marker.
// If there are no subparts we just look in the body.
//
// This intentionally does not match more complex cases
// with sub parts beeing encrypted etc. as auto processing
// these kinds of mails will be error prone and better not
// done through a filter
var mimeTree = EnigmailMime.getMimeTree(data, true);
- if (!(mimeTree.subParts.length)) {
+ if (!mimeTree.subParts.length) {
// No subParts. Check for PGP Marker in Body
- return mimeTree.body.indexOf('-----BEGIN PGP MESSAGE-----') >= 0;
+ return mimeTree.body.includes("-----BEGIN PGP MESSAGE-----");
}
// Check the type of the first subpart.
var firstPart = mimeTree.subParts[0];
var ct = firstPart.fullContentType;
- if (typeof(ct) == "string") {
+ if (typeof ct == "string") {
ct = ct.replace(/[\r\n]/g, " ");
// Proper PGP/MIME ?
if (ct.search(/application\/pgp-encrypted/i) >= 0) {
return true;
}
// Look into text/plain pgp messages and text/html messages.
- if (ct.search(/text\/plain/i) >= 0 ||
- ct.search(/text\/html/i) >= 0) {
- return firstPart.body.indexOf('-----BEGIN PGP MESSAGE-----') >= 0;
+ if (ct.search(/text\/plain/i) >= 0 || ct.search(/text\/html/i) >= 0) {
+ return firstPart.body.includes("-----BEGIN PGP MESSAGE-----");
}
}
return false;
}
/**
* filter term for OpenPGP Encrypted mail
*/
const filterTermPGPEncrypted = {
id: EnigmailConstants.FILTER_TERM_PGP_ENCRYPTED,
name: EnigmailLocale.getString("filter.term.pgpencrypted.label"),
needsBody: true,
- match: function(aMsgHdr, searchValue, searchOp) {
+ match(aMsgHdr, searchValue, searchOp) {
var folder = aMsgHdr.folder;
var stream = folder.getMsgInputStream(aMsgHdr, {});
- var messageSize = folder.hasMsgOffline(aMsgHdr.messageKey) ? aMsgHdr.offlineMessageSize : aMsgHdr.messageSize;
- var scriptInput = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance();
+ var messageSize = folder.hasMsgOffline(aMsgHdr.messageKey)
+ ? aMsgHdr.offlineMessageSize
+ : aMsgHdr.messageSize;
var data;
try {
data = NetUtil.readInputStreamToString(stream, messageSize);
- }
- catch (ex) {
- EnigmailLog.DEBUG("filters.jsm: filterTermPGPEncrypted: failed to get data.\n");
+ } catch (ex) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: filterTermPGPEncrypted: failed to get data.\n"
+ );
// If we don't know better to return false.
stream.close();
return false;
}
var isPGP = isPGPEncrypted(data);
stream.close();
- return ((searchOp == Ci.nsMsgSearchOp.Is && isPGP) ||
- (searchOp == Ci.nsMsgSearchOp.Isnt && !isPGP));
+ return (
+ (searchOp == Ci.nsMsgSearchOp.Is && isPGP) ||
+ (searchOp == Ci.nsMsgSearchOp.Isnt && !isPGP)
+ );
},
- getEnabled: function(scope, op) {
- return true;
- },
-
- getAvailable: function(scope, op) {
+ getEnabled(scope, op) {
return true;
},
- getAvailableOperators: function(scope, length) {
+ getAvailable(scope, op) {
+ return true;
+ },
+
+ getAvailableOperators(scope, length) {
length.value = 2;
return [Ci.nsMsgSearchOp.Is, Ci.nsMsgSearchOp.Isnt];
- }
+ },
};
-/**
- * Add a custom filter action. If the filter already exists, do nothing
- * (for example, if addon is disabled and re-enabled)
- *
- * @param filterObj - nsIMsgFilterCustomAction
- */
-function addFilterIfNotExists(filterObj) {
- let filterService = Cc["@mozilla.org/messenger/services/filters;1"].getService(Ci.nsIMsgFilterService);
-
- let foundFilter = null;
- try {
- foundFilter = filterService.getCustomAction(filterObj.id);
- }
- catch (ex) {}
-
- if (!foundFilter) {
- EnigmailLog.DEBUG("filters.jsm: addFilterIfNotExists: " + filterObj.id + "\n");
- filterService.addCustomAction(filterObj);
- }
-}
-
function initNewMailListener() {
EnigmailLog.DEBUG("filters.jsm: initNewMailListener()\n");
if (!gNewMailListenerInitiated) {
- let notificationService = Cc["@mozilla.org/messenger/msgnotificationservice;1"]
- .getService(Ci.nsIMsgFolderNotificationService);
- notificationService.addListener(newMailListener, notificationService.msgAdded);
+ let notificationService = Cc[
+ "@mozilla.org/messenger/msgnotificationservice;1"
+ ].getService(Ci.nsIMsgFolderNotificationService);
+ notificationService.addListener(
+ newMailListener,
+ notificationService.msgAdded
+ );
}
gNewMailListenerInitiated = true;
}
function shutdownNewMailListener() {
EnigmailLog.DEBUG("filters.jsm: shutdownNewMailListener()\n");
if (gNewMailListenerInitiated) {
- let notificationService = Cc["@mozilla.org/messenger/msgnotificationservice;1"]
- .getService(Ci.nsIMsgFolderNotificationService);
+ let notificationService = Cc[
+ "@mozilla.org/messenger/msgnotificationservice;1"
+ ].getService(Ci.nsIMsgFolderNotificationService);
notificationService.removeListener(newMailListener);
gNewMailListenerInitiated = false;
}
}
function getIdentityForSender(senderEmail, msgServer) {
- let accountManager = Cc["@mozilla.org/messenger/account-manager;1"].getService(Ci.nsIMsgAccountManager);
+ let accountManager = Cc[
+ "@mozilla.org/messenger/account-manager;1"
+ ].getService(Ci.nsIMsgAccountManager);
let identities = accountManager.getIdentitiesForServer(msgServer);
for (let i = 0; i < identities.length; i++) {
let id = identities.queryElementAt(i, Ci.nsIMsgIdentity);
if (id.email.toLowerCase() === senderEmail.toLowerCase()) {
return id;
}
}
return null;
}
var consumerList = [];
-
function JsmimeEmitter(requireBody) {
this.requireBody = requireBody;
this.mimeTree = {
partNum: "",
headers: null,
body: "",
parent: null,
- subParts: []
+ subParts: [],
};
this.stack = [];
this.currPartNum = "";
}
JsmimeEmitter.prototype = {
-
- createPartObj: function(partNum, headers, parent) {
+ createPartObj(partNum, headers, parent) {
return {
- partNum: partNum,
- headers: headers,
+ partNum,
+ headers,
body: "",
- parent: parent,
- subParts: []
+ parent,
+ subParts: [],
};
},
- getMimeTree: function() {
+ getMimeTree() {
return this.mimeTree.subParts[0];
},
/** JSMime API **/
- startMessage: function() {
+ startMessage() {
this.currentPart = this.mimeTree;
},
- endMessage: function() {},
+ endMessage() {},
- startPart: function(partNum, headers) {
- EnigmailLog.DEBUG("filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n");
+ startPart(partNum, headers) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n"
+ );
//this.stack.push(partNum);
let newPart = this.createPartObj(partNum, headers, this.currentPart);
if (partNum.indexOf(this.currPartNum) === 0) {
// found sub-part
this.currentPart.subParts.push(newPart);
- }
- else {
+ } else {
// found same or higher level
this.currentPart.subParts.push(newPart);
}
this.currPartNum = partNum;
this.currentPart = newPart;
},
- endPart: function(partNum) {
- EnigmailLog.DEBUG("filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n");
+ endPart(partNum) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: JsmimeEmitter.startPart: partNum=" + partNum + "\n"
+ );
this.currentPart = this.currentPart.parent;
},
- deliverPartData: function(partNum, data) {
- EnigmailLog.DEBUG("filters.jsm: JsmimeEmitter.deliverPartData: partNum=" + partNum + "\n");
+ deliverPartData(partNum, data) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: JsmimeEmitter.deliverPartData: partNum=" + partNum + "\n"
+ );
if (this.requireBody) {
- if (typeof(data) === "string") {
+ if (typeof data === "string") {
this.currentPart.body += data;
- }
- else {
+ } else {
this.currentPart.body += EnigmailData.arrayBufferToString(data);
}
}
- }
+ },
};
function processIncomingMail(url, requireBody, aMsgHdr) {
EnigmailLog.DEBUG("filters.jsm: processIncomingMail()\n");
let inputStream = EnigmailStreams.newStringStreamListener(msgData => {
let opt = {
strformat: "unicode",
- bodyformat: "decode"
+ bodyformat: "decode",
};
try {
let e = new JsmimeEmitter(requireBody);
let p = new jsmime.MimeParser(e, opt);
p.deliverData(msgData);
-
for (let c of consumerList) {
try {
c.consumeMessage(e.getMimeTree(), msgData, aMsgHdr);
- }
- catch (ex) {
- EnigmailLog.DEBUG("filters.jsm: processIncomingMail: exception: " + ex.toString() + "\n");
+ } catch (ex) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: processIncomingMail: exception: " +
+ ex.toString() +
+ "\n"
+ );
}
}
- }
- catch (ex) {}
+ } catch (ex) {}
});
try {
let channel = EnigmailStreams.createChannel(url);
channel.asyncOpen(inputStream, null);
- }
- catch (e) {
- EnigmailLog.DEBUG("filters.jsm: processIncomingMail: open stream exception " + e.toString() + "\n");
+ } catch (e) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: processIncomingMail: open stream exception " +
+ e.toString() +
+ "\n"
+ );
}
}
function getRequireMessageProcessing(aMsgHdr) {
- let isInbox = aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.CheckNew) || aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.Inbox);
+ let isInbox =
+ aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.CheckNew) ||
+ aMsgHdr.folder.getFlag(Ci.nsMsgFolderFlags.Inbox);
let requireBody = false;
let inboxOnly = true;
let selfSentOnly = false;
let processReadMail = false;
for (let c of consumerList) {
if (!c.incomingMailOnly) {
inboxOnly = false;
@@ -456,94 +521,110 @@ function getRequireMessageProcessing(aMs
if (!c.headersOnly) {
requireBody = true;
}
if (c.selfSentOnly) {
selfSentOnly = true;
}
}
- if (!processReadMail && aMsgHdr.isRead) return null;
- if (inboxOnly && !isInbox) return null;
+ if (!processReadMail && aMsgHdr.isRead) {
+ return null;
+ }
+ if (inboxOnly && !isInbox) {
+ return null;
+ }
if (selfSentOnly) {
let sender = EnigmailFuncs.parseEmails(aMsgHdr.author, true);
let id = null;
if (sender && sender[0]) {
id = getIdentityForSender(sender[0].email, aMsgHdr.folder.server);
}
- if (!id) return null;
+ if (!id) {
+ return null;
+ }
}
- EnigmailLog.DEBUG("filters.jsm: getRequireMessageProcessing: author: " + aMsgHdr.author + "\n");
+ EnigmailLog.DEBUG(
+ "filters.jsm: getRequireMessageProcessing: author: " + aMsgHdr.author + "\n"
+ );
- let u = EnigmailCompat.getUrlFromUriSpec(aMsgHdr.folder.getUriForMsg(aMsgHdr));
+ let u = EnigmailCompat.getUrlFromUriSpec(
+ aMsgHdr.folder.getUriForMsg(aMsgHdr)
+ );
- if (! u) {
+ if (!u) {
return null;
}
- let op = (u.spec.indexOf("?") > 0 ? "&" : "?");
+ let op = u.spec.indexOf("?") > 0 ? "&" : "?";
let url = u.spec + op + "header=enigmailFilter";
return {
- url: url,
- requireBody: requireBody
+ url,
+ requireBody,
};
}
const newMailListener = {
- msgAdded: function(aMsgHdr) {
- EnigmailLog.DEBUG("filters.jsm: newMailListener.msgAdded() - got new mail in " + aMsgHdr.folder.prettiestName + "\n");
+ msgAdded(aMsgHdr) {
+ EnigmailLog.DEBUG(
+ "filters.jsm: newMailListener.msgAdded() - got new mail in " +
+ aMsgHdr.folder.prettiestName +
+ "\n"
+ );
- if (consumerList.length === 0) return;
+ if (consumerList.length === 0) {
+ return;
+ }
let ret = getRequireMessageProcessing(aMsgHdr);
if (ret) {
processIncomingMail(ret.url, ret.requireBody, aMsgHdr);
}
- }
+ },
};
/**
messageStructure - Object:
- partNum: String - MIME part number
- headers: Object(nsIStructuredHeaders) - MIME part headers
- body: String or typedarray - the body part
- parent: Object(messageStructure) - link to the parent part
- subParts: Array of Object(messageStructure) - array of the sub-parts
*/
var EnigmailFilters = {
- onStartup: function() {
- let filterService = Cc["@mozilla.org/messenger/services/filters;1"].getService(Ci.nsIMsgFilterService);
+ onStartup() {
+ let filterService = Cc[
+ "@mozilla.org/messenger/services/filters;1"
+ ].getService(Ci.nsIMsgFilterService);
filterService.addCustomTerm(filterTermPGPEncrypted);
initNewMailListener();
},
- onShutdown: function() {
+ onShutdown() {
shutdownNewMailListener();
},
/**
* add a new consumer to listen to new mails
*
* @param consumer - Object
* - headersOnly: Boolean - needs full message body? [FUTURE]
* - incomingMailOnly: Boolean - only work on folder(s) that obtain new mail
* (Inbox and folders that listen to new mail)
* - unreadOnly: Boolean - only process unread mails
* - selfSentOnly: Boolean - only process mails with sender Email == Account Email
* - consumeMessage: function(messageStructure, rawMessageData, nsIMsgHdr)
*/
- addNewMailConsumer: function(consumer) {
+ addNewMailConsumer(consumer) {
EnigmailLog.DEBUG("filters.jsm: addNewMailConsumer()\n");
consumerList.push(consumer);
},
- removeNewMailConsumer: function(consumer) {
-
- },
+ removeNewMailConsumer(consumer) {},
moveDecrypt: filterActionMoveDecrypt,
copyDecrypt: filterActionCopyDecrypt,
- encrypt: filterActionEncrypt
+ encrypt: filterActionEncrypt,
};
--- a/mail/extensions/openpgp/content/modules/filtersWrapper.jsm
+++ b/mail/extensions/openpgp/content/modules/filtersWrapper.jsm
@@ -1,169 +1,188 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailFiltersWrapper"];
-
-
-
-
-var gNewMailListenerInitiated = false;
var gEnigmailFilters = null;
-let {
- EnigmailConstants
-} = ChromeUtils.import("chrome://openpgp/content/modules/constants.jsm");
-let {
- EnigmailLocale
-} = ChromeUtils.import("chrome://openpgp/content/modules/locale.jsm");
+let { EnigmailConstants } = ChromeUtils.import(
+ "chrome://openpgp/content/modules/constants.jsm"
+);
+let { EnigmailLocale } = ChromeUtils.import(
+ "chrome://openpgp/content/modules/locale.jsm"
+);
/**
* filter action for creating a decrypted version of the mail and
* deleting the original mail at the same time
*/
const filterActionMoveDecrypt = {
id: EnigmailConstants.FILTER_MOVE_DECRYPT,
name: EnigmailLocale.getString("filter.decryptMove.label"),
value: "movemessage",
- apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
-
+ apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
if (gEnigmailFilters) {
- gEnigmailFilters.moveDecrypt.apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow);
- }
- else {
+ gEnigmailFilters.moveDecrypt.apply(
+ aMsgHdrs,
+ aActionValue,
+ aListener,
+ aType,
+ aMsgWindow
+ );
+ } else {
aListener.OnStartCopy();
aListener.OnStopCopy(0);
}
},
- isValidForType: function(type, scope) {
- return gEnigmailFilters ? gEnigmailFilters.moveDecrypt.isValidForType(type, scope) : false;
+ isValidForType(type, scope) {
+ return gEnigmailFilters
+ ? gEnigmailFilters.moveDecrypt.isValidForType(type, scope)
+ : false;
},
- validateActionValue: function(value, folder, type) {
+ validateActionValue(value, folder, type) {
if (gEnigmailFilters) {
- return gEnigmailFilters.moveDecrypt.validateActionValue(value, folder, type);
+ return gEnigmailFilters.moveDecrypt.validateActionValue(
+ value,
+ folder,
+ type
+ );
}
return null;
},
allowDuplicates: false,
isAsync: true,
- needsBody: true
+ needsBody: true,
};
/**
* filter action for creating a decrypted copy of the mail, leaving the original
* message untouched
*/
const filterActionCopyDecrypt = {
id: EnigmailConstants.FILTER_COPY_DECRYPT,
name: EnigmailLocale.getString("filter.decryptCopy.label"),
value: "copymessage",
- apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+ apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
if (gEnigmailFilters) {
- gEnigmailFilters.copyDecrypt.apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow);
- }
- else {
+ gEnigmailFilters.copyDecrypt.apply(
+ aMsgHdrs,
+ aActionValue,
+ aListener,
+ aType,
+ aMsgWindow
+ );
+ } else {
aListener.OnStartCopy();
aListener.OnStopCopy(0);
}
},
- isValidForType: function(type, scope) {
- return gEnigmailFilters ? gEnigmailFilters.copyDecrypt.isValidForType(type, scope) : false;
+ isValidForType(type, scope) {
+ return gEnigmailFilters
+ ? gEnigmailFilters.copyDecrypt.isValidForType(type, scope)
+ : false;
},
- validateActionValue: function(value, folder, type) {
+ validateActionValue(value, folder, type) {
if (gEnigmailFilters) {
- return gEnigmailFilters.copyDecrypt.validateActionValue(value, folder, type);
+ return gEnigmailFilters.copyDecrypt.validateActionValue(
+ value,
+ folder,
+ type
+ );
}
return null;
},
allowDuplicates: false,
isAsync: true,
- needsBody: true
+ needsBody: true,
};
/**
* filter action for to encrypt a mail to a specific key
*/
const filterActionEncrypt = {
id: EnigmailConstants.FILTER_ENCRYPT,
name: EnigmailLocale.getString("filter.encrypt.label"),
value: "encryptto",
- apply: function(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
+ apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow) {
if (gEnigmailFilters) {
- gEnigmailFilters.encrypt.apply(aMsgHdrs, aActionValue, aListener, aType, aMsgWindow);
- }
- else {
+ gEnigmailFilters.encrypt.apply(
+ aMsgHdrs,
+ aActionValue,
+ aListener,
+ aType,
+ aMsgWindow
+ );
+ } else {
aListener.OnStartCopy();
aListener.OnStopCopy(0);
}
},
- isValidForType: function(type, scope) {
+ isValidForType(type, scope) {
return gEnigmailFilters ? gEnigmailFilters.encrypt.isValidForType() : false;
},
- validateActionValue: function(value, folder, type) {
+ validateActionValue(value, folder, type) {
if (gEnigmailFilters) {
return gEnigmailFilters.encrypt.validateActionValue(value, folder, type);
}
return null;
-
},
allowDuplicates: false,
isAsync: true,
- needsBody: true
+ needsBody: true,
};
-
/**
* Add a custom filter action. If the filter already exists, do nothing
* (for example, if addon is disabled and re-enabled)
*
* @param filterObj - nsIMsgFilterCustomAction
*/
function addFilterIfNotExists(filterObj) {
- let filterService = Cc["@mozilla.org/messenger/services/filters;1"].getService(Ci.nsIMsgFilterService);
+ let filterService = Cc[
+ "@mozilla.org/messenger/services/filters;1"
+ ].getService(Ci.nsIMsgFilterService);
let foundFilter = null;
try {
foundFilter = filterService.getCustomAction(filterObj.id);
- }
- catch (ex) {}
+ } catch (ex) {}
if (!foundFilter) {
filterService.addCustomAction(filterObj);
}
}
var EnigmailFiltersWrapper = {
- onStartup: function() {
- let {
- EnigmailFilters
- } = ChromeUtils.import("chrome://openpgp/content/modules/filters.jsm");
+ onStartup() {
+ let { EnigmailFilters } = ChromeUtils.import(
+ "chrome://openpgp/content/modules/filters.jsm"
+ );
gEnigmailFilters = EnigmailFilters;
addFilterIfNotExists(filterActionMoveDecrypt);
addFilterIfNotExists(filterActionCopyDecrypt);
addFilterIfNotExists(filterActionEncrypt);
gEnigmailFilters.onStartup();
},
- onShutdown: function() {
+ onShutdown() {
gEnigmailFilters.onShutdown();
gEnigmailFilters = null;
- }
+ },
};
--- a/mail/extensions/openpgp/content/modules/fixExchangeMsg.jsm
+++ b/mail/extensions/openpgp/content/modules/fixExchangeMsg.jsm
@@ -1,197 +1,231 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-
"use strict";
var EXPORTED_SYMBOLS = ["EnigmailFixExchangeMsg"];
-const EnigmailCompat = ChromeUtils.import("chrome://openpgp/content/modules/compat.jsm").EnigmailCompat;
-const EnigmailCore = ChromeUtils.import("chrome://openpgp/content/modules/core.jsm").EnigmailCore;
-const EnigmailFuncs = ChromeUtils.import("chrome://openpgp/content/modules/funcs.jsm").EnigmailFuncs;
-const EnigmailLog = ChromeUtils.import("chrome://openpgp/content/modules/log.jsm").EnigmailLog;
-const EnigmailStreams = ChromeUtils.import("chrome://openpgp/content/modules/streams.jsm").Eni