aboutsummaryrefslogtreecommitdiff
path: root/websockets/server.js
blob: 21847938f394b816d90a5f2ddaeed635f85b0597 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env node
const fs=require("fs");
const net=require("net");
const https=require("https");
const WebSocket=require("uws");

const PORT=29546;

const upstream={
	host: "localhost",
	port: 29536
};


let httpsConfig=null;
if(process.argv.length>=4){
	console.log("Reading keys for https");
	httpsConfig={
		key: fs.readFileSync(process.argv[2]),
		cert: fs.readFileSync(process.argv[3]),
	};
}

if(process.getuid()==0){
	console.log(`Old uid: ${process.getuid()}, old gid: ${process.getgid()}; setting to nobody...`);
	process.setgid("nobody");
	process.setuid("nobody");
	console.log(`New uid: ${process.getuid()}, new gid: ${process.getgid()}`);
}


let httpsServer,wsServer;
if(httpsConfig){
	httpsServer=https.createServer(httpsConfig,(req,res)=>{
		console.log("Got request in httpsServer?");
		// req.socket.end();  // ?
	});
	wsServer=new WebSocket.Server({server:httpsServer},()=>{
		console.log(`Bound websocket server to https server`);
	});
} else {
	wsServer=new WebSocket.Server({port:PORT},()=>{
		console.log(`Listening for websocket http requests on port ${PORT}`);
	});
}
wsServer.on("connection",(sock)=>{
	let netconn=null;
	let buffer=[];
	let linebuf="";

	netconn=net.connect(upstream.port,upstream.host,()=>{
		for(const item of buffer){
			netconn.write(item+"\n");
		}
		buffer=[];
	});
	netconn.on("close",()=>{
		sock.close();
	});
	netconn.on("data",(data)=>{
		linebuf+=data;
		let idx;
		while((idx=linebuf.indexOf("\n"))!=-1){
			sock.send(linebuf.slice(0,idx));
			linebuf=linebuf.slice(idx+1);
		}
	});

	sock.on("close",()=>{
		netconn.end();
	});
	sock.on("message",(data)=>{
		if(netconn.connecting)buffer.push(data);
		else netconn.write(data+"\n");
	});
});

if(httpsConfig){
	httpsServer.listen(PORT,()=>{
		console.log(`HTTPS server bound on port ${PORT}`);
	});
}

process.on("SIGINT",()=>{
	console.log("Closing server...");
	wsServer.close();
	if(httpsConfig)httpsServer.close();
});