sdp offer from client is incorrect somehow
authorjordan lavatai <jordanlavatai@gmail.com>
Wed, 12 Jul 2017 19:10:46 +0000 (12:10 -0700)
committerjordan lavatai <jordanlavatai@gmail.com>
Wed, 12 Jul 2017 19:10:46 +0000 (12:10 -0700)
client-test.js [new file with mode: 0644]
client.js
host-test.js [new file with mode: 0644]
host.js
opts.js
router.js

diff --git a/client-test.js b/client-test.js
new file mode 100644 (file)
index 0000000..503ac14
--- /dev/null
@@ -0,0 +1,222 @@
+const body = document.createElement('body')
+const root = document.createElement('div')
+document.title = "Strapp.io Client"
+const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
+
+/* TODO: This is duplicated in both client.js and host.js */
+function getPublicKey() {
+  return new Promise( (resolve, reject) => {
+    /* Check local storage for public key */
+    if (!window.localStorage.getItem('public-key')) {
+      /* If doesn't exist, generate public and private key pair, store in
+      local storage */
+      crypto.subtle.generateKey(
+        { name:'RSA-OAEP',
+        modulusLength: 2048,
+        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+        hash: {name: "SHA-256"}
+      },
+      true,
+      ['encrypt', 'decrypt']
+    ).then((keyPair) => {
+      /* TODO: Do we need to store the private key as well? */
+      crypto.subtle.exportKey('jwk', keyPair.publicKey)
+      .then((exportedKey) => {
+        window.localStorage.setItem('publicKey', exportedKey)
+        console.log('public key is' + window.localStorage.getItem('publicKey'))
+        resolve(exportedKey)
+      })
+
+    })
+  }
+  else {
+    resolve(window.localStorage.getItem('publicKey'))
+  }
+})
+
+}
+
+function sendHost(url, data) {
+  const request = new XMLHttpRequest()
+  request.open('POST', url, true)
+  request.setRequestHeader('Content-Type', 'application/json' )
+  request.setRequestHeader('X-Strapp-Type', 'ice-candidate-submission')
+  request.send(data)
+}
+
+/* Poll the server. Send get request, wait for timeout, send another request.
+Do this until...? Can be used for either reconnecting or waiting for answer*/
+function requestHostAnswer(url, data) {
+  return new Promise((resolve, reject) => {
+    const request = new XMLHttpRequest()
+    request.open('GET', url, true)
+    /* But there is no JSON? */
+    request.setRequestHeader('Content-Type', 'application/json' )
+    request.setRequestHeader('X-Strapp-Type', 'client-sdp-offer')
+    request.setRequestHeader('X-Strapp-Pubkey', data.pubKey)
+    request.setRequestHeader('X-Strapp-Offer', JSON.stringify(data.sdp))
+    request.onreadystatechange = () => {
+      if (request.status === 200) {
+        if(request.readyState === 4) {
+          console.log('Client: Recieved Answer from Host')
+          console.log(request)
+          resolve(request.response)
+        }
+      }
+      else if (request.status === 504) {
+        console.log('timed out, resending')
+        resolve(requestHostAnswer(url, data))
+      }
+      else {
+        reject('server unhandled response of status ' + request.status)
+      }
+    }
+    request.send()
+  })
+}
+
+/* Poll server for ice candidates until ice is complete */
+function requestHostICE(cpc, url, pubKey) {
+  let intervalID = window.setInterval(() => {
+    if (cpc.iceConnectionState.localeCompare('connected') !== 0
+    && cpc.iceConnectionState.localeCompare('completed') !== 0) {
+      console.log('Client: Polling server begin for intervalID = ' + intervalID)
+      console.log('Client: Requesting ICE Candidates from server')
+      const request = new XMLHttpRequest()
+      request.open('GET', url, true)
+      request.setRequestHeader('Content-Type', 'application/json' )
+      request.setRequestHeader('X-Strapp-Type', 'ice-candidate-request')
+      request.setRequestHeader('X-client-pubkey', pubKey)
+      request.onreadystatechange = () => {
+        if (request.status === 200) {
+          if(request.readyState === 4) {
+            console.log('Client: Recieved ICE response from Host')
+            let response = JSON.parse(request.response)
+            switch(response['iceState']) {
+              case "a":
+              cpc.addIceCandidate(new RTCIceCandidate(response.ice))
+              break
+              case "g": /* Gathering so let interval keep polling */
+              break
+              case "c": /* host iceState == Complete, stop bugging it */
+              clearInterval(intervalID)
+              clearTimeout()
+              break
+              default:
+              console.log('Unhandled iceState in requestHostICE()' + response['iceState'])
+              break
+            }
+          }
+        }
+        else {
+          console.log('server unhandled response of status ' + request.status)
+          clearInterval(intervalID)
+        }
+      }
+      request.send()
+    }
+    else {
+      clearTimeout()
+      clearInterval(intervalID)
+    }
+  }, 5000)
+}
+
+/* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */
+getPublicKey().then((cpk) => {
+  let dataChannel
+  console.log('Client: Create and send offer')
+  const cpc = new RTCPeerConnection(conf)
+
+  cpc.oniceconnectionstatechange = () => {
+    console.log('iceConnectionState = ' + cpc.iceConnectionState)
+  }
+
+  cpc.onnegotiationneeded = () => {
+    console.log('negotiation needed!')
+    cpc.createOffer().then((offer) => {
+      return cpc.setLocalDescription(offer)
+    })
+    .then(() => {
+      console.log('Client: Sending offer to host')
+      let offer = {
+        cmd: '> sdp pubKey',
+        sdp: cpc.localDescription,
+        pubKey: cpk.n
+      }
+      console.log(offer)
+      return requestHostAnswer(window.location, offer)
+    })
+    .then((serverResponse) => {
+      const answer = JSON.parse(serverResponse)
+      console.log('Client: Polling for ICE candidates')
+      requestHostICE(cpc, window.location, cpk.n)
+      cpc.setRemoteDescription(answer.sdp)
+      cpc.onicecandidate = (event) => {
+        if (event.candidate) {
+          console.log('Client: Sending ice candidate to host')
+          sendHost(window.location, JSON.stringify({
+            cmd: '> ice pubkey',
+            ice: event.candidate,
+            pubKey: cpk.n
+          }))
+        }
+        else {
+          console.log('Client: No more Ice Candidates to send')
+        }
+      }
+
+
+    }).catch( (err) => {
+      console.log('error in sdp handshake: ' + err)
+    })
+  }
+  /* Start data channel, triggers on negotiation needed */
+  dataChannel = cpc.createDataChannel("sendChannel");
+
+  /* Triggered when Host adds track to peer connection */
+  cpc.ontrack = (event) => {
+    let remoteRTPReceivers = cpc.getReceivers()
+    let hostScreen
+    let video = document.querySelector('video')
+    /* TODO: Audio, video, or other track? */
+    console.log(remoteRTPReceivers)
+    console.log(video)
+    hostScreen = new MediaStream([remoteRTPReceivers[0].track])
+    if(!video.srcObject) {
+      video.srcObject = hostScreen
+    }
+    console.log(hostScreen.getVideoTracks())
+    console.log(video.srcObject)
+    video.onloadedmetadata = () => {
+      video.play()
+    }
+  }
+
+  dataChannel.onmessage = (msg) => {
+    /* Get mediaStream from host and add it to the video */
+    let hostMessage = JSON.parse(msg.data)
+    console.log('Client: Renego')
+    cpc.setRemoteDescription(hostMessage.sdp).then(() => {
+      cpc.createAnswer().then((answer) => {
+        return cpc.setLocalDescription(answer)
+      }).then(() => {
+        dataChannel.send(JSON.stringify({
+          "cmd": "> screen dataChannel",
+          "sdp": cpc.localDescription
+        }))
+      })
+    })
+
+
+  }
+  dataChannel.onopen = () => {
+    document.body.innerHTML = (`<div><button> Connection with host established! </button></div> <video controls></video>`)
+  }
+
+})
+document.addEventListener('DOMContentLoaded', () => {
+
+  document.body.innerHTML = `<button> Setting up connection with host  </button>`
+
+});
index 160d5dd..4d1bf9a 100644 (file)
--- a/client.js
+++ b/client.js
@@ -2,10 +2,8 @@ const body = document.createElement('body')
 const root = document.createElement('div')\r
 document.title = "Strapp.io Client"\r
 const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }\r
