├── .eslintrc ├── .gitignore ├── LICENSE ├── README.md ├── circle.yml ├── index.js ├── lib ├── attributes.js ├── attributes │ ├── address.js │ ├── alternate-server.js │ ├── error-code.js │ ├── mapped-address.js │ ├── message-integrity.js │ ├── nonce.js │ ├── padding.js │ ├── realm.js │ ├── software.js │ ├── unknown-attributes.js │ ├── username.js │ └── xor-mapped-address.js ├── packet.js ├── stun_client.js ├── stun_comm.js ├── transports │ ├── abstract.js │ ├── index.js │ ├── tcp.js │ └── udp.js └── utils.js ├── package.json └── test ├── attributes.unit.js ├── packet.unit.js └── stun_client.unit.js /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb-base" 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | test/all*.sh 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Nico Janssens 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CircleCI](https://circleci.com/gh/MicroMinion/stun-js.svg?style=shield)](https://circleci.com/gh/MicroMinion/stun-js) 2 | [![npm](https://img.shields.io/npm/v/stun-js.svg)](https://npmjs.org/package/stun-js) 3 | 4 | # stun-js 5 | STUN (Session Traversal Utilities for NAT) library written entirely in JavaScript 6 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | machine: 2 | node: 3 | version: 6.9.0 4 | test: 5 | override: 6 | - npm run test-node 7 | - npm run build 8 | deployment: 9 | npm: 10 | branch: master 11 | commands: 12 | - echo -e "$NPM_USER\n$NPM_PASS\n$NPM_EMAIL" | npm login 13 | - npm run 2npm 14 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const Attributes = require('./lib/attributes'); 2 | const Packet = require('./lib/packet'); 3 | const StunClient = require('./lib/stun_client'); 4 | 5 | const address = require('./lib/attributes/address'); 6 | const padding = require('./lib/attributes/padding'); 7 | const transports = require('./lib/transports'); 8 | 9 | module.exports = function createClient (address, port, transport) { 10 | return new StunClient(address, port, transport) 11 | } 12 | 13 | // STUN components 14 | module.exports.Attributes = Attributes 15 | module.exports.Packet = Packet 16 | module.exports.StunClient = StunClient 17 | 18 | // STUN utils 19 | module.exports.address = address 20 | module.exports.padding = padding 21 | module.exports.transports = transports 22 | -------------------------------------------------------------------------------- /lib/attributes.js: -------------------------------------------------------------------------------- 1 | const winston = require('winston-debug'); 2 | const winstonWrapper = require('winston-meta-wrapper'); 3 | 4 | const log = winstonWrapper(winston); 5 | log.addMeta({ 6 | module: 'stun:attributes', 7 | }); 8 | 9 | // Attributes Class 10 | class Attributes { 11 | constructor() { 12 | // init 13 | this.attrs = []; 14 | // logging 15 | this.log = winstonWrapper(winston); 16 | this.log.addMeta({ 17 | module: 'stun:attributes', 18 | }); 19 | } 20 | 21 | // Attributes.TYPES[Attributes.FINGERPRINT] = 'FINGERPRINT' 22 | 23 | add(attr) { 24 | if (typeof attr.encode !== 'function') { 25 | throw new Error(`attribute ${attr} does not contain required encoding function`); 26 | } 27 | this.attrs.push(attr); 28 | } 29 | 30 | get(type) { 31 | return this.attrs.find(attr => attr.type === type); 32 | } 33 | 34 | encode(magic, tid) { 35 | const attrBytesArray = []; 36 | this.attrs.forEach((attr) => { 37 | // magic & tid must be passed to create xor encoded addresses 38 | if (attr.encode.length === 2) { 39 | attrBytesArray.push(attr.encode(magic, tid)); 40 | return; 41 | } 42 | // message integrity attr requires special treatment -- see packet.encode() 43 | if (attr.type === Attributes.MESSAGE_INTEGRITY) { 44 | return; 45 | } 46 | // all other attributes can be encoded without further ado 47 | attrBytesArray.push(attr.encode()); 48 | }); 49 | return Buffer.concat(attrBytesArray); 50 | } 51 | } 52 | 53 | // RFC 5389 (STUN) attributes 54 | Attributes.AlternateServer = require('./attributes/alternate-server'); 55 | Attributes.ErrorCode = require('./attributes/error-code'); 56 | Attributes.MappedAddress = require('./attributes/mapped-address'); 57 | Attributes.MessageIntegrity = require('./attributes/message-integrity'); 58 | Attributes.Nonce = require('./attributes/nonce'); 59 | Attributes.Realm = require('./attributes/realm'); 60 | Attributes.Software = require('./attributes/software'); 61 | Attributes.UnknownAttributes = require('./attributes/unknown-attributes'); 62 | Attributes.Username = require('./attributes/username'); 63 | Attributes.XORMappedAddress = require('./attributes/xor-mapped-address'); 64 | 65 | // RFC 5389 (STUN) attributes 66 | Attributes.MAPPED_ADDRESS = 0x0001; 67 | Attributes.USERNAME = 0x0006; 68 | Attributes.MESSAGE_INTEGRITY = 0x0008; 69 | Attributes.ERROR_CODE = 0x0009; 70 | Attributes.UNKNOWN_ATTRIBUTES = 0x000A; 71 | Attributes.REALM = 0x0014; 72 | Attributes.NONCE = 0x0015; 73 | Attributes.XOR_MAPPED_ADDRESS = 0x0020; 74 | Attributes.SOFTWARE = 0x8022; 75 | Attributes.ALTERNATE_SERVER = 0x8023; 76 | // Attributes.FINGERPRINT = 0x8028 77 | 78 | Attributes.TYPES = {}; 79 | // RFC 5389 (STUN) 80 | Attributes.TYPES[Attributes.MAPPED_ADDRESS] = Attributes.MappedAddress; 81 | Attributes.TYPES[Attributes.USERNAME] = Attributes.Username; 82 | Attributes.TYPES[Attributes.MESSAGE_INTEGRITY] = Attributes.MessageIntegrity; 83 | Attributes.TYPES[Attributes.ERROR_CODE] = Attributes.ErrorCode; 84 | Attributes.TYPES[Attributes.UNKNOWN_ATTRIBUTES] = Attributes.UnknownAttributes; 85 | Attributes.TYPES[Attributes.REALM] = Attributes.Realm; 86 | Attributes.TYPES[Attributes.NONCE] = Attributes.Nonce; 87 | Attributes.TYPES[Attributes.XOR_MAPPED_ADDRESS] = Attributes.XORMappedAddress; 88 | Attributes.TYPES[Attributes.SOFTWARE] = Attributes.Software; 89 | Attributes.TYPES[Attributes.ALTERNATE_SERVER] = Attributes.AlternateServer; 90 | 91 | Attributes.decode = (attrsBuffer, headerBuffer) => { 92 | let offset = 0; 93 | const attrs = new Attributes(); 94 | 95 | while (offset < attrsBuffer.length) { 96 | const type = attrsBuffer.readUInt16BE(offset); 97 | offset += 2; 98 | 99 | const length = attrsBuffer.readUInt16BE(offset); 100 | const blockOut = length % 4; 101 | const padding = blockOut > 0 ? 4 - blockOut : 0; 102 | offset += 2; 103 | 104 | const attrBytes = attrsBuffer.slice(offset, offset + length); 105 | offset += length + padding; 106 | const decoder = Attributes.TYPES[type]; 107 | if (decoder) { 108 | const attr = decoder.decode(attrBytes, headerBuffer); 109 | attrs.add(attr); 110 | } else { 111 | log.debug(`don't know how to process attribute ${type.toString(16)}. Ignoring ...`); 112 | } 113 | } 114 | 115 | return attrs; 116 | }; 117 | 118 | module.exports = Attributes; 119 | -------------------------------------------------------------------------------- /lib/attributes/address.js: -------------------------------------------------------------------------------- 1 | const ip = require('ip'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | const log = winstonWrapper(winston); 6 | log.addMeta({ 7 | module: 'stun:attributes', 8 | }); 9 | 10 | const IPv4 = 0x01; 11 | const IPv6 = 0x02; 12 | 13 | const xor = (a, b) => { 14 | const data = []; 15 | let aCopy = a.slice(0); 16 | let bCopy = b.slice(0); 17 | 18 | if (bCopy.length > aCopy.length) { 19 | const tmp = aCopy; 20 | aCopy = bCopy; 21 | bCopy = tmp; 22 | } 23 | 24 | for (let i = 0, len = aCopy.length; i < len; i += 1) { 25 | data.push(aCopy[i] ^ bCopy[i]); // eslint-disable-line no-bitwise 26 | } 27 | 28 | return Buffer.from(data); 29 | }; 30 | 31 | const encode = (address, port) => { 32 | // checks 33 | if (address === undefined || port === undefined) { 34 | const attrError = 'invalid address attribute'; 35 | log.error(attrError); 36 | throw new Error(attrError); 37 | } 38 | if (!ip.isV4Format(address) && !ip.isV6Format(address)) { 39 | const hostError = 'invalid address host'; 40 | log.error(hostError); 41 | throw new Error(hostError); 42 | } 43 | if (port < 0 || port > 65536) { 44 | const portError = 'invalid address port'; 45 | log.error(portError); 46 | throw new Error(portError); 47 | } 48 | // create family type 49 | const familyByte = Buffer.alloc(1); 50 | if (ip.isV4Format(address)) { 51 | familyByte.writeUInt8(IPv4); 52 | } else { 53 | familyByte.writeUInt8(IPv6); 54 | } 55 | // create address bytes 56 | const addressBytes = ip.toBuffer(address); 57 | // create null byte 58 | const nullByte = Buffer.alloc(1); 59 | nullByte.writeUInt8(0, 0); 60 | // create port bytes 61 | const portBytes = Buffer.alloc(2); 62 | portBytes.writeUInt16BE(port, 0); 63 | // concat 64 | return Buffer.concat([nullByte, familyByte, portBytes, addressBytes]); 65 | }; 66 | 67 | const encodeXor = (address, port, magic, tid) => { 68 | // checks 69 | if (address === undefined || port === undefined) { 70 | const attrError = 'invalid address attribute'; 71 | log.error(attrError); 72 | throw new Error(attrError); 73 | } 74 | if (!ip.isV4Format(address) && !ip.isV6Format(address)) { 75 | const hostError = 'invalid address host'; 76 | log.error(hostError); 77 | throw new Error(hostError); 78 | } 79 | if (port < 0 || port > 65536) { 80 | const portError = 'invalid address port'; 81 | log.error(portError); 82 | throw new Error(portError); 83 | } 84 | if (magic === undefined || tid === undefined) { 85 | const keyError = 'invalid xor keys'; 86 | log.error(keyError); 87 | throw new Error(keyError); 88 | } 89 | // magic and tid bytes -- needed for xor mapping 90 | const magicBytes = Buffer.alloc(4); 91 | magicBytes.writeUInt32BE(magic); 92 | const tidBytes = Buffer.alloc(12); 93 | tidBytes.writeUInt32BE(0); 94 | tidBytes.writeUInt32BE(0, 4); 95 | tidBytes.writeUInt32BE(tid, 8); 96 | // create family type 97 | const familyByte = Buffer.alloc(1); 98 | if (ip.isV4Format(address)) { 99 | familyByte.writeUInt8(IPv4); 100 | } else { 101 | familyByte.writeUInt8(IPv6); 102 | } 103 | // create xaddress bytes 104 | const addressBytes = ip.toBuffer(address); 105 | const xaddressBytes = xor(addressBytes, ip.isV4Format(address) ? 106 | magicBytes : Buffer.concat([magicBytes, tidBytes])); 107 | // create null byte 108 | const nullByte = Buffer.alloc(1); 109 | nullByte.writeUInt8(0, 0); 110 | // create xport bytes 111 | const portBytes = Buffer.alloc(2); 112 | portBytes.writeUInt16BE(port, 0); 113 | const xportBytes = xor(portBytes, magicBytes.slice(0, 2)); 114 | // concat 115 | return Buffer.concat([nullByte, familyByte, xportBytes, xaddressBytes]); 116 | }; 117 | 118 | const decode = (bytes) => { 119 | const family = (bytes.readUInt8(1) === IPv4) ? 4 : 6; 120 | const portBytes = bytes.slice(2, 4); // LE 121 | const addressBytes = bytes.slice(4, family === 4 ? 8 : 20); // LE 122 | const result = { 123 | family, 124 | port: portBytes.readUInt16BE(0), 125 | address: ip.toString(addressBytes, 0, family), 126 | }; 127 | return result; 128 | }; 129 | 130 | const decodeXor = (bytes, magicBytes, tidBytes) => { 131 | const family = (bytes.readUInt8(1) === IPv4) ? 4 : 6; 132 | const xportBytes = bytes.slice(2, 4); // LE 133 | const portBytes = xor(xportBytes, magicBytes.slice(0, 2)); 134 | const xaddressBytes = bytes.slice(4, family === 4 ? 8 : 20); // LE 135 | const addressBytes = xor(xaddressBytes, family === 4 ? 136 | magicBytes : Buffer.concat([magicBytes, tidBytes])); 137 | const result = { 138 | family, 139 | port: portBytes.readUInt16BE(0), 140 | address: ip.toString(addressBytes, 0, family), 141 | }; 142 | return result; 143 | }; 144 | 145 | exports.encode = encode; 146 | exports.encodeXor = encodeXor; 147 | exports.decode = decode; 148 | exports.decodeXor = decodeXor; 149 | -------------------------------------------------------------------------------- /lib/attributes/alternate-server.js: -------------------------------------------------------------------------------- 1 | const addressAttr = require('./address'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class AlternateServerAttr { 6 | constructor(address, port) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify address and port 13 | if (port === undefined || address === undefined) { 14 | const errorMsg = 'invalid alternate server attribute'; 15 | this.log.error(errorMsg); 16 | throw new Error(errorMsg); 17 | } 18 | // init 19 | this.address = address; 20 | this.port = port; 21 | this.type = 0x8023; 22 | // done 23 | this.log.debug(`alternate server attr: address = ${this.address}, port = ${this.port}`); 24 | } 25 | 26 | encode() { 27 | // type 28 | const typeBytes = Buffer.alloc(2); 29 | typeBytes.writeUInt16BE(this.type, 0); 30 | // value 31 | const valueBytes = addressAttr.encode(this.address, this.port); 32 | // length 33 | const lengthBytes = Buffer.alloc(2); 34 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 35 | // combination 36 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes]); 37 | // done 38 | return result; 39 | } 40 | } 41 | 42 | AlternateServerAttr.decode = (attrBytes) => { 43 | const result = addressAttr.decode(attrBytes); 44 | return new AlternateServerAttr(result.address, result.port); 45 | }; 46 | 47 | module.exports = AlternateServerAttr; 48 | -------------------------------------------------------------------------------- /lib/attributes/error-code.js: -------------------------------------------------------------------------------- 1 | const padding = require('./padding'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class ErrorCodeAttr { 6 | constructor(code, reason) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify error code 13 | if (code === undefined) { 14 | const undefinedCodeError = 'invalid error code attribute'; 15 | this.log.error(undefinedCodeError); 16 | throw new Error(undefinedCodeError); 17 | } 18 | if (code < 300 || code >= 700) { 19 | const invalidCodeError = 'invalid error code'; 20 | this.log.error(invalidCodeError); 21 | return new Error(invalidCodeError); 22 | } 23 | // verify reason 24 | reason = reason || ErrorCodeAttr.REASON[code]; 25 | if (reason.length >= 128) { 26 | const invalidReasonError = 'invalid error reason'; 27 | this.log.error(invalidReasonError); 28 | return new Error(invalidReasonError); 29 | } 30 | // init 31 | this.code = code; 32 | this.reason = reason; 33 | this.type = 0x0009; 34 | // done 35 | this.log.debug(`error code attr: code = ${this.code}, reason = ${this.reason}`); 36 | } 37 | 38 | encode() { 39 | // type 40 | const typeBytes = Buffer.alloc(2); 41 | typeBytes.writeUInt16BE(this.type, 0); 42 | // value 43 | const valueBytes = Buffer.alloc(4 + this.reason.length); 44 | valueBytes.writeUInt16BE(0, 0); 45 | valueBytes.writeUInt8(this.code / 100 | 0, 2); 46 | valueBytes.writeUInt8(this.code % 100, 3); 47 | valueBytes.write(this.reason, 4); 48 | // length 49 | const lengthBytes = Buffer.alloc(2); 50 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 51 | // padding 52 | const paddingBytes = padding.getBytes(valueBytes.length); 53 | // combination 54 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes, paddingBytes]); 55 | // done 56 | return result; 57 | } 58 | } 59 | 60 | // error codes 61 | ErrorCodeAttr.REASON = { 62 | 300: 'Try Alternate', 63 | 400: 'Bad Request', 64 | 401: 'Unauthorized', 65 | 403: 'Forbidden', 66 | 420: 'Unknown Attribute', 67 | 437: 'Allocation Mismatch', 68 | 438: 'Stale Nonce', 69 | 441: 'Wrong Credentials', 70 | 442: 'Unsupported Transport Protocol', 71 | 486: 'Allocation Quota Reached', 72 | 500: 'Server Error', 73 | 508: 'Insufficient Capacity', 74 | }; 75 | 76 | ErrorCodeAttr.decode = (attrBytes) => { 77 | const code = (attrBytes.readUInt8(2) * 100) + (attrBytes.readUInt8(3) % 100); 78 | const reason = attrBytes.toString('utf8', 4); 79 | 80 | if (reason.length >= 128) { 81 | throw new Error('invalid error code'); 82 | } 83 | if (code < 300 || code >= 700) { 84 | throw new Error('invalid error code'); 85 | } 86 | 87 | return new ErrorCodeAttr(code, reason); 88 | }; 89 | 90 | module.exports = ErrorCodeAttr; 91 | -------------------------------------------------------------------------------- /lib/attributes/mapped-address.js: -------------------------------------------------------------------------------- 1 | const addressAttr = require('./address'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class MappedAddressAttr { 6 | constructor(address, port) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify address and port 13 | if (address === undefined || port === undefined) { 14 | const errorMsg = 'invalid mapped address attribute'; 15 | this.log.error(errorMsg); 16 | throw new Error(errorMsg); 17 | } 18 | // init 19 | this.address = address; 20 | this.port = port; 21 | this.type = 0x0001; 22 | // done 23 | this.log.debug(`mapped address = ${this.address}, port = ${this.port}`); 24 | } 25 | 26 | encode() { 27 | // type 28 | const typeBytes = Buffer.alloc(2); 29 | typeBytes.writeUInt16BE(this.type, 0); 30 | // value 31 | const valueBytes = addressAttr.encode(this.address, this.port); 32 | // length 33 | const lengthBytes = Buffer.alloc(2); 34 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 35 | // combination 36 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes]); 37 | // done 38 | return result; 39 | } 40 | } 41 | 42 | MappedAddressAttr.decode = (attrBytes) => { 43 | const result = addressAttr.decode(attrBytes); 44 | return new MappedAddressAttr(result.address, result.port); 45 | }; 46 | 47 | module.exports = MappedAddressAttr; 48 | -------------------------------------------------------------------------------- /lib/attributes/message-integrity.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class MessageIntegrityAttr { 6 | constructor(request, hash) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify request 13 | if (request) { 14 | if (request.username === undefined || request.password === undefined) { 15 | const errorMsg = 'invalid message integrity attribute'; 16 | this.log.error(errorMsg); 17 | throw new Error(errorMsg); 18 | } 19 | } 20 | // init 21 | this.request = request; 22 | this.hash = hash; 23 | this.type = 0x0008; 24 | // done 25 | this.log.debug(`message integrity attr: request = ${JSON.stringify(this.request)}, hash = ${this.hash}`); 26 | } 27 | 28 | encode(packetBytes) { 29 | if (packetBytes === undefined) { 30 | const errorMsg = 'invalid MessageIntegrityAttr.encode attributes'; 31 | this.log.error(errorMsg); 32 | throw new Error(errorMsg); 33 | } 34 | // type 35 | const typeBytes = Buffer.alloc(2); 36 | typeBytes.writeUInt16BE(this.type, 0); 37 | // value 38 | let key; 39 | if (this.request.realm && this.request.realm !== '') { 40 | const md5 = crypto.createHash('md5'); 41 | md5.update([this.request.username, this.request.realm, this.request.password].join(':')); 42 | key = md5.digest(); 43 | } else { 44 | key = this.request.password; 45 | } 46 | const hmac = crypto.createHmac('sha1', key); 47 | hmac.update(packetBytes); 48 | const valueBytes = Buffer.from(hmac.digest()); 49 | // length 50 | const lengthBytes = Buffer.alloc(2); 51 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 52 | // combination 53 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes]); 54 | // done 55 | return result; 56 | } 57 | 58 | static decode(attrBytes) { 59 | if (attrBytes.length !== 20) { 60 | const errorMsg = 'invalid message integrity attribute'; 61 | this.log.error(errorMsg); 62 | throw new Error(errorMsg); 63 | } 64 | const hash = attrBytes.toString('hex'); 65 | return new MessageIntegrityAttr(null, hash); 66 | } 67 | } 68 | 69 | module.exports = MessageIntegrityAttr; 70 | -------------------------------------------------------------------------------- /lib/attributes/nonce.js: -------------------------------------------------------------------------------- 1 | const padding = require('./padding'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class NonceAttr { 6 | constructor(value) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify value 13 | if (value === undefined) { 14 | const errorMsg = 'invalid nonce attribute'; 15 | this.log.error(errorMsg); 16 | throw new Error(errorMsg); 17 | } 18 | // init 19 | this.value = value; 20 | this.type = 0x0015; 21 | // done 22 | this.log.debug(`nonce attr: ${this.value}`); 23 | } 24 | 25 | encode() { 26 | // type 27 | const typeBytes = Buffer.alloc(2); 28 | typeBytes.writeUInt16BE(this.type, 0); 29 | // value 30 | const valueBytes = Buffer.from(this.value); 31 | if (this.value.length >= 128 || valueBytes.length >= 764) { 32 | throw new Error('invalid nonce attribute'); 33 | } 34 | // length 35 | const lengthBytes = Buffer.alloc(2); 36 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 37 | // padding 38 | const paddingBytes = padding.getBytes(valueBytes.length); 39 | // combination 40 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes, paddingBytes]); 41 | // done 42 | return result; 43 | } 44 | } 45 | 46 | NonceAttr.decode = (attrBytes) => { 47 | const value = attrBytes.toString(); 48 | if (attrBytes.length >= 764 || value.length >= 128) { 49 | throw new Error('invalid nonce attribute'); 50 | } 51 | return new NonceAttr(value); 52 | }; 53 | 54 | module.exports = NonceAttr; 55 | -------------------------------------------------------------------------------- /lib/attributes/padding.js: -------------------------------------------------------------------------------- 1 | const PADDING_VALUE = '0x00'; 2 | 3 | const getBytes = (length) => { 4 | const paddingBytes = Buffer.alloc((4 - (length % 4)) % 4); 5 | for (let i = 0; i < paddingBytes.length; i += 1) { 6 | paddingBytes[i] = PADDING_VALUE; 7 | } 8 | return paddingBytes; 9 | }; 10 | 11 | exports.getBytes = getBytes; 12 | -------------------------------------------------------------------------------- /lib/attributes/realm.js: -------------------------------------------------------------------------------- 1 | const padding = require('./padding'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class RealmAttr { 6 | constructor(value) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify value 13 | if (value === undefined || value === '') { 14 | const errorMsg = 'invalid realm attribute'; 15 | this.log.error(errorMsg); 16 | throw new Error(errorMsg); 17 | } 18 | // init 19 | this.value = value; 20 | this.type = 0x0014; 21 | // done 22 | this.log.debug(`realm attr: ${this.value}`); 23 | } 24 | 25 | encode() { 26 | // type 27 | const typeBytes = Buffer.alloc(2); 28 | typeBytes.writeUInt16BE(this.type, 0); 29 | // value 30 | const valueBytes = Buffer.from(this.value); 31 | if (this.value.length >= 128 || valueBytes.length >= 764) { 32 | throw new Error('invalid realm attribute'); 33 | } 34 | // length 35 | const lengthBytes = Buffer.alloc(2); 36 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 37 | // padding 38 | const paddingBytes = padding.getBytes(valueBytes.length); 39 | // combination 40 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes, paddingBytes]); 41 | // done 42 | return result; 43 | } 44 | } 45 | 46 | RealmAttr.decode = (attrBytes) => { 47 | const value = attrBytes.toString(); 48 | if (attrBytes.length >= 764 || value.length >= 128) { 49 | throw new Error('invalid realm attribute'); 50 | } 51 | return new RealmAttr(value); 52 | }; 53 | 54 | module.exports = RealmAttr; 55 | -------------------------------------------------------------------------------- /lib/attributes/software.js: -------------------------------------------------------------------------------- 1 | const padding = require('./padding'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class SoftwareAttr { 6 | constructor(description) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify description 13 | if (description === undefined) { 14 | const errorMsg = 'invalid software attribute'; 15 | this.log.error(errorMsg); 16 | throw new Error(errorMsg); 17 | } 18 | // init 19 | this.description = description; 20 | this.type = 0x8022; 21 | // done 22 | this.log.debug(`software attr: ${this.description}`); 23 | } 24 | 25 | encode() { 26 | // type 27 | const typeBytes = Buffer.alloc(2); 28 | typeBytes.writeUInt16BE(this.type, 0); 29 | // value 30 | const valueBytes = Buffer.from(this.description); 31 | if (this.description.length >= 128 || valueBytes.length >= 764) { 32 | throw new Error('invalid software attribute'); 33 | } 34 | // length 35 | const lengthBytes = Buffer.alloc(2); 36 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 37 | // padding 38 | const paddingBytes = padding.getBytes(valueBytes.length); 39 | // combination 40 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes, paddingBytes]); 41 | // done 42 | return result; 43 | } 44 | } 45 | 46 | SoftwareAttr.decode = (attrBytes) => { 47 | const description = attrBytes.toString(); 48 | if (attrBytes.length >= 764 || description.length >= 128) { 49 | throw new Error('invalid software attribute'); 50 | } 51 | return new SoftwareAttr(description); 52 | }; 53 | 54 | module.exports = SoftwareAttr; 55 | -------------------------------------------------------------------------------- /lib/attributes/unknown-attributes.js: -------------------------------------------------------------------------------- 1 | const winston = require('winston-debug'); 2 | const winstonWrapper = require('winston-meta-wrapper'); 3 | 4 | class UnknownAttributesAttr { 5 | constructor(value) { 6 | // logging 7 | this.log = winstonWrapper(winston); 8 | this.log.addMeta({ 9 | module: 'stun:attributes', 10 | }); 11 | // init 12 | this.value = value; 13 | this.type = 0x000A; 14 | // done 15 | this.log.debug(`unknown attributes attr: ${JSON.stringify(this.value)}`); 16 | } 17 | 18 | // eslint-disable-next-line class-methods-use-this 19 | encode() { 20 | throw new Error('unknown-attributes.encode not implemented yet'); 21 | } 22 | } 23 | 24 | UnknownAttributesAttr.decode = (attrBytes) => { 25 | const unknownAttrs = []; 26 | let offset = 0; 27 | 28 | while (offset < attrBytes.length) { 29 | unknownAttrs.push(attrBytes.readUInt16BE(offset).toString(16)); 30 | offset += 2; 31 | } 32 | 33 | return new UnknownAttributesAttr(unknownAttrs); 34 | }; 35 | 36 | module.exports = UnknownAttributesAttr; 37 | -------------------------------------------------------------------------------- /lib/attributes/username.js: -------------------------------------------------------------------------------- 1 | const padding = require('./padding'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class UsernameAttr { 6 | constructor(name) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify name 13 | if (name === undefined) { 14 | const errorMsg = 'invalid username attribute'; 15 | this.log.error(errorMsg); 16 | throw new Error(errorMsg); 17 | } 18 | // init 19 | this.name = name; 20 | this.type = 0x0006; 21 | // debug 22 | this.log.debug(`username attr: ${this.name}`); 23 | } 24 | 25 | encode() { 26 | // type 27 | const typeBytes = Buffer.alloc(2); 28 | typeBytes.writeUInt16BE(this.type, 0); 29 | // value 30 | const valueBytes = Buffer.from(this.name); 31 | if (valueBytes.length > 512) { 32 | throw new Error('invalid username attribute'); 33 | } 34 | // length 35 | const lengthBytes = Buffer.alloc(2); 36 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 37 | // padding 38 | const paddingBytes = padding.getBytes(valueBytes.length); 39 | // combination 40 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes, paddingBytes]); 41 | // done 42 | return result; 43 | } 44 | } 45 | 46 | UsernameAttr.decode = (attrBytes) => { 47 | if (attrBytes.length > 512) { 48 | throw new Error('invalid username'); 49 | } 50 | const name = attrBytes.toString(); 51 | return new UsernameAttr(name); 52 | }; 53 | 54 | module.exports = UsernameAttr; 55 | -------------------------------------------------------------------------------- /lib/attributes/xor-mapped-address.js: -------------------------------------------------------------------------------- 1 | const addressAttr = require('./address'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | class XORMappedAddressAttr { 6 | constructor(address, port) { 7 | // logging 8 | this.log = winstonWrapper(winston); 9 | this.log.addMeta({ 10 | module: 'stun:attributes', 11 | }); 12 | // verify address and port 13 | if (address === undefined || port === undefined) { 14 | const errorMsg = 'invalid xor mapped address attribute'; 15 | this.log.error(errorMsg); 16 | throw new Error(errorMsg); 17 | } 18 | // init 19 | this.address = address; 20 | this.port = port; 21 | this.type = 0x0020; 22 | // done 23 | this.log.debug(`xor mapped address attr: ${this.address}:${this.port}`); 24 | } 25 | 26 | encode(magic, tid) { 27 | if (magic === undefined || tid === undefined) { 28 | const errorMsg = 'invalid xorMappedAddressAttr.encode params'; 29 | this.log.error(errorMsg); 30 | throw new Error(errorMsg); 31 | } 32 | // type 33 | const typeBytes = Buffer.alloc(2); 34 | typeBytes.writeUInt16BE(this.type, 0); 35 | // value 36 | const valueBytes = addressAttr.encodeXor(this.address, this.port, magic, tid); 37 | // length 38 | const lengthBytes = Buffer.alloc(2); 39 | lengthBytes.writeUInt16BE(valueBytes.length, 0); 40 | // combination 41 | const result = Buffer.concat([typeBytes, lengthBytes, valueBytes]); 42 | // done 43 | return result; 44 | } 45 | } 46 | 47 | XORMappedAddressAttr.decode = (attrBytes, headerBytes) => { 48 | const magicBytes = headerBytes.slice(4, 8); // BE 49 | const tidBytes = headerBytes.slice(8, 20); // BE 50 | 51 | const result = addressAttr.decodeXor(attrBytes, magicBytes, tidBytes); 52 | return new XORMappedAddressAttr(result.address, result.port); 53 | }; 54 | 55 | module.exports = XORMappedAddressAttr; 56 | -------------------------------------------------------------------------------- /lib/packet.js: -------------------------------------------------------------------------------- 1 | const Attributes = require('./attributes'); 2 | const winston = require('winston-debug'); 3 | const winstonWrapper = require('winston-meta-wrapper'); 4 | 5 | const log = winstonWrapper(winston); 6 | log.addMeta({ 7 | module: 'stun:packet', 8 | }); 9 | 10 | // utils 11 | const containsFlag = (number, flag) => ( 12 | (number & flag) === flag 13 | ); 14 | 15 | const containsValue = (object, value) => { 16 | let result = false; 17 | Object.keys(object).forEach((key) => { 18 | if (object[key] === value) { 19 | result = true; 20 | } 21 | }); 22 | return result; 23 | }; 24 | 25 | // packet class 26 | class Packet { 27 | constructor(method, type, attrs) { 28 | // logging 29 | this.log = winstonWrapper(winston); 30 | this.log.addMeta({ 31 | module: 'stun:packet', 32 | }); 33 | // assertions 34 | if (!containsValue(Packet.METHOD, method)) { 35 | const methodError = 'invalid packet method attribute'; 36 | this.log.error(methodError); 37 | throw new Error(methodError); 38 | } 39 | if (!containsValue(Packet.TYPE, type)) { 40 | const typeError = 'invalid packet type attribute'; 41 | this.log.error(typeError); 42 | throw new Error(typeError); 43 | } 44 | // init 45 | this.method = method; 46 | this.type = type; 47 | this.attrs = attrs || new Attributes(); 48 | this.tid = this.getTransactionId(); 49 | } 50 | 51 | // encode packet 52 | encode() { 53 | const attrsBuffer = this.attrs.encode(Packet.MAGIC_COOKIE, this.tid); 54 | let attrsLength = attrsBuffer.length; 55 | // check if we need to include a message integrity attribute 56 | const messageIntegrity = this.getAttribute(Attributes.MESSAGE_INTEGRITY); 57 | if (messageIntegrity) { 58 | attrsLength += 24; // size of the message-integrity attribute 59 | } 60 | // encode header bytes 61 | const headerBuffer = this.encodeHeader(attrsLength); 62 | // create packet bytes 63 | let packetBuffer = Buffer.concat([headerBuffer, attrsBuffer]); 64 | // append message integrity attribute if requested 65 | if (messageIntegrity) { 66 | const messageIntegrityBuffer = messageIntegrity.encode(packetBuffer); 67 | packetBuffer = Buffer.concat([packetBuffer, messageIntegrityBuffer]); 68 | } 69 | return packetBuffer; 70 | } 71 | 72 | // get attribute 73 | getAttribute(type) { 74 | return this.attrs.get(type); 75 | } 76 | 77 | // encode packet header 78 | encodeHeader(length) { 79 | const type = this.method | this.type; 80 | const encodedHeader = Buffer.alloc(Packet.HEADER_LENGTH); 81 | encodedHeader.writeUInt16BE((type & 0x3fff), 0); 82 | encodedHeader.writeUInt16BE(length, 2); 83 | encodedHeader.writeUInt32BE(Packet.MAGIC_COOKIE, 4); 84 | encodedHeader.writeUInt32BE(0, 8); 85 | encodedHeader.writeUInt32BE(0, 12); 86 | encodedHeader.writeUInt32BE(this.tid, 16); 87 | return encodedHeader; 88 | } 89 | 90 | // generate tansaction ID 91 | // eslint-disable-next-line class-methods-use-this 92 | getTransactionId() { 93 | return Math.random() * Packet.TID_MAX; 94 | } 95 | } 96 | 97 | // packet header length 98 | Packet.HEADER_LENGTH = 20; 99 | // STUN magic cookie 100 | Packet.MAGIC_COOKIE = 0x2112A442; // fixed 101 | // max transaction ID (32bit) 102 | Packet.TID_MAX = Math.pow(2, 32); // eslint-disable-line no-restricted-properties 103 | // message types 104 | Packet.TYPE = { 105 | REQUEST: 0x0000, 106 | INDICATION: 0x0010, 107 | SUCCESS_RESPONSE: 0x0100, 108 | ERROR_RESPONSE: 0x0110, 109 | }; 110 | // STUN method 111 | Packet.METHOD = {}; 112 | Packet.METHOD.BINDING = 0x0001; 113 | 114 | // decode packet 115 | Packet.decode = (bytes, isFrame) => { 116 | // check if packet starts with 0b00 117 | if (!Packet.isStunPacket(bytes)) { 118 | log.debug('this is not a STUN packet'); 119 | return; 120 | } 121 | // check if buffer contains enough bytes to parse header 122 | if (bytes.length < Packet.HEADER_LENGTH) { 123 | log.debug('not enough bytes to parse STUN header, giving up'); 124 | return; 125 | } 126 | // parse header 127 | const headerBytes = bytes.slice(0, Packet.HEADER_LENGTH); 128 | const header = Packet.decodeHeader(headerBytes); 129 | // check magic cookie 130 | if (header.magic !== Packet.MAGIC_COOKIE) { 131 | const incorrectMagicCookieError = 'magic cookie field has incorrect value'; 132 | log.error(incorrectMagicCookieError); 133 | throw new Error(incorrectMagicCookieError); 134 | } 135 | // check if length attribute is valid 136 | if (header.length % 4 !== 0) { 137 | log.debug('attributes are not padded to a multiple of 4 bytes, giving up'); 138 | return; 139 | } 140 | // check if buffer contains enough bytes to parse Attributes 141 | if (bytes.length < Packet.HEADER_LENGTH + header.length) { 142 | log.debug('not enough bytes to parse attributes, giving up'); 143 | return; 144 | } 145 | const attrsBytes = bytes.slice(Packet.HEADER_LENGTH, Packet.HEADER_LENGTH + header.length); 146 | const attrs = Attributes.decode(attrsBytes, headerBytes); 147 | 148 | const packet = new Packet(header.method, header.type, attrs); 149 | packet.tid = header.tid; 150 | 151 | const result = {}; 152 | result.packet = packet; 153 | result.remainingBytes = bytes.slice(Packet.HEADER_LENGTH + header.length, bytes.length); 154 | // do we expect remaining bytes? 155 | if (isFrame && result.remainingBytes.length !== 0) { 156 | const errorMsg = 'not expecting remaining bytes after processing full frame packet'; 157 | log.error(errorMsg); 158 | throw new Error(errorMsg); 159 | } 160 | // done 161 | return result; 162 | }; 163 | 164 | // decode packet header 165 | Packet.decodeHeader = (bytes) => { 166 | const header = {}; 167 | const methodType = bytes.readUInt16BE(0); 168 | header.length = bytes.readUInt16BE(2); 169 | header.magic = bytes.readUInt32BE(4); 170 | header.tid = bytes.readUInt32BE(16); 171 | header.type = (methodType & 0x0110); 172 | header.method = (methodType & 0xFEEF); 173 | return header; 174 | }; 175 | 176 | // check if this is a STUN packet (starts with 0b00) 177 | Packet.isStunPacket = (bytes) => { 178 | const block = bytes.readUInt8(0); 179 | const bit1 = containsFlag(block, 0x80); 180 | const bit2 = containsFlag(block, 0x40); 181 | return (!bit1 && !bit2); 182 | }; 183 | 184 | module.exports = Packet; 185 | -------------------------------------------------------------------------------- /lib/stun_client.js: -------------------------------------------------------------------------------- 1 | const Attributes = require('./attributes'); 2 | const Packet = require('./packet'); 3 | const Q = require('q'); 4 | const StunComm = require('./stun_comm'); 5 | const winston = require('winston-debug'); 6 | const winstonWrapper = require('winston-meta-wrapper'); 7 | 8 | // Create bind request message 9 | const composeBindRequest = () => { 10 | // create packet 11 | const packet = new Packet(Packet.METHOD.BINDING, Packet.TYPE.REQUEST); 12 | // encode packet 13 | const message = packet.encode(); 14 | return message; 15 | }; 16 | 17 | // Create bind request message 18 | const composeBindIndication = () => { 19 | // create packet 20 | const packet = new Packet(Packet.METHOD.BINDING, Packet.TYPE.INDICATION); 21 | // encode packet 22 | const message = packet.encode(); 23 | return message; 24 | }; 25 | 26 | // Constructor 27 | class StunClient extends StunComm { 28 | constructor(stunHost, stunPort, transport) { 29 | super(stunHost, stunPort, transport); 30 | // logging 31 | this.log = winstonWrapper(winston); 32 | this.log.addMeta({ 33 | module: 'stun:client', 34 | }); 35 | // inheritance 36 | } 37 | 38 | /** StunComm operations */ 39 | 40 | // Bind request 41 | bindP() { 42 | return this.sendBindRequestP() 43 | .then((bindReply) => { 44 | const errorCode = bindReply.getAttribute(Attributes.ERROR_CODE); 45 | // check if the reply includes an error code attr 46 | if (errorCode) { 47 | throw new Error(`bind error: ${errorCode.reason}`); 48 | } 49 | let mappedAddressAttr = bindReply.getAttribute(Attributes.XOR_MAPPED_ADDRESS); 50 | if (!mappedAddressAttr) { 51 | mappedAddressAttr = bindReply.getAttribute(Attributes.MAPPED_ADDRESS); 52 | } 53 | const mappedAddress = { 54 | address: mappedAddressAttr.address, 55 | port: mappedAddressAttr.port, 56 | }; 57 | return Q.fcall(() => mappedAddress); 58 | }); 59 | } 60 | 61 | bind(onSuccess, onFailure) { 62 | if (onSuccess === undefined || onFailure === undefined) { 63 | const errorMsg = 'bind callback handlers are undefined'; 64 | this.log.error(errorMsg); 65 | throw new Error(errorMsg); 66 | } 67 | this.bindP() 68 | .then((result) => { 69 | onSuccess(result); 70 | }) 71 | .catch((error) => { 72 | onFailure(error); 73 | }); 74 | } 75 | 76 | /** Message transmission */ 77 | 78 | // Send STUN bind request 79 | sendBindRequestP() { 80 | this.log.debug('send bind request (using promises)'); 81 | const message = composeBindRequest(); 82 | return this.sendStunRequestP(message); 83 | } 84 | 85 | sendBindRequest(onSuccess, onFailure) { 86 | this.log.debug('send bind request'); 87 | if (onSuccess === undefined || onFailure === undefined) { 88 | const errorMsg = 'send bind request callback handlers are undefined'; 89 | this.log.error(errorMsg); 90 | throw new Error(errorMsg); 91 | } 92 | this.sendBindRequestP() 93 | .then((reply) => { 94 | onSuccess(reply); 95 | }) 96 | .catch((error) => { 97 | onFailure(error); 98 | }); 99 | } 100 | 101 | // Send STUN bind indication 102 | sendBindIndicationP() { 103 | this.log.debug('send bind indication (using promises)'); 104 | const message = composeBindIndication(); 105 | return this.sendStunIndicationP(message); 106 | } 107 | 108 | sendBindIndication(onSuccess, onFailure) { 109 | this.log.debug('send bind indication'); 110 | if (onSuccess === undefined || onFailure === undefined) { 111 | const errorMsg = 'send bind indication callback handlers are undefined'; 112 | this.log.debug(errorMsg); 113 | throw new Error(errorMsg); 114 | } 115 | this.sendBindIndicationP() 116 | .then((reply) => { 117 | onSuccess(reply); 118 | }) 119 | .catch((error) => { 120 | onFailure(error); 121 | }); 122 | } 123 | } 124 | 125 | module.exports = StunClient; 126 | -------------------------------------------------------------------------------- /lib/stun_comm.js: -------------------------------------------------------------------------------- 1 | const Args = require('args-js'); 2 | const events = require('events'); 3 | const myUtils = require('./utils'); 4 | const Packet = require('./packet'); 5 | const Q = require('q'); 6 | const UdpTransport = require('./transports/udp'); 7 | const winston = require('winston-debug'); 8 | const winstonWrapper = require('winston-meta-wrapper'); 9 | 10 | const MAX_RETRANSMISSIONS = 5; 11 | 12 | // Create client 13 | class StunComm extends events.EventEmitter { 14 | constructor(...args) { 15 | super(); 16 | // logging 17 | this.log = winstonWrapper(winston); 18 | this.log.addMeta({ 19 | module: 'stun:client', 20 | }); 21 | // parse args 22 | const functionArgs = new Args([ 23 | { stunHost: Args.STRING | Args.Required }, 24 | { stunPort: Args.INT | Args.Required }, 25 | { transport: Args.OBJECT | Args.Optional } 26 | ], args); 27 | // init 28 | this.stunHost = functionArgs.stunHost; 29 | this.stunPort = functionArgs.stunPort; 30 | this.transport = functionArgs.transport; 31 | if (this.transport === undefined) { 32 | this.transport = new UdpTransport(); 33 | } 34 | this.unackedSendOperations = {}; 35 | this.decoders = []; 36 | this.decoders.push({ 37 | decoder: Packet.decode, 38 | listener: this.dispatchStunPacket.bind(this), 39 | }); 40 | this.availableBytes = Buffer.alloc(0); 41 | // register error handler 42 | myUtils.mixinEventEmitterErrorFunction(this); 43 | } 44 | 45 | init(onReady, onFailure) { 46 | this.transport.init( 47 | this.stunHost, 48 | this.stunPort, 49 | onReady, 50 | this.onIncomingData(), 51 | this.onError(onFailure) // eslint-disable-line comma-dangle 52 | ); 53 | } 54 | 55 | initP() { 56 | const deferred = Q.defer(); 57 | this.init( 58 | () => { // on success 59 | deferred.resolve(); 60 | }, 61 | (error) => { 62 | deferred.reject(error); 63 | } // eslint-disable-line comma-dangle 64 | ); 65 | return deferred.promise; 66 | } 67 | 68 | // Close client 69 | close(done) { 70 | this.log.debug('closing client'); 71 | this.transport.close(done); 72 | } 73 | 74 | closeP() { 75 | this.log.debug('closing client'); 76 | return this.transport.closeP(); 77 | } 78 | 79 | /** STUN communication */ 80 | 81 | // Send STUN request 82 | sendStunRequest(bytes, onResponse, onFailure) { 83 | // get tid 84 | const tid = bytes.readUInt32BE(16); 85 | this.log.debug(`sending stun request with TID ${tid}`); 86 | // store response handlers for this tid 87 | if (this.unackedSendOperations[tid] === undefined) { 88 | this.unackedSendOperations[tid] = { 89 | onResponse, 90 | onFailure, 91 | }; 92 | } 93 | // send bytes 94 | this.transport.send( 95 | bytes, 96 | () => { // on success 97 | // do nothing 98 | }, 99 | (error) => { // on failure 100 | onFailure(error); 101 | } // eslint-disable-line comma-dangle 102 | ); 103 | // when stun transport is unreliable 104 | if (!this.transport.isReliable()) { 105 | // set # of retransmissions if undefined 106 | if (this.unackedSendOperations[tid].remainingRetransmissionAttempts === undefined) { 107 | this.unackedSendOperations[tid].remainingRetransmissionAttempts = MAX_RETRANSMISSIONS; 108 | } 109 | // start retransmission timer 110 | const timeout = setTimeout( 111 | () => { 112 | if (this.unackedSendOperations[tid].remainingRetransmissionAttempts === 0) { 113 | // stopping retransmission 114 | const errorMsg = 'giving up, no more retransmission attempts left'; 115 | this.log.error(errorMsg); 116 | this.error(errorMsg, onFailure); 117 | delete this.unackedSendOperations[tid]; 118 | } else { 119 | this.unackedSendOperations[tid].remainingRetransmissionAttempts -= 1; 120 | this.sendStunRequest(bytes, onResponse, onFailure); 121 | } 122 | }, 123 | this.transport.getTimeoutDelay() // eslint-disable-line comma-dangle 124 | ); 125 | this.unackedSendOperations[tid].retransmissionTimeout = timeout; 126 | } 127 | } 128 | 129 | sendStunRequestP(bytes) { 130 | const deferred = Q.defer(); 131 | this.sendStunRequest( 132 | bytes, 133 | (stunResponse) => { // on response 134 | deferred.resolve(stunResponse); 135 | }, 136 | (error) => { // on failure 137 | deferred.reject(error); 138 | } // eslint-disable-line comma-dangle 139 | ); 140 | return deferred.promise; 141 | } 142 | 143 | // Send STUN indication 144 | sendStunIndicationP(bytes) { 145 | return this.transport.sendP(bytes); 146 | } 147 | 148 | sendStunIndication(bytes, onSuccess, onFailure) { 149 | if (onSuccess === undefined || onFailure === undefined) { 150 | const errorMsg = 'send stun indication callback handlers are undefined'; 151 | this.log.error(errorMsg); 152 | throw new Error(errorMsg); 153 | } 154 | this.transport.send(bytes, onSuccess, onFailure); 155 | } 156 | 157 | // Incoming data handler 158 | onIncomingData() { 159 | return (bytes, rinfo, isFrame) => { 160 | this.log.debug(`receiving data from ${JSON.stringify(rinfo)}`); 161 | this.availableBytes = Buffer.concat([this.availableBytes, bytes]); 162 | this.parseIncomingData(rinfo, isFrame); 163 | }; 164 | } 165 | 166 | parseIncomingData(rinfo, isFrame) { 167 | // iterate over registered decoders 168 | for (const i in this.decoders) { 169 | const decoder = this.decoders[i].decoder; 170 | const listener = this.decoders[i].listener; 171 | // execute decoder 172 | const decoding = decoder(this.availableBytes, isFrame); 173 | // if decoding was successful 174 | if (decoding) { 175 | // store remaining bytes (if any) for later use 176 | this.availableBytes = decoding.remainingBytes; 177 | // dispatch packet 178 | listener(decoding.packet, rinfo); 179 | // if there are remaining bytes, then trigger new parsing round 180 | if (this.availableBytes.length !== 0) { 181 | this.parseIncomingData(rinfo, isFrame); 182 | } 183 | // and break 184 | break; 185 | } 186 | } 187 | } 188 | 189 | dispatchStunPacket(stunPacket, rinfo) { 190 | switch (stunPacket.type) { 191 | case Packet.TYPE.SUCCESS_RESPONSE: 192 | this.log.debug(`incoming STUN success response with tid ${stunPacket.tid}`); 193 | this.onIncomingStunResponse(stunPacket); 194 | break; 195 | case Packet.TYPE.ERROR_RESPONSE: 196 | this.log.debug(`incoming STUN error response with tid ${stunPacket.tid}`); 197 | this.onIncomingStunResponse(stunPacket); 198 | break; 199 | case Packet.TYPE.INDICATION: 200 | this.log.debug('incoming STUN indication'); 201 | this.onIncomingStunIndication(stunPacket, rinfo); 202 | break; 203 | default: 204 | const errorMsg = "don't know how to process incoming STUN message -- dropping it on the floor"; 205 | this.log.error(errorMsg); 206 | throw new Error(errorMsg); 207 | } 208 | } 209 | 210 | // Incoming STUN reply 211 | onIncomingStunResponse(stunPacket) { 212 | const sendOperation = this.unackedSendOperations[stunPacket.tid]; 213 | if (sendOperation === undefined) { 214 | const noSendOperationFoundMessage = `cannot find associated STUN request for TID ${stunPacket.tid} -- ignoring request`; 215 | this.log.error(noSendOperationFoundMessage); 216 | return; 217 | } 218 | // stop retransmission timer (if present) 219 | const timeout = this.unackedSendOperations[stunPacket.tid].retransmissionTimeout; 220 | if (timeout) { 221 | clearTimeout(timeout); 222 | } 223 | // this is a stun reply 224 | const onResponseCallback = this.unackedSendOperations[stunPacket.tid].onResponse; 225 | if (onResponseCallback) { 226 | onResponseCallback(stunPacket); 227 | delete this.unackedSendOperations[stunPacket.tid]; 228 | } else { 229 | const errorMsg = `no handler available to process response with tid ${stunPacket.tid}`; 230 | this.log.error(errorMsg); 231 | throw new Error(errorMsg); 232 | } 233 | } 234 | 235 | // Incoming STUN indication 236 | onIncomingStunIndication(stunPacket, rinfo) { 237 | this.emit('indication', stunPacket, rinfo); 238 | } 239 | 240 | // Error handler 241 | onError(callback) { 242 | return (error) => { 243 | const errorMsg = `client error: ${error}`; 244 | this.log.error(errorMsg); 245 | this.error(new Error(errorMsg), callback); 246 | }; 247 | } 248 | } 249 | 250 | module.exports = StunComm; 251 | -------------------------------------------------------------------------------- /lib/transports/abstract.js: -------------------------------------------------------------------------------- 1 | const events = require('events'); 2 | const myUtils = require('../utils'); 3 | const Q = require('q'); 4 | const winston = require('winston-debug'); 5 | const winstonWrapper = require('winston-meta-wrapper'); 6 | 7 | class AbstractTransport extends events.EventEmitter { 8 | constructor() { 9 | // event emitter 10 | super(); 11 | // logging 12 | this.log = winstonWrapper(winston); 13 | this.log.addMeta({ 14 | module: 'stun:transports', 15 | }); 16 | // register error handler 17 | myUtils.mixinEventEmitterErrorFunction(this); 18 | } 19 | 20 | isReliable() { 21 | const errorMsg = 'AbstractTransport.isReliable function not implemented'; 22 | this.log.error(errorMsg); 23 | this.error(errorMsg); 24 | } 25 | 26 | getTimeoutDelay() { 27 | const errorMsg = 'AbstractTransport.getTimeoutDelay function not implemented'; 28 | this.log.error(errorMsg); 29 | this.error(errorMsg); 30 | } 31 | 32 | send() { 33 | const errorMsg = 'AbstractTransport.send function not implemented'; 34 | this.log.error(errorMsg); 35 | this.error(errorMsg); 36 | } 37 | 38 | sendP(bytes) { 39 | const deferred = Q.defer(); 40 | this.send( 41 | bytes, 42 | () => { // on success 43 | deferred.resolve(); 44 | }, 45 | (error) => { 46 | const errorMsg = `tcp wrapper could not send bytes to ${this.host}:${this.port}. ${error}`; 47 | this.log.error(errorMsg); 48 | deferred.reject(errorMsg); 49 | } // eslint-disable-line comma-dangle 50 | ); 51 | return deferred.promise; 52 | } 53 | 54 | close() { 55 | const errorMsg = 'AbstractTransport.close function not implemented'; 56 | this.log.error(errorMsg); 57 | this.error(errorMsg); 58 | } 59 | 60 | closeP() { 61 | const deferred = Q.defer(); 62 | this.close( 63 | () => { // on success 64 | deferred.resolve(); 65 | } // eslint-disable-line comma-dangle 66 | ); 67 | return deferred.promise; 68 | } 69 | } 70 | 71 | module.exports = AbstractTransport; 72 | -------------------------------------------------------------------------------- /lib/transports/index.js: -------------------------------------------------------------------------------- 1 | const tcpTransport = require('./tcp'); 2 | const udpTransport = require('./udp'); 3 | 4 | module.exports = { 5 | TCP: tcpTransport, 6 | UDP: udpTransport, 7 | }; 8 | -------------------------------------------------------------------------------- /lib/transports/tcp.js: -------------------------------------------------------------------------------- 1 | const AbstractTransport = require('./abstract'); 2 | const merge = require('merge'); 3 | const net = require('net'); 4 | const winston = require('winston-debug'); 5 | const winstonWrapper = require('winston-meta-wrapper'); 6 | 7 | class TcpWrapper extends AbstractTransport { 8 | constructor(args) { 9 | super(); 10 | if (!(this instanceof TcpWrapper)) { 11 | return new TcpWrapper(args); 12 | } 13 | // init 14 | this.args = merge(Object.create(TcpWrapper.DEFAULTS), args); 15 | // logging 16 | this.log = winstonWrapper(winston); 17 | this.log.addMeta({ 18 | module: 'stun:transports:tcp', 19 | }); 20 | } 21 | 22 | init(host, port, onReady, onData, onError) { 23 | // init 24 | this.host = host; 25 | this.port = port; 26 | // create and store tcp socket 27 | const client = net.createConnection(this.port, this.host); 28 | this.client = client; 29 | this.log.debug(`creating TCP connection with ${this.host}:${this.port}`); 30 | // add socket event handlers 31 | client.on('error', onError); 32 | client.on('data', (bytes) => { 33 | this.log.debug(`incoming data: ${bytes.length} bytes`); 34 | const rinfo = {}; 35 | rinfo.address = this.host; 36 | rinfo.port = parseInt(this.port, 10); 37 | rinfo.family = net.isIPv4(this.host) ? 'IPv4' : 'IPv6'; 38 | rinfo.size = bytes.length; 39 | onData(bytes, rinfo, false); 40 | }); 41 | client.on('connect', () => { 42 | // stop and remove timer 43 | clearTimeout(client.connectionTimeout); 44 | delete client.connectionTimeout; 45 | // fire ready callback 46 | onReady(); 47 | // localport represents connection 48 | this.log.addMeta({ 49 | conn: this.client.localPort, 50 | }); 51 | }); 52 | client.on('close', () => { 53 | this.log.debug('TCP connection closed'); 54 | }); 55 | // init connection timeout 56 | client.connectionTimeout = setTimeout(() => { 57 | this.log.error('connection timeout'); 58 | onError('TCP connection timeout'); 59 | }, this.args.connectTimeout); 60 | } 61 | 62 | // eslint-disable-next-line class-methods-use-this 63 | isReliable() { 64 | return true; 65 | } 66 | 67 | // eslint-disable-next-line class-methods-use-this 68 | getTimeoutDelay() { 69 | return 0; 70 | } 71 | 72 | send(bytes, onSuccess, onFailure) { 73 | this.log.debug(`outgoing data: ${bytes.length} bytes`); 74 | if (onSuccess === undefined || onFailure === undefined) { 75 | const errorMsg = 'tcp send bytes callback handlers are undefined'; 76 | this.log.error(errorMsg); 77 | throw new Error(errorMsg); 78 | } 79 | const flushed = this.client.write(bytes, 'binary', () => { 80 | this.log.debug('message sent'); 81 | }); 82 | if (!flushed) { 83 | this.log.debug(`high water -- buffer size = ${this.client.bufferSize}`); 84 | this.client.once('drain', () => { 85 | this.log.debug(`drained -- buffer size = ${this.client.bufferSize}`); 86 | onSuccess(); 87 | }); 88 | } else { 89 | onSuccess(); 90 | } 91 | } 92 | 93 | close(done) { 94 | this.client.once('close', () => { 95 | if (done) { 96 | done(); 97 | } 98 | }); 99 | this.client.destroy(); 100 | } 101 | } 102 | 103 | TcpWrapper.DEFAULTS = { 104 | connectTimeout: 100, 105 | }; 106 | 107 | module.exports = TcpWrapper; 108 | -------------------------------------------------------------------------------- /lib/transports/udp.js: -------------------------------------------------------------------------------- 1 | const AbstractTransport = require('./abstract'); 2 | const dgram = require('dgram'); 3 | const winston = require('winston-debug'); 4 | const winstonWrapper = require('winston-meta-wrapper'); 5 | 6 | class UdpWrapper extends AbstractTransport { 7 | constructor(socket) { 8 | super(); 9 | // create dgram if socker is undefined 10 | this.socket = (socket === undefined) ? dgram.createSocket('udp4') : socket; 11 | this.externalSocket = (socket !== undefined); 12 | // logging 13 | this.log = winstonWrapper(winston); 14 | this.log.addMeta({ 15 | module: 'stun:transports:udp', 16 | }); 17 | } 18 | 19 | init(host, port, onReady, onData, onError) { 20 | // init 21 | this.host = host; 22 | this.port = port; 23 | // if socket is defined/used externally 24 | if (this.externalSocket) { 25 | // store original message and error listeners, if any 26 | this.messageListeners = this.socket.listeners('message'); 27 | this.errorListeners = this.socket.listeners('error'); 28 | // temp remove these listeners ... 29 | this.messageListeners.forEach((callback) => { 30 | this.socket.removeListener('message', callback); 31 | }); 32 | this.errorListeners.forEach((callback) => { 33 | this.socket.removeListener('error', callback); 34 | }); 35 | } 36 | // register our own handlers 37 | this.socket.on('message', (message, rinfo) => { 38 | onData(message, rinfo, true); 39 | }); 40 | this.socket.on('error', onError); 41 | onReady(); 42 | } 43 | 44 | // eslint-disable-next-line class-methods-use-this 45 | isReliable() { 46 | return false; 47 | } 48 | 49 | // eslint-disable-next-line class-methods-use-this 50 | getTimeoutDelay() { 51 | return 500; 52 | } 53 | 54 | send(bytes, onSuccess, onFailure) { 55 | if (onSuccess === undefined || onFailure === undefined) { 56 | const errorMsg = 'udp send bytes callback handlers are undefined'; 57 | this.log.error(errorMsg); 58 | throw new Error(errorMsg); 59 | } 60 | this.socket.send(bytes, 0, bytes.length, this.port, this.host, (error) => { 61 | if (error) { 62 | onFailure(error); 63 | return; 64 | } 65 | onSuccess(); 66 | }); 67 | } 68 | 69 | close(done) { 70 | // if socket is defined/used externally 71 | if (this.externalSocket) { 72 | // remove temp listeners 73 | this.socket.listeners('message').forEach((callback) => { 74 | this.socket.removeListener('message', callback); 75 | }); 76 | this.socket.listeners('error').forEach((callback) => { 77 | this.socket.removeListener('error', callback); 78 | }); 79 | // restore the original listeners 80 | this.messageListeners.forEach((callback) => { 81 | this.socket.on('message', callback); 82 | }); 83 | this.errorListeners.forEach((callback) => { 84 | this.socket.on('error', callback); 85 | }); 86 | // and remove refs to these original listeners 87 | this.messageListeners = []; 88 | this.errorListeners = []; 89 | // fire callback 90 | if (done) { 91 | done(); 92 | } 93 | } else { 94 | // close socket 95 | this.socket.close(() => { 96 | // fire callback 97 | if (done) { 98 | done(); 99 | } 100 | }); 101 | } 102 | } 103 | } 104 | 105 | module.exports = UdpWrapper; 106 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events').EventEmitter; 2 | 3 | const mixinEventEmitterErrorFunction = (object) => { 4 | // verify attrs 5 | if (object === undefined) { 6 | throw new Error('object is undefined -- cannot execute mixinEventEmitterErrorFunction'); 7 | } 8 | if (!(object instanceof EventEmitter)) { 9 | throw new Error('object is not an EventEmitter -- cannot execute mixinEventEmitterErrorFunction'); 10 | } 11 | // assign error function 12 | object.error = (error, callback) => { 13 | // verify if error is defined 14 | if (error === undefined) { 15 | throw new Error('error is undefined -- cannot execute error'); 16 | } 17 | // execute callback (such as onFailure handler) 18 | if (callback !== undefined) { 19 | callback(error); 20 | return; 21 | } 22 | // if error listener(s) registered, then throw error event 23 | if (object.listeners('error').length > 0) { 24 | object.emit('error', error); 25 | return; 26 | } 27 | // else throw exception 28 | throw new Error(error); 29 | }; 30 | }; 31 | 32 | module.exports.mixinEventEmitterErrorFunction = mixinEventEmitterErrorFunction; 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "stun-js", 3 | "version": "0.7.0", 4 | "description": "STUN (Session Traversal Utilities for NAT) library written entirely in JavaScript", 5 | "main": "index.js", 6 | "keywords": [ 7 | "nat", 8 | "stun", 9 | "udp" 10 | ], 11 | "author": { 12 | "name": "Nico Janssens", 13 | "email": "nico.b.janssens@gmail.com" 14 | }, 15 | "license": "MIT", 16 | "engines": { 17 | "node": ">=6.9.0" 18 | }, 19 | "browser": { 20 | "dgram": "chrome-dgram", 21 | "net": "chrome-net", 22 | "winston": "winston-browser" 23 | }, 24 | "dependencies": { 25 | "args-js": "^0.10.12", 26 | "chrome-dgram": "3.0.1", 27 | "chrome-net": "3.3.0", 28 | "ip": "^1.1.4", 29 | "merge": "^1.2.0", 30 | "q": "1.4.1", 31 | "winston": "^2.3.1", 32 | "winston-browser": "1.0.0", 33 | "winston-debug": "^1.1.0", 34 | "winston-meta-wrapper": "1.2.0" 35 | }, 36 | "devDependencies": { 37 | "babel-preset-es2015": "^6.22.0", 38 | "babelify": "7.3.0", 39 | "browserify": "^14.1.0", 40 | "chai": "3.5.0", 41 | "chai-as-promised": "6.0.0", 42 | "eslint": "^3.19.0", 43 | "eslint-config-airbnb": "^15.0.1", 44 | "eslint-config-airbnb-base": "^11.3.1", 45 | "eslint-plugin-import": "^2.7.0", 46 | "eslint-plugin-jsx-a11y": "^5.0.1", 47 | "eslint-plugin-react": "^7.0.1", 48 | "mocha": "^3.2.0", 49 | "publish": "0.6.0", 50 | "uglify-js": "^2.7.5" 51 | }, 52 | "repository": { 53 | "type": "git", 54 | "url": "git://github.com/microminion/stun-js.git" 55 | }, 56 | "scripts": { 57 | "build": "browserify -s StunClient -e -t [ babelify --global --presets [ es2015 ] ] ./ | uglifyjs -c warnings=false -m > stun.min.js", 58 | "build-debug": "browserify -s StunClient -e ./ > stun.debug.js", 59 | "size": "npm run build && cat stun.min.js | gzip | wc -c", 60 | "test-node": "./node_modules/.bin/mocha test/*.unit.js", 61 | "clean": "rm -f stun.*.js && rm -rf node_modules", 62 | "2npm": "publish" 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /test/attributes.unit.js: -------------------------------------------------------------------------------- 1 | const Attributes = require('../lib/attributes'); 2 | const Packet = require('../lib/packet'); 3 | const chai = require('chai'); 4 | const expect = chai.expect; 5 | 6 | describe('#STUN attributes', () => { 7 | it('should encode and decode an address attribute', done => { 8 | const testAddress = '127.0.0.1'; 9 | const testPort = 2345; 10 | const address = require('../lib/attributes/address'); 11 | const bytes = address.encode(testAddress, testPort); 12 | const decodedAddress = address.decode(bytes); 13 | expect(decodedAddress.family).to.equal(4) 14 | expect(decodedAddress.address).to.exist 15 | expect(decodedAddress.address).to.equal(testAddress) 16 | expect(decodedAddress.port).to.exist 17 | expect(decodedAddress.port).to.equal(testPort) 18 | done() 19 | }) 20 | 21 | it('should encode and decode an alternate-server attribute', done => { 22 | const testAddress = '127.0.0.1'; 23 | const testPort = 2345; 24 | const AlternateServer = Attributes.AlternateServer; 25 | const alternateServer = new AlternateServer(testAddress, testPort); 26 | const bytes = alternateServer.encode(); 27 | const decodedAlternateServer = AlternateServer.decode(bytes.subarray(4, bytes.lenght)); 28 | expect(decodedAlternateServer.address).to.exist 29 | expect(decodedAlternateServer.address).to.equal(testAddress) 30 | expect(decodedAlternateServer.port).to.exist 31 | expect(decodedAlternateServer.port).to.equal(testPort) 32 | done() 33 | }) 34 | 35 | it('should encode and decode an error code attribute', done => { 36 | const testCode = 401; 37 | const ErrorCode = Attributes.ErrorCode; 38 | const errorCode = new ErrorCode(testCode); 39 | const bytes = errorCode.encode(); 40 | const decodedErrorCode = ErrorCode.decode(bytes.subarray(4, bytes.lenght)); 41 | expect(decodedErrorCode.code).to.exist 42 | expect(decodedErrorCode.code).to.equal(testCode) 43 | expect(decodedErrorCode.reason).to.exist 44 | expect(decodedErrorCode.reason).to.equal('Unauthorized') 45 | done() 46 | }) 47 | 48 | it('should encode and decode a mapped-address attribute', done => { 49 | const testAddress = '127.0.0.1'; 50 | const testPort = 2345; 51 | const MappedAddress = Attributes.MappedAddress; 52 | const mappedAddress = new MappedAddress(testAddress, testPort); 53 | const bytes = mappedAddress.encode(); 54 | const decodedMappedAddress = MappedAddress.decode(bytes.subarray(4, bytes.lenght)); 55 | expect(decodedMappedAddress.address).to.exist 56 | expect(decodedMappedAddress.address).to.equal(testAddress) 57 | expect(decodedMappedAddress.port).to.exist 58 | expect(decodedMappedAddress.port).to.equal(testPort) 59 | done() 60 | }) 61 | 62 | it('should encode and decode a message-integrity attribute', done => { 63 | const testRealm = 'test.io'; 64 | const testUser = 'foo'; 65 | const testPwd = 'bar'; 66 | const testPacket = Buffer.from('abcdefghjkl'); 67 | const MessageIntegrity = Attributes.MessageIntegrity; 68 | const messageIntegrity = new MessageIntegrity({ 69 | username: testUser, 70 | password: testPwd, 71 | realm: testRealm 72 | }); 73 | const bytes = messageIntegrity.encode(testPacket); 74 | const decodedMessageIntegrity = MessageIntegrity.decode(bytes.subarray(4, bytes.lenght)); 75 | expect(decodedMessageIntegrity).to.exist 76 | expect(decodedMessageIntegrity.hash).to.exist 77 | done() 78 | }) 79 | 80 | it('should encode and decode a nonce attribute', done => { 81 | const testNonce = 'abcdefg'; 82 | const Nonce = Attributes.Nonce; 83 | const nonce = new Nonce(testNonce); 84 | const bytes = nonce.encode(); 85 | const length = bytes.readUInt16BE(2); 86 | const decodedNonce = Nonce.decode(bytes.subarray(4, 4 + length)); 87 | expect(decodedNonce.value).to.exist 88 | expect(decodedNonce.value).to.equal(testNonce) 89 | done() 90 | }) 91 | 92 | it('should encode and decode a realm attribute', done => { 93 | const testRealm = 'test.io'; 94 | const Realm = Attributes.Realm; 95 | const realm = new Realm(testRealm); 96 | const bytes = realm.encode(); 97 | const length = bytes.readUInt16BE(2); 98 | const decodedRealm = Realm.decode(bytes.subarray(4, 4 + length)); 99 | expect(decodedRealm.value).to.exist 100 | expect(decodedRealm.value).to.equal(testRealm) 101 | done() 102 | }) 103 | 104 | it('should encode and decode a software attribute', done => { 105 | const testDescription = 'my awesome product'; 106 | const Software = Attributes.Software; 107 | const software = new Software(testDescription); 108 | const bytes = software.encode(); 109 | const length = bytes.readUInt16BE(2); 110 | const decodedSoftware = Software.decode(bytes.subarray(4, 4 + length)); 111 | expect(decodedSoftware.description).to.exist 112 | expect(decodedSoftware.description).to.equal(testDescription) 113 | done() 114 | }) 115 | 116 | it('should encode and decode an unknown-attribtes attribute', done => { 117 | // TODO: add test case once encode operation of unknown-attributes is implemented 118 | done() 119 | }) 120 | 121 | it('should encode and decode a username attribute', done => { 122 | const testUser = 'foo'; 123 | const Username = Attributes.Username; 124 | const username = new Username(testUser); 125 | const bytes = username.encode(); 126 | const length = bytes.readUInt16BE(2); 127 | const decodedUsername = Username.decode(bytes.subarray(4, 4 + length)); 128 | expect(decodedUsername.name).to.exist 129 | expect(decodedUsername.name).to.equal(testUser) 130 | done() 131 | }) 132 | 133 | it('should encode and decode an xor-mapped-address attribute', done => { 134 | const testAddress = '127.0.0.1'; 135 | const testPort = 2345; 136 | const tid = Math.random() * Packet.TID_MAX; 137 | const magic = Packet.MAGIC_COOKIE; 138 | const testHeaderBytes = createTestHeaderBytes(magic, tid); 139 | const XORMappedAddress = Attributes.XORMappedAddress; 140 | const xorMappedAddress = new XORMappedAddress(testAddress, testPort); 141 | const bytes = xorMappedAddress.encode(magic, tid); 142 | const decodedXORMappedAddress = XORMappedAddress.decode(bytes.subarray(4, bytes.lenght), testHeaderBytes); 143 | expect(decodedXORMappedAddress.address).to.exist 144 | expect(decodedXORMappedAddress.address).to.equal(testAddress) 145 | expect(decodedXORMappedAddress.port).to.exist 146 | expect(decodedXORMappedAddress.port).to.equal(testPort) 147 | done() 148 | }) 149 | }) 150 | 151 | function createTestHeaderBytes (magic, tid) { 152 | const encodedHeader = Buffer.alloc(Packet.HEADER_LENGTH); 153 | const type = Packet.METHOD.ALLOCATE; 154 | const length = 0; 155 | encodedHeader.writeUInt16BE((type & 0x3fff), 0) 156 | encodedHeader.writeUInt16BE(length, 2) 157 | encodedHeader.writeUInt32BE(magic, 4) 158 | encodedHeader.writeUInt32BE(0, 8) 159 | encodedHeader.writeUInt32BE(0, 12) 160 | encodedHeader.writeUInt32BE(tid, 16) 161 | return encodedHeader 162 | } 163 | -------------------------------------------------------------------------------- /test/packet.unit.js: -------------------------------------------------------------------------------- 1 | const Packet = require('../lib/packet'); 2 | 3 | const chai = require('chai'); 4 | const expect = chai.expect; 5 | 6 | describe('#STUN operations', () => { 7 | it('should encode and decode a binding request', done => { 8 | const packet = new Packet(Packet.METHOD.BINDING, Packet.TYPE.REQUEST); 9 | const data = packet.encode(); 10 | const stunDecoding = Packet.decode(data); 11 | const decodedPacket = stunDecoding.packet; 12 | expect(decodedPacket.method).to.equal(Packet.METHOD.BINDING) 13 | expect(decodedPacket.type).to.equal(Packet.TYPE.REQUEST) 14 | const remainingBytes = stunDecoding.remainingBytes; 15 | expect(remainingBytes.length).to.equal(0) 16 | done() 17 | }) 18 | 19 | it('should encode and decode a binding indication', done => { 20 | const packet = new Packet(Packet.METHOD.BINDING, Packet.TYPE.INDICATION); 21 | const data = packet.encode(); 22 | const stunDecoding = Packet.decode(data); 23 | const decodedPacket = stunDecoding.packet; 24 | expect(decodedPacket.method).to.equal(Packet.METHOD.BINDING) 25 | expect(decodedPacket.type).to.equal(Packet.TYPE.INDICATION) 26 | const remainingBytes = stunDecoding.remainingBytes; 27 | expect(remainingBytes.length).to.equal(0) 28 | done() 29 | }) 30 | }) 31 | -------------------------------------------------------------------------------- /test/stun_client.unit.js: -------------------------------------------------------------------------------- 1 | const dgram = require('dgram'); 2 | const StunClient = require('../lib/stun_client'); 3 | const transports = require('../lib/transports'); 4 | 5 | const winston = require('winston-debug'); 6 | winston.level = 'debug' 7 | 8 | const chai = require('chai'); 9 | const chaiAsPromised = require('chai-as-promised'); 10 | const expect = chai.expect; 11 | chai.use(chaiAsPromised) 12 | chai.should() 13 | 14 | if (!process.env.STUN_ADDR) { 15 | throw new Error('STUN_ADDR undefined -- giving up') 16 | } 17 | if (!process.env.STUN_PORT) { 18 | throw new Error('STUN_PORT undefined -- giving up') 19 | } 20 | 21 | const stunAddr = process.env.STUN_ADDR; 22 | const stunPort = parseInt(process.env.STUN_PORT); 23 | 24 | const socketPort = 20000; 25 | 26 | describe('#STUN operations', function () { 27 | this.timeout(10000) 28 | 29 | it('should execute STUN bind operation over UDP socket using promises', done => { 30 | let retransmissionTimer; 31 | // send a STUN bind request and verify the reply 32 | const sendBindRequest = (client, socket) => { 33 | client.bindP() 34 | .then(mappedAddress => { 35 | // end retransmissionTimer 36 | clearTimeout(retransmissionTimer) 37 | // verify the mapped address 38 | expect(mappedAddress).not.to.be.undefined 39 | expect(mappedAddress).to.have.property('address') 40 | expect(mappedAddress).to.have.property('port') 41 | return client.closeP() 42 | }) 43 | .then(() => { 44 | // check the socket's event listeners (should not include any STUN client handler) 45 | expect(socket.listeners('message').length).to.equal(1) 46 | expect(socket.listeners('error').length).to.equal(1) 47 | // close socket 48 | socket.close(() => { 49 | done() 50 | }) 51 | }) 52 | .catch(error => { 53 | done(error) 54 | }) 55 | }; 56 | // create socket 57 | const socket = dgram.createSocket('udp4'); 58 | socket.on('message', (message, rinfo) => { // 59 | done(new Error('message callback should not be fired')) 60 | }) 61 | socket.on('error', error => { 62 | done(error) 63 | }) 64 | socket.on('listening', () => { 65 | // create stun client and pass socket over 66 | const transport = new transports.UDP(socket); 67 | const client = new StunClient(stunAddr, stunPort, transport); 68 | client.init(() => { 69 | // retransmission timer -- we're using UDP ... 70 | retransmissionTimer = setTimeout(() => { 71 | console.log('resending BIND request') 72 | sendBindRequest(client, socket) 73 | }, 3000) 74 | // bind request 75 | sendBindRequest(client, socket) 76 | }) 77 | }) 78 | socket.bind(socketPort) 79 | }) 80 | 81 | it('should execute STUN bind operation over UDP socket using promises + un-existing server', done => { 82 | let retransmissionTimer; 83 | // send a STUN bind request and verify the reply 84 | const sendBindRequest = (client, socket) => { 85 | client.bindP() 86 | .then(() => { 87 | done(new Error('promise should not resolve')) 88 | }) 89 | .catch(error => { 90 | expect(error).not.to.be.undefined 91 | done() 92 | }) 93 | }; 94 | // create socket 95 | const socket = dgram.createSocket('udp4'); 96 | socket.on('message', (message, rinfo) => { // 97 | done(new Error('message callback should not be fired')) 98 | }) 99 | socket.on('error', error => { 100 | done(error) 101 | }) 102 | socket.on('listening', () => { 103 | // create stun client and pass socket over 104 | const transport = new transports.UDP(socket); 105 | const client = new StunClient('1.2.3.4', stunPort, transport); 106 | client.init(() => { 107 | // bind request 108 | sendBindRequest(client, socket) 109 | }) 110 | }) 111 | socket.bind(socketPort) 112 | }) 113 | 114 | it('should execute STUN bind operation over TCP socket using callbacks', done => { 115 | const transport = new transports.TCP(); 116 | const client = new StunClient(stunAddr, stunPort, transport); 117 | // if something fails 118 | const onFailure = error => { 119 | done(error) 120 | }; 121 | // check bind results 122 | const onBindSuccess = mappedAddress => { 123 | expect(mappedAddress).not.to.be.undefined 124 | expect(mappedAddress).to.have.property('address') 125 | expect(mappedAddress).to.have.property('port') 126 | // expect(mappedAddress.address).to.equal(testGW) 127 | client.close(() => { 128 | done() 129 | }) 130 | }; 131 | // execute bind operation 132 | client.init(() => { 133 | client.bind(onBindSuccess, onFailure) 134 | }) 135 | }) 136 | 137 | it('should execute multiple concurrent STUN bind operations over TCP sockets using callbacks', done => { 138 | const nbClients = 10; 139 | const clients = []; 140 | let nbBindSuccesses = 0; 141 | let nbClientsClosed = 0; 142 | 143 | const createClient = () => { 144 | const transport = new transports.TCP(); 145 | const client = new StunClient(stunAddr, stunPort, transport); 146 | // if something fails 147 | const onFailure = error => { 148 | done(error) 149 | }; 150 | // check bind results 151 | const onBindSuccess = mappedAddress => { 152 | expect(mappedAddress).not.to.be.undefined 153 | expect(mappedAddress).to.have.property('address') 154 | expect(mappedAddress).to.have.property('port') 155 | nbBindSuccesses++ 156 | if (nbBindSuccesses === nbClients) { 157 | closeAllClients() 158 | } 159 | }; 160 | // execute bind operation 161 | client.init(() => { 162 | client.bind(onBindSuccess, onFailure) 163 | }) 164 | // store client ref 165 | clients.push(client) 166 | }; 167 | 168 | var closeAllClients = () => { 169 | clients.forEach(client => { 170 | client.close(() => { 171 | nbClientsClosed++ 172 | if (nbClientsClosed === nbClients) { 173 | done() 174 | } 175 | }) 176 | }) 177 | } 178 | 179 | for (let i = 0; i < nbClients; i++) { 180 | createClient() 181 | } 182 | }) 183 | 184 | it('should execute multiple concurrent STUN bind operations over UDP sockets using callbacks', done => { 185 | const nbClients = 10; 186 | const clients = []; 187 | let nbBindSuccesses = 0; 188 | let nbClientsClosed = 0; 189 | 190 | const createClient = () => { 191 | const transport = new transports.UDP(); 192 | const client = new StunClient(stunAddr, stunPort, transport); 193 | // if something fails 194 | const onFailure = error => { 195 | done(error) 196 | }; 197 | // check bind results 198 | const onBindSuccess = mappedAddress => { 199 | expect(mappedAddress).not.to.be.undefined 200 | expect(mappedAddress).to.have.property('address') 201 | expect(mappedAddress).to.have.property('port') 202 | nbBindSuccesses++ 203 | if (nbBindSuccesses === nbClients) { 204 | closeAllClients() 205 | } 206 | }; 207 | // execute bind operation 208 | client.init(() => { 209 | client.bind(onBindSuccess, onFailure) 210 | }) 211 | // store client ref 212 | clients.push(client) 213 | }; 214 | 215 | var closeAllClients = () => { 216 | clients.forEach(client => { 217 | client.close(() => { 218 | nbClientsClosed++ 219 | if (nbClientsClosed === nbClients) { 220 | done() 221 | } 222 | }) 223 | }) 224 | } 225 | 226 | for (let i = 0; i < nbClients; i++) { 227 | createClient() 228 | } 229 | }) 230 | 231 | it('should execute STUN bind operation over TCP socket using callbacks + un-existing server', done => { 232 | const transport = new transports.TCP(); 233 | const client = new StunClient('1.2.3.4', stunPort, transport); 234 | // execute bind operation 235 | client.init(() => { 236 | done('did not expect init operation to succeed') 237 | }, error => { 238 | expect(error.message).to.be.a('string') 239 | expect(error.message).to.include('TCP connection timeout') 240 | done() 241 | }) 242 | }) 243 | 244 | it('should execute STUN bind operation over unspecified UDP socket using promises', done => { 245 | let retransmissionTimer; 246 | // send a STUN bind request and verify the reply 247 | const sendBindRequest = client => { 248 | client.bindP() 249 | .then(mappedAddress => { 250 | // end retransmissionTimer 251 | clearTimeout(retransmissionTimer) 252 | // verify the mapped address 253 | expect(mappedAddress).not.to.be.undefined 254 | expect(mappedAddress).to.have.property('address') 255 | expect(mappedAddress).to.have.property('port') 256 | return client.closeP() 257 | }) 258 | .then(() => { 259 | done() 260 | }) 261 | .catch(error => { 262 | done(error) 263 | }) 264 | }; 265 | // create stun client and pass socket over 266 | const client = new StunClient(stunAddr, stunPort); 267 | client.init(() => { 268 | // retransmission timer -- we're using UDP ... 269 | retransmissionTimer = setTimeout(() => { 270 | console.log('resending BIND request') 271 | sendBindRequest(client) 272 | }, 3000) 273 | // bind request 274 | sendBindRequest(client) 275 | }) 276 | }) 277 | }) 278 | --------------------------------------------------------------------------------