dns-packet-typescript
Version:
An abstract-encoding compliant module for encoding / decoding DNS packets
89 lines • 3.12 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodingLength = exports.decode = exports.encode = void 0;
var types = require("./types");
var classes = require("./classes");
var name = require("./name");
var ropt = require("./ropt");
var index_1 = require("./index");
var renc_1 = require("./renc");
function encode(a, buf, offset) {
if (offset === void 0) { offset = 0; }
if (!buf) {
buf = Buffer.allocUnsafe(encodingLength(a));
}
if (!offset) {
offset = 0;
}
var oldOffset = offset;
name.encode(a.name, buf, offset);
offset += name.encode.bytes;
buf.writeUInt16BE(types.toType(a.type), offset);
if (a.type.toUpperCase() === 'OPT') {
if (a.name !== '.') {
throw new Error('OPT name must be root.');
}
buf.writeUInt16BE(a.udpPayloadSize || 4096, offset + 2);
buf.writeUInt8(a.extendedRcode || 0, offset + 4);
buf.writeUInt8(a.ednsVersion || 0, offset + 5);
buf.writeUInt16BE(a.flags || 0, offset + 6);
offset += 8;
ropt.encode(a.options || [], buf, offset);
offset += ropt.encode.bytes;
}
else {
var klass = classes.toClass(a.class === undefined ? 'IN' : a.class);
if (a.flush) {
klass |= index_1.FLUSH_MASK;
} // the 1st bit of the class is the flush bit
buf.writeUInt16BE(klass, offset + 2);
buf.writeUInt32BE(a.ttl || 0, offset + 4);
offset += 8;
var enc = renc_1.renc(a.type);
enc.encode(a.data, buf, offset);
offset += enc.encode.bytes;
}
encode.bytes = offset - oldOffset;
return buf;
}
exports.encode = encode;
encode.bytes = 0;
function decode(buf, offset) {
if (offset === void 0) { offset = 0; }
if (!offset) {
offset = 0;
}
var a = {};
var oldOffset = offset;
a.name = name.decode(buf, offset);
offset += name.decode.bytes;
a.type = types.toString(buf.readUInt16BE(offset));
if (a.type === 'OPT') {
a.udpPayloadSize = buf.readUInt16BE(offset + 2);
a.extendedRcode = buf.readUInt8(offset + 4);
a.ednsVersion = buf.readUInt8(offset + 5);
a.flags = buf.readUInt16BE(offset + 6);
a.flag_do = ((a.flags >> 15) & 0x1) === 1;
a.options = ropt.decode(buf, offset + 8);
offset += 8 + ropt.decode.bytes;
}
else {
var klass = buf.readUInt16BE(offset + 2);
a.ttl = buf.readUInt32BE(offset + 4);
a.class = classes.toString(klass & index_1.NOT_FLUSH_MASK);
a.flush = !!(klass & index_1.FLUSH_MASK);
var enc = renc_1.renc(a.type);
a.data = enc.decode(buf, offset + 8);
offset += 8 + enc.decode.bytes;
}
decode.bytes = offset - oldOffset;
return a;
}
exports.decode = decode;
decode.bytes = 0;
function encodingLength(a) {
var data = (a.data !== null && a.data !== undefined) ? a.data : a.options;
return name.encodingLength(a.name) + 8 + (renc_1.renc(a.type).encodingLength(data));
}
exports.encodingLength = encodingLength;
//# sourceMappingURL=answer.js.map
;