Skip to content

Commit e21660d

Browse files
author
debian
committed
1.1.0 fix bugs
1 parent 7169c82 commit e21660d

File tree

12 files changed

+268
-128
lines changed

12 files changed

+268
-128
lines changed

goagent/3.1.35/local/cert_util.py

+54-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,21 @@
1414
import logging
1515

1616

17+
current_path = os.path.dirname(os.path.abspath(__file__))
18+
python_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, os.pardir, 'python27', '1.0'))
19+
data_path = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir, os.pardir, 'data', 'goagent'))
20+
if not os.path.isdir(data_path):
21+
data_path = current_path
22+
23+
noarch_lib = os.path.abspath( os.path.join(python_path, 'lib', 'noarch'))
24+
sys.path.append(noarch_lib)
25+
26+
if sys.platform == "win32":
27+
win32_lib = os.path.abspath( os.path.join(python_path, 'lib', 'win32'))
28+
sys.path.append(win32_lib)
29+
elif sys.platform == "linux" or sys.platform == "linux2":
30+
linux_lib = os.path.abspath( os.path.join(python_path, 'lib', 'linux'))
31+
sys.path.append(linux_lib)
1732

1833
import OpenSSL
1934

@@ -123,9 +138,11 @@ class CertUtil(object):
123138
"""CertUtil module, based on mitmproxy"""
124139

125140
ca_vendor = 'GoAgent'
126-
ca_keyfile = 'CA.crt'
141+
ca_keyfile = os.path.join(data_path, 'CA.crt')
127142
ca_thumbprint = ''
128-
ca_certdir = 'certs'
143+
ca_certdir = os.path.join(data_path, 'certs')
144+
if not os.path.isdir(ca_certdir):
145+
os.mkdir(ca_certdir)
129146
ca_lock = threading.Lock()
130147

131148
@staticmethod
@@ -247,7 +264,8 @@ def win32_notify( msg="msg", title="Title"):
247264

248265
@staticmethod
249266
def import_ca(certfile):
250-
commonname = os.path.splitext(os.path.basename(certfile))[0]
267+
#commonname = os.path.splitext(os.path.basename(certfile))[0]
268+
commonname = "GoAgent CA - GoAgent"
251269
if sys.platform.startswith('win'):
252270
import ctypes
253271
with open(certfile, 'rb') as fp:
@@ -298,8 +316,27 @@ class CRYPT_HASH_BLOB(ctypes.Structure):
298316
if not os.path.exists(pemfile):
299317
return os.system('cp "%s" "%s" && update-ca-certificates' % (certfile, new_certfile))
300318
elif any(os.path.isfile('%s/certutil' % x) for x in os.environ['PATH'].split(os.pathsep)):
301-
cmd_line = 'certutil -L -d sql:$HOME/.pki/nssdb | grep "%s" || certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "%s" -i "%s"' % (commonname, commonname, certfile)
302-
return os.system(cmd_line)
319+
# certutil -L -d sql:$HOME/.pki/nssdb | grep "%s" || % commonname,
320+
# remove old cert first
321+
cmd_line = 'certutil -d sql:$HOME/.pki/nssdb -D -n "%s" ' % commonname
322+
os.system(cmd_line)
323+
324+
# install new cert
325+
cmd_line = 'certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "%s" -i "%s"' % (commonname, certfile)
326+
os.system(cmd_line)
327+
328+
#Firefox:
329+
firefox_config_path = get_linux_firefox_path()
330+
if not firefox_config_path:
331+
return
332+
333+
cmd_line = 'certutil -d %s -D -n "%s" ' % (firefox_config_path, commonname)
334+
os.system(cmd_line) # remove old cert first
335+
336+
cmd_line = 'certutil -d %s -A -t "C,," -n "%s" -i "%s"' % (firefox_config_path, commonname, certfile)
337+
os.system(cmd_line) # install new cert
338+
339+
return 0
303340
else:
304341
logging.warning('please install *libnss3-tools* package to import GoAgent root ca')
305342
return 0
@@ -362,7 +399,19 @@ def check_ca():
362399
if not os.path.exists(certdir):
363400
os.makedirs(certdir)
364401

