2 * @file HTTP(S) Router that treats the first directory in a URL's path as
9 const fs
= require('fs')
11 const dlog
= (msg
) => console
.log(msg
)
14 /** Regular expression for valid routes
15 * @var {Object.RegEx} validRoutes - matches valid route names
17 validRoutes
: /[a-zA-Z][a-zA-Z0-9\-_]*/,
20 * @summary Synchronize Reading Multiple Files
21 * @desc reads an array of files into an object, whose keys are the
22 * input filenames, and values are the data read
23 * @arg {string[]} files - array of file names to read
24 * @arg {Object} [readOpts] - options to pass to fs.readFile()
26 syncReads
: (files
, readOpts
) => new Promise((resolve
,reject
) => {
27 dlog(`syncReads: ${files}`)
30 const read_cb
= (fileName
) => (err
, data
) => {
34 results
[fileName
] = data
35 if (++count
== files
.length
)
38 if (readOpts
== undefined)
39 readOpts
= { encoding
: 'utf8' }
40 files
.forEach((file
) => fs
.readFile(file
, readOpts
, read_cb(file
)))
44 * @summary Main router listener
45 * @desc listens for client requests and services routes/files
46 * @arg {http.ClientRequest} request
47 * @arg {http.ServerResponse} response
49 listener: function (request
,response
) {
50 dlog(`Received request ${request.method} ${request.url}`)
51 const htArgv
= request
.url
.slice(1).split('?')
52 let routePath
= htArgv
[0].split('/')[0]
53 let routeName
= routePath
[0]
54 let route
= this.routes
[routeName
]
56 if (route
.host
== (request
.headers
['x-forwarded-for'] ||
57 request
.connection
.remoteAddress
))
58 this.serveHost(response
, route
, htArgv
)
60 this.serveRoute(response
, route
)
62 else if (this.validRoutes
.test(routeName
)) {
63 route
= this.createRoute(routeName
, this.httpsOpts
)
64 this.serveHost(response
, route
, htArgv
)
67 this.serveFile(response
, routePath
)
72 * @summary Serve a route to an http client
73 * @desc routes may be bound to the filesystem, or to an outgoing host
74 * @arg {http.ServerResponse} response - response object to use
75 * @arg {string} routeName - name of the route to follow
77 serveRoute: function (response
, routeName
) {
81 * @summary Create a new route
82 * @desc makes a new route for the given route name
83 * @arg {string} routeName - name of the new route
84 * @arg {string} host - Origin address from the request that made this
85 * route (for security verification on the socket)
86 * @arg {Object} [httpsOpts] - key and cert for tls
88 createRoute: function (routeName
, host
, httpsOpts
) {
89 dlog(`Creating ${httpsOpts ? 'TLS ' : ''}route ${routeName} from ${host}`)
90 if (routeName
in this.routes
)
91 throw new Error(`route ${routeName} already exists`)
92 const httpd
= httpsOpts
93 ? require('https').createServer(httpsOpts
)
94 : require('http').createServer()
95 const wsd
= new require('ws').Server({
97 verifyClient
: (info
) => info
.origin
== host
&& (info
.secure
|| !httpsOpts
)
100 pendingResponses
: new Map([]),
107 wsd
.on('connection', (socket
) =>
108 socket
.on('message', (msg
) =>
109 this.hostMessage(msg
,route
)))
110 this.routes
[routeName
] = route
115 * @summary handle host message
116 * @desc receives a message from a host, handles the command (first character),
117 * and responds to either the host or the client, or both. Commands
118 * are whitespace separated strings.
120 * < clientKey requestID payload
121 * Route 'payload' to the client identified by 'clientKey', in
122 * response to the request identified by 'requestID'
123 * ! errorMessage errorCode [offendingMessage]
124 * Notify host that an error has occured, providing a message
125 * and error code. 'offendingMessage', if present, is the
126 * message received from the remote that triggered the error.
127 * @arg {string} message - raw string from the host
128 * @arg {Object} route - the route over
130 hostMessage: function (message
, route
) {
131 const argv
= message
.split(' ')
132 const command
= argv
[0][0]
134 dlog(`Received host message from ${route.name}: ${command}`)
137 if (argv
.length
== 3) {
138 const response
= route
.pendingResponses
.get(argv
[0] + argv
[1])
139 response
.writeHead(200, { 'Content-Type': 'application/octet-stream' })
140 response
.write(argv
[2])
144 route
.socket
.send(`! "Insufficient arguments" 0 ${message}`)
148 if (argv
.length
== 3)
149 argv
[0] += `\nIn message: ${argv[2]}`
150 console
.log(`Error[${route.host}|${argv[1]}]:${argv[0]}`)
156 * @summary Serve a file to an http client after a request
157 * @desc reads files from the system to be distributed to clients, and
158 * buffers recently accessed files
159 * @arg {http.ServerResponse} response - the response object to use
160 * @arg {string} filePath - location of the file on disk to service
162 serveFile: function (response
, filePath
) {
166 * @summary Start main HTTP server
167 * @desc starts up an HTTP or HTTPS server used for routing
168 * @arg {number|string} port - local system port to bind to
169 * @arg {Object} [tls] - if present, startHttpServer will start in tls
170 * mode. supported properties:
171 * 'certfile': certificate file location
172 * 'keyfile': key file location
174 startHttpServer: function (port
, tls
) {
176 throw new Error('httpd already running')
177 if (tls
== undefined)
178 this.httpd
= require('http').createServer(this.listener
)
179 else if (!('key' in tls
) || !('cert' in tls
))
180 throw new Error('HTTPS requires a valid key and cert')
182 this.syncReads([tls
.keyfile
, tls
.certfile
]).then((results
) => {
183 Object
.defineProperty(this, 'httpsOpts', {
185 key
: results
[tls
.keyfile
],
186 cert
: results
[tls
.certfile
]
189 this.httpd
= require('https').createServer(httpsOpts
, this.listener
)
191 this.httpd
.listen(port
)
192 console
.log(`HTTP${(tls == undefined) ? 'S' : ''} ` +
193 `Server Started on Port ${port}`)
197 // exports.create = (opts) => { return {
199 // listener: function (request, response) {
200 // console.log('server handling request')
201 // const serveFile = (fPath) => {
202 // fs.readFile(fPath, { encoding: 'utf8' }, (err, data) => {
203 // if (err || data == undefined) {
204 // response.writeHead(404)
208 // response.writeHead(200, { 'Content-Type': mime.lookup(fPath) })
209 // response.write(data)
214 // const htArgv = request.url.slice(1).split("?")
215 // let routePath = htArgv[0].split('/')
216 // let routeName = routePath[0]
219 // if (routeName === '' || routeName === 'index.html')
220 // serveFile(opts['index'])
221 // else if (routeName in opts['bindings']) {
222 // let localPath = path.normalize(opts['bindings'][routeName].concat(path.sep + routePath.slice(1).join(path.sep)))
223 // if (localPath.includes(opts['bindings'][routeName])) {
224 // fs.readdir(localPath, (err, files) => {
226 // serveFile(localPath)
228 // serveFile(`${localPath}/index.html`)
232 // console.log(`SEC: ${localPath} references files not in route`)
235 // /* TODO: Handle reconnecting host */
236 // else if (routeName in router.routes) {
237 // const route = router.routes[routeName]
238 // const clients = route['clients']
239 // const headerData = request.headers['x-strapp-type']
244 // /* Client is INIT GET */
245 // if (headerData === undefined) {
246 // console.log('client init GET')
247 // response.writeHead(200, { 'Content-Type': 'text/html' })
248 // response.write(`${router.skelPage[0]}${router.clientJS}${router.skelPage[1]}`)
250 // //TODO: if route.socket == undefined: have server delay this send until host connects
251 // // (this happens when a client connects to an active route with no currently-online host)
253 // else if (headerData.localeCompare('ice-candidate-request') === 0) {
254 // console.log('Server: received ice-candidate-request from Client')
255 // let pubKey = request.headers['x-client-pubkey']
256 // clients.set(pubKey, response)
257 // pubKey = '{ "pubKey": "' + pubKey + '" }'
258 // route.socket.send(pubKey)
260 // else if (headerData.localeCompare('ice-candidate-submission') === 0) {
261 // console.log('Server: recieved ice-candidate-submission from Client')
263 // request.on('data', (chunk) => {
265 // }).on('end', () => {
266 // console.log('Sending ice-candidate-submission to Host')
267 // data = Buffer.concat(data).toString();
268 // clients.set(JSON.parse(data)['pubKey'], response)
269 // route.socket.send(data)
272 // else if (headerData.localeCompare('client-sdp-offer') === 0){ /* Client sent offer, waiting for answer */
273 // console.log('Server: Sending client offer to host')
274 // clients.set(JSON.parse(request.headers['x-client-offer'])['pubKey'], response)
275 // route.socket.send(request.headers['x-client-offer'])
277 // console.log('Unhandled stuff')
278 // console.log(request.headers)
283 // router.routes[routeName] = true
284 // const newRoute = {}
285 // newRoute.clients = new Map([])
286 // newRoute.host = request.headers['x-forwarded-for'] || request.connection.remoteAddress
287 // getport().then( (port) => {
288 // newRoute.port = port
289 // if (opts['no-tls'])
290 // newRoute.httpd = http.createServer()
292 // newRoute.httpd = https.createServer(router.httpsOpts)
293 // newRoute.httpd.listen(newRoute.port)
294 // newRoute.wsd = new ws.Server( { server: newRoute.httpd } )
295 // newRoute.wsd.on('connection', (sock) => {
296 // console.log(`${routeName} server has been established`)
297 // newRoute.socket = sock
299 // /* Handle all messages from host */
300 // sock.on('message', (hostMessage) => {
301 // hostMessage = JSON.parse(hostMessage)
302 // response = newRoute.clients.get(hostMessage['clientPubKey'])
304 // /* If the host response is a answer */
305 // if (hostMessage['cmd'].localeCompare('< sdp pubKey') === 0) {
306 // console.log('Server: Sending host answer to client')
307 // response.writeHead(200, { 'Content-Type': 'application/json' })
308 // response.write(JSON.stringify(hostMessage))
311 // else if (hostMessage['cmd'].localeCompare('< ice pubKey') === 0){
312 // /* if the host response is an ice candidate */
313 // console.log('Server: Handling host ICE message')
314 // let iceState = hostMessage['iceState']
315 // /* If there are any ice candidates, send them back */
316 // switch(iceState) {
318 // response.writeHead('200', {'x-strapp-type': 'ice-candidate-available'})
319 // response.write(JSON.stringify(hostMessage))
323 // console.log('Server: Host is still gathering candidates, keep trying')
324 // response.writeHead('200', {'x-strapp-type': 'ice-state-gathering'})
325 // response.write(JSON.stringify(hostMessage))
329 // console.log('Server: Host has completed gathering candidates')
330 // response.writeHead('200', {'x-strapp-type': 'ice-state-complete'})
331 // response.write(JSON.stringify(hostMessage))
335 // console.log('unhandled iceState from host')
343 // console.log(`Listening for websocket ${newRoute.host} on port ${newRoute.port}`)
344 // router.routes[routeName] = newRoute
346 // response.writeHead(200, { 'Content-Type': 'text/html' })
347 // response.write(`${router.skelPage[0]}` +
348 // `\tconst _strapp_port = ${newRoute.port}\n` +
349 // `\tconst _strapp_protocol = '${router.wsProtocol}'\n` +
350 // `${router.hostJS}\n${router.skelPage[1]}`)
355 // startHttpd: () => require('http').createServer(this.listener)