File size: 11,396 Bytes
d44e3b5
 
 
a3113b3
bb5f1a6
 
3bb34cc
d44e3b5
82641f8
d44e3b5
a3113b3
 
0b10343
a3113b3
d44e3b5
 
 
a3113b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb66da
d44e3b5
 
 
 
 
 
 
6cb66da
 
d44e3b5
 
 
 
 
 
 
 
 
f1ca1c5
d44e3b5
 
 
 
f1ca1c5
 
 
 
a3113b3
 
 
 
 
d44e3b5
a3113b3
d44e3b5
 
 
6cb66da
 
a3113b3
82641f8
a3113b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82641f8
d44e3b5
a3113b3
 
6cb66da
bb5f1a6
a3113b3
bb5f1a6
a3113b3
6cb66da
a3113b3
 
 
 
 
 
6cb66da
a3113b3
 
 
bb5f1a6
a3113b3
 
 
 
 
 
 
 
 
 
bb5f1a6
a3113b3
 
 
 
 
 
 
bb5f1a6
a3113b3
 
bb5f1a6
6cb66da
a3113b3
6cb66da
bb5f1a6
 
a3113b3
 
 
 
bb5f1a6
a3113b3
 
 
 
82641f8
a3113b3
 
 
 
 
 
 
 
 
 
bb5f1a6
a3113b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb5f1a6
a3113b3
bb5f1a6
a3113b3
 
 
 
 
 
 
bb5f1a6
 
a3113b3
 
 
 
 
 
bb5f1a6
a3113b3
 
 
 
 
 
 
 
 
 
 
 
 
 
bb5f1a6
 
a3113b3
bb5f1a6
 
 
 
 
 
6cb66da
 
a3113b3
 
 
d44e3b5
 
6cb66da
 
 
 
bb5f1a6
a3113b3
 
 
 
 
6cb66da
 
 
 
d44e3b5
 
a3113b3
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
const http = require('http');
const { spawn } = require('child_process');

const PROXY_PORT_OMNITOOL = 4444;
const CONTAINER_HOST = '127.0.0.1';
const CONTAINER_PORT_OMNITOOL = 1688;
const PROTOCOL = 'https';
let OMNITOOL_READY = false;
let OMNITOOL_PRE_READY = false;
let ALREADY_STARTING = false;
let IFRAME = false;
const OMNITOOL_STATUS_CHECK_INTERVAL = 2000; // 2 seconds

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

// HTML templates and constants
const START_SERVER_BUTTON_HTML = `<button id="startServerButton" onclick="startServer()">Start Omnitool Server</button>`;
const GOTO_OMNITOOL_BUTTON_HTML = `<button id="exitIframeButton" onclick="exitIframe()">GOTO OMNITOOL</button>`;
const LOG_CONTAINER_HTML = `<div id="logContainer"></div>`;
const COMMON_STYLES = `
    <style>
        #logContainer {
            height: 400px;
            overflow-y: scroll;
            background-color: black;
            color: lime;
            font-family: 'Courier New', Courier, monospace;
            padding: 10px;
            white-space: pre-wrap;
            border: 1px solid #ddd;
        }
        .highlight-button {
            animation: pulseAnimation 1s infinite;
            background-color: yellow;
            color: black;
            font-weight: bold;
        }                    
        @keyframes pulseAnimation {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
    </style>`;

