sdp offer from client is incorrect somehow
[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 console.log(`route is ${route}`)
131 /* If the route exists, check if we are a returning host or a new client */
132 if (route) {
133 if (route.bind) {
134 htArgv[0] = htArgv[0].replace(`${routeName}`,'')
135 if (htArgv[0][0] === '/')
136 htArgv[0] = htArgv[0].slice(1)
137 this.serveBind(response, route.bind, htArgv)
138 }
139 //TODO: auth better than this (ip spoofing is easy)
140 // but this will require a more involved host-creation process
141 // that isn't just "give you a route if it's available" on visit
142 /* else if (route.origin == (request.headers['x-forwarded-for'] ||
143 request.connection.remoteAddress))
144 this.serveHost(response, route, htArgv)
145 else */
146 else {
147 this.serveClient(request, response, route)
148 }
149 }
150 /* If it's a valid routename that doesn't exist, make this client a host */
151 else if (this.validRoutes.test(routeName)) {
152 this.routes[routeName] = true
153 require('get-port')()
154 .then((port) => {
155 this.createHost(routeName, htArgv, port, request, response)
156 })
157 .catch((err) => {
158 delete this.routes[routeName]
159 console.log(err)
160 })
161 }
162 /* Try servicing files if we have a root directory for it */
163 else if (this.httpdRoot) {
164 let realPath = require('path').join(this.httpdRoot, htArgv[0])
165 if (realPath == this.httpdRoot)
166 realPath += '/index.html'
167 if (realPath.indexOf(`${this.httpdRoot}/`) == 0) {
168 const stat_cb = (err, stat) => {
169 if (err) {
170 response.writeHead(404)
171 response.end()
172 console.log(err)
173 }
174 else if (stat.isDirectory()) {
175 realPath += '/index.html'
176 require('fs').lstat(realPath, stat_cb)
177 }
178 else if (stat.isFile())
179 this.serveFile(response, realPath)
180 else {
181 response.writeHead(403)
182 response.end()
183 }
184 }
185 require('fs').lstat(realPath, stat_cb)
186 }
187 else {
188 response.writeHead(400)
189 response.end()
190 }
191 }
192 /* Unhandled */
193 else {
194 response.writeHead(404)
195 response.end()
196 }
197 },
198
199 /** @func
200 * @summary Serves a binding to a client
201 * @desc Resolves a binding and serves a response to the client
202 * @arg {http.ServerResponse} response - the response to use
203 * @arg {Object} bind - the binding to serve the client
204 * @arg {string[]} argv - path and arguments for the bind
205 */
206 serveBind: function (response, bind, argv) {
207 dlog(`Serving binding ${bind.path}/${argv[0]}`)
208 if (bind.dir) {
209 if (argv[0] == '')
210 argv[0] = 'index.html'
211 this.serveFile(response, require('path').join(bind.path, argv[0]))
212 }
213 else
214 this.serveFile(response, bind.path)
215 },
216
217 /** @func
218 * @summary Serve a route to an http client
219 * @desc routes may be bound to the filesystem, or to an outgoing host
220 * @arg {http.ClientRequest} request - request from the client
221 * @arg {http.ServerResponse} response - response object to use
222 * @arg {Object} route - route associated with client request
223 */
224 serveClient: function (request, response, route) {
225 const type = request.headers['x-strapp-type']
226 const pubKey = request.headers['x-strapp-pubkey']
227 dlog(`Client ${type || 'HT'} request routed to ${route.name}`)
228 switch (type) {
229 case null:
230 case undefined:
231 response.writeHead(200, { 'Content-Type': 'text/html' })
232 response.write(`${this.skelPage[0]}${this.clientJS}${this.skelPage[1]}`)
233 response.end()
234 break
235 case 'ice-candidate-request':
236 case 'ice-candidate-submission':
237 case 'client-sdp-offer':
238 let data = ''
239 if (pubKey) {
240 let data = request.headers['x-strapp-offer']
241 route.pendingResponses.addResponse(pubKey, response)
242 route.socket.send(`${pubKey} ${type} ${data}`)
243 }
244 else {
245 response.writeHead(401)
246 response.end()
247 }
248 break
249 default:
250 response.writeHead(400)
251 response.end()
252 }
253 },
254
255 /** @func
256 * @summary Create a new route for a host
257 * @desc makes a new route for the given route name
258 * @arg {string} routeName - name of the new route
259 * @arg {string[]} argv - Origin address from the request that made this
260 * route (for security verification on the socket)
261 * @arg {number|string} port - the port to listen on for websocket
262 * @arg {http.ClientRequest} request - host's request
263 * @arg {http.ServerResponse} response - responder
264 */
265 createHost: function (routeName, argv, port, request, response) {
266 const origin = (request.headers['x-forwarded-for'] ||
267 request.connection.remoteAddress)
268 dlog(`New ${this.httpsOpts?'TLS ':''}route ${routeName}:${port}=>${origin}`)
269 const httpd = this.httpsOpts
270 ? require('https').createServer(this.httpsOpts)
271 : require('http').createServer()
272 const route = {
273 pendingResponses: new Map([]),
274 origin: origin,
275 httpd: httpd,
276 name: routeName,
277 port: port,
278 wsd: undefined,
279 socket: undefined
280 }
281 route.httpd.listen(port)
282 route.wsd = new (require('ws').Server)({ server: httpd })
283 .on('connection', (socket) => {
284 route.socket = socket
285 socket.on('message', (msg) =>
286 this.hostMessage(msg,route))
287 })
288 route.pendingResponses.addResponse = function (key, response_p) {
289 let responses = this.get(key) || []
290 responses.push(response_p)
291 this.set(key, responses)
292 }
293 this.routes[routeName] = route
294 this.serveHost(response, route, argv)
295 },
296
297 /** @func
298 * @summary Serve a route to an authorized http host
299 * @desc services host application to the client, establishing a socket
300 * @arg {http.ServerResponse} response - response object to use
301 * @arg {Object} route - the route that belongs to this host
302 * @arg {string[]} argv - vector of arguments sent to the host
303 */
304 serveHost: function (response, route, argv) {
305 dlog(`Serving host ${route.origin}`)
306 response.writeHead(200, { 'Content-Type': 'text/html' })
307 response.write(`${this.skelPage[0]}` +
308 `\tconst _strapp_port = ${route.port}\n` +
309 `\tconst _strapp_protocol = ` +
310 `'${this.httpsOpts ? 'wss' : 'ws'}'\n` +
311 `${this.hostJS}\n${this.skelPage[1]}`)
312 response.end()
313 },
314
315 /** @func
316 * @summary handle host message
317 * @desc receives a message from a host, handles the command (first character),
318 * and responds to either the host or the client, or both. Commands
319 * are whitespace separated strings.
320 * Commands:
321 * Forward Payload to Client)
322 * < clientKey payload [header]
323 * Route 'payload' to the client identified by 'clientKey'.
324 * The optional 'header' argument is a stringified JSON object,
325 * which will be written to the HTTP response header
326 * In case of multiple requests from a single client, the
327 * oldest request will be serviced on arrival of message
328 * Translate SDP and Forward to Client)
329 * ^ clientKey sdp [header]
330 * Route the JSON object 'sdp' to the client, after translating
331 * for interop between browsers using planB or Unified. Other
332 * than the interop step, this is identical to the '<' command
333 * Error)
334 * ! errorMessage errorCode [offendingMessage]
335 * Notify host that an error has occured, providing a message
336 * and error code. 'offendingMessage', if present, is the
337 * message received from the remote that triggered the error.
338 * @arg {string} message - raw string from the host
339 * @arg {Object} route - the route over
340 */
341 hostMessage: function (message, route) {
342 const argv = message.split(' ')
343 const command = argv[0][0]
344 argv = argv.slice(1)
345 dlog(`Received host message from ${route.name}: ${command}`)
346 switch (command) {
347 case '^':
348 if (argv.length < 2) {
349 dlog(`Malformed '${command}' command from ${route.origin}`)
350 route.socket.send(`! "Insufficient arguments" 0 ${message}`)
351 break
352 }
353 argv[1] = JSON.parse(argv[1])
354 //TODO: interop step
355 argv[1] = JSON.stringify(argv[1])
356 //TODO: argv[1] = encryptForClient(argv[0], argv[1])
357 /* Fallthrough to '<' behavior after translating argv[1] */
358 case '<':
359 const response = route.pendingResponses.get(argv[0]).shift()
360 if (!response)
361 route.socket.send(`! "No pending responses for client ${argv[0]}" 0 `
362 + message)
363 else if (argv.length === 2 || argv.length === 3) {
364 const header = argv.length === 3 ? JSON.parse(argv[2]) : {}
365 if (!('Content-Type' in header))
366 header['Content-Type'] = 'application/octet-stream'
367 response.writeHead(200, header)
368 response.write(argv[1])
369 response.end()
370 }
371 else
372 route.socket.send(`! "Insufficient arguments" 0 ${message}`)
373 break
374 case '!':
375 if (argv.length === 3)
376 argv[0] += `\nIn message: ${argv[2]}`
377 console.log(`Error[${route.origin}|${argv[1]}]:${argv[0]}`)
378 break
379 default:
380 route.socket.send(`! "Unknown command '${command}'" 0 ${message}`)
381 dlog(`Host ${route.origin} send unknown command: ${message}`)
382 break
383 }
384 },
385
386 /** @func
387 * @summary Serve a file to an http client after a request
388 * @desc reads files from the system to be distributed to clients, and
389 * buffers recently accessed files
390 * @arg {http.ServerResponse} response - the response object to use
391 * @arg {string} filePath - relative location of the file
392 */
393 serveFile: function (response, filePath, rootPath) {
394 //TODO: Make a buffer to hold recently used files, and only read if we
395 // have to (don't forget to preserve mimetype)
396 require('fs').readFile(filePath, { encoding: 'utf8' }, (err, data) => {
397 if (err || data == undefined)
398 response.writeHead(404)
399 else {
400 response.writeHead(200, {
401 'Content-Type': require('mime').lookup(filePath)
402 })
403 response.write(data)
404 }
405 response.end()
406 })
407 },
408
409 /** @func
410 * @summary Synchronize Reading Multiple Files
411 * @desc reads an array of files into an object, whose keys are the
412 * input filenames, and values are the data read
413 * @arg {string[]} files - array of file names to read
414 * @arg {Object} [readOpts] - options to pass to fs.readFile()
415 */
416 syncReads: (files, readOpts) => new Promise((resolve,reject) => {
417 dlog(`syncing reads from ${files}`)
418 let count = 0
419 let results = {}
420 const read_cb = (fileName) => (err, data) => {
421 if (err)
422 reject(err)
423 else
424 results[fileName] = data
425 if (++count === files.length)
426 resolve(results)
427 }
428 if (readOpts == undefined)
429 readOpts = { encoding: 'utf8' }
430 files.forEach((file) =>
431 require('fs').readFile(file, readOpts, read_cb(file)))
432 })
433 }
434
435 module.exports = exports