2 * Copyright (c) 2014-2015 Sylvain Peyrefitte
4 * This file is part of node-rdpjs.
6 * node-rdpjs is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20var type = require('../core').type;
21var log = require('../core').log;
22var error = require('../core').error;
25 * Parse tag(T) field of BER TLV
26 * And check with expected tag
27 * @param s {type.Stream}
28 * @param tag {spec.tag}
29 * @returns {Boolean} True for valid tag matching
31function decodeTag(s, tag) {
32 var nextTag = new type.UInt8().read(s).value;
33 if (tag.tagNumber > 30) {
34 nextTagNumber = new type.UInt8().read(s).value;
37 nextTagNumber = nextTag & 0x1F;
40 return ((nextTag & 0xE0) === (tag.tagClass | tag.tagFormat)) && (nextTagNumber === tag.tagNumber);
44 * Parse length(L) field of BER TLV
45 * @param s {type.Stream}
48function decodeLength(s) {
49 var size = new type.UInt8().read(s).value;
53 size = new type.UInt8().read(s).value;
56 size = new type.UInt16Be().read(s).value;
59 throw new error.ProtocolError('NODE_RDP_ASN1_BER_INVALID_LENGTH');
66 * Decode tuple TLV (Tag Length Value) of BER
67 * @param s {type.Stream}
68 * @param tag {spec.Asn1Tag} expected tag
69 * @returns {type.BinaryString} Value of tuple
71function decode(s, tag) {
72 if (!decodeTag(s, tag)) {
73 throw new error.ProtocolError('NODE_RDP_ASN1_BER_INVALID_TAG');
75 var length = decodeLength(s);
78 return new type.Stream(0);
80 return new type.BinaryString(null,{ readLength : new type.CallableValue(length) }).read(s);
83function encodeTag(tag) {
84 if(tag.tagNumber > 30) {
85 return new type.Component([new type.UInt8(tag.tagClass | tag.tagFormat | 0x1F), new type.UInt8(tag.tagNumber)]);
88 return new type.UInt8((tag.tagClass | tag.tagFormat) | (tag.tagNumber & 0x1F));
92function encodeLength(length) {
94 return new type.Component([new type.UInt8(0x82), new type.UInt16Be(length)]);
97 return new type.UInt8(length);
101function encode(tag, buffer) {
102 return new type.Component([encodeTag(tag), encodeLength(buffer.size()), buffer]);