writer.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
  2. var assert = require('assert');
  3. var ASN1 = require('./types');
  4. var errors = require('./errors');
  5. ///--- Globals
  6. var newInvalidAsn1Error = errors.newInvalidAsn1Error;
  7. var DEFAULT_OPTS = {
  8. size: 1024,
  9. growthFactor: 8
  10. };
  11. ///--- Helpers
  12. function merge(from, to) {
  13. assert.ok(from);
  14. assert.equal(typeof(from), 'object');
  15. assert.ok(to);
  16. assert.equal(typeof(to), 'object');
  17. var keys = Object.getOwnPropertyNames(from);
  18. keys.forEach(function(key) {
  19. if (to[key])
  20. return;
  21. var value = Object.getOwnPropertyDescriptor(from, key);
  22. Object.defineProperty(to, key, value);
  23. });
  24. return to;
  25. }
  26. ///--- API
  27. function Writer(options) {
  28. options = merge(DEFAULT_OPTS, options || {});
  29. this._buf = new Buffer(options.size || 1024);
  30. this._size = this._buf.length;
  31. this._offset = 0;
  32. this._options = options;
  33. // A list of offsets in the buffer where we need to insert
  34. // sequence tag/len pairs.
  35. this._seq = [];
  36. var self = this;
  37. this.__defineGetter__('buffer', function() {
  38. if (self._seq.length)
  39. throw new InvalidAsn1Error(self._seq.length + ' unended sequence(s)');
  40. return self._buf.slice(0, self._offset);
  41. });
  42. }
  43. Writer.prototype.writeByte = function(b) {
  44. if (typeof(b) !== 'number')
  45. throw new TypeError('argument must be a Number');
  46. this._ensure(1);
  47. this._buf[this._offset++] = b;
  48. };
  49. Writer.prototype.writeInt = function(i, tag) {
  50. if (typeof(i) !== 'number')
  51. throw new TypeError('argument must be a Number');
  52. if (typeof(tag) !== 'number')
  53. tag = ASN1.Integer;
  54. var sz = 4;
  55. while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000)) &&
  56. (sz > 1)) {
  57. sz--;
  58. i <<= 8;
  59. }
  60. if (sz > 4)
  61. throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff');
  62. this._ensure(2 + sz);
  63. this._buf[this._offset++] = tag;
  64. this._buf[this._offset++] = sz;
  65. while (sz-- > 0) {
  66. this._buf[this._offset++] = ((i & 0xff000000) >> 24);
  67. i <<= 8;
  68. }
  69. };
  70. Writer.prototype.writeNull = function() {
  71. this.writeByte(ASN1.Null);
  72. this.writeByte(0x00);
  73. };
  74. Writer.prototype.writeEnumeration = function(i, tag) {
  75. if (typeof(i) !== 'number')
  76. throw new TypeError('argument must be a Number');
  77. if (typeof(tag) !== 'number')
  78. tag = ASN1.Enumeration;
  79. return this.writeInt(i, tag);
  80. };
  81. Writer.prototype.writeBoolean = function(b, tag) {
  82. if (typeof(b) !== 'boolean')
  83. throw new TypeError('argument must be a Boolean');
  84. if (typeof(tag) !== 'number')
  85. tag = ASN1.Boolean;
  86. this._ensure(3);
  87. this._buf[this._offset++] = tag;
  88. this._buf[this._offset++] = 0x01;
  89. this._buf[this._offset++] = b ? 0xff : 0x00;
  90. };
  91. Writer.prototype.writeString = function(s, tag) {
  92. if (typeof(s) !== 'string')
  93. throw new TypeError('argument must be a string (was: ' + typeof(s) + ')');
  94. if (typeof(tag) !== 'number')
  95. tag = ASN1.OctetString;
  96. var len = Buffer.byteLength(s);
  97. this.writeByte(tag);
  98. this.writeLength(len);
  99. if (len) {
  100. this._ensure(len);
  101. this._buf.write(s, this._offset);
  102. this._offset += len;
  103. }
  104. };
  105. Writer.prototype.writeBuffer = function(buf, tag) {
  106. if (typeof(tag) !== 'number')
  107. throw new TypeError('tag must be a number');
  108. if (!Buffer.isBuffer(buf))
  109. throw new TypeError('argument must be a buffer');
  110. this.writeByte(tag);
  111. this.writeLength(buf.length);
  112. this._ensure(buf.length);
  113. buf.copy(this._buf, this._offset, 0, buf.length);
  114. this._offset += buf.length;
  115. };
  116. Writer.prototype.writeStringArray = function(strings) {
  117. if ((!strings instanceof Array))
  118. throw new TypeError('argument must be an Array[String]');
  119. var self = this;
  120. strings.forEach(function(s) {
  121. self.writeString(s);
  122. });
  123. };
  124. // This is really to solve DER cases, but whatever for now
  125. Writer.prototype.writeOID = function(s, tag) {
  126. if (typeof(s) !== 'string')
  127. throw new TypeError('argument must be a string');
  128. if (typeof(tag) !== 'number')
  129. tag = ASN1.OID;
  130. if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
  131. throw new Error('argument is not a valid OID string');
  132. function encodeOctet(bytes, octet) {
  133. if (octet < 128) {
  134. bytes.push(octet);
  135. } else if (octet < 16384) {
  136. bytes.push((octet >>> 7) | 0x80);
  137. bytes.push(octet & 0x7F);
  138. } else if (octet < 2097152) {
  139. bytes.push((octet >>> 14) | 0x80);
  140. bytes.push(((octet >>> 7) | 0x80) & 0xFF);
  141. bytes.push(octet & 0x7F);
  142. } else if (octet < 268435456) {
  143. bytes.push((octet >>> 21) | 0x80);
  144. bytes.push(((octet >>> 14) | 0x80) & 0xFF);
  145. bytes.push(((octet >>> 7) | 0x80) & 0xFF);
  146. bytes.push(octet & 0x7F);
  147. } else {
  148. bytes.push(((octet >>> 28) | 0x80) & 0xFF);
  149. bytes.push(((octet >>> 21) | 0x80) & 0xFF);
  150. bytes.push(((octet >>> 14) | 0x80) & 0xFF);
  151. bytes.push(((octet >>> 7) | 0x80) & 0xFF);
  152. bytes.push(octet & 0x7F);
  153. }
  154. }
  155. var tmp = s.split('.');
  156. var bytes = [];
  157. bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
  158. tmp.slice(2).forEach(function(b) {
  159. encodeOctet(bytes, parseInt(b, 10));
  160. });
  161. var self = this;
  162. this._ensure(2 + bytes.length);
  163. this.writeByte(tag);
  164. this.writeLength(bytes.length);
  165. bytes.forEach(function(b) {
  166. self.writeByte(b);
  167. });
  168. };
  169. Writer.prototype.writeLength = function(len) {
  170. if (typeof(len) !== 'number')
  171. throw new TypeError('argument must be a Number');
  172. this._ensure(4);
  173. if (len <= 0x7f) {
  174. this._buf[this._offset++] = len;
  175. } else if (len <= 0xff) {
  176. this._buf[this._offset++] = 0x81;
  177. this._buf[this._offset++] = len;
  178. } else if (len <= 0xffff) {
  179. this._buf[this._offset++] = 0x82;
  180. this._buf[this._offset++] = len >> 8;
  181. this._buf[this._offset++] = len;
  182. } else if (len <= 0xffffff) {
  183. this._shift(start, len, 1);
  184. this._buf[this._offset++] = 0x83;
  185. this._buf[this._offset++] = len >> 16;
  186. this._buf[this._offset++] = len >> 8;
  187. this._buf[this._offset++] = len;
  188. } else {
  189. throw new InvalidAsn1ERror('Length too long (> 4 bytes)');
  190. }
  191. };
  192. Writer.prototype.startSequence = function(tag) {
  193. if (typeof(tag) !== 'number')
  194. tag = ASN1.Sequence | ASN1.Constructor;
  195. this.writeByte(tag);
  196. this._seq.push(this._offset);
  197. this._ensure(3);
  198. this._offset += 3;
  199. };
  200. Writer.prototype.endSequence = function() {
  201. var seq = this._seq.pop();
  202. var start = seq + 3;
  203. var len = this._offset - start;
  204. if (len <= 0x7f) {
  205. this._shift(start, len, -2);
  206. this._buf[seq] = len;
  207. } else if (len <= 0xff) {
  208. this._shift(start, len, -1);
  209. this._buf[seq] = 0x81;
  210. this._buf[seq + 1] = len;
  211. } else if (len <= 0xffff) {
  212. this._buf[seq] = 0x82;
  213. this._buf[seq + 1] = len >> 8;
  214. this._buf[seq + 2] = len;
  215. } else if (len <= 0xffffff) {
  216. this._shift(start, len, 1);
  217. this._buf[seq] = 0x83;
  218. this._buf[seq + 1] = len >> 16;
  219. this._buf[seq + 2] = len >> 8;
  220. this._buf[seq + 3] = len;
  221. } else {
  222. throw new InvalidAsn1Error('Sequence too long');
  223. }
  224. };
  225. Writer.prototype._shift = function(start, len, shift) {
  226. assert.ok(start !== undefined);
  227. assert.ok(len !== undefined);
  228. assert.ok(shift);
  229. this._buf.copy(this._buf, start + shift, start, start + len);
  230. this._offset += shift;
  231. };
  232. Writer.prototype._ensure = function(len) {
  233. assert.ok(len);
  234. if (this._size - this._offset < len) {
  235. var sz = this._size * this._options.growthFactor;
  236. if (sz - this._offset < len)
  237. sz += len;
  238. var buf = new Buffer(sz);
  239. this._buf.copy(buf, 0, 0, this._offset);
  240. this._buf = buf;
  241. this._size = sz;
  242. }
  243. };
  244. ///--- Exported API
  245. module.exports = Writer;