+/**
+* @file Node entry and main driver
+* @author Jordan Lavatai, Ken Grimes
+* @version 0.0.1
+* @license AGPL-3.0
+* @copyright loljk 2017
+* @summary HTTP(S) Router that uses the first directory in the requested URL
+* as the route name
+*/
const fs = require('fs')
const ws = require('ws')
+const path = require('path')
+const http = require('http')
const https = require('https')
const getport = require('get-port')
const mime = require('mime')
+const opts = require('./opts.js')
-const argv = require('minimist')(process.argv.slice(2), {
- string: [ 'ca-cert', 'ca-key', 'config', 'client-js', 'host-js', 'electron', 'port' ],
- boolean: [ 'remote-host' ],
- alias: { c: 'config',
- j: 'client-js',
- J: 'host-js',
- C: 'ca-cert',
- K: 'ca-key',
- e: 'electron',
- r: 'remote-host',
- p: 'port'
- },
- default: { config: undefined,
- 'client-js': 'client.js',
- 'host-js': 'host.js',
- 'ca-cert': 'stunnel.cert',
- 'ca-key': 'stunnel.key',
- 'remote-host': true,
- 'port': 2443
- },
- stopEarly: true,
- unknown: (opt) => {
- console.log(process.argv.join(" ") + '\nUnknown operator: ' + opt + `
-Usage: strapp [OPTION]...
-Route https connections from a hardware port to a remote host, and initiate
-peer-to-peer connection with clients.
-
-CONFIG
- -c, --config=path Configuration file to use (/etc/strapp.conf)
- - overridden by command line opts
- -j, --client-js=path Path to the client Strapp code (./strapp-client.js)
- -J, --host-js=path Path to the host Strapp code (./strapp-host.js)
- -C, --ca-cert=path Accessible location of the CA Cert (./stunnel.cert)
- -K, --ca-key=path Accessible location of the CA Key (./stunnel.key)
- -p, --port=number The local port to bind HTTPS listener to (2443)
-
-ROUTING
- -e, --electron=route Route to the local electron user (nil)
- - enables optional electron dependency
- -d, --dedicated=route Route all incoming connections to this route (nil)
- - used in conjunction with '-e=my_route'
-
-(c)2017 jk software
-`)
- process.exit()
- }
-})
-
-//TODO: if (argv['config'] !== undefined), read and apply to argv without overwrite
-if (argv['www-path'] == undefined)
- argv['www-path'] = 'www'
-else if (String(argv['www-path']).endsWith('/'))
- argv['www-path'] = argv['www-path'].slice(0,-1)
-
-const routerOpts = {
- key: fs.readFileSync(argv['ca-key']),
- cert: fs.readFileSync(argv['ca-cert'])
-}
-const skelPage = String(fs.readFileSync('skel.html')).split("<!--STRAPP-->")
-const clientJS = fs.readFileSync(argv['client-js'])
-const hostJS = fs.readFileSync(argv['host-js'])
-const routes = {}
-const fileBuf = {}
-let fbSize = 0
-fs.readdirSync(argv['www-path']).forEach((file) => {
- if (fbSize++ < 50) {
- fileBuf[file] = { mime: mime.lookup(argv['www-path'] + '/' + file),
- data: fs.readFileSync(argv['www-path'] + '/' + file)
- }
- }
-})
-
-const router = https.createServer(routerOpts, (request, response) => {
- const htArgv = request.url.slice(1).split("?")
- let routeName = htArgv[0].split('/')[0]
- if (routeName === '')
- routeName = 'index.html'
- if (routeName.indexOf('.') != -1) {
- if (routeName in fileBuf) {
- response.writeHead(200, { 'Content-Type': fileBuf[routeName].mime })
- response.write(fileBuf[routeName].data)
+const router = {
+ skelPage: fs.readFileSync('./skel.html', { encoding: 'utf8' }).split('<!--STRAPP_SRC-->'),
+ clientJS: fs.readFileSync(opts['client-js']),
+ hostJS: fs.readFileSync(opts['host-js']),
+ routes: {},
+ httpsOpt: undefined,
+ httpd: undefined,
+ wsProtocol: opts['no-tls'] ? 'ws' : 'wss',
+ respond: (request,response) => {
+ const serveFile = (fPath) => {
+ fs.readFile(fPath, { encoding: 'utf8' }, (err, data) => {
+ if (err || data == undefined) {
+ response.writeHead(404)
+ response.end()
+ }
+ else {
+ response.writeHead(200, { 'Content-Type': mime.lookup(fPath) })
+ response.write(data)
+ response.end()
+ }
+ })
}
- else {
- if ('404.html' in fileBuf) {
- response.writeHead(404, fileBuf['404.html'].mime)
- response.write(fileBuf['404.html'].data)
+ const htArgv = request.url.slice(1).split("?")
+ let routePath = htArgv[0].split('/')
+ let routeName = routePath[0]
+ if (routeName === '' || routeName === 'index.html')
+ serveFile(opts['index'])
+ else if (routeName in opts['bindings']) {
+ let localPath = path.normalize(opts['bindings'][routeName].concat(path.sep + routePath.slice(1).join(path.sep)))
+ if (localPath.includes(opts['bindings'][routeName])) {
+ fs.readdir(localPath, (err, files) => {
+ if (err)
+ serveFile(localPath)
+ else
+ serveFile(`${localPath}/index.html`)
+ })
+ }
+ else {
+ console.log(`SEC: ${localPath} references files not in route`)
}
- else
- response.writeHead(404)
}
- response.end()
- }
- else if (routeName in routes) {
- const route = routes[routeName]
- response.writeHead(200, { 'Content-Type': 'text/html' })
- response.write(skelPage[0] + clientJS + skelPage[1])
- response.end()
- route.socket.send(request.headers['x-forwarded-for'] || request.connection.remoteAddress)
- }
- else {
- routes[htArgv[0]] = true
- const newRoute = {}
- newRoute.host = request.headers['x-forwarded-for'] || request.connection.remoteAddress
- getport().then( (port) => {
- newRoute.port = port
- newRoute.httpd = https.createServer(routerOpts, (request, response) => {
- }).listen(newRoute.port)
-
- newRoute.ws = new ws.Server( { server: newRoute.httpd } )
- newRoute.ws.on('connection', (ws) => { console.log("socket connected"); newRoute.socket = ws; ws.send("CONNECTED") } )
- newRoute.ws.on('message', (msg) => { console.log("Received message" + msg) })
- console.log("Listening for websocket " + newRoute.host + " on port " + newRoute.port)
- routes[htArgv[0]] = newRoute
- }).then(() => {
+ else if (routeName in router.routes) {
+ const route = router.routes[routeName]
response.writeHead(200, { 'Content-Type': 'text/html' })
- response.write(skelPage[0] + 'const _strapp_host = \'www.strapp.io\'\n\tconst _strapp_port = \'' + newRoute.port + '\'\n' + hostJS + skelPage[1])
+ response.write(`${router.skelPage[0]}${router.clientJS}${router.skelPage[1]}`)
response.end()
- })
+ //TODO: if route.socket == undefined: have server delay this send until host connects
+ // (this happens when a client connects to an active route with no currently-online host)
+ route.socket.send(request.headers['x-forwarded-for'] || request.connection.remoteAddress)
+ }
+ else {
+ router.routes[routeName] = true
+ const newRoute = {}
+ newRoute.host = request.headers['x-forwarded-for'] || request.connection.remoteAddress
+ getport().then( (port) => {
+ newRoute.port = port
+ if (opts['no-tls'])
+ newRoute.httpd = http.createServer()
+ else
+ newRoute.httpd = https.createServer(router.httpsOpts)
+ newRoute.httpd.listen(newRoute.port)
+ newRoute.wsd = new ws.Server( { server: newRoute.httpd } )
+ newRoute.wsd.on('connection', (sock) => {
+ newRoute.socket = sock
+ sock.on('message', (msg) => { console.log(`[${newRoute.host}] ${msg}`) })
+ })
+ console.log(`Listening for websocket ${newRoute.host} on port ${newRoute.port}`)
+ router.routes[routeName] = newRoute
+ }).then(() => {
+ response.writeHead(200, { 'Content-Type': 'text/html' })
+ response.write(`${router.skelPage[0]}` +
+ `\tconst _strapp_port = ${newRoute.port}\n` +
+ `\tconst _strapp_protocol = '${router.wsProtocol}'\n` +
+ `${router.hostJS}\n${router.skelPage[1]}`)
+ response.end()
+ })
+ }
+
+ }
}
-}).listen(argv['port'])
-//TODO: if ("electron" in process.versions) open a local renderwindow, and route to it
+ /**
+ * @summary Boot up the router. With TLS, we must wait for file reads to sync.
+ */
+ if (!opts['no-tls']) {
+ let filesRead = 0
+ let key = undefined
+ let cert = undefined
+ const syncRead = () => {
+ if (++filesRead == 2) {
+ if (key == undefined)
+ console.log(`ERR: Key ${opts['ca-key']} inaccessible, tls will fail`)
+ if(cert == undefined)
+ console.log(`ERR: Cert ${opts['ca-cert']} inaccessible, tls will fail`)
+ else if (key != undefined) {
+ router.httpsOpts = { cert: cert, key: key}
+ router.httpd = https.createServer(router.httpsOpts, router.respond)
+ .listen(opts['port'])
+ }
+ }
+ }
+ fs.readFile(opts['ca-key'], { encoding: 'utf8' }, (err, data) => {
+ if (!err) key = data
+ syncRead()
+ })
+ fs.readFile(opts['ca-cert'], { encoding: 'utf8' }, (err, data) => {
+ if (!err) cert = data
+ syncRead()
+ })
+ }
+ else
+ router.httpd = http.createServer(router.respond).listen(opts['port'])
+ //TODO: if ("electron" in process.versions) open a local renderwindow, and route to it