402+
def get_linux_firefox_path():
403+
home_path = os.path.expanduser("~")
404+
firefox_path = os.path.join(home_path, ".mozilla/firefox")
405+
if not os.path.isdir(firefox_path):
406+
return
407+
408+
for filename in os.listdir(firefox_path):
409+
if filename.endswith(".default") and os.path.isdir(os.path.join(firefox_path, filename)):
410+
config_path = os.path.join(firefox_path, filename)
411+
return config_path
412+
365413

366414
if __name__ == '__main__':
367415
#capath = os.path.join(os.path.dirname(os.path.abspath(__file__)), CertUtil.ca_keyfile)
368416
CertUtil.check_ca()
417+
#print get_linux_firefox_path()

goagent/3.1.35/local/connect_manager.py

+61-49
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
#!/usr/bin/env python
22
# coding:utf-8
33

4-
import sys
54
import os
65
import errno
76
import binascii
87
import time
9-
import thread
108
import socket
119
import select
1210
import Queue
@@ -155,8 +153,8 @@ def __init__(self):
155153
self.max_retry = 3
156154
self.timeout = 3
157155
self.max_timeout = 5
158-
self.max_thread_num = 40
159-
self.connection_pool_num = 30
156+
self.max_thread_num = 10
157+
self.connection_pool_num = 20
160158

161159
self.conn_pool = Connect_pool() #Queue.PriorityQueue()
162160

@@ -173,10 +171,15 @@ def save_ssl_connection_for_reuse(self, ssl_sock):
173171

174172
while self.conn_pool.qsize() > self.connection_pool_num:
175173
t, ssl_sock = self.conn_pool.get_slowest()
176-
if t < 300:
174+
175+
if t < 500:
177176
#self.conn_pool.put( (ssl_sock.handshake_time, ssl_sock) )
177+
ssl_sock.close()
178178
return
179-
ssl_sock.close()
179+
else:
180+
ssl_sock.close()
181+
182+
180183

181184
def create_ssl_connection(self):
182185

@@ -268,6 +271,7 @@ def connect_thread():
268271
if ssl_sock:
269272
ssl_sock.last_use_time = time.time()
270273
self.conn_pool.put((ssl_sock.handshake_time, ssl_sock))
274+
time.sleep(1)
271275
finally:
272276
self.thread_num_lock.acquire()
273277
self.thread_num -= 1
@@ -282,6 +286,7 @@ def create_more_connection():
282286
p = threading.Thread(target = connect_thread)
283287
p.daemon = True
284288
p.start()
289+
time.sleep(0.5)
285290

286291

287292
while True:
@@ -320,14 +325,19 @@ def create_more_connection():
320325

321326

322327
class Forward_connection_manager():
323-
timeout = 3
324-
max_timeout = 5
328+
timeout = 1
329+
max_timeout = 10
325330
tcp_connection_cache = Queue.PriorityQueue()
331+
thread_num_lock = threading.Lock()
332+
thread_num = 0
333+
max_thread_num = 10
334+
335+
def create_connection(self, port=443, sock_life=5):
336+
if port != 443:
337+
logging.warn("forward port %d not supported.", port)
338+
return None
326339

327-
def create_connection(self, sock_life=5):
328-
def _create_connection(ip_port, queobj, delay=0):
329-
if delay != 0:
330-
time.sleep(delay)
340+
def _create_connection(ip_port):
331341
ip = ip_port[0]
332342
sock = None
333343
# start connection time record
@@ -358,54 +368,52 @@ def _create_connection(ip_port, queobj, delay=0):
358368
logging.debug("tcp conn %s time:%d", ip, conn_time * 1000)
359369

