router functional
[henge/kiak.git] / router.js
1 /**
2 * @file HTTP(S) Router that treats the first directory in a URL's path as
3 * a route to a host.
4 * @author Ken Grimes
5 * @version 0.0.1
6 * @license AGPL-3.0
7 * @copyright Strapp.io
8 */
9
10 const dlog = (msg) => console.log(msg)
11
12 exports = {
13 /** Regular expression for valid routes
14 * @prop {Object.RegEx} validRoutes - matches valid route names
15 */
16 validRoutes: /[a-zA-Z][a-zA-Z0-9\-_]*/,
17
18 /** A map of routes
19 * @prop {Object.Map} routes - all the routes!
20 */
21 routes: {},
22
23 /** Parameters set on bootup (startHttpServer)
24 * @prop {string[2]} skelPage - html document split in twain for JS injection
25 * @prop {string} clientJS - jerverscripps to inject in skelPage for clients
26 * @prop {string} hostJS - jerverscripps for the hosts
27 * @prop {string} httpdRoot - a normalized path for http-servable files
28 * @prop {string} bindJail - jail bindings to this path
29 */
30 skelPage: undefined,
31 clientJS: undefined,
32 hostJS: undefined,
33 httpdRoot: undefined,
34 bindJail: undefined,
35
36 /** @func
37 * @summary Start main HTTP server
38 * @desc starts up an HTTP or HTTPS server used for routing
39 * @arg {Object} conf - object containing configuration properties
40 * @prop {number|string} conf.port - local system port to bind to
41 * @prop {string} conf.skelFile - location of the skeleton HTML page
42 * @prop {string} conf.clientJS - client JS file
43 * @prop {string} conf.hostJS - host JS file
44 * @prop {string} [conf.httpdRoot] - root path of http-accessible files, if
45 * undefined no files are accessible
46 * @prop {Object} [conf.tls] - if present, startHttpServer will use tls
47 * @prop {string} [conf.tls.certFile] - tls certificate file
48 * @prop {string} [conf.tls.keyFile] - tls public key file
49 */
50 startHttpServer: function (conf) {
51 if ('httpd' in this)
52 throw new Error('httpd already running')
53 if (conf.tls == undefined)
54 this.httpd = require('http').createServer((req, res) =>
55 this.httpdListener(req, res))
56 else if (!('keyFile' in conf.tls) || !('certFile' in conf.tls))
57 throw new Error('HTTPS requires a valid key and cert')
58 else
59 this.syncReads([conf.tls.keyFile, conf.tls.certFile]).then((results) => {
60 Object.defineProperty(this, 'httpsOpts', {
61 value: {
62 key: results[conf.tls.keyFile],
63 cert: results[conf.tls.certFile]
64 }
65 })
66 this.httpd =
67 require('https').createServer(this.httpsOpts, (request,response) =>
68 this.httpdListener(request,response))
69 .listen(conf.port)
70 })
71 if (conf.httpdRoot) {
72 this.httpdRoot = require('path').normalize(conf.httpdRoot)
73 while (this.httpdRoot[this.httpdRoot.length - 1] == require('path').sep)
74 this.httpdRoot = this.httpdRoot.slice(0,-1)
75 }
76 this.syncReads([conf.skelFile, conf.clientJS, conf.hostJS])
77 .then((results) => {
78 this.skelPage = results[conf.skelFile].split('<!--STRAPP_SRC-->')
79 this.clientJS = results[conf.clientJS]
80 this.hostJS = results[conf.hostJS]
81 })
82 .catch((err) => {
83 console.log(err)
84 })
85 console.log(`HTTP${(conf.tls == undefined) ? '' : 'S'} ` +
86 `Server Started on port ${conf.port}${this.httpdRoot ?
87 `, serving files from ${this.httpdRoot}`:''}`)
88 },
89
90 /** @func
91 * @summary Create a binding for the server
92 * @desc makes a new route which is bound to a file or a path. routes
93 * bound to files always serve that file, regardless of any
94 * additional path parameters provided by the URI
95 * @arg {string} routeName - the route to create
96 * @arg {string} path - the path to the file or directory to bind
97 */
98 createBind: function (routeName, path) {
99 dlog(`Binding ${routeName} to ${path}`)
100 if (routeName in this.routes)
101 throw new Error(`route ${routeName} already exists`)
102 path = require('path').normalize(path)
103 if (this.bindJail
104 && path.indexOf(`${this.bindJail}/`) !== 0
105 && this.bindJail != path)
106 throw new Error(`${routeName}:${path} jailed to ${this.bindJail}`)
107 if (require('fs').existsSync(path)) {
108 this.routes[routeName] = {
109 bind: {
110 path: path,
111 dir: require('fs').lstatSync(path).isDirectory()
112 }
113 }
114 }
115 else
116 throw new Error(`${path} not found, ${routeName} not bound`)
117 },
118
119 /** @func
120 * @summary Router
121 * @desc listens for http client requests and services routes/files
122 * @arg {http.ClientRequest} request
123 * @arg {http.ServerResponse} response
124 */
125 httpdListener: function (request,response) {
126 dlog(`Received request ${request.method} ${request.url}`)
127 let htArgv = request.url.slice(1).split('?')
128 const routeName = htArgv[0].split('/')[0]
129 let route = this.routes[routeName]
130 /* If the route exists, check if we are a returning host or a new client */
131 if (route) {
132 if (route.bind) {
133 htArgv[0] = htArgv[0].replace(`${routeName}`,'')
134 if (htArgv[0][0] === '/')
135 htArgv[0] = htArgv[0].slice(1)
136 this.serveBind(response, route.bind, htArgv)
137 }
138 //TODO: auth better than this (ip spoofing is easy)
139 else if (route.origin == (request.headers['x-forwarded-for'] ||
140 request.connection.remoteAddress))
141 this.serveHost(response, route, htArgv)
142 else
143 this.serveClient(request, response, route)
144 }
145 /* If it's a valid routename that doesn't exist, make this client a host */
146 else if (this.validRoutes.test(routeName)) {
147 this.routes[routeName] = true
148 require('get-port')()
149 .then((port) => {
150 this.createHost(routeName, htArgv, port, request, response)
151 })
152 .catch((err) => {
153 delete this.routes[routeName]
154 console.log(err)
155 })
156 }
157 /* Try servicing files if we have a root directory for it */
158 else if (this.httpdRoot) {
159 let realPath = require('path').join(this.httpdRoot, htArgv[0])
160 if (realPath == this.httpdRoot)
161 realPath += '/index.html'
162 if (realPath.indexOf(`${this.httpdRoot}/`) == 0) {
163 const stat_cb = (err, stat) => {
164 if (err) {
165 response.writeHead(404)
166 response.end()
167 console.log(err)
168 }
169 else if (stat.isDirectory()) {
170 realPath += '/index.html'
171 require('fs').lstat(realPath, stat_cb)
172 }
173 else if (stat.isFile())
174 this.serveFile(response, realPath)
175 else {
176 response.writeHead(403)
177 response.end()
178 }
179 }
180 require('fs').lstat(realPath, stat_cb)
181 }
182 else {
183 response.writeHead(400)
184 response.end()
185 }
186 }
187 /* Unhandled */
188 else {
189 response.writeHead(404)
190 response.end()
191 }
192 },
193
194 /** @func
195 * @summary Serves a binding to a client
196 * @desc Resolves a binding and serves a response to the client
197 * @arg {http.ServerResponse} response - the response to use
198 * @arg {Object} bind - the binding to serve the client
199 * @arg {string[]} argv - path and arguments for the bind
200 */
201 serveBind: function (response, bind, argv) {
202 dlog(`Serving binding ${bind.path}/${argv[0]}`)
203 if (bind.dir) {
204 if (argv[0] == '')
205 argv[0] = 'index.html'
206 this.serveFile(response, require('path').join(bind.path, argv[0]))
207 }
208 else
209 this.serveFile(response, bind.path)
210 },
211
212 /** @func
213 * @summary Serve a route to an http client
214 * @desc routes may be bound to the filesystem, or to an outgoing host
215 * @arg {http.ClientRequest} request - request from the client
216 * @arg {http.ServerResponse} response - response object to use
217 * @arg {Object} route - route associated with client request
218 */
219 serveClient: function (request, response, route) {
220 const type = request.headers['x-strapp-type']
221 const pubKey = request.headers['x-strapp-pubkey']
222 dlog(`Client ${type || 'HT'} request routed to ${route.name}`)
223 switch (type) {
224 case null:
225 case undefined:
226 response.writeHead(200, { 'Content-Type': 'text/html' })
227 response.write(`${this.skelPage[0]}${this.clientJS}${this.skelPage[1]}`)
228 response.end()
229 break
230 case 'ice-candidate-request':
231 case 'ice-candidate-submission':
232 case 'client-sdp-offer':
233 let data = ''
234 if (pubKey) {
235 route.pendingResponses.addResponse(pubKey, response)
236 request.on('data', (chunk) => data += chunk)
237 request.on('end', () => route.socket.send(`${pubKey} ${type} ${data}`))
238 }
239 else {
240 response.writeHead(401)
241 response.end()
242 }
243 break
244 default:
245 response.writeHead(400)
246 response.end()
247 }
248 },
249
250 /** @func
251 * @summary Create a new route for a host
252 * @desc makes a new route for the given route name
253 * @arg {string} routeName - name of the new route
254 * @arg {string[]} argv - Origin address from the request that made this
255 * route (for security verification on the socket)
256 * @arg {number|string} port - the port to listen on for websocket
257 * @arg {http.ClientRequest} request - host's request
258 * @arg {http.ServerResponse} response - responder
259 */
260 createHost: function (routeName, argv, port, request, response) {
261 const origin = (request.headers['x-forwarded-for'] ||
262 request.connection.remoteAddress)
263 dlog(`New ${this.httpsOpts?'TLS ':''}route ${routeName}:${port}=>${origin}`)
264 const httpd = this.httpsOpts
265 ? require('https').createServer(this.httpsOpts)
266 : require('http').createServer()
267 const route = {
268 pendingResponses: new Map([]),
269 origin: origin,
270 httpd: httpd,
271 name: routeName,
272 port: port,
273 wsd: undefined,
274 socket: undefined
275 }
276 route.httpd.listen(port)
277 route.wsd = new (require('ws').Server)({
278 server: httpd
279 //verifyClient: (info) =>
280 //info.origin == origin && (info.secure || !this.httpsOpts)
281 })
282 route.wsd.on('connection', (socket) => {
283 route.socket = socket
284 socket.on('message', (msg) =>
285 this.hostMessage(msg,route))
286 })
287 route.pendingResponses.addResponse = function (key, response_p) {
288 let responses = this.get(key) || []
289 this.set(key, responses.push(response_p))
290 }
291 this.routes[routeName] = route
292 this.serveHost(response, route, argv)
293 },
294
295 /** @func
296 * @summary Serve a route to an authorized http host
297 * @desc services host application to the client, establishing a socket
298 * @arg {http.ServerResponse} response - response object to use
299 * @arg {Object} route - the route that belongs to this host
300 * @arg {string[]} argv - vector of arguments sent to the host
301 */
302 serveHost: function (response, route, argv) {
303 dlog(`Serving host ${route.origin}`)
304 response.writeHead(200, { 'Content-Type': 'text/html' })
305 response.write(`${this.skelPage[0]}` +
306 `\tconst _strapp_port = ${route.port}\n` +
307 `\tconst _strapp_protocol = ` +
308 `'${this.httpsOpts ? 'wss' : 'ws'}'\n` +
309 `${this.hostJS}\n${this.skelPage[1]}`)
310 response.end()
311 },
312
313 /** @func
314 * @summary handle host message
315 * @desc receives a message from a host, handles the command (first character),
316 * and responds to either the host or the client, or both. Commands
317 * are whitespace separated strings.
318 * Commands:
319 * Forward Payload to Client)
320 * < clientKey payload [header]
321 * Route 'payload' to the client identified by 'clientKey'.
322 * The optional 'header' argument is a stringified JSON object,
323 * which will be written to the HTTP response header
324 * In case of multiple requests from a single client, the
325 * oldest request will be serviced on arrival of message
326 * Translate SDP and Forward to Client)
327 * ^ clientKey sdp [header]
328 * Route the JSON object 'sdp' to the client, after translating
329 * for interop between browsers using planB or Unified. Other
330 * than the interop step, this is identical to the '<' command
331 * Error)
332 * ! errorMessage errorCode [offendingMessage]
333 * Notify host that an error has occured, providing a message
334 * and error code. 'offendingMessage', if present, is the
335 * message received from the remote that triggered the error.
336 * @arg {string} message - raw string from the host
337 * @arg {Object} route - the route over
338 */
339 hostMessage: function (message, route) {
340 const argv = message.split(' ')
341 const command = argv[0][0]
342 argv = argv.slice(1)
343 dlog(`Received host message from ${route.name}: ${command}`)
344 switch (command) {
345 case '^':
346 if (argv.length < 2) {
347 dlog(`Malformed '${command}' command from ${route.origin}`)
348 route.socket.send(`! "Insufficient arguments" 0 ${message}`)
349 break
350 }
351 argv[1] = JSON.parse(argv[1])
352 //TODO: interop step
353 argv[1] = JSON.stringify(argv[1])
354 //TODO: argv[1] = encryptForClient(argv[0], argv[1])
355 /* Fallthrough to '<' behavior after translating argv[1] */
356 case '<':
357 const response = route.pendingResponses.get(argv[0]).shift()
358 if (!response)
359 route.socket.send(`! "No pending responses for client ${argv[0]}" 0 `
360 + message)
361 else if (argv.length === 2 || argv.length === 3) {
362 const header = argv.length === 3 ? JSON.parse(argv[2]) : {}
363 if (!('Content-Type' in header))
364 header['Content-Type'] = 'application/octet-stream'
365 response.writeHead(200, header)
366 response.write(argv[1])
367 response.end()
368 }
369 else
370 route.socket.send(`! "Insufficient arguments" 0 ${message}`)
371 break
372 case '!':
373 if (argv.length === 3)
374 argv[0] += `\nIn message: ${argv[2]}`
375 console.log(`Error[${route.origin}|${argv[1]}]:${argv[0]}`)
376 break
377 default:
378 route.socket.send(`! "Unknown command '${command}'" 0 ${message}`)
379 dlog(`Host ${route.origin} send unknown command: ${message}`)
380 break
381 }
382 },
383
384 /** @func
385 * @summary Serve a file to an http client after a request
386 * @desc reads files from the system to be distributed to clients, and
387 * buffers recently accessed files
388 * @arg {http.ServerResponse} response - the response object to use
389 * @arg {string} filePath - relative location of the file
390 */
391 serveFile: function (response, filePath, rootPath) {
392 //TODO: Make a buffer to hold recently used files, and only read if we
393 // have to (don't forget to preserve mimetype)
394 require('fs').readFile(filePath, { encoding: 'utf8' }, (err, data) => {
395 if (err || data == undefined)
396 response.writeHead(404)
397 else {
398 response.writeHead(200, {
399 'Content-Type': require('mime').lookup(filePath)
400 })
401 response.write(data)
402 }
403 response.end()
404 })
405 },
406
407 /** @func
408 * @summary Synchronize Reading Multiple Files
409 * @desc reads an array of files into an object, whose keys are the
410 * input filenames, and values are the data read
411 * @arg {string[]} files - array of file names to read
412 * @arg {Object} [readOpts] - options to pass to fs.readFile()
413 */
414 syncReads: (files, readOpts) => new Promise((resolve,reject) => {
415 dlog(`syncing reads from ${files}`)
416 let count = 0
417 let results = {}
418 const read_cb = (fileName) => (err, data) => {
419 if (err)
420 reject(err)
421 else
422 results[fileName] = data
423 if (++count === files.length)
424 resolve(results)
425 }
426 if (readOpts == undefined)
427 readOpts = { encoding: 'utf8' }
428 files.forEach((file) =>
429 require('fs').readFile(file, readOpts, read_cb(file)))
430 })
431 }
432
433 module.exports = exports