2 * @file Node entry and main driver
3 * @author Jordan Lavatai, Ken Grimes
6 * @copyright loljk 2017
7 * @summary HTTP(S) Router that uses the first directory in the requested URL
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')
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']),
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)
36 response
.writeHead(200, { 'Content-Type': mime
.lookup(fPath
) })
42 const htArgv
= request
.url
.slice(1).split("?")
43 let routePath
= htArgv
[0].split('/')
44 let routeName
= routePath
[0]
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
) => {
56 serveFile(`${localPath}/index.html`)
60 console
.log(`SEC: ${localPath} references files not in route`)
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']
71 /* Client is INIT GET */
72 if (headerData
=== undefined) {
73 console
.log('client init GET')
74 response
.writeHead(200, { 'Content-Type': 'text/html' })
75 response
.write(`${router.skelPage[0]}${router.clientJS}${router.skelPage[1]}`)
77 //TODO: if route.socket == undefined: have server delay this send until host connects
78 // (this happens when a client connects to an active route with no currently-online host)
80 else if (headerData
.localeCompare('ice-candidate-request') === 0){
81 console
.log('Server: received ice-candidate-request from Client')
83 request
.on('data', (chunk
) => {
86 data
= Buffer
.concat(data
).toString();
87 console
.log('Sending ice-candidate-request to Host' + data
)
88 clients
.set(data
, response
)
89 route
.socket
.send(data
)
92 else if (headerData
.localeCompare('ice-candidate-submission') === 0) {
93 console
.log('Server: recieved ice-candidate-submission from Client')
95 request
.on('data', (chunk
) => {
98 console
.log('Sending ice-candidate-submission to Host' + data
)
99 data
= Buffer
.concat(data
).toString();
100 clients
.set(JSON
.parse(data
)['pubKey'], response
)
101 route
.socket
.send(data
)
104 else if (headerData
.localeCompare('client-sdp-offer') === 0){ /* Client sent offer, waiting for answer */
105 console
.log('Server: Sending client offer to host')
106 clients
.set(JSON
.parse(request
.headers
['x-client-offer'])['pubKey'], response
)
107 route
.socket
.send(request
.headers
['x-client-offer'])
109 console
.log('Unhandled stuff')
110 console
.log(request
.headers
)
115 router
.routes
[routeName
] = true
117 newRoute
.clients
= new Map([])
118 newRoute
.host
= request
.headers
['x-forwarded-for'] || request
.connection
.remoteAddress
119 getport().then( (port
) => {
122 newRoute
.httpd
= http
.createServer()
124 newRoute
.httpd
= https
.createServer(router
.httpsOpts
)
125 newRoute
.httpd
.listen(newRoute
.port
)
126 newRoute
.wsd
= new ws
.Server( { server
: newRoute
.httpd
} )
127 newRoute
.wsd
.on('connection', (sock
) => {
128 console
.log(`${routeName} server has been established`)
129 newRoute
.socket
= sock
131 /* Handle all messages from host */
132 sock
.on('message', (hostMessage
) => {
133 hostMessage
= JSON
.parse(hostMessage
)
134 response
= newRoute
.clients
.get(hostMessage
['clientPubKey'])
136 /* If the host response is a answer */
137 if (hostMessage
['cmd'].localeCompare('< sdp pubKey') === 0) {
138 console
.log('Server: Sending host answer to client')
139 response
.writeHead(200, { 'Content-Type': 'application/json' })
140 response
.write(JSON
.stringify(hostMessage
))
143 else if (hostMessage
['cmd'].localeCompare('< ice pubKey') === 0){
144 /* if the host response is an ice candidate */
145 console
.log('Server: Sending host ice candidate')
146 let iceCandidateAvailable
= hostMessage
['iceCandidateAvailable']
147 /* If there are any ice candidates, send them back */
148 if (iceCandidateAvailable
) {
149 response
.writeHead('200', {'x-strapp-type': 'ice-candidate-available'})
150 response
.write(JSON
.stringify(hostMessage
))
153 else { /* If not, srequest processed successfully, but there isnt anything yet*/
154 console
.log('Server: No ice candidate available for response')
155 response
.writeHead('204', {'x-strapp-type': 'ice-candidate-unavailable'})
160 console
.log('unhandled message cmd from host')
166 console
.log(`Listening for websocket ${newRoute.host} on port ${newRoute.port}`)
167 router
.routes
[routeName
] = newRoute
169 response
.writeHead(200, { 'Content-Type': 'text/html' })
170 response
.write(`${router.skelPage[0]}` +
171 `\tconst _strapp_port = ${newRoute.port}\n` +
172 `\tconst _strapp_protocol = '${router.wsProtocol}'\n` +
173 `${router.hostJS}\n${router.skelPage[1]}`)
183 * @summary Boot up the router. With TLS, we must wait for file reads to sync.
185 if (!opts
['no-tls']) {
190 const syncRead
= () => {
191 if (++filesRead
== 2) {
192 if (key
== undefined)
193 console
.log(`ERR: Key ${opts['ca-key']} inaccessible, tls will fail`)
194 if(cert
== undefined)
195 console
.log(`ERR: Cert ${opts['ca-cert']} inaccessible, tls will fail`)
196 else if (key
!= undefined) {
197 router
.httpsOpts
= { cert
: cert
, key
: key
}
198 router
.httpd
= https
.createServer(router
.httpsOpts
, router
.respond
)
199 .listen(opts
['port'])
203 fs
.readFile(opts
['ca-key'], { encoding
: 'utf8' }, (err
, data
) => {
207 fs
.readFile(opts
['ca-cert'], { encoding
: 'utf8' }, (err
, data
) => {
208 if (!err
) cert
= data
213 router
.httpd
= http
.createServer(router
.respond
).listen(opts
['port'])
215 //TODO: if ("electron" in process.versions) open a local renderwindow, and route to it