360370
# put ssl socket object to output queobj
361-
queobj.put(sock)
371+
self.tcp_connection_cache.put((time.time(), sock))
362372
except Exception as e:
363-
# any socket.error, put Excpetions to output queobj.
364-
queobj.put(e)
365373
conn_time = int((time.time() - start_time) * 1000)
366374
logging.debug("tcp conn %s fail t:%d", ip, conn_time)
367375
google_ip.report_connect_fail(ip)
368376
#logging.info("create_tcp report fail ip:%s", ip)
369377
if sock:
370378
sock.close()
379+
finally:
380+
self.thread_num_lock.acquire()
381+
self.thread_num -= 1
382+
self.thread_num_lock.release()
371383

372-
def recycle_connection(count, queobj):
373-
for i in range(count):
374-
sock = queobj.get()
375-
if sock and not isinstance(sock, Exception):
376-
self.tcp_connection_cache.put((time.time(), sock))
377-
378-
try:
379-
ctime, sock = self.tcp_connection_cache.get_nowait()
380-
if time.time() - ctime < sock_life:
381-
return sock
382-
except Queue.Empty:
383-
pass
384384

385+
while True:
386+
try:
387+
ctime, sock = self.tcp_connection_cache.get_nowait()
388+
if time.time() - ctime < sock_life:
389+
return sock
390+
else:
391+
sock.close()
392+
continue
393+
except Queue.Empty:
394+
break
385395

386-
port = 443
387396
start_time = time.time()
388-
#while time.time() - start_time < self.max_timeout:
389-
for j in range(3):
390-
addresses = []
391-
for i in range(3):
397+
while time.time() - start_time < self.max_timeout:
398+
399+
if self.thread_num < self.max_thread_num:
392400
ip = google_ip.get_gws_ip()
393401
if not ip:
394-
logging.warning("no gws ip.")
402+
logging.error("no gws ip.")
395403
return
396-
addresses.append((ip, port))
397-
398-
addrs = addresses
399-
queobj = Queue.Queue()
400-
delay = 0
401-
for addr in addrs:
402-
thread.start_new_thread(_create_connection, (addr, queobj, delay))
403-
#delay += 0.05
404-
for i in range(len(addrs)):
405-
result = queobj.get()
406-
if not isinstance(result, (socket.error, OSError, IOError)):
407-
thread.start_new_thread(recycle_connection, (len(addrs)-i-1, queobj))
408-
return result
404+
addr = (ip, port)
405+
self.thread_num_lock.acquire()
406+
self.thread_num += 1
407+
self.thread_num_lock.release()
408+
p = threading.Thread(target=_create_connection, args=(addr,))
409+
p.daemon = True
410+
p.start()
411+
412+
try:
413+
ctime, sock = self.tcp_connection_cache.get(timeout=0.4)
414+
return sock
415+
except:
416+
continue
409417
logging.warning('create tcp connection fail.')
410418

411419

@@ -425,6 +433,10 @@ def forward_socket(self, local, remote, timeout=60, tick=2, bufsize=8192):
425433
for sock in ins:
426434
data = sock.recv(bufsize)
427435
if not data:
436+
if sock is remote:
437+
logging.debug("forward remote disconnected.")
438+
else:
439+
logging.debug("forward local disconnected.")
428440
return
429441

430442
if sock is remote:
@@ -433,15 +445,15 @@ def forward_socket(self, local, remote, timeout=60, tick=2, bufsize=8192):
433445
else:
434446
remote.sendall(data)
435447
timecount = timeout
436-
except NetWorkIOError as e:
448+
except Exception as e:
437449
if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE):
438-
raise
450+
logging.exception("forward except:%s.", e)
439451
finally:
440452
if local:
441453
local.close()
442454
if remote:
443455
remote.close()
444-
logging.debug("forward closed.")
456+
445457

446458

447459

goagent/3.1.35/local/google_ip.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424

2525
# const value:
26-
max_check_ip_thread_num = 10
26+
max_check_ip_thread_num = 5
2727
max_good_ip_num = 4000 # stop scan ip when enough
2828

2929

