jue89 / node-openssl-dtls

DTLS1.2 bindings for node.js
MIT License
11 stars 6 forks source link

feat: add getPeer per rinfo #6

Open nicgirault opened 7 months ago

nicgirault commented 7 months ago

In order to use this package as a proxy without opening one backend socket per peer (and thus make the proxy scale above the number of available ports), being able to access peers per socket remote info is needed.

Here is the code I am writing in order to integrate this project with https://github.com/coapjs/node-coap (see https://github.com/coapjs/node-coap/issues/253) and where we see this need of the method added in the pull request:

import { createServer } from "openssl-dtls"
import { EventEmitter } from "events"

export class DTLSSocket extends EventEmitter {
  constructor(options) {
    super()
    this.dtlsServer = createServer(options)

    this.dtlsServer.on("secureConnection", peer => {
      peer.on("message", msg => {
        this.emit("message", msg, peer.address())
      })
    })
  }

  send(message, port, host, callback) {
    // here I duplicate https://github.com/jue89/node-openssl-dtls/blob/7e16a03d504d72d0d7027a7111e6a21f79ca3692/server.js#L51
    const key = `${host} ${port}`
    const peer = this.dtlsServer.peers[key]

    if (peer) {
      peer.send(message)
      callback()
    } else {
      callback(new Error('No client connection stored at this address'))
    }
  }
}