summaryrefslogtreecommitdiffstats
path: root/comm/mail/modules/DNS.jsm
blob: de913aa5cd98104b8e87c828a7646e64887b796b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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
/* 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/. */

/**
 * This module is responsible for performing DNS queries using ctypes for
 * loading system DNS libraries on Linux, Mac and Windows.
 */

const EXPORTED_SYMBOLS = ["DNS", "SRVRecord"];

var DNS = null;

if (typeof Components !== "undefined") {
  var { ctypes } = ChromeUtils.importESModule(
    "resource://gre/modules/ctypes.sys.mjs"
  );
  var { BasePromiseWorker } = ChromeUtils.importESModule(
    "resource://gre/modules/PromiseWorker.sys.mjs"
  );
}

var LOCATION = "resource:///modules/DNS.jsm";

// These constants are luckily shared, but with different names
var NS_T_TXT = 16; // DNS_TYPE_TXT
var NS_T_SRV = 33; // DNS_TYPE_SRV
var NS_T_MX = 15; // DNS_TYPE_MX

// For Linux and Mac.
function load_libresolv(os) {
  this._open(os);
}

load_libresolv.prototype = {
  library: null,

  // Tries to find and load library.
  _open(os) {
    function findLibrary() {
      let lastException = null;
      let candidates = [];
      if (os == "FreeBSD") {
        candidates = [{ name: "c", suffix: ".7" }];
      } else if (os == "OpenBSD") {
        candidates = [{ name: "c", suffix: "" }];
      } else {
        candidates = [
          { name: "resolv.9", suffix: "" },
          { name: "resolv", suffix: ".2" },
          { name: "resolv", suffix: "" },
        ];
      }
      let tried = [];
      for (let candidate of candidates) {
        try {
          let name = ctypes.libraryName(candidate.name) + candidate.suffix;
          tried.push(name);
          return ctypes.open(name);
        } catch (ex) {
          lastException = ex;
        }
      }
      throw new Error(
        "Could not find libresolv in any of " +
          tried +
          " Exception: " +
          lastException +
          "\n"
      );
    }

    // Declaring functions to be able to call them.
    function declare(aSymbolNames, ...aArgs) {
      let lastException = null;
      if (!Array.isArray(aSymbolNames)) {
        aSymbolNames = [aSymbolNames];
      }

      for (let name of aSymbolNames) {
        try {
          return library.declare(name, ...aArgs);
        } catch (ex) {
          lastException = ex;
        }
      }
      library.close();
      throw new Error(
        "Failed to declare " +
          aSymbolNames +
          " Exception: " +
          lastException +
          "\n"
      );
    }

    let library = (this.library = findLibrary());
    this.res_search = declare(
      ["res_9_search", "res_search", "__res_search"],
      ctypes.default_abi,
      ctypes.int,
      ctypes.char.ptr,
      ctypes.int,
      ctypes.int,
      ctypes.unsigned_char.ptr,
      ctypes.int
    );
    this.res_query = declare(
      ["res_9_query", "res_query", "__res_query"],
      ctypes.default_abi,
      ctypes.int,
      ctypes.char.ptr,
      ctypes.int,
      ctypes.int,
      ctypes.unsigned_char.ptr,
      ctypes.int
    );
    this.dn_expand = declare(
      ["res_9_dn_expand", "dn_expand", "__dn_expand"],
      ctypes.default_abi,
      ctypes.int,
      ctypes.unsigned_char.ptr,
      ctypes.unsigned_char.ptr,
      ctypes.unsigned_char.ptr,
      ctypes.char.ptr,
      ctypes.int
    );
    this.dn_skipname = declare(
      ["res_9_dn_skipname", "dn_skipname", "__dn_skipname"],
      ctypes.default_abi,
      ctypes.int,
      ctypes.unsigned_char.ptr,
      ctypes.unsigned_char.ptr
    );
    this.ns_get16 = declare(
      ["res_9_ns_get16", "ns_get16", "_getshort"],
      ctypes.default_abi,
      ctypes.unsigned_int,
      ctypes.unsigned_char.ptr
    );
    this.ns_get32 = declare(
      ["res_9_ns_get32", "ns_get32", "_getlong"],
      ctypes.default_abi,
      ctypes.unsigned_long,
      ctypes.unsigned_char.ptr
    );

    this.QUERYBUF_SIZE = 1024;
    this.NS_MAXCDNAME = 255;
    this.NS_HFIXEDSZ = 12;
    this.NS_QFIXEDSZ = 4;
    this.NS_RRFIXEDSZ = 10;
    this.NS_C_IN = 1;
  },

  close() {
    this.library.close();
    this.library = null;
  },

  // Maps record to SRVRecord, TXTRecord, or MXRecord according to aTypeID and
  // returns it.
  _mapAnswer(aTypeID, aAnswer, aIdx, aLength) {
    if (aTypeID == NS_T_SRV) {
      let prio = this.ns_get16(aAnswer.addressOfElement(aIdx));
      let weight = this.ns_get16(aAnswer.addressOfElement(aIdx + 2));
      let port = this.ns_get16(aAnswer.addressOfElement(aIdx + 4));

      let hostbuf = ctypes.char.array(this.NS_MAXCDNAME)();
      let hostlen = this.dn_expand(
        aAnswer.addressOfElement(0),
        aAnswer.addressOfElement(aLength),
        aAnswer.addressOfElement(aIdx + 6),
        hostbuf,
        this.NS_MAXCDNAME
      );
      let host = hostlen > -1 ? hostbuf.readString() : null;
      return new SRVRecord(prio, weight, host, port);
    } else if (aTypeID == NS_T_TXT) {
      // TODO should only read dataLength characters.
      let data = ctypes.unsigned_char.ptr(aAnswer.addressOfElement(aIdx + 1));

      return new TXTRecord(data.readString());
    } else if (aTypeID == NS_T_MX) {
      let prio = this.ns_get16(aAnswer.addressOfElement(aIdx));

      let hostbuf = ctypes.char.array(this.NS_MAXCDNAME)();
      let hostlen = this.dn_expand(
        aAnswer.addressOfElement(0),
        aAnswer.addressOfElement(aLength),
        aAnswer.addressOfElement(aIdx + 2),
        hostbuf,
        this.NS_MAXCDNAME
      );
      let host = hostlen > -1 ? hostbuf.readString() : null;
      return new MXRecord(prio, host);
    }
    return {};
  },

  // Performs a DNS query for aTypeID on a certain address (aName) and returns
  // array of records of aTypeID.
  lookup(aName, aTypeID) {
    let qname = ctypes.char.array()(aName);
    let answer = ctypes.unsigned_char.array(this.QUERYBUF_SIZE)();
    let length = this.res_search(
      qname,
      this.NS_C_IN,
      aTypeID,
      answer,
      this.QUERYBUF_SIZE
    );

    // There is an error.
    if (length < 0) {
      return [];
    }

    let results = [];
    let idx = this.NS_HFIXEDSZ;

    let qdcount = this.ns_get16(answer.addressOfElement(4));
    let ancount = this.ns_get16(answer.addressOfElement(6));

    for (let qdidx = 0; qdidx < qdcount && idx < length; qdidx++) {
      idx +=
        this.NS_QFIXEDSZ +
        this.dn_skipname(
          answer.addressOfElement(idx),
          answer.addressOfElement(length)
        );
    }

    for (let anidx = 0; anidx < ancount && idx < length; anidx++) {
      idx += this.dn_skipname(
        answer.addressOfElement(idx),
        answer.addressOfElement(length)
      );
      let rridx = idx;
      let type = this.ns_get16(answer.addressOfElement(rridx));
      let dataLength = this.ns_get16(answer.addressOfElement(rridx + 8));

      idx += this.NS_RRFIXEDSZ;

      if (type === aTypeID) {
        let resource = this._mapAnswer(aTypeID, answer, idx, length);
        resource.type = type;
        resource.nsclass = this.ns_get16(answer.addressOfElement(rridx + 2));
        resource.ttl = this.ns_get32(answer.addressOfElement(rridx + 4)) | 0;
        results.push(resource);
      }
      idx += dataLength;
    }
    return results;
  },
};

