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