// Function to generate HTML content based on server status
function generateHTMLContent(newUrl) {
    let startButtonDisabled = OMNITOOL_PRE_READY || OMNITOOL_READY || ALREADY_STARTING ? 'disabled' : '';
    let startButtonClass = !startButtonDisabled ? 'highlight-button' : '';
    let gotoButtonClass = IFRAME ? 'highlight-button' : '';

    // set the startButton to disabled if OMNITOOL_PRE_READY or OMNITOOL_READY or ALREADY_STARTING are true
    let buttonsHTML = `<button id="startServerButton" class="${startButtonClass}" onclick="startServer()" ${startButtonDisabled}>Start Omnitool Server</button>`;

    if (IFRAME) 
    {
        buttonsHTML += `<button id="exitIframeButton" class="${gotoButtonClass}" onclick="exitIframe()">GOTO OMNITOOL</button>`;
    }

    return `
        <html>
            <head>
                <title>Proxy Server</title>
                ${COMMON_STYLES}
            </head>
            <body>
                ${buttonsHTML}
                ${LOG_CONTAINER_HTML}
                <script>
                    function startServer() {
                        document.getElementById('startServerButton').classList.remove
                        ('highlight-button');
                        document.getElementById('startServerButton').disabled = true;


                        fetch('/start-omnitool-server')
                            .then(response => response.json())
                            .then(data => startLogPolling());
  
    
                    }

                    function exitIframe() {
                        window.open('${newUrl}', '_blank');
                    }

                    function startLogPolling() {

                        const interval = setInterval(() => {
                            fetch('/omnitool-logs')
                                .then(response => response.json())
                                .then(data => {
                                    const logContainer = document.getElementById('logContainer');
                                    logContainer.innerText = data.logs.join("\\n");
                                    if (data.ready) {
                                        clearInterval(interval);
                                    }
                                    else {
                                        scrollToBottom(logContainer);
                                    }
                                });
                        }, 500);
                    }

                    function scrollToBottom(element) {
                        element.scrollTop = element.scrollHeight;
                    }

                    startLogPolling();
                </script>
            </body>
        </html>`;
}


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}`);
        });

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

        omnitoolStartProcess.on('close', (code) =>
        {
            const message = `Omnitool server process exited with code: ${code}`;
            console.log(message);
            omnitoolLogs.push(message);

            ALREADY_STARTING = false;
            if (code === 0)
            {
                resolve();
            } else
            {
                reject(`Omnitool server did not start properly.`);
            }
        });
    });
}

function setOmnitoolReady()
{
    if (OMNITOOL_PRE_READY === false) 
    {
        OMNITOOL_PRE_READY = true;
        console.log('Omnitool server is (PRE) ready! ');
        setTimeout(() =>
        {
            console.log('Omnitool server is (NOW) ready! ');
            OMNITOOL_READY = true;
        }, 2000); // Delay by 2 second
    }
}

async function periodicCheckOmnitoolStatus() {
    console.log("Starting async operation...");
    try
    {
        await checkOmnitoolStatus();
    }
    catch (error)
    {
        console.log(`Omnitool not ready: ${error} (IFRAME = ${IFRAME}`);
        OMNITOOL_READY = false;
        OMNITOOL_PRE_READY = false;
    }
    // Schedule the next execution
    setTimeout(periodicCheckOmnitoolStatus, OMNITOOL_STATUS_CHECK_INTERVAL);
}


async function checkOmnitoolStatus()
{

    console.log(`BEFORE: Checking Omnitool status: PRE_READY = ${OMNITOOL_PRE_READY}, READY = ${OMNITOOL_READY}, IFRAME = ${IFRAME}, ALREADY_STARTING = ${ALREADY_STARTING}`);

    return new Promise((resolve, reject) =>
    {
        const options = {
            hostname: CONTAINER_HOST,
            port: CONTAINER_PORT_OMNITOOL,
            path: '/',
            method: 'GET'
        };

        const req = http.request(options, (res) =>
        {
            if (res.statusCode === 200)
            {
                IFRAME = false;
                setOmnitoolReady();
            } 
            else
            {
                OMNITOOL_READY = false;
                OMNITOOL_PRE_READY = false;
            }
            resolve();
        });

        req.on('error', (error) =>
        {
            if (error.code === 'ECONNREFUSED')
            {
                IFRAME  = true;
            }
        });

        req.end();
    });


}



async function startRequestForwardingServer(proxy_port)
{
    const server = http.createServer(async (req, res) =>
    {

        console.log("------------------");
        const localUrl = req.headers['host'];
        const hostname = localUrl.split(':')[0];
        const newUrl = `${PROTOCOL}://${hostname}:${PROXY_PORT_OMNITOOL}`;

        if (!OMNITOOL_READY || IFRAME)
        {
            // Handle GET requests here
            console.log(`Omnitool Server:OMNITOOL_READY =  ${OMNITOOL_READY}`);
            if (req.method === 'GET')
            {
                switch (req.url)
                {
                    case '/start-omnitool-server':
                        {

                            console.log(`Omnitool Server:ALREADY_STARTING =  ${ALREADY_STARTING}`);
                            if (ALREADY_STARTING) 
                            {
                                res.writeHead(200, { 'Content-Type': 'text/html' });
                                res.end("Omnitool server already starting");
                                return;
                            }
                            try
                            {
                                await startOmnitoolServer();
                                res.writeHead(200, { 'Content-Type': 'text/html' });
                                res.end("Omnitool server started successfully");
                            }
                            catch (error)
                            {
                                console.error(error);
                                ALREADY_STARTING = false;
                                res.writeHead(500, { 'Content-Type': 'text/html' });
                                res.end(`Error starting Omnitool server: ${error}`);
                            }

                            return;
                        }

                    case '/omnitool-logs':
                        {
                            res.writeHead(200, { 'Content-Type': 'application/json' });
                            const reply = { logs: omnitoolLogs, ready: OMNITOOL_PRE_READY };
                            res.end(JSON.stringify(reply));
                            return;
                        }

                    case '/':
                        {
                            res.writeHead(200, { 'Content-Type': 'text/html' });
                            res.end(generateHTMLContent(newUrl));
                            return;
                        }

                    default:
                        res.writeHead(404, { 'Content-Type': 'text/html' });
                        res.end(`<html><body><h1>404 Not Found</h1><p>The requested URL ${req.url} was not found on this server.</p></body></html>`);
                        return;
                }
            }
            else 
            {
                // Handle non-GET requests here
                res.writeHead(405, { 'Content-Type': 'text/html' });
                res.end(`<html><body><h1>405 Method Not Allowed</h1><p>The request method ${req.method} is not allowed for the URL ${req.url}.</p></body></html>`);
            }
        }
        else
        {
            // Proxy logic...
            const options = { hostname: CONTAINER_HOST, port: CONTAINER_PORT_OMNITOOL, path: req.url, method: req.method, headers: req.headers };
            const proxy = http.request(options, (proxyRes) =>
            {
                res.writeHead(proxyRes.statusCode, proxyRes.headers);
                proxyRes.pipe(res, { end: true });
            });
            req.pipe(proxy, { end: true });
        }
    });

    server.listen(proxy_port, '0.0.0.0');
    console.log(`Request forwarding server listening on port ${proxy_port}`);
}

async function startManagementServer()
{
    try
    {
        await startRequestForwardingServer(PROXY_PORT_OMNITOOL);

        // Set the interval in milliseconds (e.g., 2000 milliseconds = 2 seconds)

        // Use setInterval to schedule the function
        setInterval(checkOmnitoolStatus, OMNITOOL_STATUS_CHECK_INTERVAL);
    } catch (error)
    {
        console.error('Failed to start servers:', error);
    }
}

startManagementServer();