forked from xyuanmu/XX-Mini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.py
261 lines (228 loc) · 10.3 KB
/
proxy.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
254
255
256
257
258
259
260
261
#!/usr/bin/env python2
# coding:utf-8
# Based on GAppProxy 2.0.0 by Du XiaoGang <dugang.2008@gmail.com>
# Based on WallProxy 0.4.0 by Hust Moon <www.ehust@gmail.com>
# Contributor:
# Phus Lu <phus.lu@gmail.com>
# Hewig Xu <hewigovens@gmail.com>
# Ayanamist Yang <ayanamist@gmail.com>
# V.E.O <V.E.O@tom.com>
# Max Lv <max.c.lv@gmail.com>
# AlsoTang <alsotang@gmail.com>
# Christopher Meng <cickumqt@gmail.com>
# Yonsm Guo <YonsmGuo@gmail.com>
# Parkman <cseparkman@gmail.com>
# Ming Bai <mbbill@gmail.com>
# Bin Yu <yubinlove1991@gmail.com>
# lileixuan <lileixuan@gmail.com>
# Cong Ding <cong@cding.org>
# Zhang Youfu <zhangyoufu@gmail.com>
# Lu Wei <luwei@barfoo>
# Harmony Meow <harmony.meow@gmail.com>
# logostream <logostream@gmail.com>
# Rui Wang <isnowfy@gmail.com>
# Wang Wei Qiang <wwqgtxx@gmail.com>
# Felix Yan <felixonmars@gmail.com>
# QXO <qxodream@gmail.com>
# Geek An <geekan@foxmail.com>
# Poly Rabbit <mcx_221@foxmail.com>
# oxnz <yunxinyi@gmail.com>
# Shusen Liu <liushusen.smart@gmail.com>
# Yad Smood <y.s.inside@gmail.com>
# Chen Shuang <cs0x7f@gmail.com>
# cnfuyu <cnfuyu@gmail.com>
# cuixin <steven.cuixin@gmail.com>
__version__ = '1.1'
import sys
import os
sys.dont_write_bytecode = True
__file__ = os.path.abspath(__file__)
if os.path.islink(__file__):
__file__ = getattr(os, 'readlink', lambda x: x)(__file__)
work_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(work_path)
sys.path.append(os.path.abspath( os.path.join(work_path, 'lib')))
if sys.platform.startswith("linux"): sys.path.append(work_path + '/lib.egg/lib/')
from config import config
from OpenSSL import version as openssl_version
from pac_server import PACServerHandler, ProxyUtil
from xlog import getLogger
xlog = getLogger("gae_proxy")
xlog.set_buffer(500)
data_path = os.path.join(work_path, 'data')
if not os.path.isdir(data_path): os.mkdir(data_path)
if config.log_file:
log_file = os.path.join(data_path, "local.log")
xlog.set_file(log_file)
def summary():
appids = '|'.join(config.GAE_APPIDS)
if len(appids) > 56:
appids = appids[:55] + '..'
info = '-'*80
info += '\nXX-Mini Version : %s (python/%s pyopenssl/%s)\n' % (__version__, sys.version.split()[0], openssl_version.__version__)
info += 'Listen Address : %s:%d\n' % (config.LISTEN_IP if config.LISTEN_IP == '127.0.0.1' else ProxyUtil.get_listen_ip(), config.LISTEN_PORT)
info += 'Setting File : %sproxy.ini\n' % (config.MANUAL_LOADED + '/') if config.MANUAL_LOADED else ''
info += '%s Proxy : %s:%s\n' % (config.PROXY_TYPE, config.PROXY_HOST, config.PROXY_PORT) if config.PROXY_ENABLE else ''
info += 'GAE APPID : %s\n' % appids
info += 'Pac Server : http://%s:%d/%s\n' % (config.PAC_IP if config.PAC_IP == '127.0.0.1' else ProxyUtil.get_listen_ip(), config.PAC_PORT, config.PAC_FILE) if config.PAC_ENABLE else ''
info += 'Pac File : file://%s\n' % os.path.abspath(os.path.join(data_path, config.PAC_FILE)) if config.PAC_ENABLE else ''
info += '-'*80
return info
xlog.info(summary())
xlog.set_time()
if config.LISTEN_DEBUGINFO:
xlog.set_debug()
import time
import traceback
import random
import threading
import urllib2
import simple_http_server
import proxy_handler
import connect_control
import connect_manager
from cert_util import CertUtil
from google_ip_range import ip_range
from google_ip import google_ip
from check_local_network import _simple_check_worker as simple_check_worker
from gae_handler import spawn_later
# launcher/module_init will check this value for start/stop finished
ready = False
def pre_start():
def get_windows_running_process_list():
import os
import glob
import ctypes
import collections
Process = collections.namedtuple('Process', 'pid name exe')
process_list = []
if os.name == 'nt':
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
lpidProcess= (ctypes.c_ulong * 1024)()
cb = ctypes.sizeof(lpidProcess)
cbNeeded = ctypes.c_ulong()
ctypes.windll.psapi.EnumProcesses(ctypes.byref(lpidProcess), cb, ctypes.byref(cbNeeded))
nReturned = cbNeeded.value/ctypes.sizeof(ctypes.c_ulong())
pidProcess = [i for i in lpidProcess][:nReturned]
has_queryimage = hasattr(ctypes.windll.kernel32, 'QueryFullProcessImageNameA')
for pid in pidProcess:
hProcess = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid)
if hProcess:
modname = ctypes.create_string_buffer(2048)
count = ctypes.c_ulong(ctypes.sizeof(modname))
if has_queryimage:
ctypes.windll.kernel32.QueryFullProcessImageNameA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
else:
ctypes.windll.psapi.GetModuleFileNameExA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
exe = modname.value
name = os.path.basename(exe)
process_list.append(Process(pid=pid, name=name, exe=exe))
ctypes.windll.kernel32.CloseHandle(hProcess)
elif sys.platform.startswith('linux'):
for filename in glob.glob('/proc/[0-9]*/cmdline'):
pid = int(filename.split('/')[2])
exe_link = '/proc/%d/exe' % pid
if os.path.exists(exe_link):
exe = os.readlink(exe_link)
name = os.path.basename(exe)
process_list.append(Process(pid=pid, name=name, exe=exe))
else:
try:
import psutil
process_list = psutil.get_process_list()
except Exception as e:
xlog.exception('psutil.get_windows_running_process_list() failed: %r', e)
return process_list
if sys.platform == 'cygwin':
xlog.info('cygwin is not officially supported, please continue at your own risk :)')
#sys.exit(-1)
elif os.name == 'posix':
try:
import resource
resource.setrlimit(resource.RLIMIT_NOFILE, (8192, -1))
except Exception as e:
pass
elif os.name == 'nt':
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW(u'GoAgent v%s' % __version__)
if not config.LISTEN_VISIBLE:
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
else:
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 1)
if config.LOVE_ENABLE and random.randint(1, 100) <= 20:
title = ctypes.create_unicode_buffer(1024)
ctypes.windll.kernel32.GetConsoleTitleW(ctypes.byref(title), len(title)-1)
ctypes.windll.kernel32.SetConsoleTitleW('%s %s' % (title.value, random.choice(config.LOVE_TIP)))
blacklist = {'360safe': False,
'QQProtect': False, }
softwares = [k for k, v in blacklist.items() if v]
if softwares:
tasklist = '\n'.join(x.name for x in get_windows_running_process_list()).lower()
softwares = [x for x in softwares if x.lower() in tasklist]
if softwares:
title = u'GoAgent 建议'
error = u'某些安全软件(如 %s)可能和本软件存在冲突,造成 CPU 占用过高。\n如有此现象建议暂时退出此安全软件来继续运行GoAgent' % ','.join(softwares)
ctypes.windll.user32.MessageBoxW(None, error, title, 0)
#sys.exit(0)
if config.GAE_APPIDS[0] == 'gae_proxy':
xlog.critical('please edit %s to add your appid to [gae] !', config.CONFIG_FILENAME)
sys.exit(-1)
if config.PAC_ENABLE:
pac_ip = config.PAC_IP
url = 'http://%s:%d/%s' % (pac_ip, config.PAC_PORT, config.PAC_FILE)
spawn_later(600, urllib2.build_opener(urllib2.ProxyHandler({})).open, url)
def main():
global ready
for i in range(50):
check_network = simple_check_worker()
if check_network:
break
else:
time.sleep(3)
if (i+1)%5 == 0: xlog.error('Failed to connect to network, please check!')
if i+1 == 50: return
pre_start()
ip_range.load()
google_ip.check()
connect_control.keep_running = True
connect_manager.https_manager.load_config()
xlog.debug("## GAEProxy set keep_running: %s", connect_control.keep_running)
CertUtil.init_ca()
proxy_daemon = simple_http_server.HTTPServer((config.LISTEN_IP, config.LISTEN_PORT), proxy_handler.GAEProxyHandler)
proxy_thread = threading.Thread(target=proxy_daemon.serve_forever)
proxy_thread.setDaemon(True)
proxy_thread.start()
if config.PAC_ENABLE:
pac_daemon = simple_http_server.HTTPServer((config.PAC_IP, config.PAC_PORT), PACServerHandler)
pac_thread = threading.Thread(target=pac_daemon.serve_forever)
pac_thread.setDaemon(True)
pac_thread.start()
urllib2.urlopen('http://127.0.0.1:%d/%s' % (config.PAC_PORT, config.PAC_FILE))
#PACServerHandler.do_GET()
ready = True # checked by launcher.module_init
while connect_control.keep_running:
time.sleep(1)
xlog.info("Exiting gae_proxy module...")
proxy_daemon.shutdown()
proxy_daemon.server_close()
proxy_thread.join()
if config.PAC_ENABLE:
pac_daemon.shutdown()
pac_daemon.server_close()
pac_thread.join()
ready = False # checked by launcher.module_init
xlog.debug("## GAEProxy set keep_running: %s", connect_control.keep_running)
# called by launcher/module/stop
def terminate():
xlog.info("start to terminate GAE_Proxy")
connect_control.keep_running = False
xlog.debug("## Set keep_running: %s", connect_control.keep_running)
if __name__ == '__main__':
try:
main()
except Exception:
traceback.print_exc(file=sys.stdout)
except KeyboardInterrupt:
terminate()
sys.exit()