// For Windows.
function load_dnsapi() {
  this._open();
}

load_dnsapi.prototype = {
  library: null,

  // Tries to find and load library.
  _open() {
    function declare(aSymbolName, ...aArgs) {
      try {
        return library.declare(aSymbolName, ...aArgs);
      } catch (ex) {
        throw new Error(
          "Failed to declare " + aSymbolName + " Exception: " + ex + "\n"
        );
      }
    }

    let library = (this.library = ctypes.open(ctypes.libraryName("DnsAPI")));

    this.DNS_SRV_DATA = ctypes.StructType("DNS_SRV_DATA", [
      { pNameTarget: ctypes.jschar.ptr },
      { wPriority: ctypes.unsigned_short },
      { wWeight: ctypes.unsigned_short },
      { wPort: ctypes.unsigned_short },
      { Pad: ctypes.unsigned_short },
    ]);

    this.DNS_TXT_DATA = ctypes.StructType("DNS_TXT_DATA", [
      { dwStringCount: ctypes.unsigned_long },
      { pStringArray: ctypes.jschar.ptr.array(1) },
    ]);

    this.DNS_MX_DATA = ctypes.StructType("DNS_MX_DATA", [
      { pNameTarget: ctypes.jschar.ptr },
      { wPriority: ctypes.unsigned_short },
      { Pad: ctypes.unsigned_short },
    ]);

    this.DNS_RECORD = ctypes.StructType("_DnsRecord");
    this.DNS_RECORD.define([
      { pNext: this.DNS_RECORD.ptr },
      { pName: ctypes.jschar.ptr },
      { wType: ctypes.unsigned_short },
      { wDataLength: ctypes.unsigned_short },
      { Flags: ctypes.unsigned_long },
      { dwTtl: ctypes.unsigned_long },
      { dwReserved: ctypes.unsigned_long },
      { Data: this.DNS_SRV_DATA }, // it's a union, can be cast to many things
    ]);

    this.PDNS_RECORD = ctypes.PointerType(this.DNS_RECORD);
    this.DnsQuery_W = declare(
      "DnsQuery_W",
      ctypes.winapi_abi,
      ctypes.long,
      ctypes.jschar.ptr,
      ctypes.unsigned_short,
      ctypes.unsigned_long,
      ctypes.voidptr_t,
      this.PDNS_RECORD.ptr,
      ctypes.voidptr_t.ptr
    );
    this.DnsRecordListFree = declare(
      "DnsRecordListFree",
      ctypes.winapi_abi,
      ctypes.void_t,
      this.PDNS_RECORD,
      ctypes.int
    );

    this.ERROR_SUCCESS = ctypes.Int64(0);
    this.DNS_QUERY_STANDARD = 0;
    this.DnsFreeRecordList = 1;
  },

  close() {
    this.library.close();
    this.library = null;
  },

  // Maps record to SRVRecord, TXTRecord, or MXRecord according to aTypeID and
  // returns it.
  _mapAnswer(aTypeID, aData) {
    if (aTypeID == NS_T_SRV) {
      let srvdata = ctypes.cast(aData, this.DNS_SRV_DATA);

      return new SRVRecord(
        srvdata.wPriority,
        srvdata.wWeight,
        srvdata.pNameTarget.readString(),
        srvdata.wPort
      );
    } else if (aTypeID == NS_T_TXT) {
      let txtdata = ctypes.cast(aData, this.DNS_TXT_DATA);
      if (txtdata.dwStringCount > 0) {
        return new TXTRecord(txtdata.pStringArray[0].readString());
      }
    } else if (aTypeID == NS_T_MX) {
      let mxdata = ctypes.cast(aData, this.DNS_MX_DATA);

      return new MXRecord(mxdata.wPriority, mxdata.pNameTarget.readString());
    }
    return {};
  },

  // Performs a DNS query for aTypeID on a certain address (aName) and returns
  // array of records of aTypeID (e.g. SRVRecord, TXTRecord, or MXRecord).
  lookup(aName, aTypeID) {
    let queryResultsSet = this.PDNS_RECORD();
    let qname = ctypes.jschar.array()(aName);
    let dnsStatus = this.DnsQuery_W(
      qname,
      aTypeID,
      this.DNS_QUERY_STANDARD,
      null,
      queryResultsSet.address(),
      null
    );

    // There is an error.
    if (ctypes.Int64.compare(dnsStatus, this.ERROR_SUCCESS) != 0) {
      return [];
    }

    let results = [];
    for (
      let presult = queryResultsSet;
      presult && !presult.isNull();
      presult = presult.contents.pNext
    ) {
      let result = presult.contents;
      if (result.wType == aTypeID) {
        let resource = this._mapAnswer(aTypeID, result.Data);
        resource.type = result.wType;
        resource.nsclass = 0;
        resource.ttl = result.dwTtl | 0;
        results.push(resource);
      }
    }

    this.DnsRecordListFree(queryResultsSet, this.DnsFreeRecordList);
    return results;
  },
};

