updates
[henge/kiak.git] / main.js
1 const fs = require('fs')
2 const ws = require('ws')
3 const https = require('https')
4 const http = require('http')
5 const getport = require('get-port')
6 const argv = require('minimist')(process.argv.slice(2))
7
8 const http_redirect = http.createServer((request, response) => {
9 response.writeHead(301, { "Location": "https://" + request.headers['host'] + request.url})
10 response.end()
11 }).listen(2080)
12
13 const https_router_opts = {
14 key: fs.readFileSync('stunnel.key'),
15 cert: fs.readFileSync('stunnel.cert')
16 }
17
18 let https_routes = {}
19 const https_router = https.createServer(https_router_opts, (request, response) => {
20 let ht_argv = request.url.slice(1).split("?")
21 console.log(ht_argv)
22 if (ht_argv[0] in https_routes) {
23 response.writeHead(200, { 'Content-Type': 'text/plain' })
24 response.write('You are a remote client\r\n')
25 let route = https_routes[ht_argv[0]]
26 response.write('You should connect to ' + route.host + "\r\nOn port: " + route.port + "\r\n")
27 response.end()
28 }
29 else if (ht_argv[0].indexOf(".") == -1) {
30 https_routes[ht_argv[0]] = 'true'
31 response.writeHead(200, { 'Content-Type': 'text/html' })
32 let new_route = {}
33 new_route.host = request.headers['x-forwarded-for'] || request.connection.remoteAddress
34 getport().then( (port) => {
35 new_route.port = port
36 new_route.httpd = https.createServer(https_router_opts, (request, response) => {
37 }).listen(port)
38 new_route.ws = new ws.Server( { server: new_route.httpd } )
39 new_route.ws.on('connection', (ws) => { console.log("socket connected"); ws.send("CONNECTED") } )
40 new_route.ws.on('message', (msg) => { console.log("Received message" + msg) })
41 console.log("Listening for websocket socket " + new_route.port + " on " + new_route.host)
42 console.log(new_route)
43 https_routes[ht_argv[0]] = new_route
44 }).then(() => {
45 let str = String(fs.readFileSync('remote-server.html'))
46 response.write(str.replace("$HOST",new_route.host.slice(7)).replace("$PORT",new_route.port))
47 response.end()
48 })
49 }
50 }).listen(2443)
51
52
53
54 if ("electron" in process.versions);
55