-
Notifications
You must be signed in to change notification settings - Fork 22
/
shadowsocks.js
359 lines (330 loc) · 9.62 KB
/
shadowsocks.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
const dgram = require('dgram');
const exec = require('child_process').exec;
const client = dgram.createSocket('udp4');
const version = require('./package.json').version;
const db = require('./db');
const rop = require('./runOtherProgram');
const http = require('http');
let clientIp = [];
let ssConfig = '127.0.0.1:6001';
let managerConfig = '0.0.0.0:6002';
const argv = process.argv.filter((ele, index) => index > 1);
argv.forEach((f, index) => {
if(f === '--manager' || f === '-m') {
managerConfig = argv[index + 1];
}
if(f === '--shadowsocks' || f === '-s') {
ssConfig = argv[index + 1];
}
});
const mPort = +managerConfig.split(':')[1];
const host = ssConfig.split(':')[0];
const port = +ssConfig.split(':')[1];
client.bind(mPort);
let shadowsocksType = 'libev';
let isNewPython = false;
let lastFlow;
const sendPing = () => {
client.send(Buffer.from('ping'), port, host);
client.send(Buffer.from('list'), port, host);
};
const addMessageCache = [];
const sendAddMessage = (messagePort, messagePassword) => {
addMessageCache.push({ port: messagePort, password: messagePassword});
return Promise.resolve('ok');
};
setInterval(async () => {
let number = 10;
if(addMessageCache.length >= 600) {
number = Math.ceil(addMessageCache.length / 60);
}
for(let i = 0; i < number; i++) {
if(!addMessageCache.length && !libevListed) { continue; }
const message = addMessageCache.shift();
if(!message) { continue; }
const exists = !!portsForLibevObj[message.port];
if(exists) { continue; }
console.log(`增加ss端口: ${ message.port } ${ message.password }`);
client.send(`add: {"server_port": ${ message.port }, "password": "${ message.password }"}`, port, host);
rop.run(message.port, message.password);
}
}, 1000);
const sendDelMessage = (messagePort) => {
console.log(`删除ss端口: ${ messagePort }`);
client.send(`remove: {"server_port": ${ messagePort } }`, port, host);
rop.kill(messagePort);
return Promise.resolve('ok');
};
let existPort = [];
let existPortUpdatedAt = Date.now();
const setExistPort = flow => {
existPort = [];
if(Array.isArray(flow)) {
existPort = flow.map(f => +f.server_port);
} else {
for(const f in flow) {
existPort.push(+f);
}
}
existPortUpdatedAt = Date.now();
};
const compareWithLastFlow = (flow, lastFlow) => {
if(shadowsocksType === 'python') {
return flow;
}
const realFlow = {};
if(!lastFlow) {
for(const f in flow) {
if(flow[f] <= 0) { delete flow[f]; }
}
return flow;
}
for(const f in flow) {
if(lastFlow[f]) {
realFlow[f] = flow[f] - lastFlow[f];
} else {
realFlow[f] = flow[f];
}
}
if(Object.keys(realFlow).map(m => realFlow[m]).sort((a, b) => a > b)[0] < 0) {
return flow;
}
for(const r in realFlow) {
if(realFlow[r] <= 0) { delete realFlow[r]; }
}
return realFlow;
};
let firstFlow = true;
let libevListed = false;
let portsForLibev = [];
let portsForLibevObj = {};
const connect = () => {
client.on('message', async msg => {
const msgStr = new String(msg);
if(msgStr.substr(0, 4) === 'pong') {
shadowsocksType = 'python';
} else if(msgStr.substr(0, 2) === '[{') {
isNewPython = true;
portsForLibev = JSON.parse(msgStr);
portsForLibevObj = {};
portsForLibev.forEach(f => {
portsForLibevObj[f.server_port] = f.password;
});
if(!libevListed) {
resend();
libevListed = true;
}
} else if(msgStr.substr(0, 3) === '[\n\t') {
portsForLibev = JSON.parse(msgStr);
portsForLibevObj = {};
portsForLibev.forEach(f => {
portsForLibevObj[f.server_port] = f.password;
});
if(!libevListed) {
resend();
libevListed = true;
}
} else if(msgStr.substr(0, 5) === 'stat:') {
let flow = JSON.parse(msgStr.substr(5));
setExistPort(flow);
const realFlow = compareWithLastFlow(flow, lastFlow);
const getConnectedIp = port => {
setTimeout(() => {
getIp(+port).then(ips => {
ips.forEach(ip => {
clientIp.push({ port: +port, time: Date.now(), ip });
});
});
}, Math.ceil(Math.random() * 3 * 60 * 1000));
};
if((new Date()).getMinutes() % 3 === 0) {
for(const rf in realFlow) {
if(realFlow[rf]) {
getConnectedIp(rf);
}
}
}
lastFlow = flow;
const insertFlow = Object.keys(realFlow).map(m => {
return {
port: +m,
flow: +realFlow[m],
time: Date.now(),
};
}).filter(f => {
return f.flow > 0;
});
const accounts = await db.listAccount();
if(shadowsocksType === 'python' && !isNewPython) {
insertFlow.forEach(fe => {
const account = accounts.filter(f => {
return fe.port === f.port;
})[0];
if(!account) {
sendDelMessage(fe.port);
}
});
} else {
portsForLibev.forEach(async f => {
const account = accounts.filter(a => a.port === +f.server_port)[0];
if(!account) {
sendDelMessage(+f.server_port);
} else if (account.password !== f.password) {
sendDelMessage(f.server_port);
sendAddMessage(f.server_port, account);
}
});
}
if(insertFlow.length > 0) {
if(firstFlow) {
firstFlow = false;
} else {
const insertPromises = [];
for(let i = 0; i < Math.ceil(insertFlow.length/50); i++) {
const insert = db.insertFlow(insertFlow.slice(i * 50, i * 50 + 50));
insertPromises.push(insert);
}
Promise.all(insertPromises).then();
}
}
};
});
client.on('error', err => {
console.error(`client error: `, err);
});
client.on('close', () => {
console.error(`client close`);
});
};
const startUp = async () => {
client.send(Buffer.from('ping'), port, host);
const accounts = await db.listAccount();
for(const account of accounts) {
sendAddMessage(account.port, account.password);
}
};
const resend = async () => {
if(Date.now() - existPortUpdatedAt >= 180 * 1000) {
existPort = [];
}
const accounts = await db.listAccount();
for(const account of accounts) {
if(!existPort.includes(account.port)) {
sendAddMessage(account.port, account.password);
}
}
};
let isGfw = 0;
let getGfwStatusTime = null;
const getGfwStatus = () => {
if(getGfwStatusTime && isGfw === 0 && Date.now() - getGfwStatusTime < 600 * 1000) { return; }
getGfwStatusTime = Date.now();
const sites = [
'baidu.com:80',
];
const site = sites[0];
// const site = sites[+Math.random().toString().substr(2) % sites.length];
const req = http.request({
hostname: site.split(':')[0],
port: +site.split(':')[1],
path: '/',
method: 'GET',
timeout: 2000,
}, res => {
if(res.statusCode >= 200 && res.statusCode < 400) {
isGfw = 0;
}
res.setEncoding('utf8');
res.on('data', (chunk) => {});
res.on('end', () => {});
});
req.on('timeout', () => {
req.abort();
isGfw += 1;
});
req.on('error', (e) => {
isGfw += 1;
});
req.end();
};
connect();
startUp();
setInterval(() => {
sendPing();
resend();
getGfwStatus();
}, 60 * 1000);
const addAccount = (port, password) => {
return db.addAccount(port, password).then(success => {
sendAddMessage(port, password);
}).then(() => {
return { port, password };
});
};
const removeAccount = port => {
return db.removeAccount(port).then(() => {
return sendDelMessage(port);
}).then(() => {
return { port };
});
};
const changePassword = (port, password) => {
return db.updateAccount(port, password).then(() => {
return sendDelMessage(port);
}).then(() => {
return sendAddMessage(port, password);
}).then(() => {
return { port };
});
};
const listAccount = () => {
return Promise.resolve(db.listAccount());
};
const getFlow = (options) => {
const startTime = options.startTime || 0;
const endTime = options.endTime || Date.now();
return db.getFlow(options);
};
const getVersion = () => {
return Promise.resolve({
version: version + 'T',
isGfw: !!(isGfw > 5),
});
};
const getIp = port => {
const cmd = `ss -an | grep ":${ port } " | grep ESTAB | awk '{print $6}' | cut -d: -f1 | grep -v 127.0.0.1 | uniq -d`;
return new Promise((resolve, reject) => {
exec(cmd, function(err, stdout, stderr){
if(err) {
reject(stderr);
} else {
const result = [];
stdout.split('\n').filter(f => f).forEach(f => {
if(result.indexOf(f) < 0) { result.push(f); }
});
resolve(result);
}
});
});
};
const getClientIp = port => {
clientIp = clientIp.filter(f => {
return Date.now() - f.time <= 15 * 60 * 1000;
});
const result = [];
clientIp.filter(f => {
return Date.now() - f.time <= 15 * 60 * 1000 && f.port === port;
}).map(m => {
return m.ip;
}).forEach(f => {
if(result.indexOf(f) < 0) { result.push(f); }
});
return Promise.resolve(result);
};
exports.addAccount = addAccount;
exports.removeAccount = removeAccount;
exports.changePassword = changePassword;
exports.listAccount = listAccount;
exports.getFlow = getFlow;
exports.getVersion = getVersion;
exports.getClientIp = getClientIp;