-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdns-server.js
82 lines (74 loc) · 2.81 KB
/
dns-server.js
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
const DnsProxyServer = require("@aiorosdev/dns-proxy-lib");
const sudo = require("sudo-prompt");
const { io } = require("socket.io-client");
const fs = require("fs");
const path = require("path");
class DnsServer {
constructor(config) {
this.config = config;
this.inProcess = true;
this.inProcessDNSServer = new DnsProxyServer(config);
this.socket = null;
this.messageCallback = null;
}
getSocket() {
if (!this.socket) {
this.socket = io("http://127.0.0.1:3000");
this.socket.on("message", (message, callback) => {
if (this.messageCallback) {
this.messageCallback(message.message, message.rinfo);
}
});
}
return this.socket;
}
runSeparateProcess() {
console.log("Couldn't run DNS server. Root/administrator permissions might be needed, trying to request them for a child process DNS server.");
// Find executable if available, otherwise run the node script
let executable = process.execPath + " " + path.resolve(__dirname, "dns-server-child.js");
if (process.platform == "win32" && fs.existsSync("./dns-server-child.exe")) {
executable = path.resolve(__dirname, "dns-server-child.exe");
} else if (fs.existsSync("./dns-server-child")) {
executable = path.resolve(__dirname, "dns-server-child");
}
if (process.platform == "win32") {
executable = executable.replace(/\//g, "\\");
}
let command = executable + " --config " + Buffer.from(JSON.stringify(this.config)).toString("base64");
this.inProcess = false;
sudo.exec(command, {name: "Console Streaming Server"}, (error, stdout, stderr) => {
if (error) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
throw error;
}
});
setTimeout(() => {
this.getSocket()?.emit("request", {command: "start"}, (response) => {console.log("response: ", response)});
}, 1000);
}
run() {
try {
if (this.messageCallback) {
this.inProcessDNSServer.onMessageReceived(this.messageCallback);
}
this.inProcessDNSServer.run();
this.inProcessDNSServer.socket.on("error", (err) => {this.runSeparateProcess();});
} catch(ex) {
this.runSeparateProcess();
}
}
stop() {
if (this.inProcess) {
this.inProcessDNSServer.stop();
} else {
this.getSocket()?.emit("request", {command: "stop"}, (response) => {
this.getSocket()?.disconnect();
});
}
}
onMessageReceived(callback) {
this.messageCallback = callback;
}
}
module.exports = DnsServer;