summaryrefslogtreecommitdiffstats
path: root/comm/mail/extensions/openpgp/content/modules/wksMimeHandler.jsm
blob: 40a8d221f06fac5f08d5c4862b407a5471a8828e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* 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 = ["EnigmailWksMimeHandler"];

const { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);

const lazy = {};

XPCOMUtils.defineLazyModuleGetters(lazy, {
  EnigmailConstants: "chrome://openpgp/content/modules/constants.jsm",
  EnigmailDecryption: "chrome://openpgp/content/modules/decryption.jsm",
  EnigmailLog: "chrome://openpgp/content/modules/log.jsm",
  EnigmailSingletons: "chrome://openpgp/content/modules/singletons.jsm",
  EnigmailVerify: "chrome://openpgp/content/modules/mimeVerify.jsm",
});

XPCOMUtils.defineLazyGetter(lazy, "l10n", () => {
  return new Localization(["messenger/openpgp/openpgp.ftl"], true);
});

/**
 *  Module for handling response messages from OpenPGP Web Key Service
 */

var gDebugLog = false;

var EnigmailWksMimeHandler = {
  /***
   * register a PGP/MIME verify object the same way PGP/MIME encrypted mail is handled
   */
  registerContentTypeHandler() {
    lazy.EnigmailLog.DEBUG(
      "wksMimeHandler.jsm: registerContentTypeHandler()\n"
    );
    let reg = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);

    let pgpMimeClass = Cc["@mozilla.org/mimecth;1?type=multipart/encrypted"];

    reg.registerFactory(
      pgpMimeClass,
      "Enigmail WKD Response Handler",
      "@mozilla.org/mimecth;1?type=application/vnd.gnupg.wks",
      null
    );
  },

  newHandler() {
    lazy.EnigmailLog.DEBUG("wksMimeHandler.jsm: newHandler()\n");

    let v = new PgpWkdHandler();
    return v;
  },
};

// MimeVerify Constructor
function PgpWkdHandler(protocol) {
  this.inStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
    Ci.nsIScriptableInputStream
  );
}