// Used to make results of different libraries consistent for SRV queries.
function SRVRecord(aPrio, aWeight, aHost, aPort) {
  this.prio = aPrio;
  this.weight = aWeight;
  this.host = aHost;
  this.port = aPort;
}

// Used to make results of different libraries consistent for TXT queries.
function TXTRecord(aData) {
  this.data = aData;
}

// Used to make results of different libraries consistent for MX queries.
function MXRecord(aPrio, aHost) {
  this.prio = aPrio;
  this.host = aHost;
}

if (typeof Components === "undefined") {
  /* eslint-env worker */

  // We are in a worker, wait for our message then execute the wanted method.
  /* import-globals-from /toolkit/components/workerloader/require.js */
  importScripts("resource://gre/modules/workers/require.js");
  let PromiseWorker = require("resource://gre/modules/workers/PromiseWorker.js");

  let worker = new PromiseWorker.AbstractWorker();
  worker.dispatch = function (aMethod, aArgs = []) {
    return self[aMethod](...aArgs);
  };
  worker.postMessage = function (...aArgs) {
    self.postMessage(...aArgs);
  };
  worker.close = function () {
    self.close();
  };
  self.addEventListener("message", msg => worker.handleMessage(msg));

  // eslint-disable-next-line no-unused-vars
  function execute(aOS, aMethod, aArgs) {
    let DNS = aOS == "WINNT" ? new load_dnsapi() : new load_libresolv(aOS);
    return DNS[aMethod].apply(DNS, aArgs);
  }
} else {
  // We are loaded as a JSM, provide the async front that will start the
  // worker.
  var dns_async_front = {
    /**
     * Constants for use with the lookup function.
     */
    TXT: NS_T_TXT,
    SRV: NS_T_SRV,
    MX: NS_T_MX,

    /**
     * Do an asynchronous DNS lookup. The returned promise resolves with
     * one of the Answer objects as defined above, or rejects with the
     * error from the worker.
     *
     * Example: DNS.lookup("_caldavs._tcp.example.com", DNS.SRV)
     *
     * @param aName           The aName to look up.
     * @param aTypeID         The RR type to look up as a constant.
     * @returns A promise resolved when completed.
     */
    lookup(aName, aTypeID) {
      let worker = new BasePromiseWorker(LOCATION);
      return worker.post("execute", [
        Services.appinfo.OS,
        "lookup",
        [...arguments],
      ]);
    },

    /** Convenience functions */
    srv(aName) {
      return this.lookup(aName, NS_T_SRV);
    },
    txt(aName) {
      return this.lookup(aName, NS_T_TXT);
    },
    mx(aName) {
      return this.lookup(aName, NS_T_MX);
    },
  };
  DNS = dns_async_front;
}