data channel between host + client, sending/receiving ice candidates when needed...
[henge/kiak.git] / main.js
1 /**
2 * @file Node entry and main driver
3 * @author Jordan Lavatai, Ken Grimes
4 * @version 0.0.1
5 * @license AGPL-3.0
6 * @copyright loljk 2017
7 * @summary HTTP(S) Router that uses the first directory in the requested URL
8 * as the route name
9 */
10 const fs = require('fs')
11 const ws = require('ws')
12 const path = require('path')
13 const http = require('http')
14 const https = require('https')
15 const getport = require('get-port')
16 const mime = require('mime')
17 const opts = require('./opts.js')
18
19 const router = {
20 skelPage: fs.readFileSync('./skel.html', { encoding: 'utf8' }).split('<!--STRAPP_SRC-->'),
21 clientJS: fs.readFileSync(opts['client-js']),
22 hostJS: fs.readFileSync(opts['host-js']),
23 routes: {},
24 httpsOpt: undefined,
25 httpd: undefined,
26 wsProtocol: opts['no-tls'] ? 'ws' : 'wss',
27 respond: (request,response) => {
28 console.log('server handling request')
29 const serveFile = (fPath) => {
30 fs.readFile(fPath, { encoding: 'utf8' }, (err, data) => {
31 if (err || data == undefined) {
32 response.writeHead(404)
33 response.end()
34 }
35 else {
36 response.writeHead(200, { 'Content-Type': mime.lookup(fPath) })
37 response.write(data)
38 response.end()
39 }
40 })
41 }
42 const htArgv = request.url.slice(1).split("?")
43 let routePath = htArgv[0].split('/')
44 let routeName = routePath[0]
45
46
47 if (routeName === '' || routeName === 'index.html')
48 serveFile(opts['index'])
49 else if (routeName in opts['bindings']) {
50 let localPath = path.normalize(opts['bindings'][routeName].concat(path.sep + routePath.slice(1).join(path.sep)))
51 if (localPath.includes(opts['bindings'][routeName])) {
52 fs.readdir(localPath, (err, files) => {
53 if (err)
54 serveFile(localPath)
55 else
56 serveFile(`${localPath}/index.html`)
57 })
58 }
59 else {
60 console.log(`SEC: ${localPath} references files not in route`)
61 }
62 }
63 /* TODO: Handle reconnecting host */
64 else if (routeName in router.routes) {
65 const route = router.routes[routeName]
66 const clients = route['clients']
67 const headerData = request.headers['x-strapp-type']
68
69
70
71
72 /* Client is INIT GET */
73 if (headerData === undefined) {
74 console.log('client init GET')
75 response.writeHead(200, { 'Content-Type': 'text/html' })
76 response.write(`${router.skelPage[0]}${router.clientJS}${router.skelPage[1]}`)
77 response.end()
78 //TODO: if route.socket == undefined: have server delay this send until host connects
79 // (this happens when a client connects to an active route with no currently-online host)
80 }
81 else if (headerData.localeCompare('ice-candidate-request') === 0) {
82 console.log('Server: received ice-candidate-request from Client')
83 let pubKey = request.headers['x-client-pubkey']
84 clients.set(pubKey, response)
85 pubKey = '{ "pubKey": "' + pubKey + '" }'
86 route.socket.send(pubKey)
87 }
88 else if (headerData.localeCompare('ice-candidate-submission') === 0) {
89 console.log('Server: recieved ice-candidate-submission from Client')
90 let data = []
91 request.on('data', (chunk) => {
92 data.push(chunk)
93 }).on('end', () => {
94 console.log('Sending ice-candidate-submission to Host')
95 data = Buffer.concat(data).toString();
96 clients.set(JSON.parse(data)['pubKey'], response)
97 route.socket.send(data)
98 })
99 }
100 else if (headerData.localeCompare('client-sdp-offer') === 0){ /* Client sent offer, waiting for answer */
101 console.log('Server: Sending client offer to host')
102 clients.set(JSON.parse(request.headers['x-client-offer'])['pubKey'], response)
103 route.socket.send(request.headers['x-client-offer'])
104 } else {
105 console.log('Unhandled stuff')
106 console.log(request.headers)
107 }
108
109 }
110 else {
111 router.routes[routeName] = true
112 const newRoute = {}
113 newRoute.clients = new Map([])
114 newRoute.host = request.headers['x-forwarded-for'] || request.connection.remoteAddress
115 getport().then( (port) => {
116 newRoute.port = port
117 if (opts['no-tls'])
118 newRoute.httpd = http.createServer()
119 else
120 newRoute.httpd = https.createServer(router.httpsOpts)
121 newRoute.httpd.listen(newRoute.port)
122 newRoute.wsd = new ws.Server( { server: newRoute.httpd } )
123 newRoute.wsd.on('connection', (sock) => {
124 console.log(`${routeName} server has been established`)
125 newRoute.socket = sock
126
127 /* Handle all messages from host */
128 sock.on('message', (hostMessage) => {
129 hostMessage = JSON.parse(hostMessage)
130 response = newRoute.clients.get(hostMessage['clientPubKey'])
131
132 /* If the host response is a answer */
133 if (hostMessage['cmd'].localeCompare('< sdp pubKey') === 0) {
134 console.log('Server: Sending host answer to client')
135 response.writeHead(200, { 'Content-Type': 'application/json' })
136 response.write(JSON.stringify(hostMessage))
137 response.end()
138 }
139 else if (hostMessage['cmd'].localeCompare('< ice pubKey') === 0){
140 /* if the host response is an ice candidate */
141 console.log('Server: Sending host ice candidate')
142 let iceCandidateAvailable = hostMessage['iceCandidateAvailable']
143 /* If there are any ice candidates, send them back */
144 if (iceCandidateAvailable) {
145 response.writeHead('200', {'x-strapp-type': 'ice-candidate-available'})
146 response.write(JSON.stringify(hostMessage))
147 response.end()
148 }
149 else { /* If not, srequest processed successfully, but there isnt anything yet*/
150 console.log('Server: No ice candidate available for response')
151 response.writeHead('204', {'x-strapp-type': 'ice-candidate-unavailable'})
152 response.end()
153 }
154 }
155 else {
156 console.log('unhandled message cmd from host')
157 }
158
159 })
160 })
161
162 console.log(`Listening for websocket ${newRoute.host} on port ${newRoute.port}`)
163 router.routes[routeName] = newRoute
164 }).then(() => {
165 response.writeHead(200, { 'Content-Type': 'text/html' })
166 response.write(`${router.skelPage[0]}` +
167 `\tconst _strapp_port = ${newRoute.port}\n` +
168 `\tconst _strapp_protocol = '${router.wsProtocol}'\n` +
169 `${router.hostJS}\n${router.skelPage[1]}`)
170 response.end()
171 })
172 }
173
174
175 }
176 }
177
178 /**
179 * @summary Boot up the router. With TLS, we must wait for file reads to sync.
180 */
181 if (!opts['no-tls']) {
182 console.log('tls')
183 let filesRead = 0
184 let key = undefined
185 let cert = undefined
186 const syncRead = () => {
187 if (++filesRead == 2) {
188 if (key == undefined)
189 console.log(`ERR: Key ${opts['ca-key']} inaccessible, tls will fail`)
190 if(cert == undefined)
191 console.log(`ERR: Cert ${opts['ca-cert']} inaccessible, tls will fail`)
192 else if (key != undefined) {
193 router.httpsOpts = { cert: cert, key: key}
194 router.httpd = https.createServer(router.httpsOpts, router.respond)
195 .listen(opts['port'])
196 }
197 }
198 }
199 fs.readFile(opts['ca-key'], { encoding: 'utf8' }, (err, data) => {
200 if (!err) key = data
201 syncRead()
202 })
203 fs.readFile(opts['ca-cert'], { encoding: 'utf8' }, (err, data) => {
204 if (!err) cert = data
205 syncRead()
206 })
207 }
208 else
209 router.httpd = http.createServer(router.respond).listen(opts['port'])
210
211 //TODO: if ("electron" in process.versions) open a local renderwindow, and route to it