@@ -46,6 +46,7 @@ class Check_ip():
4646
gws_ip_list = [] # gererate from ip_dict, sort by handshake_time, when get_batch_ip
4747
ip_lock = threading.Lock()
4848
iplist_need_save = 0
49+
iplist_saved_time = 0
4950
last_sort_time_for_gws = 0 # keep status for avoid wast too many cpu
5051

5152
network_fail_time = 0 # keep status for avoid retry too frequently
@@ -103,8 +104,13 @@ def load_ip(self):
103104
p.start()
104105

105106
def save_ip_list(self, force=False):
106-
if self.iplist_need_save == 0 and not force:
107-
return
107+
if not force:
108+
if self.iplist_need_save == 0:
109+
return
110+
if time.time() - self.iplist_saved_time < 10:
111+
return
112+
113+
self.iplist_saved_time = time.time()
108114

109115
try:
110116
self.ip_lock.acquire()
@@ -408,6 +414,8 @@ def check_exist_ip(self):
408414
self.update_ip(ip_str, result.handshake_time)
409415
logging.info("check_exist_ip update ip:%s server:%s time:%d", ip_str, result.server_type, result.handshake_time)
410416

417+
time.sleep(1)
418+
411419
self.save_ip_list()
412420

413421
if __name__ != "__main__":

goagent/3.1.35/local/pac_server.py

+2-30
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,6 @@
44
import sys
55
import os
66
import glob
7-
8-
sys.path += glob.glob('%s/*.egg' % os.path.dirname(os.path.abspath(__file__)))
9-
10-
try:
11-
import gevent
12-
import gevent.socket
13-
import gevent.server
14-
import gevent.queue
15-
import gevent.event
16-
import gevent.monkey
17-
gevent.monkey.patch_all(subprocess=True)
18-
except ImportError:
19-
gevent = None
20-
217
import base64
228
import time
239
import re
@@ -26,14 +12,6 @@
2612
import BaseHTTPServer
2713
import urllib2
2814
import urlparse
29-
try:
30-
import OpenSSL
31-
except ImportError:
32-
OpenSSL = None
33-
try:
34-
import dnslib
35-
except ImportError:
36-
dnslib = None
3715

3816

3917
from config import config
@@ -69,10 +47,7 @@ def update_pacfile(filename):
6947
logging.info('try download %r to update_pacfile(%r)', config.PAC_ADBLOCK, filename)
7048
adblock_content = opener.open(config.PAC_ADBLOCK).read()
7149
logging.info('%r downloaded, try convert it with adblock2pac', config.PAC_ADBLOCK)
72-
if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
73-
jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.adblock2pac, (adblock_content, 'FindProxyForURLByAdblock', blackhole, default))
74-
else:
75-
jsrule = PacUtil.adblock2pac(adblock_content, 'FindProxyForURLByAdblock', blackhole, default)
50+
jsrule = PacUtil.adblock2pac(adblock_content, 'FindProxyForURLByAdblock', blackhole, default)
7651
content += '\r\n' + jsrule + '\r\n'
7752
logging.info('%r downloaded and parsed', config.PAC_ADBLOCK)
7853
else:
@@ -87,10 +62,7 @@ def update_pacfile(filename):
8762
logging.info('try download %r to update_pacfile(%r)', config.PAC_GFWLIST, filename)
8863
autoproxy_content = base64.b64decode(opener.open(config.PAC_GFWLIST).read())
8964
logging.info('%r downloaded, try convert it with autoproxy2pac', config.PAC_GFWLIST)
90-
if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
91-
jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.autoproxy2pac, (autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default))
92-
else:
93-
jsrule = PacUtil.autoproxy2pac(autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default)
65+
jsrule = PacUtil.autoproxy2pac(autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default)
9466
content += '\r\n' + jsrule + '\r\n'
9567
logging.info('%r downloaded and parsed', config.PAC_GFWLIST)
9668
except Exception as e:

0 commit comments

Comments
 (0)