+ /* Handle all messages from host */
+ sock.on('message', (hostMessage) => {
+ hostMessage = JSON.parse(hostMessage)
+ response = newRoute.clients.get(hostMessage['clientPubKey'])
+
+ /* If the host response is a answer */
+ if (hostMessage['cmd'].localeCompare('< sdp pubKey') === 0) {
+ console.log('Server: Sending host answer to client')
+ response.writeHead(200, { 'Content-Type': 'application/json' })
+ response.write(JSON.stringify(hostMessage))
+ response.end()
+ }
+ else if (hostMessage['cmd'].localeCompare('< ice pubKey') === 0){
+ /* if the host response is an ice candidate */
+ console.log('Server: Handling host ICE message')
+ let iceState = hostMessage['iceState']
+ /* If there are any ice candidates, send them back */
+ switch(iceState) {
+ case "a":
+ response.writeHead('200', {'x-strapp-type': 'ice-candidate-available'})
+ response.write(JSON.stringify(hostMessage))
+ response.end()
+ break
+ case "g":
+ console.log('Server: Host is still gathering candidates, keep trying')
+ response.writeHead('200', {'x-strapp-type': 'ice-state-gathering'})
+ response.write(JSON.stringify(hostMessage))
+ response.end()
+ break
+ case "c":
+ console.log('Server: Host has completed gathering candidates')
+ response.writeHead('200', {'x-strapp-type': 'ice-state-complete'})
+ response.write(JSON.stringify(hostMessage))
+ response.end()
+ break
+ default:
+ console.log('unhandled iceState from host')
+ break
+ }
+ }
+
+ })
+ })
+
+ console.log(`Listening for websocket ${newRoute.host} on port ${newRoute.port}`)
+ router.routes[routeName] = newRoute
+ }).then(() => {
+ response.writeHead(200, { 'Content-Type': 'text/html' })
+ response.write(`${router.skelPage[0]}` +
+ `\tconst _strapp_port = ${newRoute.port}\n` +
+ `\tconst _strapp_protocol = '${router.wsProtocol}'\n` +
+ `${router.hostJS}\n${router.skelPage[1]}`)
+ response.end()
+ })
+ }
+
+
+ }
+ }
+
+ /**
+ * @summary Boot up the router. With TLS, we must wait for file reads to sync.
+ */
+ if (!opts['no-tls']) {
+ console.log('tls')
+ let filesRead = 0
+ let key = undefined
+ let cert = undefined
+ const syncRead = () => {
+ if (++filesRead == 2) {
+ if (key == undefined)
+ console.log(`ERR: Key ${opts['ca-key']} inaccessible, tls will fail`)
+ if(cert == undefined)
+ console.log(`ERR: Cert ${opts['ca-cert']} inaccessible, tls will fail`)
+ else if (key != undefined) {
+ router.httpsOpts = { cert: cert, key: key}
+ router.httpd = https.createServer(router.httpsOpts, router.respond)
+ .listen(opts['port'])
+ }
+ }
+ }
+ fs.readFile(opts['ca-key'], { encoding: 'utf8' }, (err, data) => {
+ if (!err) key = data
+ syncRead()
+ })
+ fs.readFile(opts['ca-cert'], { encoding: 'utf8' }, (err, data) => {
+ if (!err) cert = data
+ syncRead()
+ })
+ }
+ else
+ router.httpd = http.createServer(router.respond).listen(opts['port'])