2 * @file HTTP(S) Router that treats the first directory in a URL's path as
10 const dlog
= (msg
) => console
.log(msg
)
13 /** Regular expression for valid routes
14 * @prop {Object.RegEx} validRoutes - matches valid route names
16 validRoutes
: /[a-zA-Z][a-zA-Z0-9\-_]*/,
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
32 * @summary Start main HTTP server
33 * @desc starts up an HTTP or HTTPS server used for routing
34 * @arg {Object} conf - object containing configuration properties
35 * @prop {number|string} conf.port - local system port to bind to
36 * @prop {string} conf.skelFile - location of the skeleton HTML page
37 * @prop {string} conf.clientJS - client JS file
38 * @prop {string} conf.hostJS - host JS file
39 * @prop {string} [conf.httpdRoot] - root path of http-accessible files, if
40 * undefined no files are accessible
41 * @prop {Object} [conf.tls] - if present, startHttpServer will use tls
42 * @prop {string} [conf.tls.certFile] - tls certificate file
43 * @prop {string} [conf.tls.keyFile] - tls public key file
45 startHttpServer: function (conf
) {
47 throw new Error('httpd already running')
48 if (conf
.tls
== undefined)
49 this.httpd
= require('http').createServer(this.httpdListener
)
50 else if (!('keyFile' in conf
.tls
) || !('certFile' in conf
.tls
))
51 throw new Error('HTTPS requires a valid key and cert')
53 this.syncReads([conf
.tls
.keyFile
, conf
.tls
.certFile
]).then((results
) => {
54 Object
.defineProperty(this, 'httpsOpts', {
56 key
: results
[conf
.tls
.keyFile
],
57 cert
: results
[conf
.tls
.certFile
]
61 require('https').createServer(this.httpsOpts
, this.httpdListener
)
63 this.httpd
.listen(conf
.port
)
65 conf
.httpdRoot
? require('path').normalize(conf
.httpdRoot
) : undefined
66 while (this.httpdRoot
[this.httpdRoot
.length
- 1] == require('path').sep
)
67 this.httpdRoot
= this.httpdRoot
.slice(0,-1)
68 this.syncReads(conf
.skelFile
, conf
.clientJS
, conf
.hostJS
)
70 this.skelPage
= results
[conf
.skelFile
].split('<!--STRAPP_SRC-->')
71 this.clientJS
= results
[conf
.clientJS
]
72 this.hostJS
= results
[conf
.hostJS
]
77 console
.log(`HTTP${(conf.tls == undefined) ? 'S' : ''} ` +
78 `Server Started on port ${conf.port}${this.httpdRoot ?
79 `, serving files
from ${this.httpdRoot}
`:''}`)
83 * @summary Create a binding for the server
84 * @desc makes a new route which is bound to a file or a path. routes
85 * bound to files always serve that file, regardless of any
86 * additional path parameters provided by the URI
87 * @arg {string} routeName - the route to create
88 * @arg {string} path - the path to the file or directory to bind
90 createBind: function (routeName
, path
) {
91 dlog(`Binding ${routeName} to ${path}`)
92 if (routeName
in this.routes
)
93 throw new Error(`route ${routeName} already exists`)
94 path
= require('path').normalize(path
)
96 && path
.indexOf(`${this.bindJail}/`) !== 0
97 && this.bindJail
!= path
)
98 throw new Error(`${routeName}:${path} jailed to ${this.bindJail}`)
99 if (require('fs').existsSync(path
)) {
100 this.route
[routeName
] = {
103 dir
: require('fs').lstatSync(path
).isDirectory()
108 throw new Error(`${path} not found, ${routeName} not bound`)
113 * @desc listens for http client requests and services routes/files
114 * @arg {http.ClientRequest} request
115 * @arg {http.ServerResponse} response
117 httpdListener: function (request
,response
) {
118 dlog(`Received request ${request.method} ${request.url}`)
119 let htArgv
= request
.url
.slice(1).split('?')
120 const routeName
= htArgv
[0].split('/')[0]
121 const route
= this.routes
[routeName
]
122 /* If the route exists, check if we are a returning host or a new client */
125 htArgv
[0] = htArgv
[0].replace(`${routeName}`,'')
126 if (htArgv
[0][0] === '/')
127 htArgv
[0] = htArgv
[0].slice(1)
128 this.serveBind(response
, route
.bind
, htArgv
)
130 //TODO: auth better than this (ip spoofing is easy)
131 else if (route
.host
== (request
.headers
['x-forwarded-for'] ||
132 request
.connection
.remoteAddress
))
133 this.serveHost(response
, route
, htArgv
)
135 this.serveClient(request
, response
, route
)
137 /* If it's a valid routename that doesn't exist, make this client a host */
138 else if (this.validRoutes
.test(routeName
)) {
139 route
= this.createRoute(routeName
, this.httpsOpts
)
140 this.serveHost(response
, route
, htArgv
)
142 /* Try servicing files if we have a root directory for it */
143 else if (this.httpdRoot
) {
144 let realPath
= require('path').join(this.httpdRoot
, htArgv
[0])
145 if (realPath
== this.httpdRoot
)
146 realPath
+= '/index.html'
147 if (realPath
.indexOf(`${this.httpdRoot}/`) == 0) {
148 const stat_cb
= (err
, stat
) => {
150 response
.writeHead(404)
154 else if (stat
.isDirectory()) {
155 realPath
+= '/index.html'
156 require('fs').lstat(realPath
, stat_cb
)
158 else if (stat
.isFile())
159 this.serveFile(response
, realPath
)
161 response
.writeHead(403)
165 require('fs').lstat(realPath
, stat_cb
)
168 response
.writeHead(400)
174 response
.writeHead(404)
180 * @summary Serves a binding to a client
181 * @desc Resolves a binding and serves a response to the client
182 * @arg {http.ServerResponse} response - the response to use
183 * @arg {Object} bind - the binding to serve the client
184 * @arg {string[]} argv - path and arguments for the bind
186 serveBind: function (response
, bind
, argv
) {
187 dlog(`Serving binding ${bind.path}/${argv[0]}`)
190 argv
[0] = 'index.html'
191 this.serveFile(response
, require('path').join(bind
.path
, argv
[0]))
194 this.serveFile(response
, bind
.path
)
198 * @summary Serve a route to an http client
199 * @desc routes may be bound to the filesystem, or to an outgoing host
200 * @arg {http.ClientRequest} request - request from the client
201 * @arg {http.ServerResponse} response - response object to use
202 * @arg {Object} route - route associated with client request
204 serveClient: function (request
, response
, route
) {
205 const type
= request
.headers
['x-strapp-type']
206 const pubKey
= request
.headers
['x-strapp-pubkey']
207 dlog(`Client ${type || 'HT'} request routed to ${route.name}`)
211 response
.writeHead(200, { 'Content-Type': 'text/html' })
212 response
.write(`${this.skelPage[0]}${this.clientJS}${this.skelPage[1]}`)
215 case 'ice-candidate-request':
216 case 'ice-candidate-submission':
217 case 'client-sdp-offer':
220 route
.pendingResponses
.addResponse(pubKey
, response
)
221 request
.on('data', (chunk
) => data
+= chunk
)
222 request
.on('end', () => route
.socket
.send(`${pubKey} ${type} ${data}`))
225 response
.writeHead(401)
230 response
.writeHead(400)
236 * @summary Serve a route to an authorized http host
237 * @desc services host application to the client, establishing a socket
238 * @arg {http.ServerResponse} response - response object to use
239 * @arg {Object} route - the route that belongs to this host
240 * @arg {string[]} argv - vector of arguments sent to the host
242 serveHost: function (response
, route
, argv
) {
243 response
.writeHead(200, { 'Content-Type': 'text/html' })
244 response
.write(`${this.skelPage[0]}` +
245 `\tconst _strapp_port = ${route.port}\n` +
246 `\tconst _strapp_protocol = ` +
247 `${this.httpsOpts ? 'wss' : 'ws'}'\n` +
248 `${this.hostJS}\n${this.skelPage[1]}`)
253 * @summary Create a new route
254 * @desc makes a new route for the given route name
255 * @arg {string} routeName - name of the new route
256 * @arg {string} host - Origin address from the request that made this
257 * route (for security verification on the socket)
258 * @arg {Object} [httpsOpts] - key and cert for tls
259 * @returns {Object} a route object containing host, socket, and servers
261 createRoute: function (routeName
, host
, httpsOpts
) {
262 dlog(`Creating ${httpsOpts ? 'TLS ' : ''}route ${routeName} from ${host}`)
263 if (routeName
in this.routes
)
264 throw new Error(`route ${routeName} already exists`)
265 const httpd
= httpsOpts
266 ? require('https').createServer(httpsOpts
)
267 : require('http').createServer()
269 pendingResponses
: new Map([]),
277 require('get-port')().then((port
) => {
279 route
.httpd
.listen(port
)
280 route
.wsd
= new require('ws').Server({
282 verifyClient
: (info
) =>
283 info
.origin
== host
&& (info
.secure
|| !httpsOpts
)
285 route
.wsd
.on('connection', (socket
) =>
286 socket
.on('message', (msg
) =>
287 this.hostMessage(msg
,route
)))
289 route
.pendingResponses
.addResponse = function (key
, response
) {
290 let responses
= this.get(key
) || []
291 this.set(key
, responses
.push(response
))
293 this.routes
[routeName
] = route
298 * @summary handle host message
299 * @desc receives a message from a host, handles the command (first character),
300 * and responds to either the host or the client, or both. Commands
301 * are whitespace separated strings.
303 * Forward Payload to Client)
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 * Translate SDP and Forward to Client)
311 * ^ clientKey sdp [header]
312 * Route the JSON object 'sdp' to the client, after translating
313 * for interop between browsers using planB or Unified. Other
314 * than the interop step, this is identical to the '<' command
316 * ! errorMessage errorCode [offendingMessage]
317 * Notify host that an error has occured, providing a message
318 * and error code. 'offendingMessage', if present, is the
319 * message received from the remote that triggered the error.
320 * @arg {string} message - raw string from the host
321 * @arg {Object} route - the route over
323 hostMessage: function (message
, route
) {
324 const argv
= message
.split(' ')
325 const command
= argv
[0][0]
327 dlog(`Received host message from ${route.name}: ${command}`)
330 if (argv
.length
< 2) {
331 dlog(`Malformed '${command}' command from ${route.host}`)
332 route
.socket
.send(`! "Insufficient arguments" 0 ${message}`)
335 argv
[1] = JSON
.parse(argv
[1])
337 argv
[1] = JSON
.stringify(argv
[1])
338 //TODO: argv[1] = encryptForClient(argv[0], argv[1])
339 /* Fallthrough to '<' behavior after translating argv[1] */
341 const response
= route
.pendingResponses
.get(argv
[0]).shift()
343 route
.socket
.send(`! "No pending responses for client ${argv[0]}" 0 `
345 else if (argv
.length
=== 2 || argv
.length
=== 3) {
346 const header
= argv
.length
=== 3 ? JSON
.parse(argv
[2]) : {}
347 if (!('Content-Type' in header
))
348 header
['Content-Type'] = 'application/octet-stream'
349 response
.writeHead(200, header
)
350 response
.write(argv
[1])
354 route
.socket
.send(`! "Insufficient arguments" 0 ${message}`)
357 if (argv
.length
=== 3)
358 argv
[0] += `\nIn message: ${argv[2]}`
359 console
.log(`Error[${route.host}|${argv[1]}]:${argv[0]}`)
362 route
.socket
.send(`! "Unknown command '${command}'" 0 ${message}`)
363 dlog(`Host ${route.host} send unknown command: ${message}`)
369 * @summary Serve a file to an http client after a request
370 * @desc reads files from the system to be distributed to clients, and
371 * buffers recently accessed files
372 * @arg {http.ServerResponse} response - the response object to use
373 * @arg {string} filePath - relative location of the file
375 serveFile: function (response
, filePath
, rootPath
) {
376 //TODO: Make a buffer to hold recently used files, and only read if we
377 // have to (don't forget to preserve mimetype)
378 require('fs').readFile(filePath
, { encoding
: 'utf8' }, (err
, data
) => {
379 if (err
|| data
== undefined)
380 response
.writeHead(404)
382 response
.writeHead(200, {
383 'Content-Type': require('mime').lookup(filePath
)
392 * @summary Synchronize Reading Multiple Files
393 * @desc reads an array of files into an object, whose keys are the
394 * input filenames, and values are the data read
395 * @arg {string[]} files - array of file names to read
396 * @arg {Object} [readOpts] - options to pass to fs.readFile()
398 syncReads
: (files
, readOpts
) => new Promise((resolve
,reject
) => {
399 dlog(`syncReads: ${files}`)
402 const read_cb
= (fileName
) => (err
, data
) => {
406 results
[fileName
] = data
407 if (++count
=== files
.length
)
410 if (readOpts
== undefined)
411 readOpts
= { encoding
: 'utf8' }
412 files
.forEach((file
) =>
413 require('fs').readFile(file
, readOpts
, read_cb(file
)))