-
Notifications
You must be signed in to change notification settings - Fork 74
/
xray.py
253 lines (215 loc) · 7.21 KB
/
xray.py
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
import atexit
import json
import re
import subprocess
import threading
from collections import deque
from contextlib import contextmanager
from config import DEBUG, SSL_CERT_FILE, SSL_KEY_FILE, XRAY_API_PORT
from logger import logger
class XRayConfig(dict):
"""
Loads Xray config json
config must contain an inbound with the API_INBOUND tag name which handles API requests
"""
def __init__(self, config: str, peer_ip: str):
config = json.loads(config)
self.api_port = XRAY_API_PORT
self.ssl_cert = SSL_CERT_FILE
self.ssl_key = SSL_KEY_FILE
self.peer_ip = peer_ip
super().__init__(config)
self._apply_api()
def to_json(self, **json_kwargs):
return json.dumps(self, **json_kwargs)
def _apply_api(self):
for inbound in self.get('inbounds', []):
if inbound.get('protocol') == 'dokodemo-door':
self['inbounds'].remove(inbound)
for rule in self.get('routing', {}).get("rules", []):
api_tag = self.get('api', {}).get('tag')
if api_tag and rule.get('outboundTag') == api_tag:
self['routing']['rules'].remove(rule)
self["api"] = {
"services": [
"HandlerService",
"StatsService",
"LoggerService"
],
"tag": "API"
}
self["stats"] = {}
self["policy"] = {
"levels": {
"0": {
"statsUserUplink": True,
"statsUserDownlink": True
}
},
"system": {
"statsInboundDownlink": False,
"statsInboundUplink": False,
"statsOutboundDownlink": True,
"statsOutboundUplink": True
}
}
inbound = {
"listen": "0.0.0.0",
"port": self.api_port,
"protocol": "dokodemo-door",
"settings": {
"address": "127.0.0.1"
},
"streamSettings": {
"security": "tls",
"tlsSettings": {
"certificates": [
{
"certificateFile": self.ssl_cert,
"keyFile": self.ssl_key
}
]
}
},
"tag": "API_INBOUND"
}
try:
self["inbounds"].insert(0, inbound)
except KeyError:
self["inbounds"] = []
self["inbounds"].insert(0, inbound)
rule = {
"inboundTag": [
"API_INBOUND"
],
"source": [
"127.0.0.1",
self.peer_ip
],
"outboundTag": "API",
"type": "field"
}
try:
self["routing"]["rules"].insert(0, rule)
except KeyError:
self["routing"] = {"rules": []}
self["routing"]["rules"].insert(0, rule)
class XRayCore:
def __init__(self,
executable_path: str = "/usr/bin/xray",
assets_path: str = "/usr/share/xray"):
self.executable_path = executable_path
self.assets_path = assets_path
self.version = self.get_version()
self.process = None
self.restarting = False
self._logs_buffer = deque(maxlen=100)
self._temp_log_buffers = {}
self._on_start_funcs = []
self._on_stop_funcs = []
self._env = {
"XRAY_LOCATION_ASSET": assets_path
}
atexit.register(lambda: self.stop() if self.started else None)
def get_version(self):
cmd = [self.executable_path, "version"]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('utf-8')
m = re.match(r'^Xray (\d+\.\d+\.\d+)', output)
if m:
return m.groups()[0]
def __capture_process_logs(self):
def capture_and_debug_log():
while self.process:
output = self.process.stdout.readline()
if output:
output = output.strip()
self._logs_buffer.append(output)
for buf in list(self._temp_log_buffers.values()):
buf.append(output)
logger.debug(output)
elif not self.process or self.process.poll() is not None:
break
def capture_only():
while self.process:
output = self.process.stdout.readline()
if output:
output = output.strip()
self._logs_buffer.append(output)
for buf in list(self._temp_log_buffers.values()):
buf.append(output)
elif not self.process or self.process.poll() is not None:
break
if DEBUG:
threading.Thread(target=capture_and_debug_log).start()
else:
threading.Thread(target=capture_only).start()
@contextmanager
def get_logs(self):
buf = deque(self._logs_buffer, maxlen=100)
buf_id = id(buf)
try:
self._temp_log_buffers[buf_id] = buf
yield buf
except (EOFError, TimeoutError):
pass
finally:
del self._temp_log_buffers[buf_id]
del buf
@property
def started(self):
if not self.process:
return False
if self.process.poll() is None:
return True
return False
def start(self, config: XRayConfig):
if self.started is True:
raise RuntimeError("Xray is started already")
if config.get('log', {}).get('logLevel') in ('none', 'error'):
config['log']['logLevel'] = 'warning'
cmd = [
self.executable_path,
"run",
'-config',
'stdin:'
]
self.process = subprocess.Popen(
cmd,
env=self._env,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True
)
self.process.stdin.write(config.to_json())
self.process.stdin.flush()
self.process.stdin.close()
self.__capture_process_logs()
# execute on start functions
for func in self._on_start_funcs:
threading.Thread(target=func).start()
def stop(self):
if not self.started:
return
self.process.terminate()
self.process = None
logger.warning("Xray core stopped")
# execute on stop functions
for func in self._on_stop_funcs:
threading.Thread(target=func).start()
def restart(self, config: XRayConfig):
if self.restarting is True:
return
self.restarting = True
try:
logger.warning("Restarting Xray core...")
self.stop()
self.start(config)
finally:
self.restarting = False
def on_start(self, func: callable):
self._on_start_funcs.append(func)
return func
def on_stop(self, func: callable):
self._on_stop_funcs.append(func)
return func