1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | "use strict";
|
24 |
|
25 | var EventEmitter = require('events').EventEmitter,
|
26 | PendingRequests = require('./pending'),
|
27 | net = require('net'),
|
28 | util = require('util');
|
29 |
|
30 | var Request = function (opts) {
|
31 | this.question = opts.question;
|
32 | this.server = opts.server;
|
33 |
|
34 | if (typeof(this.server) === 'string' || this.server instanceof String)
|
35 | this.server = { address: this.server, port: 53, type: 'udp'};
|
36 |
|
37 | if (!this.server || !this.server.address || !net.isIP(this.server.address))
|
38 | throw new Error("Server object must be supplied with at least address");
|
39 |
|
40 | if (!this.server.type || ['udp', 'tcp'].indexOf(this.server.type))
|
41 | this.server.type = 'udp';
|
42 |
|
43 | if (!this.server.port)
|
44 | this.server.port = 53;
|
45 |
|
46 | this.timeout = opts.timeout || 4 * 1000;
|
47 | this.try_edns = opts.try_edns || false;
|
48 |
|
49 | this.fired = false;
|
50 | this.id = undefined;
|
51 | };
|
52 | util.inherits(Request, EventEmitter);
|
53 |
|
54 | Request.prototype.handle = function (err, answer) {
|
55 | if (!this.fired) {
|
56 | this.emit('message', err, answer);
|
57 | this.done();
|
58 | }
|
59 | };
|
60 |
|
61 | Request.prototype.done = function () {
|
62 | this.fired = true;
|
63 | clearTimeout(this.timer_);
|
64 | PendingRequests.remove(this);
|
65 | this.emit('end');
|
66 | this.id = undefined;
|
67 | };
|
68 |
|
69 | Request.prototype.handleTimeout = function () {
|
70 | if (!this.fired) {
|
71 | this.emit('timeout');
|
72 | this.done();
|
73 | }
|
74 | };
|
75 |
|
76 | Request.prototype.send = function () {
|
77 | var self = this;
|
78 |
|
79 | this.timer_ = setTimeout(function () {
|
80 | self.handleTimeout();
|
81 | }, this.timeout);
|
82 |
|
83 | PendingRequests.send(this);
|
84 | };
|
85 |
|
86 | Request.prototype.cancel = function () {
|
87 | this.emit('cancelled');
|
88 | this.done();
|
89 | };
|
90 |
|
91 | module.exports = function (opts) {
|
92 | return new Request(opts);
|
93 | };
|