forked from shadowsocks/shadowsocks-dotcloud
-
Notifications
You must be signed in to change notification settings - Fork 467
/
local.js
229 lines (205 loc) · 6.34 KB
/
local.js
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
import net from 'net';
import fs from 'fs';
import WebSocket, {createWebSocketStream} from 'ws';
import parseArgs from 'minimist';
import {HttpsProxyAgent} from 'https-proxy-agent';
import {Encryptor} from './encrypt.js';
import {inetNtoa, createTransform} from './utils.js';
import {pipeline} from 'node:stream/promises';
const options = {
alias: {
b: 'local_address',
l: 'local_port',
s: 'server',
r: 'remote_port',
k: 'password',
c: 'config_file',
m: 'method',
},
string: ['local_address', 'server', 'password', 'config_file', 'method'],
default: {
config_file: './config.json',
},
};
const configFromArgs = parseArgs(process.argv.slice(2), options);
const configContent = fs.readFileSync(configFromArgs.config_file);
const config = JSON.parse(configContent);
for (let k in configFromArgs) {
const v = configFromArgs[k];
config[k] = v;
}
let SERVER = config.server;
const REMOTE_PORT = config.remote_port;
const LOCAL_ADDRESS = config.local_address;
const PORT = config.local_port;
const KEY = config.password;
let METHOD = config.method;
const timeout = Math.floor(config.timeout * 1000);
const HTTPPROXY = process.env.http_proxy;
if (HTTPPROXY) {
console.log('http proxy:', HTTPPROXY);
}
const prepareServer = function (address) {
const serverUrl = new URL(address);
if (!serverUrl.hostname) {
serverUrl.hostname = address;
serverUrl.pathname = '/';
}
if (!serverUrl.port) {
serverUrl.port = REMOTE_PORT;
}
return serverUrl.toString();
};
if (SERVER instanceof Array) {
SERVER = SERVER.map((s) => prepareServer(s));
} else {
SERVER = prepareServer(SERVER);
}
const getServer = function () {
if (SERVER instanceof Array) {
return SERVER[Math.floor(Math.random() * SERVER.length)];
} else {
return SERVER;
}
};
var server = net.createServer(async (conn) => {
console.log('local connected');
server.getConnections(function (err, count) {
console.log('concurrent connections:', count);
});
const encryptor = new Encryptor(KEY, METHOD);
let ws;
let remoteAddr = null;
let remotePort = null;
let addrToSend = '';
const aServer = getServer();
conn.on('error', (err) => console.error(`local: ${err}`));
let data = await conn.read();
while (!data) {
await new Promise((resolve, reject) => {
conn.once('readable', resolve);
});
data = await conn.read();
}
// handshake
conn.write(Buffer.from([5, 0]));
const nextCmd = data.indexOf(5, 1);
if (nextCmd !== -1) {
data = data.subarray(nextCmd);
} else {
data = await conn.read();
while (!data) {
await new Promise((resolve, reject) => {
conn.once('readable', resolve);
});
data = await conn.read();
}
}
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
let headerLength = 5;
if (data.length < headerLength) {
conn.end();
return;
}
const cmd = data[1];
const addrtype = data[3];
if (cmd !== 1) {
console.log('unsupported cmd:', cmd);
const reply = Buffer.from('\u0005\u0007\u0000\u0001', 'binary');
writer.write(reply);
conn.end();
return;
}
if (![1, 3, 4].includes(addrtype)) {
console.log('unsupported addrtype:', addrtype);
conn.end();
return;
}
addrToSend = data.subarray(3, 4).toString('binary');
// read address and port
if (addrtype === 1) {
// ipv4
headerLength = 4 + 4 + 2;
if (data.length < headerLength) {
conn.end();
return;
}
remoteAddr = inetNtoa(4, data.subarray(4, 8));
addrToSend += data.subarray(4, 10).toString('binary');
remotePort = new DataView(data.buffer).getUint16(8);
} else if (addrtype === 4) {
// ipv6
headerLength = 4 + 16 + 2;
if (data.length < headerLength) {
conn.end();
return;
}
remoteAddr = inetNtoa(6, Buffer.from(data.subarray(4, 20)));
addrToSend += data.subarray(4, 22).toString('binary');
remotePort = new DataView(data.buffer).getUint16(20);
} else {
const addrLen = data[4];
headerLength = 5 + addrLen + 2;
if (data.length < headerLength) {
conn.end();
return;
}
remoteAddr = new TextDecoder().decode(data.subarray(5, 5 + addrLen));
addrToSend += data.subarray(4, 5 + addrLen + 2).toString('binary');
remotePort = new DataView(data.buffer).getUint16(5 + addrLen);
}
let buf = Buffer.alloc(10);
buf.write('\u0005\u0000\u0000\u0001', 0, 4, 'binary');
buf.write('\u0000\u0000\u0000\u0000', 4, 4, 'binary');
buf.writeUInt16BE(remotePort, 8);
conn.write(buf);
// connect to remote server
// ws = new WebSocket aServer, protocol: "binary"
if (HTTPPROXY) {
// WebSocket endpoint for the proxy to connect to
const endpoint = aServer;
const parsed = new URL(endpoint);
//console.log('attempting to connect to WebSocket %j', endpoint);
// create an instance of the `HttpsProxyAgent` class with the proxy server information
const opts = new URL(HTTPPROXY);
// IMPORTANT! Set the `secureEndpoint` option to `false` when connecting
// over "ws://", but `true` when connecting over "wss://"
opts.secureEndpoint = parsed.protocol ? parsed.protocol == 'wss:' : false;
const agent = new HttpsProxyAgent(opts);
ws = new WebSocket(aServer, {
protocol: 'binary',
agent,
});
} else {
ws = new WebSocket(aServer, {
protocol: 'binary',
});
}
ws.on('error', (err) => console.error(`local: ${err}`));
const wss = createWebSocketStream(ws);
console.log(`connecting ${remoteAddr} via ${aServer}`);
const writable = createTransform(encryptor.encrypt.bind(encryptor));
writable.pipe(wss);
writable.write(data.subarray(3));
pipeline(conn, writable).catch(
(e) => e.name !== 'AbortError' && console.error(`local: ${e}`),
);
pipeline(wss, createTransform(encryptor.decrypt.bind(encryptor)), conn).catch(
(e) => e.name !== 'AbortError' && console.error(`local: ${e}`),
);
});
server.listen(PORT, LOCAL_ADDRESS, function () {
const address = server.address();
console.log('server listening at', address);
});
server.on('error', function (e) {
if (e.code === 'EADDRINUSE') {
console.log('address in use, aborting');
}
process.exit(1);
});
export default server;