const http = require('http'); const { spawn } = require('child_process'); const PROXY_PORT = 4444; // Change this to a port different from 1688 const TARGET_HOST = '127.0.0.1'; const TARGET_PORT = 1688; let OMNITOOL_READY = false; let ALREADY_STARTING = false; const VERSION = '0.0.4a'; 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`)) { console.log('Omnitool server started successfully'); setTimeout(() => { OMNITOOL_READY = true; resolve(); }, 1000); // Delay by 1 second } }); 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.`); } }); }); } async function startRequestForwardingServer() { const server = http.createServer((req, res) => handleRoutes(req, res)); server.listen(PROXY_PORT, '0.0.0.0'); console.log(`Request forwarding server listening on port ${PROXY_PORT}`); } async function handleRoutes(req, res) { if ( !OMNITOOL_READY && (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_READY }; res.end(JSON.stringify(reply)); return; } case '/': { const localUrl = req.headers['host']; let htmlContent = `