-
Notifications
You must be signed in to change notification settings - Fork 791
/
Copy pathoutline_shadowsocks_server.ts
174 lines (160 loc) · 6.03 KB
/
outline_shadowsocks_server.ts
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
// Copyright 2018 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as child_process from 'child_process';
import * as jsyaml from 'js-yaml';
import * as mkdirp from 'mkdirp';
import * as path from 'path';
import * as file from '../infrastructure/file';
import * as logging from '../infrastructure/logging';
import {ShadowsocksAccessKey, ShadowsocksServer} from '../model/shadowsocks_server';
/** Represents an outline-ss-server configuration with multiple services. */
export interface OutlineSSServerConfig {
services: {
listeners: {
type: string;
address: string;
}[];
keys: {
id: string;
cipher: string;
secret: string;
}[];
}[];
}
// Runs outline-ss-server.
export class OutlineShadowsocksServer implements ShadowsocksServer {
private ssProcess: child_process.ChildProcess;
private ipCountryFilename?: string;
private ipAsnFilename?: string;
private isReplayProtectionEnabled = false;
/**
* @param binaryFilename The location for the outline-ss-server binary.
* @param configFilename The location for the outline-ss-server config.
* @param verbose Whether to run the server in verbose mode.
* @param metricsLocation The location from where to serve the Prometheus data metrics.
*/
constructor(
private readonly binaryFilename: string,
private readonly configFilename: string,
private readonly verbose: boolean,
private readonly metricsLocation: string
) {}
/**
* Configures the Shadowsocks Server with country data to annotate Prometheus data metrics.
* @param ipCountryFilename The location of the ip-country.mmdb IP-to-country database file.
*/
configureCountryMetrics(ipCountryFilename: string): OutlineShadowsocksServer {
this.ipCountryFilename = ipCountryFilename;
return this;
}
/**
* Configures the Shadowsocks Server with ASN data to annotate Prometheus data metrics.
* @param ipAsnFilename The location of the ip-asn.mmdb IP-to-ASN database file.
*/
configureAsnMetrics(ipAsnFilename: string): OutlineShadowsocksServer {
this.ipAsnFilename = ipAsnFilename;
return this;
}
enableReplayProtection(): OutlineShadowsocksServer {
this.isReplayProtectionEnabled = true;
return this;
}
// Promise is resolved after the outline-ss-config config is updated and the SIGHUP sent.
// Keys may not be active yet.
// TODO(fortuna): Make promise resolve when keys are ready.
update(keys: ShadowsocksAccessKey[]): Promise<void> {
return this.writeConfigFile(keys).then(() => {
if (!this.ssProcess) {
this.start();
return Promise.resolve();
} else {
this.ssProcess.kill('SIGHUP');
}
});
}
private writeConfigFile(keys: ShadowsocksAccessKey[]): Promise<void> {
return new Promise((resolve, reject) => {
const validKeys: ShadowsocksAccessKey[] = keys.filter((key) => {
if (!isAeadCipher(key.cipher)) {
logging.error(
`Cipher ${key.cipher} for access key ${key.id} is not supported: use an AEAD cipher instead.`
);
return false;
}
return true;
});
const config: OutlineSSServerConfig = {services: []};
const keysByPort: Record<number, ShadowsocksAccessKey[]> = {};
for (const key of validKeys) {
(keysByPort[key.port] ??= []).push(key);
}
for (const port in keysByPort) {
const service = {
listeners: [
{type: 'tcp', address: `[::]:${port}`},
{type: 'udp', address: `[::]:${port}`},
],
keys: keysByPort[port].map((key) => ({
id: key.id,
cipher: key.cipher,
secret: key.secret,
})),
};
config.services.push(service);
}
mkdirp.sync(path.dirname(this.configFilename));
try {
file.atomicWriteFileSync(this.configFilename, jsyaml.safeDump(config, {sortKeys: true}));
resolve();
} catch (error) {
reject(error);
}
});
}
private start() {
const commandArguments = ['-config', this.configFilename, '-metrics', this.metricsLocation];
if (this.ipCountryFilename) {
commandArguments.push('-ip_country_db', this.ipCountryFilename);
}
if (this.ipAsnFilename) {
commandArguments.push('-ip_asn_db', this.ipAsnFilename);
}
if (this.verbose) {
commandArguments.push('-verbose');
}
if (this.isReplayProtectionEnabled) {
commandArguments.push('--replay_history=10000');
}
logging.info('======== Starting Outline Shadowsocks Service ========');
logging.info(`${this.binaryFilename} ${commandArguments.map((a) => `"${a}"`).join(' ')}`);
this.ssProcess = child_process.spawn(this.binaryFilename, commandArguments);
this.ssProcess.on('error', (error) => {
logging.error(`Error spawning outline-ss-server: ${error}`);
});
this.ssProcess.on('exit', (code, signal) => {
logging.info(`outline-ss-server has exited with error. Code: ${code}, Signal: ${signal}`);
logging.info('Restarting');
this.start();
});
// This exposes the outline-ss-server output on the docker logs.
// TODO(fortuna): Consider saving the output and expose it through the manager service.
this.ssProcess.stdout.pipe(process.stdout);
this.ssProcess.stderr.pipe(process.stderr);
}
}
// List of AEAD ciphers can be found at https://shadowsocks.org/en/spec/AEAD-Ciphers.html
function isAeadCipher(cipherAlias: string) {
cipherAlias = cipherAlias.toLowerCase();
return cipherAlias.endsWith('gcm') || cipherAlias.endsWith('poly1305');
}