// PgpWkdHandler implementation
PgpWkdHandler.prototype = {
  data: "",
  mimePartNumber: "",
  uri: null,
  backgroundJob: false,

  QueryInterface: ChromeUtils.generateQI(["nsIStreamListener"]),

  onStartRequest(request, ctxt) {
    lazy.EnigmailLog.DEBUG("wksMimeHandler.jsm: onStartRequest\n"); // always log this one

    this.mimeSvc = request.QueryInterface(Ci.nsIPgpMimeProxy);
    if ("messageURI" in this.mimeSvc) {
      this.uri = this.mimeSvc.messageURI;
    } else {
      this.uri = ctxt;
    }

    if ("mimePart" in this.mimeSvc) {
      this.mimePartNumber = this.mimeSvc.mimePart;
    } else {
      this.mimePartNumber = "";
    }
    this.data = "";
    this.msgWindow = lazy.EnigmailVerify.lastWindow;
    this.backgroundJob = false;

    if (this.uri) {
      this.backgroundJob =
        this.uri.spec.search(/[&?]header=(print|quotebody)/) >= 0;
    }
  },

  onDataAvailable(req, dummy, stream, offset, count) {
    if ("messageURI" in this.mimeSvc) {
      // TB >= 67
      stream = dummy;
      count = offset;
    }

    LOCAL_DEBUG("wksMimeHandler.jsm: onDataAvailable: " + count + "\n");
    if (count > 0) {
      this.inStream.init(stream);
      let data = this.inStream.read(count);
      this.data += data;
    }
  },

  onStopRequest() {
    lazy.EnigmailLog.DEBUG("wksMimeHandler.jsm: onStopRequest\n");

    if (this.data.search(/-----BEGIN PGP MESSAGE-----/i) >= 0) {
      this.decryptChallengeData();
    }

    let jsonStr = this.requestToJsonString(this.data);

    if (this.data.search(/^\s*type:\s+confirmation-request/im) >= 0) {
      lazy.l10n.formatValue("wkd-message-body-req").then(value => {
        this.returnData(value);
      });
    } else {
      lazy.l10n.formatValue("wkd-message-body-process").then(value => {
        this.returnData(value);
      });
    }

    this.displayStatus(jsonStr);
  },

  decryptChallengeData() {
    lazy.EnigmailLog.DEBUG("wksMimeHandler.jsm: decryptChallengeData()\n");
    let windowManager = Services.wm;
    let win = windowManager.getMostRecentWindow(null);
    let statusFlagsObj = {};

    let res = lazy.EnigmailDecryption.decryptMessage(
      win,
      0,
      this.data,
      null, // date
      {},
      {},
      statusFlagsObj,
      {},
      {},
      {},
      {},
      {},
      {}
    );

    if (statusFlagsObj.value & lazy.EnigmailConstants.DECRYPTION_OKAY) {
      this.data = res;
    }
    lazy.EnigmailLog.DEBUG(
      "wksMimeHandler.jsm: decryptChallengeData: decryption result: " +
        res +
        "\n"
    );
  },

  // convert request data into JSON-string and parse it
  requestToJsonString() {
    // convert
    let lines = this.data.split(/\r?\n/);
    let s = "{";
    for (let l of lines) {
      let m = l.match(/^([^\s:]+)(:\s*)([^\s].+)$/);
      if (m && m.length >= 4) {
        s += '"' + m[1].trim().toLowerCase() + '": "' + m[3].trim() + '",';
      }
    }

    s = s.substr(0, s.length - 1) + "}";

    return s;
  },

  // return data to libMime
  returnData(message) {
    lazy.EnigmailLog.DEBUG("wksMimeHandler.jsm: returnData():\n");

    let msg =
      'Content-Type: text/plain; charset="utf-8"\r\n' +
      "Content-Transfer-Encoding: 8bit\r\n\r\n" +
      message +
      "\r\n";

    if ("outputDecryptedData" in this.mimeSvc) {
      this.mimeSvc.outputDecryptedData(msg, msg.length);
    } else {
      let gConv = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(
        Ci.nsIStringInputStream
      );
      gConv.setData(msg, msg.length);
      try {
        this.mimeSvc.onStartRequest(null);
        this.mimeSvc.onDataAvailable(null, gConv, 0, msg.length);
        this.mimeSvc.onStopRequest(null, 0);
      } catch (ex) {
        lazy.EnigmailLog.ERROR(
          "wksMimeHandler.jsm: returnData(): mimeSvc.onDataAvailable failed:\n" +
            ex.toString()
        );
      }
    }
  },

  displayStatus(jsonStr) {
    lazy.EnigmailLog.DEBUG("wksMimeHandler.jsm: displayStatus\n");
    if (this.msgWindow === null || this.backgroundJob) {
      return;
    }

    try {
      LOCAL_DEBUG("wksMimeHandler.jsm: displayStatus displaying result\n");
      let headerSink = lazy.EnigmailSingletons.messageReader;

      if (headerSink) {
        headerSink.processDecryptionResult(
          this.uri,
          "wksConfirmRequest",
          jsonStr,
          this.mimePartNumber
        );
      }
    } catch (ex) {
      lazy.EnigmailLog.writeException("wksMimeHandler.jsm", ex);
    }
  },
};

////////////////////////////////////////////////////////////////////
// General-purpose functions, not exported

function LOCAL_DEBUG(str) {
  if (gDebugLog) {
    lazy.EnigmailLog.DEBUG(str);
  }
}

function initModule() {
  let nspr_log_modules = Services.env.get("NSPR_LOG_MODULES");
  let matches = nspr_log_modules.match(/wksMimeHandler:(\d+)/);

  if (matches && matches.length > 1) {
    if (matches[1] > 2) {
      gDebugLog = true;
    }
  }
}

initModule();