mime.jsm 13.8 KB
Newer Older
1
2
3
/*
 * 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
4
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
 */
6
7
8

"use strict";

9
var EXPORTED_SYMBOLS = ["EnigmailMime"];
10

11
12
13
14
const jsmime = ChromeUtils.import("resource:///modules/jsmime.jsm").jsmime;
const EnigmailData = ChromeUtils.import("chrome://enigmail/content/modules/data.jsm").EnigmailData;
const EnigmailRNG = ChromeUtils.import("chrome://enigmail/content/modules/rng.jsm").EnigmailRNG;
const EnigmailStreams = ChromeUtils.import("chrome://enigmail/content/modules/streams.jsm").EnigmailStreams;
15

16
var EnigmailMime = {
17
18
19
20
21
22
23
  /***
   * create a string of random characters suitable to use for a boundary in a
   * MIME message following RFC 2045
   *
   * @return: string of 33 random characters and digits
   */
  createBoundary: function() {
24
    return EnigmailRNG.generateRandomString(33);
25
26
27
28
29
30
31
32
  },

  /***
   * determine the "boundary" part of a mail content type.
   *
   * @contentTypeStr: the string containing all parts of a content-type.
   *               (e.g. multipart/mixed; boundary="xyz") --> returns "xyz"
   *
33
   * @return: String containing the boundary parameter; or ""
34
35
36
   */

  getBoundary: function(contentTypeStr) {
37
    return EnigmailMime.getParameter(contentTypeStr, "boundary");
38
39
  },

40
41
42
43
44
45
  /***
   * determine the "protocol" part of a mail content type.
   *
   * @contentTypeStr: the string containing all parts of a content-type.
   *               (e.g. multipart/signed; protocol="xyz") --> returns "xyz"
   *
46
   * @return: String containing the protocol parameter; or ""
47
48
49
   */

  getProtocol: function(contentTypeStr) {
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    return EnigmailMime.getParameter(contentTypeStr, "protocol");
  },

  /***
   * determine an arbitrary "parameter" part of a mail header.
   *
   * @param headerStr: the string containing all parts of the header.
   * @param parameter: the parameter we are looking for
   *
   *
   * 'multipart/signed; protocol="xyz"', 'protocol' --> returns "xyz"
   *
   * @return: String containing the parameter; or ""
   */

  getParameter: function(headerStr, parameter) {
    let paramsArr = EnigmailMime.getAllParameters(headerStr);
    parameter = parameter.toLowerCase();
    if (parameter in paramsArr) {
      return paramsArr[parameter];
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
    else
      return "";
  },

  /***
   * get all parameter attributes of a mail header.
   *
   * @param headerStr: the string containing all parts of the header.
   *
   * @return: Array of Object containing the key value pairs
   *
   * 'multipart/signed; protocol="xyz"'; boundary="xxx"
   *  --> returns [ ["protocol": "xyz"], ["boundary": "xxx"] ]
   */

  getAllParameters: function(headerStr) {

    headerStr = headerStr.replace(/[\r\n]+[ \t]+/g, "");
    let hdrMap = jsmime.headerparser.parseParameterHeader(";" + headerStr, true, true);

    let paramArr = [];
    let i = hdrMap.entries();
    let p = i.next();
    while (p.value) {
      paramArr[p.value[0].toLowerCase()] = p.value[1];
      p = i.next();
    }

    return paramArr;
100
101
  },

102
103
104
105
106
107
108
109
110
111
  /***
   * determine the "charset" part of a mail content type.
   *
   * @contentTypeStr: the string containing all parts of a content-type.
   *               (e.g. multipart/mixed; charset="utf-8") --> returns "utf-8"
   *
   * @return: String containing the charset parameter; or null
   */

  getCharset: function(contentTypeStr) {
112
    return EnigmailMime.getParameter(contentTypeStr, "charset");
113
114
115
116
117
118
119
120
  },

  /**
   * Convert a MIME header value into a UTF-8 encoded representation following RFC 2047
   */
  encodeHeaderValue: function(aStr) {
    let ret = "";

Patrick Brunschwig's avatar
Patrick Brunschwig committed
121
    if (aStr.search(/[^\x01-\x7F]/) >= 0) { // eslint-disable-line no-control-regex
122
123
124
125
126
127
      let s = EnigmailData.convertFromUnicode(aStr, "utf-8");
      ret = "=?UTF-8?B?" + btoa(s) + "?=";
    }
    else {
      ret = aStr;
    }
Patrick Brunschwig's avatar
Patrick Brunschwig committed
128

129
130
    return ret;
  },
131

132
  /**
133
   * format MIME header with maximum length of 72 characters.
134
135
136
137
138
139
140
   */
  formatHeaderData: function(hdrValue) {
    let header;
    if (Array.isArray(hdrValue)) {
      header = hdrValue.join("").split(" ");
    }
    else {
141
      header = hdrValue.split(/ +/);
142
    }
143

144
145
146
147
148
149
150
151
152
153
    let line = "";
    let lines = [];

    for (let i = 0; i < header.length; i++) {
      if (line.length + header[i].length >= 72) {
        lines.push(line + "\r\n");
        line = " " + header[i];
      }
      else {
        line += " " + header[i];
154
      }
155
    }
156

157
    lines.push(line);
158

159
160
    return lines.join("").trim();
  },
161

162
163
164
165
166
  /**
   * Correctly encode and format a set of email addresses for RFC 2047
   */
  formatEmailAddress: function(addressData) {
    const adrArr = addressData.split(/, */);
Patrick Brunschwig's avatar
Patrick Brunschwig committed
167

168
169
    for (let i in adrArr) {
      try {
170
        const m = adrArr[i].match(/(.*[\w\s]+?)<([\w-][\w.-]+@[\w-][\w.-]+[a-zA-Z]{1,4})>/);
171
172
        if (m && m.length == 3) {
          adrArr[i] = this.encodeHeaderValue(m[1]) + " <" + m[2] + ">";
Patrick Brunschwig's avatar
Patrick Brunschwig committed
173
        }
174
175
176
      }
      catch (ex) {}
    }
Patrick Brunschwig's avatar
Patrick Brunschwig committed
177

178
179
    return adrArr.join(", ");
  },
Patrick Brunschwig's avatar
Patrick Brunschwig committed
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
  /**
   * Extract the subject from the 1st line of the message body, if the message body starts
   * with: "Subject: ...\r?\n\r?\n".
   *
   * @param msgBody - String: message body
   *
   * @return
   * if subject is found:
   *  Object:
   *    - messageBody - String: message body without subject
   *    - subject     - String: extracted subject
   *
   * if subject not found: null
   */
  extractSubjectFromBody: function(msgBody) {
    let m = msgBody.match(/^(\r?\n?Subject: [^\r\n]+\r?\n\r?\n)/i);
    if (m && m.length > 0) {
      let subject = m[0].replace(/[\r\n]/g, "");
      subject = subject.substr(9);
      msgBody = msgBody.substr(m[0].length);

      return {
        messageBody: msgBody,
        subject: subject
      };
    }

    return null;
  },

211
212
213
214
  /***
   * determine if the message data contains a first mime part with content-type = "text/rfc822-headers"
   * if so, extract the corresponding field(s)
   */
Patrick Brunschwig's avatar
Patrick Brunschwig committed
215

216
217
218
  extractProtectedHeaders: function(contentData) {
    // find first MIME delimiter. Anything before that delimiter is the top MIME structure
    let m = contentData.search(/^--/m);
219

220
221
222
223
224
    if (m < 0) {
      // we got a single, simple MIME part without any sub-parts
      m = contentData.length;
    }

225
226
227
228
229
230
    let protectedHdr = ["subject", "date", "from",
      "to", "cc", "reply-to", "references",
      "newsgroups", "followup-to", "message-id"
    ];
    let newHeaders = {};

231
232
233
    // read headers of first MIME part and extract the boundary parameter
    let outerHdr = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
    outerHdr.initialize(contentData.substr(0, m));
234

235
236
    let ct = outerHdr.extractHeader("content-type", false) || "";
    if (ct === "") return null;
237

238
239
240
    let startPos = -1,
      endPos = -1,
      bound = "";
241

242
243
244
245
246
    if (ct.search(/^multipart\//i) === 0) {
      // multipart/xyz message type
      if (m < 5) {
        return null;
      }
247
248


249
250
      bound = EnigmailMime.getBoundary(ct);
      if (bound === "") return null;
251

252
      // search for "outer" MIME delimiter(s)
Patrick Brunschwig's avatar
Patrick Brunschwig committed
253
      let r = new RegExp("^--" + bound.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"), "mg");
254
255
256

      startPos = -1;
      endPos = -1;
257

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
      // 1st match: start of 1st MIME-subpart
      let match = r.exec(contentData);
      if (match && match.index) {
        startPos = match.index;
      }

      // 2nd  match: end of 1st MIME-subpart
      match = r.exec(contentData);
      if (match && match.index) {
        endPos = match.index;
      }

      if (startPos < 0 || endPos < 0) return null;
    }
    else {
      startPos = contentData.length;
      endPos = 0;
    }
276

277
278
279
    let headers = Cc["@mozilla.org/messenger/mimeheaders;1"].createInstance(Ci.nsIMimeHeaders);
    headers.initialize(contentData.substring(0, startPos));

280
281
282
283
    // we got a potentially protected header. Let's check ...
    ct = headers.extractHeader("content-type", false) || "";
    if (this.getParameter(ct, "protected-headers").search(/^v1$/i) !== 0) return null;

284
285
286
287
288
289
    for (let i in protectedHdr) {
      if (headers.hasHeader(protectedHdr[i])) {
        newHeaders[protectedHdr[i]] = jsmime.headerparser.decodeRFC2047Words(headers.extractHeader(protectedHdr[i], true)) || undefined;
      }
    }

290
291
292
293
294
295
    // contentBody holds the complete 1st MIME part
    let contentBody = contentData.substring(startPos + bound.length + 3, endPos);
    let i = contentBody.search(/^[A-Za-z]/m); // skip empty lines
    if (i > 0) {
      contentBody = contentBody.substr(i);
    }
296

297
    headers.initialize(contentBody);
298

299
    let innerCt = headers.extractHeader("content-type", false) || "";
300
    if (!(innerCt.search(/^text\/(plain|rfc822-headers)/i) === 0 && innerCt.search(/; *protected-headers="?v1"?/i) > 0)) {
301
302
      startPos = -1;
      endPos = -1;
303
    }
304
305
306
307

    return {
      newHeaders: newHeaders,
      startPos: startPos,
Patrick Brunschwig's avatar
Patrick Brunschwig committed
308
309
      endPos: endPos,
      securityLevel: 0
310
    };
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
  },

  /**
   * Get the part number from a URI spec (e.g. mailbox:///folder/xyz?part=1.2.3.5)
   *
   * @param spec: String - the URI spec to inspect
   *
   * @return String: the mime part number (or "" if none found)
   */
  getMimePartNumber: function(spec) {
    let m = spec.match(/([\?&]part=)(\d+(\.\d+)*)/);

    if (m && m.length >= 3) {
      return m[2];
    }

    return "";
328
329
  },

330
331
332
333
334
335
336
337
338
339
  /**
   * Try to determine if the message structure is a known MIME structure,
   * based on the MIME part number and the uriSpec.
   *
   * @param mimePartNumber: String - the MIME part we are requested to decrypt
   * @param uriSpec:        String - the URI spec of the message (or msg part) loaded by TB
   *
   * @return Boolean: true: regular message structure, MIME part is safe to be decrypted
   *                  false: otherwise
   */
340
  isRegularMimeStructure: function(mimePartNumber, uriSpec, acceptSubParts = false) {
341
    if (mimePartNumber.length === 0) return true;
342
343

    if (acceptSubParts && (mimePartNumber.search(/^1(\.1)*$/) === 0)) return true;
344
    if (mimePartNumber === "1") return true;
345
346
347
348
349
350

    if (!uriSpec) return true;

    // is the message a subpart of a complete attachment?
    let msgPart = this.getMimePartNumber(uriSpec);
    if (msgPart.length > 0) {
351
      // load attached messages
352
353
      if (mimePartNumber.indexOf(msgPart) === 0 &&
        mimePartNumber.substr(msgPart.length).search(/^(\.1)+$/) === 0) return true;
354
355
356
357

      // load attachments of attached messages
      if (msgPart.indexOf(mimePartNumber) === 0 &&
        uriSpec.search(/[\?&]filename=/) > 0) return true;
358
359
360
361
362
363
    }

    return false;
  },


Patrick Brunschwig's avatar
Patrick Brunschwig committed
364
365
366
367
368
369
370
371
372
373
374
  /**
   * Parse a MIME message and return a tree structur of TreeObject
   *
   * @param url:         String   - the URL to load and parse
   * @param getBody:     Boolean  - if true, delivers the body text of each MIME part
   * @param callbackFunc Function - the callback function that is called asynchronously
   *                                when parsing is complete.
   *                                Function signature: callBackFunc(TreeObject)
   *
   * @return undefined
   */
375
  getMimeTreeFromUrl: function(url, getBody = false, callbackFunc) {
376
    function onData(data) {
377
      let tree = getMimeTree(data, getBody);
378
379
380
381
382
383
384
385
386
387
      callbackFunc(tree);
    }

    let chan = EnigmailStreams.createChannel(url);
    let bufferListener = EnigmailStreams.newStringStreamListener(onData);
    chan.asyncOpen(bufferListener, null);
  },

  getMimeTree: getMimeTree

388
};
389
390

/**
Patrick Brunschwig's avatar
Patrick Brunschwig committed
391
 * Parse a MIME message and return a tree structure of TreeObject.
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
 *
 * TreeObject contains the following main parts:
 *     - partNum: String
 *     - headers: Map, containing all headers.
 *         Special headers for contentType and charset
 *     - body: String, if getBody == true
 *     - subParts: Array of TreeObject
 *
 * @param mimeStr: String  - a MIME structure to parse
 * @param getBody: Boolean - if true, delivers the body text of each MIME part
 *
 * @return TreeObject, or NULL in case of failure
 */
function getMimeTree(mimeStr, getBody = false) {

  let mimeTree = {
      partNum: "",
      headers: null,
      body: "",
      parent: null,
      subParts: []
    },
    stack = [],
    currentPart = "",
    currPartNum = "";

  const jsmimeEmitter = {

    createPartObj: function(partNum, headers, parent) {
      let ct;

      if (headers.has("content-type")) {
        ct = headers.contentType.type;
        let it = headers.get("content-type").entries();
        for (let i of it) {
          ct += '; ' + i[0] + '="' + i[1] + '"';
        }
      }

      return {
        partNum: partNum,
        headers: headers,
        fullContentType: ct,
        body: "",
        parent: parent,
        subParts: []
      };
    },

    /** JSMime API **/
    startMessage: function() {
      currentPart = mimeTree;
    },

    endMessage: function() {},

    startPart: function(partNum, headers) {
      //dump("mime.jsm: jsmimeEmitter.startPart: partNum=" + partNum + "\n");
      partNum = "1" + (partNum !== "" ? "." : "") + partNum;
      let newPart = this.createPartObj(partNum, headers, currentPart);

      if (partNum.indexOf(currPartNum) === 0) {
        // found sub-part
        currentPart.subParts.push(newPart);
      }
      else {
        // found same or higher level
        currentPart.subParts.push(newPart);
      }
      currPartNum = partNum;
      currentPart = newPart;
    },
    endPart: function(partNum) {
      //dump("mime.jsm: jsmimeEmitter.startPart: partNum=" + partNum + "\n");
      currentPart = currentPart.parent;
    },

    deliverPartData: function(partNum, data) {
      //dump("mime.jsm: jsmimeEmitter.deliverPartData: partNum=" + partNum + " / " + typeof data + "\n");
      if (typeof(data) === "string") {
        currentPart.body += data;
      }
      else {
        currentPart.body += EnigmailData.arrayBufferToString(data);
      }
    }
  };

  let opt = {
    strformat: "unicode",
    bodyformat: getBody ? "decode" : "none"
  };


  try {
    let p = new jsmime.MimeParser(jsmimeEmitter, opt);
    p.deliverData(mimeStr);
    return mimeTree.subParts[0];
  }
  catch (ex) {
    return null;
  }
}