+/**
+ * @file Node entry and main driver
+ * @author Jordan Lavatai, Ken Grimes
+ * @version 0.0.1
+ * @license AGPL-3.0
+ * @copyright jk software 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.
+const skelPage = fs.readFileSync('./skel.html', { encoding: 'utf8' }).split('<!--STRAPP_SRC-->')
+const clientJS = fs.readFileSync(opts['client-js'])
+const hostJS = fs.readFileSync(opts['host-js'])
+const routes = {}
+const httpsOpts = (opts['no-tls'] ?
+ undefined :
+ {
+ key: fs.readFileSync(opts['ca-key']),
+ cert: fs.readFileSync(opts['ca-cert'])
+ })
-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 routeConnection = (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()
+ }
+ })
}
-})
-
-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)
+ 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 {
- if ('404.html' in fileBuf) {
- response.writeHead(404, fileBuf['404.html'].mime)
- response.write(fileBuf['404.html'].data)
- }
- else
- response.writeHead(404)
+ console.log(`SEC: ${localPath} references files not in route`)
}
- 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.write(`${skelPage[0]}${clientJS}${skelPage[1]}`)
response.end()
route.socket.send(request.headers['x-forwarded-for'] || request.connection.remoteAddress)
}
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)
-
+ if (opts['no-tls'])
+ newRoute.httpd = http.createServer()
+ else
+ newRoute.httpd = https.createServer(httpsOpts)
+ newRoute.httpd.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) })
routes[htArgv[0]] = newRoute
}).then(() => {
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(skelPage[0] + 'const _strapp_port = \'' + newRoute.port + '\'\n' + hostJS + skelPage[1])
response.end()
})
}
-}).listen(argv['port'])
+}
+
+const router = ((opts['no-tls']) ?
+ http.createServer(routeConnection) :
+ https.createServer(httpsOpts, routeConnection))
+ .listen(opts['port'])
//TODO: if ("electron" in process.versions) open a local renderwindow, and route to it