-let dataChannel\r
-let hostScreen\r
 \r
-/* TODO: duplicate in both client.js and host.js */\r
+/* TODO: This is duplicated in both client.js and host.js */\r
 function getPublicKey() {\r
   return new Promise( (resolve, reject) => {\r
     /* Check local storage for public key */\r
@@ -55,7 +53,7 @@ function requestHostAnswer(url, data) {
     /* But there is no JSON? */\r
     request.setRequestHeader('Content-Type', 'application/json' )\r
     request.setRequestHeader('X-Strapp-Type', 'client-sdp-offer')\r
-    request.setRequestHeader('X-Client-Offer', JSON.stringify(data))\r
+    request.setRequestHeader('X-Strapp-Pubkey', data.pubKey)\r
     request.onreadystatechange = () => {\r
       if (request.status === 200) {\r
         if(request.readyState === 4) {\r
@@ -72,7 +70,7 @@ function requestHostAnswer(url, data) {
         reject('server unhandled response of status ' + request.status)\r
       }\r
     }\r
-    request.send()\r
+    request.send(data)\r
   })\r
 }\r
 \r
@@ -125,6 +123,7 @@ function requestHostICE(cpc, url, pubKey) {
 \r
 /* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */\r
 getPublicKey().then((cpk) => {\r
+  let dataChannel\r
   console.log('Client: Create and send offer')\r
   const cpc = new RTCPeerConnection(conf)\r
 \r
@@ -170,16 +169,16 @@ getPublicKey().then((cpk) => {
       console.log('error in sdp handshake: ' + err)\r
     })\r
   }\r
-  /* Start data channel */\r
+  /* Start data channel, triggers on negotiation needed */\r
   dataChannel = cpc.createDataChannel("sendChannel");\r
+\r
+  /* Triggered when Host adds track to peer connection */\r
   cpc.ontrack = (event) => {\r
-    console.log(`track event is ${event}`)\r
-    let remoteRTPSenders = cpc.getSenders()\r
     let remoteRTPReceivers = cpc.getReceivers()\r
-    console.log(remoteRTPReceivers)\r
-    /* Add each remoteRTPSenders.track to own stream */\r
+    let hostScreen\r
     let video = document.querySelector('video')\r
-    video.autoplay = true\r
+    /* TODO: Audio, video, or other track? */\r
+    console.log(remoteRTPReceivers)\r
     console.log(video)\r
     hostScreen = new MediaStream([remoteRTPReceivers[0].track])\r
     if(!video.srcObject) {\r
@@ -187,14 +186,15 @@ getPublicKey().then((cpk) => {
     }\r
     console.log(hostScreen.getVideoTracks())\r
     console.log(video.srcObject)\r
-    video.play()\r
     video.onloadedmetadata = () => {\r
       video.play()\r
     }\r
   }\r
+\r
   dataChannel.onmessage = (msg) => {\r
     /* Get mediaStream from host and add it to the video */\r
     let hostMessage = JSON.parse(msg.data)\r
+    console.log('Client: Renego')\r
     cpc.setRemoteDescription(hostMessage.sdp).then(() => {\r
       cpc.createAnswer().then((answer) => {\r
         return cpc.setLocalDescription(answer)\r
diff --git a/host-test.js b/host-test.js
new file mode 100644 (file)
index 0000000..9c9fe56
--- /dev/null
@@ -0,0 +1,233 @@
+document.title = "Strapp.io Host"
+
+
+const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
+const clients = new Map([])
+const iceCandidates = []
+let dataChannel
+let screenStream /* TODO: Remove if can access localStreams */
+let tracks = []
+let hpk
+
+/* TODO: duplicate in both client.js and host.jhs */
+function getPublicKey() {
+  return new Promise( (resolve, reject) => {
+    /* Check local storage for public key */
+    if (!window.localStorage.getItem('public-key')) {
+      console.log('public key is undefined')
+      /* If doesn't exist, generate public and private key pair, store in
+      local storage */
+      crypto.subtle.generateKey(
+        { name:'RSA-OAEP',
+        modulusLength: 2048,
+        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+        hash: {name: "SHA-256"}
+      },
+      true,
+      ['encrypt', 'decrypt']
+    ).then((keyPair) => {
+      /* TODO: Do we need to store the private key as well? */
+      crypto.subtle.exportKey('jwk', keyPair.publicKey)
+      .then((exportedKey) => {
+        window.localStorage.setItem('publicKey', exportedKey)
+        console.log('public key is' + window.localStorage.getItem('publicKey'))
+        resolve(exportedKey)
+      })
+
+    })
+  }
+  else {
+    resolve(window.localStorage.getItem('publicKey'))
+    }
+  })
+}
+
+function sendClientICE(clientPubKey, hostPubKey, iceCandidate) {
+  console.log('Host: Allocating ice candidate for client')
+  console.log(iceCandidate)
+  iceCandidates.push(JSON.stringify({
+    cmd: "< ice pubKey",
+    ice: iceCandidate,
+    hostPubKey: hostPubKey, /* TODO: do we need to send this? */
+    clientPubKey: clientPubKey,
+    iceState: "a"
+  }))
+}
+
+function handleNewClientConnection(pubKey, sdpOffer) {
+  /* New Client Connection*/
+  hpc = new RTCPeerConnection(conf)
+  console.log('handleNewClientConnections()')
+  console.log(sdpOffer)
+  clients.set(pubKey, hpc)
+  console.log(pubKey)
+  hpc.setRemoteDescription(sdpOffer)
+  .then(() => {
+    hpc.createAnswer().then((answer) => {
+      return hpc.setLocalDescription(answer)
+    })
+    .then(() => {
+
+      hpc.onicecandidate = (event) => {
+        if (event.candidate) {
+          sendClientICE(pubKey, hpk.n, event.candidate)
+        }
+        else {
+          console.log('Host: Finished allocating ICE candidates')
+        }
+      }
+      console.log('Host: Sending answer to Client ')
+      wsock.send(JSON.stringify({
+        cmd: '< sdp pubKey',
+        sdp: hpc.localDescription,
+        hostPubKey: hpk.n,
+        clientPubKey: pubKey
+      }))
+
+    }).catch((err) => {
+      console.log(`error in host answer ${err}`)
+    })
+  }).catch((error) => {
+    console.log(`error in setRemoteDescription ${error}`)
+  })
+  hpc.oniceconnectionstatechange = () => {
+    console.log('iceConnectionState = ' + hpc.iceConnectionState)
+  }
+  hpc.ondatachannel = (evt) => {
+    dataChannel = evt.channel
+    dataChannel.onmessage = (msg) => {
+      let clientMessage = JSON.parse(msg.data)
+      console.log(`client message is ${clientMessage}`)
+      hpc.setRemoteDescription(clientMessage.sdp).then(() => {
+        console.log('should be streaming now')
+      })
+    }
+    dataChannel.onopen = () => {
+      /* If !screenStream, gUM */
+      screenStream.getTracks().forEach( (track) => {
+        hpc.addTrack(track, screenStream)
+      })
+      console.log(hpc.getSenders())
+      /* Create offer */
+      hpc.createOffer().then((offer) => {
+        return hpc.setLocalDescription(offer)
+      }).then( () => {
+        dataChannel.send(JSON.stringify({
+          "cmd": "< screen dataChannel",
+          "sdp": hpc.localDescription,
+          "pubKey": hpc['hpk'].n
+        }))
+      })
+    }
+  }
+  hpc.onnegotiationneeded = () => {
+    console.log('negotiation needed')
+  }
+
+}
+
+function handleNewIceCandidate(msg) {
+  console.log('Host: Adding new ice candidate')
+  const hpc = clients.get(msg.pubKey)
+  let candidate = new RTCIceCandidate(msg.ice)
+  hpc.addIceCandidate(candidate)
+}
+
+function handleIceRequest(msg) {
+  console.log('Host: Handling ice candidate request')
+  console.log(iceCandidates)
+  const hpc = clients.get(msg.pubKey)
+  const iceCandidate = iceCandidates.pop()
+  if (iceCandidate !== undefined) {
+    wsock.send(iceCandidate)
+  } else {
+    if (hpc.iceGatheringState.localeCompare('gathering') === 0) {
+      wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "g"}`)
+    }
+    else if (hpc.iceGatheringState.localeCompare('complete') === 0) {
+      wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "c"}`)
+    }
+
+  }
+
+}
+if ("WebSocket" in window) {
+  document.addEventListener('DOMContentLoaded', (event) => {
+    document.body.innerHTML = '<div>Choose options for client</div> <video autoplay></video>'
+    navigator.mediaDevices.getUserMedia({
+        video : { mediaSource: "screen",
+        width: {max: '1920'},
+        height: {max: '1080'},
+        frameRate: {max: '10'}} })
+    .then(function(mediaStream) {
+      let video = document.querySelector('video')
+      screenStream = mediaStream
+      console.log(mediaStream)
+      video.srcObject = mediaStream
+      console.log('Grabbed media')
+      video.onloadedmetadata = function(e) {
+        console.log(e)
+        video.play()
+      }
+    })
+    .catch(function(err) {
+      document.body.innerHTML = 'Help me help you. Reload the page and allow screen sharing!'
+      console.log(err);
+    }); // always check for errors at the end.
+
+    getPublicKey()
+    .then((hpkVal) => {
+      hpk = hpkVal
+    })
+    wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
+    wsock.onopen = () => {
+      console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
+    }
+
+    wsock.onmessage = (serverMsg) => {
+      /* msg is either offer or ice candidate or ice candidate request*/
+
+      /* What if data null? */
+      console.log(`serverMsg = ${serverMsg.data}`)
+
+      let msg = serverMsg.data.split(' ')
+      let clientID = msg[0]
+      let type =  msg[1]
+      let data = JSON.parse(msg.splice(2).join())
+
+      if (clients.has(clientID)) {
+        switch (type) {
+          case 'ice-candidate-submission':
+            handleNewIceCandidate(msg)
+            break
+          case 'ice-candidate-request':
+            handleIceRequest(msg)
+            break
+          case 'client-sdp-offer':
+            //repeatedoffer shouldnt happen here
+      }
+      }
+      else {
+        switch (type) {
+          case 'client-sdp-offer':
+            handleNewClientConnection(clientID, data)
+            break
+          case 'ice-candidate-request':
+            handleIceRequest()
+            break
+          case 'ice-candidate-submission':
+            handleNewIceCandidate
+            break
+        }
+      }
+    }
+
+
+
+  })
+}
+else {
+  document.addEventListener('DOMContentLoaded', () => {
+    document.body.innerHTML = 'Websockets not supported in your browser'
+  })
+}
diff --git a/host.js b/host.js
index d280812..1e47380 100644 (file)
--- a/host.js
+++ b/host.js
@@ -7,7 +7,7 @@ const iceCandidates = []
 let dataChannel\r
 let screenStream /* TODO: Remove if can access localStreams */\r
 let tracks = []\r
-\r
+let hpk\r
 \r
 /* TODO: duplicate in both client.js and host.jhs */\r
 function getPublicKey() {\r
@@ -42,44 +42,47 @@ function getPublicKey() {
   })\r
 }\r
 \r
+function sendClientICE(clientPubKey, hostPubKey, iceCandidate) {\r
+  console.log('Host: Allocating ice candidate for client')\r
+  console.log(iceCandidate)\r
+  iceCandidates.push(JSON.stringify({\r
+    cmd: "< ice pubKey",\r
+    ice: iceCandidate,\r
+    hostPubKey: hostPubKey, /* TODO: do we need to send this? */\r
+    clientPubKey: clientPubKey,\r
+    iceState: "a"\r
+  }))\r
+}\r
+\r
 function handleNewClientConnection(offer) {\r
   /* New Client Connection*/\r
   hpc = new RTCPeerConnection(conf)\r
   //console.log(offer)\r
   clients.set(offer.pubKey, hpc)\r
+  console.log(offer.sdp)\r
   hpc.setRemoteDescription(offer.sdp)\r
   .then(() => {\r
     hpc.createAnswer().then((answer) => {\r
       return hpc.setLocalDescription(answer)\r
     })\r
     .then(() => {\r
-      getPublicKey().then((hpk) => {\r
-        hpc['hpk'] = hpk\r
-        hpc.onicecandidate = (event) => {\r
-          if (event.candidate) {\r
-            console.log('Host: Allocating ice candidate for client')\r
-            iceCandidates.push(JSON.stringify({\r
-              cmd: "< ice pubKey",\r
-              ice: event.candidate,\r
-              hostPubKey: hpk.n, /* TODO: do we need to send this? */\r
-              clientPubKey: offer.pubKey,\r
-              iceState: "a"\r
-            }))\r
-          }\r
-          else {\r
-            console.log('Host: Finished sending ICE candidates')\r
-          }\r
-        }\r
-        console.log('Host: Sending answer to Client ')\r
-        wsock.send(JSON.stringify({\r
-          cmd: '< sdp pubKey',\r
-          sdp: hpc.localDescription,\r
-          hostPubKey: hpk.n,\r
-          clientPubKey: offer.pubKey\r
-        }))\r
 \r
+      hpc.onicecandidate = (event) => {\r
+        if (event.candidate) {\r
+          sendClientICE(offer.pubKey, hpk.n, event.candidate)\r
+        }\r
+        else {\r
+          console.log('Host: Finished allocating ICE candidates')\r
+        }\r
+      }\r
+      console.log('Host: Sending answer to Client ')\r
+      wsock.send(JSON.stringify({\r
+        cmd: '< sdp pubKey',\r
+        sdp: hpc.localDescription,\r
+        hostPubKey: hpk.n,\r
+        clientPubKey: offer.pubKey\r
+      }))\r
 \r
-      })\r
     }).catch((err) => {\r
       console.log(`error in host answer ${err}`)\r
     })\r
@@ -91,12 +94,13 @@ function handleNewClientConnection(offer) {
     dataChannel = evt.channel\r
     dataChannel.onmessage = (msg) => {\r
       let clientMessage = JSON.parse(msg.data)\r
-      console.log(clientMessage)\r
+      console.log(`client message is ${clientMessage}`)\r
       hpc.setRemoteDescription(clientMessage.sdp).then(() => {\r
         console.log('should be streaming now')\r
       })\r
     }\r
     dataChannel.onopen = () => {\r
+      /* If !screenStream, gUM */\r
       screenStream.getTracks().forEach( (track) => {\r
         hpc.addTrack(track, screenStream)\r
       })\r
@@ -168,6 +172,10 @@ if ("WebSocket" in window) {
       console.log(err);\r
     }); // always check for errors at the end.\r
 \r
+    getPublicKey()\r
+    .then((hpkVal) => {\r
+      hpk = hpkVal\r
+    })\r
     wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)\r
     wsock.onopen = () => {\r
       console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)\r
@@ -177,6 +185,7 @@ if ("WebSocket" in window) {
       /* msg is either offer or ice candidate or ice candidate request*/\r
 \r
       /* What if data null? */\r
+      console.log(`serverMsg = ${serverMsg.data}`)\r
       let msg = JSON.parse(serverMsg.data)\r
 \r
       const clientID = msg.pubKey\r
diff --git a/opts.js b/opts.js
index 917ddcd..5767cf6 100644 (file)
--- a/opts.js
+++ b/opts.js
@@ -42,8 +42,8 @@ exports = require('minimist')(process.argv.slice(2), {
  */
 exports['defaults'] = {
   config:      '/etc/strapp.conf:~/.strapp/strapp.conf:./strapp.conf',
-  'client-js': './client.js',
-  'host-js':   './host.js',
+  'client-js': './client-test.js',
+  'host-js':   './host-test.js',
   tls:         true,
   'ca-cert':   '../certs/cert.pem',
   'ca-key':    '../certs/key.pem',
index d8e9a8b..411c488 100644 (file)
--- a/router.js
+++ b/router.js
@@ -15,6 +15,11 @@ exports = {
    */
   validRoutes: /[a-zA-Z][a-zA-Z0-9\-_]*/,
 
+  /** A map of routes
+   * @prop {Object.Map} routes - all the routes!
+   */
+  routes: {},
+
   /** Parameters set on bootup (startHttpServer)
    * @prop {string[2]} skelPage - html document split in twain for JS injection
    * @prop {string} clientJS - jerverscripps to inject in skelPage for clients
@@ -28,7 +33,7 @@ exports = {
   httpdRoot: undefined,
   bindJail: undefined,
 
-  /** @func    
+  /** @func
    * @summary Start main HTTP server
    * @desc    starts up an HTTP or HTTPS server used for routing
    * @arg     {Object} conf - object containing configuration properties
@@ -46,7 +51,8 @@ exports = {
     if ('httpd' in this)
       throw new Error('httpd already running')
     if (conf.tls == undefined)
-      this.httpd = require('http').createServer(this.httpdListener)
+      this.httpd = require('http').createServer((req, res) =>
+                                                this.httpdListener(req, res))
     else if (!('keyFile' in conf.tls) || !('certFile' in conf.tls))
       throw new Error('HTTPS requires a valid key and cert')
     else
@@ -58,14 +64,16 @@ exports = {
           }
         })
         this.httpd =
-          require('https').createServer(this.httpsOpts, this.httpdListener)
+          require('https').createServer(this.httpsOpts, (request,response) =>
+                                        this.httpdListener(request,response))
+          .listen(conf.port)
       })
-    this.httpd.listen(conf.port)
-    this.httpdRoot =
-      conf.httpdRoot ? require('path').normalize(conf.httpdRoot) : undefined
-    while (this.httpdRoot[this.httpdRoot.length - 1] == require('path').sep)
-      this.httpdRoot = this.httpdRoot.slice(0,-1)
-    this.syncReads(conf.skelFile, conf.clientJS, conf.hostJS)
+    if (conf.httpdRoot) {
+      this.httpdRoot = require('path').normalize(conf.httpdRoot)
+      while (this.httpdRoot[this.httpdRoot.length - 1] == require('path').sep)
+        this.httpdRoot = this.httpdRoot.slice(0,-1)
+    }
+    this.syncReads([conf.skelFile, conf.clientJS, conf.hostJS])
       .then((results) => {
         this.skelPage = results[conf.skelFile].split('<!--STRAPP_SRC-->')
         this.clientJS = results[conf.clientJS]
@@ -74,8 +82,8 @@ exports = {
       .catch((err) => {
         console.log(err)
       })
-    console.log(`HTTP${(conf.tls == undefined) ? 'S' : ''} ` +
-                `Server Started on port ${conf.port}${this.httpdRoot ? 
+    console.log(`HTTP${(conf.tls == undefined) ? '' : 'S'} ` +
+                `Server Started on port ${conf.port}${this.httpdRoot ?
                 `, serving files from ${this.httpdRoot}`:''}`)
   },
 
@@ -97,7 +105,7 @@ exports = {
         && this.bindJail != path)
       throw new Error(`${routeName}:${path} jailed to ${this.bindJail}`)
     if (require('fs').existsSync(path)) {
-      this.route[routeName] = {
+      this.routes[routeName] = {
         bind: {
           path: path,
           dir: require('fs').lstatSync(path).isDirectory()
@@ -108,7 +116,7 @@ exports = {
       throw new Error(`${path} not found, ${routeName} not bound`)
   },
 
-  /** @func    
+  /** @func
    * @summary Router
    * @desc    listens for http client requests and services routes/files
    * @arg     {http.ClientRequest} request
@@ -118,7 +126,8 @@ exports = {
     dlog(`Received request ${request.method} ${request.url}`)
     let htArgv = request.url.slice(1).split('?')
     const routeName = htArgv[0].split('/')[0]
-    const route = this.routes[routeName]
+    let route = this.routes[routeName]
+    console.log(`route is ${route}`)
     /* If the route exists, check if we are a returning host or a new client */
     if (route) {
       if (route.bind) {
@@ -128,16 +137,27 @@ exports = {
         this.serveBind(response, route.bind, htArgv)
       }
       //TODO: auth better than this (ip spoofing is easy)
-      else if (route.host == (request.headers['x-forwarded-for'] ||
+      // but this will require a more involved host-creation process
+      // that isn't just "give you a route if it's available" on visit
+      /* else if (route.origin == (request.headers['x-forwarded-for'] ||
                          request.connection.remoteAddress))
         this.serveHost(response, route, htArgv)
-      else
+      else */
+      else {
         this.serveClient(request, response, route)
+      }
     }
     /* If it's a valid routename that doesn't exist, make this client a host */
     else if (this.validRoutes.test(routeName)) {
-      route = this.createRoute(routeName, this.httpsOpts)
-      this.serveHost(response, route, htArgv)
+       this.routes[routeName] = true
+      require('get-port')()
+        .then((port) => {
+          this.createHost(routeName, htArgv, port, request, response)
+        })
+        .catch((err) => {
+          delete this.routes[routeName]
+          console.log(err)
+        })
     }
     /* Try servicing files if we have a root directory for it */
     else if (this.httpdRoot) {
@@ -194,7 +214,7 @@ exports = {
       this.serveFile(response, bind.path)
   },
 
-  /** @func    
+  /** @func
    * @summary Serve a route to an http client
    * @desc    routes may be bound to the filesystem, or to an outgoing host
    * @arg     {http.ClientRequest} request - request from the client
@@ -217,9 +237,9 @@ exports = {
     case 'client-sdp-offer':
       let data = ''
       if (pubKey) {
+        let data = request.headers['x-strapp-offer']
         route.pendingResponses.addResponse(pubKey, response)
-        request.on('data', (chunk) => data += chunk)
-        request.on('end', () => route.socket.send(`${pubKey} ${type} ${data}`))
+        route.socket.send(`${pubKey} ${type} ${data}`)
       }
       else {
         response.writeHead(401)
@@ -232,66 +252,64 @@ exports = {
     }
   },
 
-  /** @func    
-   * @summary Serve a route to an authorized http host
-   * @desc    services host application to the client, establishing a socket
-   * @arg     {http.ServerResponse} response - response object to use
-   * @arg     {Object} route - the route that belongs to this host
-   * @arg     {string[]} argv - vector of arguments sent to the host
-   */
-  serveHost: function (response, route, argv) {
-    response.writeHead(200, { 'Content-Type': 'text/html' })
-    response.write(`${this.skelPage[0]}` +
-                   `\tconst _strapp_port = ${route.port}\n` +
-                   `\tconst _strapp_protocol = ` +
-                   `${this.httpsOpts ? 'wss' : 'ws'}'\n` +
-                   `${this.hostJS}\n${this.skelPage[1]}`)
-    response.end()
-  },
-
-  /** @func    
-   * @summary Create a new route
+  /** @func
+   * @summary Create a new route for a host
    * @desc    makes a new route for the given route name
    * @arg     {string} routeName - name of the new route
-   * @arg     {string} host - Origin address from the request that made this
+   * @arg     {string[]} argv - Origin address from the request that made this
    *                          route (for security verification on the socket)
-   * @arg     {Object} [httpsOpts] - key and cert for tls
-   * @returns {Object} a route object containing host, socket, and servers
+   * @arg     {number|string} port - the port to listen on for websocket
+   * @arg     {http.ClientRequest} request - host's request
+   * @arg     {http.ServerResponse} response - responder
    */
-  createRoute: function (routeName, host, httpsOpts) {
-    dlog(`Creating ${httpsOpts ? 'TLS ' : ''}route ${routeName} from ${host}`)
-    if (routeName in this.routes)
-      throw new Error(`route ${routeName} already exists`)
-    const httpd = httpsOpts
-          ? require('https').createServer(httpsOpts)
+  createHost: function (routeName, argv, port, request, response) {
+    const origin = (request.headers['x-forwarded-for'] ||
+                    request.connection.remoteAddress)
+    dlog(`New ${this.httpsOpts?'TLS ':''}route ${routeName}:${port}=>${origin}`)
+    const httpd = this.httpsOpts
+          ? require('https').createServer(this.httpsOpts)
           : require('http').createServer()
     const route = {
       pendingResponses: new Map([]),
-      host: host,
+      origin: origin,
       httpd: httpd,
       name: routeName,
-      port: undefined,
+      port: port,
       wsd: undefined,
       socket: undefined
     }
-    require('get-port')().then((port) => {
-      route.port = port
-      route.httpd.listen(port)
-      route.wsd = new require('ws').Server({
-        server:route.httpd,
-        verifyClient: (info) =>
-          info.origin == host && (info.secure || !httpsOpts)
+    route.httpd.listen(port)
+    route.wsd = new (require('ws').Server)({ server: httpd })
+      .on('connection', (socket) => {
+        route.socket = socket
+        socket.on('message', (msg) =>
+                  this.hostMessage(msg,route))
       })
-      route.wsd.on('connection', (socket) =>
-                   socket.on('message', (msg) =>
-                             this.hostMessage(msg,route)))
-    })
-    route.pendingResponses.addResponse = function (key, response) {
+    route.pendingResponses.addResponse = function (key, response_p) {
       let responses = this.get(key) || []
-      this.set(key, responses.push(response))
+      responses.push(response_p)
+      this.set(key, responses)
     }
     this.routes[routeName] = route
-    return route
+    this.serveHost(response, route, argv)
+  },
+
+  /** @func
+   * @summary Serve a route to an authorized http host
+   * @desc    services host application to the client, establishing a socket
+   * @arg     {http.ServerResponse} response - response object to use
+   * @arg     {Object} route - the route that belongs to this host
+   * @arg     {string[]} argv - vector of arguments sent to the host
+   */
+  serveHost: function (response, route, argv) {
+    dlog(`Serving host ${route.origin}`)
+    response.writeHead(200, { 'Content-Type': 'text/html' })
+    response.write(`${this.skelPage[0]}` +
+                   `\tconst _strapp_port = ${route.port}\n` +
+                   `\tconst _strapp_protocol = ` +
+                   `'${this.httpsOpts ? 'wss' : 'ws'}'\n` +
+                   `${this.hostJS}\n${this.skelPage[1]}`)
+    response.end()
   },
 
   /** @func
@@ -328,7 +346,7 @@ exports = {
     switch (command) {
     case '^':
       if (argv.length < 2) {
-        dlog(`Malformed '${command}' command from ${route.host}`)
+        dlog(`Malformed '${command}' command from ${route.origin}`)
         route.socket.send(`! "Insufficient arguments" 0 ${message}`)
         break
       }
@@ -356,16 +374,16 @@ exports = {
     case '!':
       if (argv.length === 3)
         argv[0] += `\nIn message: ${argv[2]}`
-      console.log(`Error[${route.host}|${argv[1]}]:${argv[0]}`)
+      console.log(`Error[${route.origin}|${argv[1]}]:${argv[0]}`)
       break
     default:
       route.socket.send(`! "Unknown command '${command}'" 0 ${message}`)
-      dlog(`Host ${route.host} send unknown command: ${message}`)
+      dlog(`Host ${route.origin} send unknown command: ${message}`)
       break
     }
   },
 
-  /** @func    
+  /** @func
    * @summary Serve a file to an http client after a request
    * @desc    reads files from the system to be distributed to clients, and
    *          buffers recently accessed files
@@ -387,8 +405,8 @@ exports = {
       response.end()
     })
   },
-  
-  /** @func   
+
+  /** @func
    * @summary Synchronize Reading Multiple Files
    * @desc    reads an array of files into an object, whose keys are the
    *          input filenames, and values are the data read
@@ -396,7 +414,7 @@ exports = {
    * @arg     {Object} [readOpts] - options to pass to fs.readFile()
    */
   syncReads: (files, readOpts) => new Promise((resolve,reject) => {
-    dlog(`syncReads: ${files}`)
+    dlog(`syncing reads from ${files}`)
     let count = 0
     let results = {}
     const read_cb = (fileName) => (err, data) => {
@@ -412,5 +430,6 @@ exports = {
     files.forEach((file) =>
                   require('fs').readFile(file, readOpts, read_cb(file)))
   })
-  
 }
+
+module.exports = exports