Commit eeb559ec authored by nanahira's avatar nanahira

manual lookup

parent 16665cdc
Pipeline #21236 failed with stages
in 93 minutes and 56 seconds
...@@ -3,6 +3,8 @@ import { Server, createConnection } from 'net'; ...@@ -3,6 +3,8 @@ import { Server, createConnection } from 'net';
import { hashAddress } from './src/hash-address'; import { hashAddress } from './src/hash-address';
import { createLogger } from 'bunyan'; import { createLogger } from 'bunyan';
import { Socket } from 'net'; import { Socket } from 'net';
import Address from 'ipaddr.js';
import dns from 'dns';
declare module 'net' { declare module 'net' {
interface Server { interface Server {
...@@ -24,20 +26,34 @@ const log = createLogger({ name: 'switcher' }); ...@@ -24,20 +26,34 @@ const log = createLogger({ name: 'switcher' });
const server: Server = createProxyServer({ const server: Server = createProxyServer({
auth: true, auth: true,
createProxyConnection: async (info) => { createProxyConnection: async (info) => {
let socket: Socket; const src: Address.IPv4 | Address.IPv6 = info.socket[targetIpSym];
log.info( log.info(
`Connecting to ${info.dstHost}:${info.dstPort} with ${info.socket[targetIpSym]}`, `Connecting to ${info.dstHost}:${info.dstPort} with ${src?.toString()}`,
); );
try { let socket: Socket;
socket = createConnection({ if (src) {
host: info.dstHost, try {
port: info.dstPort, const lookup = await dns.promises.lookup(
localAddress: info.socket[targetIpSym] || undefined, info.dstHost,
}); src.kind() === 'ipv4' ? 4 : 6,
} catch (e) { );
log.warn( socket = createConnection({
`Failed to connect to ${info.dstHost}:${info.dstPort}, retrying direct connection: ${e}`, host: lookup.address,
); port: info.dstPort,
localAddress: src.toString(),
});
} catch (e) {
log.warn(
`Remote ${
info.dstHost
} does not support ${src.kind()}, fallback to direct connect.`,
);
socket = createConnection({
host: info.dstHost,
port: info.dstPort,
});
}
} else {
socket = createConnection({ socket = createConnection({
host: info.dstHost, host: info.dstHost,
port: info.dstPort, port: info.dstPort,
...@@ -56,8 +72,9 @@ server.on('proxy-auth', (socket, username, password, callback) => { ...@@ -56,8 +72,9 @@ server.on('proxy-auth', (socket, username, password, callback) => {
return; return;
} }
const token = `${username}:${password}`; const token = `${username}:${password}`;
socket[targetIpSym] = hashAddress(process.env.CIDR, token).toString(); const address = hashAddress(process.env.CIDR, token);
log.info(`Mapped ${token} to ${socket[targetIpSym]}`); socket[targetIpSym] = address;
log.info(`Mapped ${token} to ${address.toString()}`);
callback(true); callback(true);
}); });
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment