-
Notifications
You must be signed in to change notification settings - Fork 15
/
DtlsServer.js
66 lines (45 loc) · 1.65 KB
/
DtlsServer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"use strict";
var log = require( 'logg' ).getLogger( 'dtls.DtlsServer' );
var util = require( 'util' );
var EventEmitter = require( 'events' ).EventEmitter;
var DtlsSocket = require( './DtlsSocket' );
var KeyContext = require( './KeyContext' );
var DtlsServer = function( dgramSocket, options ) {
this.dgram = dgramSocket;
this.keyContext = new KeyContext( options );
this.sockets = {};
this.dgram.on( 'message', this._onMessage.bind( this ) );
};
util.inherits( DtlsServer, EventEmitter );
DtlsServer.createServer = function( options, callback ) {
var dgram = require( 'dgram' );
var dgramSocket = dgram.createSocket( options );
var dtlsServer = new DtlsServer( dgramSocket, options );
if( callback )
dtlsServer.on( 'message', callback );
return dtlsServer;
};
DtlsServer.prototype.close = function() {
this.dgram.close();
};
DtlsServer.prototype.bind = function( port ) {
if( !this.keyContext )
throw new Error(
'Cannot act as a server without a certificate. ' +
'Use options.cert to specify certificate.' );
this.dgram.bind( port );
};
DtlsServer.prototype._onMessage = function( message, rinfo ) {
var socketKey = rinfo.address + ':' + rinfo.port;
var socket = this.sockets[ socketKey ];
if( !socket ) {
this.sockets[ socketKey ] = socket =
new DtlsSocket( this.dgram, rinfo, this.keyContext, true );
socket.once( 'secureConnect', function( socket ) {
log.info( 'Handshake done' );
this.emit( 'secureConnection', socket );
}.bind( this ));
}
socket.handle( message );
};
module.exports = DtlsServer;