forked from shadowsocks/shadowsocks-dotcloud
-
Notifications
You must be signed in to change notification settings - Fork 468
/
Copy pathserver.js
156 lines (136 loc) · 3.85 KB
/
server.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
import net from 'net';
import fs from 'fs';
import http from 'http';
import {WebSocketServer, createWebSocketStream} from 'ws';
import parseArgs from 'minimist';
import {Encryptor} from './encrypt.js';
import {inetNtoa, createTransform} from './utils.js';
import {pipeline} from 'node:stream/promises';
const options = {
alias: {
b: 'local_address',
r: 'remote_port',
k: 'password',
c: 'config_file',
m: 'method',
},
string: ['local_address', 'password', 'method', 'config_file'],
default: {
config_file: './config.json',
},
};
const configFromArgs = parseArgs(process.argv.slice(2), options);
const configFile = configFromArgs.config_file;
const configContent = fs.readFileSync(configFile);
const config = JSON.parse(configContent);
if (process.env.PORT) {
config['remote_port'] = +process.env.PORT;
}
if (process.env.KEY) {
config['password'] = process.env.KEY;
}
if (process.env.METHOD) {
config['method'] = process.env.METHOD;
}
for (let k in configFromArgs) {
const v = configFromArgs[k];
config[k] = v;
}
const LOCAL_ADDRESS = config.local_address;
const PORT = config.remote_port;
const KEY = config.password;
let METHOD = config.method;
const server = http.createServer(function (_, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('asdf.');
});
const wsserver = new WebSocketServer({
server,
autoPong: true,
allowSynchronousEvents: true,
perMessageDeflate: false,
});
wsserver.on('connection', async (ws) => {
console.log('concurrent connections:', wsserver.clients.size);
const encryptor = new Encryptor(KEY, METHOD);
let remoteAddr;
let remotePort;
ws.on('error', (err) => console.error(`server: ${err}`));
const conn = createWebSocketStream(ws);
const readable = conn.pipe(
createTransform(encryptor.decrypt.bind(encryptor)),
);
readable.on('error', (e) => console.error(`server: ${e}`));
let data = await readable.read();
while (!data) {
await new Promise((resolve, reject) => {
readable.once('readable', resolve);
});
data = await readable.read();
}
let headerLength = 2;
if (data.length < headerLength) {
conn.end();
return;
}
const addrtype = data[0];
if (![1, 3, 4].includes(addrtype)) {
console.warn(`unsupported addrtype: ${addrtype}`);
conn.end();
return;
}
// read address and port
if (addrtype === 1) {
// ipv4
headerLength = 1 + 4 + 2;
if (data.length < headerLength) {
conn.end();
return;
}
remoteAddr = inetNtoa(4, data.subarray(1, 5));
remotePort = data.readUInt16BE(5);
} else if (addrtype === 4) {
// ipv6
headerLength = 1 + 16 + 2;
if (data.length < headerLength) {
conn.end();
return;
}
remoteAddr = inetNtoa(6, data.subarray(1, 17));
remotePort = data.readUInt16BE(17);
} else {
let addrLen = data[1];
headerLength = 2 + addrLen + 2;
if (data.length < headerLength) {
conn.end();
return;
}
remoteAddr = data.subarray(2, 2 + addrLen).toString('binary');
remotePort = data.readUInt16BE(2 + addrLen);
}
const remote = net.connect(remotePort, remoteAddr);
remote.on('error', (err) => console.error(`server: ${err}`));
console.log('connecting', remoteAddr);
if (data.length > headerLength) {
remote.write(data.subarray(headerLength));
}
pipeline(readable, remote).catch(
(e) => e.name !== 'AbortError' && console.error(`server: ${e}`),
);
pipeline(
remote,
createTransform(encryptor.encrypt.bind(encryptor)),
conn,
).catch((e) => e.name !== 'AbortError' && console.error(`server: ${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;