UNPKG

@cliz/inlets

Version:
66 lines (65 loc) 2.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const cli_1 = require("@cliz/cli"); const net = require("net"); const debug = require('debug')('inlets:tunnel:tcp'); const logger = cli_1.doreamon.logger.getLogger('tunnel:tcp '); async function createServer(ctx, options) { const { containerId, domain } = options; const container = ctx.container.get(containerId); if (!container) { throw new Error(`unknown container with id: ${containerId}`); } if (!container.wsSocket) { throw new Error(`container wsSocket is required with id: ${containerId}`); } const sourcePort = container.sourcePort || await cli_1.api.network.getAvailablePort(); ctx.container.set(containerId, 'sourcePort', sourcePort); container.wsSocket.emit('tcp:ready', { host: domain, port: sourcePort, }); createSourceTCPServer(domain, sourcePort, (server) => { container.sourceServer = server; }, (sourceSocket) => { ctx.container.registerRequest(containerId, sourceSocket.requestId, sourceSocket); container.wsSocket.emit('tcp:connect', { id: containerId, requestId: sourceSocket.requestId, ip: sourceSocket.remoteAddress, }); }); } exports.default = createServer; function createSourceTCPServer(domain, port, onServerCreate, onSocketConnect) { const server = net.createServer(socket => { const requestId = cli_1.doreamon.uuid(); socket.requestId = requestId; logger.info(`[tunnel:tcp ][user][request][start] request id: ${socket.requestId}, ip: ${socket.remoteAddress}`); socket.on('error', error => { logger.error(`socket error:`, error); }); socket.on('end', () => { logger.info(`[tunnel:tcp ][user][request][end] request id: ${socket.requestId}, ip: ${socket.remoteAddress}`); }); onSocketConnect(socket); }); server.listen(port, '0.0.0.0', () => { logger.info(`[tunnel:tcp ] listen at 0.0.0.0:${port}`); onServerCreate(server); }); } function destroy(tcpSocket) { const data = [ 'HTTP/1.1 404 Not Found', 'Content-Type: text/plain; charset=utf-8', 'Content-Length: 9', `Date: ${new Date().toUTCString()}`, 'Connection: keep-alive', 'Keep-Alive: timeout=5', '', 'Not Found' ]; tcpSocket.write(data.join('\r\n')); tcpSocket.destroy(); }