File size: 4,913 Bytes
b59d98b
8cac065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b59d98b
 
 
 
8cac065
b59d98b
8cac065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b59d98b
 
 
 
8cac065
 
b59d98b
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const fastify = require('fastify')({ logger: true });
const { spawn } = require('child_process');
const { createProxyMiddleware } = require('http-proxy-middleware');

let OMNITOOL_READY = false;
let ALREADY_STARTING = false;

const PROXY_PORT = 4444;
const TARGET_HOST = '0.0.0.0';
const PROXY_TARGET = 'http://0.0.0.0:1688';
const VERSION = '0.0.2c';

console.log(`************ Omnitool Proxy Server v${VERSION} ************`);
let omnitoolLogs = [];

async function startOmnitoolServer() {
    if (ALREADY_STARTING) return;
    ALREADY_STARTING = true;

    console.log('Starting Omnitool Server...');
    return new Promise((resolve, reject) => {
        const omnitoolStartProcess = spawn('./omnitool_start.sh');

        omnitoolStartProcess.stdout.on('data', (data) => {
            omnitoolLogs.push(data.toString());
            console.log(`omnitool stdout: ${data}`);
            if (data.toString().includes(`Server has started and is ready to accept connections`)) {
                OMNITOOL_READY = true;
                console.log('Omnitool server started successfully');
                resolve();
            }
        });

        omnitoolStartProcess.stderr.on('data', (data) => {
            console.error(`omnitool stderr: ${data}`);
        });

        omnitoolStartProcess.on('close', (code) => {
            console.log(`Omnitool server process exited with code ${code}`);
            if (!OMNITOOL_READY) {
                ALREADY_STARTING = false;
                reject(`Omnitool server did not start within the timeout period.`);
            }
        });
    });
}

fastify.get('/', async (request, reply) => {
    const localUrl = request.headers['host'];

    if (!OMNITOOL_READY) {
        let htmlContent = `
            <html>
                <head><title>Proxy Server</title></head>
                <body>
                    <button id="startServerButton" onclick="startServer()">Start Omnitool Server</button>
                    <button id="exitIframeButton" onclick="window.open('http://${localUrl}', '_blank')" disabled>Exit Iframe</button>
                    <div id="logs" style="white-space: pre-wrap;"></div>
                    <script>
                        function startServer() {
                            document.getElementById('startServerButton').disabled = true;
                            fetch('/start-omnitool-server')
                                .then(response => response.json())
                                .then(data => {
                                    startLogPolling();
                                });
                        }

                        function startLogPolling() {
                            const interval = setInterval(() => {
                                fetch('/omnitool-logs')
                                    .then(response => response.json())
                                    .then(data => {
                                        document.getElementById('logs').innerText = data.logs.join("\\n");
                                        if (data.ready) {
                                            clearInterval(interval);
                                            window.location.reload(); // Refresh the page when Omnitool is ready
                                        }
                                    });
                            }, 1000);
                        }

                        startLogPolling();
                    </script>
                </body>
            </html>
        `;
        reply.type('text/html').send(htmlContent);
    } else {
        console.log('Proxying request as OMNITOOL is ready');
        const proxy = createProxyMiddleware({
            target: PROXY_TARGET,
            changeOrigin: true,
            ws: true,
            logLevel: 'debug'
        });
        proxy(request.raw, reply.raw, () => {});
    }
});

fastify.get('/omnitool-logs', async (request, reply) => {
    reply.send({ logs: omnitoolLogs, ready: OMNITOOL_READY });
});

fastify.get('/start-omnitool-server', async (request, reply) => {
    if (!OMNITOOL_READY) {
        if (ALREADY_STARTING) {
            return { message: "Omnitool server already starting" };
        }
        try {
            await startOmnitoolServer();
            reply.send({ message: "Omnitool server started successfully" });
        } catch (error) {
            console.error(error);
            reply.send({ message: `Error starting Omnitool server: ${error}` });
        }
    } else {
        reply.send({ message: "Omnitool server already running" });
    }
});

const start = async () => {
    try {
        await fastify.listen({ port: PROXY_PORT, host: TARGET_HOST });
        console.log(`Server is listening on http://${TARGET_HOST}:${PROXY_PORT}`);
    } catch (err) {
        console.error(`Error starting server: ${err}`);
        process.exit(1);
    }
};

start();