def writepac(enable): myenv = Gtenv("") path = myenv.getpath() file = path + "/static/gtproxy.pac" if not os.path.exists(file): return file_object = open(file) try: list_of_all_the_lines = file_object.readlines() line = list_of_all_the_lines[1] pos = line.find('return "DIRECT";') if (pos > 0): usingproxy = False else: usingproxy = True if enable: if not usingproxy: del list_of_all_the_lines[1] else: if usingproxy: list_of_all_the_lines.insert(1,' return "DIRECT";\r\n') finally: file_object.close() file_object = open(file,'w') try: file_object.writelines(list_of_all_the_lines) finally: file_object.close()
def decrpt(content): myenv = Gtenv("") path = myenv.getpath() with open(path+'/proxy.dll') as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p) d = content[693:1385] d = rsa.decrypt(base64.decodestring(d), privkey) ip = content[2079:2771] ip = rsa.decrypt(base64.decodestring(ip), privkey) return(d,ip)
def realtimeloadcfg(self): return import ProxyConfig from gt.gtcore.env import Gtenv myenv = Gtenv("") path = myenv.getpath() print path cfgfile = path + '/config.json' cfgcls = ProxyConfig.config(cfgfile) (rdtrules,mdfrules,repostrules) = cfgcls.read() self.mdfrules = mdfrules['Rules'] self.redirectrules = rdtrules['Rules'] self.repostrules = repostrules['Rules']
def writelicjs(): s = "" myenv = Gtenv("") s = '{"istrial":' if myenv.istrial: s = s + "1" else: s = s + "0" s = s + ",\"version\":\""+myenv.verison + "\"," s = s + "\"licdate\":\"" + myenv.licdate.strftime('%Y-%m-%d') + "\"}" path = myenv.getpath() fname = path + "/static/license.js" fo = open(fname,'w') fo.write(s) fo.close()
def haslic(): myenv = Gtenv("") path = myenv.getpath() localip = myenv.getip() licfile = path + "/" + localip + ".lic" if not os.path.isfile(licfile): return 0,date.today() + timedelta(-1) fobject = open(licfile) content = "" try: content = fobject.read() finally: fobject.close() (d,ip) = decrpt(content) if ip != localip: return 0,date.today() + timedelta(-1) b = datetime.strptime(d,"%Y%m%d") b = b.date() a = date(2015,1,1) has = (b - a).days return has,b
def haskey(): has = 0 from gt.gtcore.env import Gtenv myenv = Gtenv("") path = myenv.getpath() f = path + '/key.triallic' if os.path.exists(f): file_object = open(f) key = '' try: key = file_object.read( ) finally: file_object.close( ) if len(key)>8: key1 = key[0:4] key2 = key[4:7] key3 = key[7:12] machid = getid() days = int(key2,16) if days < 9999: days = days % 1000 a = date(2015,1,1) a = a + datetime.timedelta(days) s = a.strftime('%Y%m%d') s = machid + s t = mymd5(s) s = t[0:1] + t[8:9] + t[16:17] + t[24:25] if key1 == s: s = machid + key1 + key2 + a.strftime('%Y%m%d') t = mymd5(s) s = t[0:1] + t[8:9] + t[16:17] + t[24:25] + t[31:32] if key3 == s: has = days if has > 730: has = 0 return has,date(2015,1,1) + datetime.timedelta(has)
def authtrial(): from gt.gtcore.env import Gtenv myenv = Gtenv(".") path = myenv.getpath() print haskey()
def startweb(): #parse_command_line is very important tornado.options.parse_command_line() #print tornado.options.options.as_dict() path = sys.path[0] if os.path.isfile(path): path = os.path.dirname(path) #print path gtdir = path webenv = Gtenv(path) path = webenv.getpath() logfile = '' try: cf = ConfigParser.ConfigParser() cf.read(path + "/service.ini") logfile = path + "/" + cf.get("log","local") except Exception as e: pass if logfile == '': logfile = path + "/" +DEFAULT_LOG_FILENAME daemon = False max_log_size = 2 logger = logSetup (logfile, max_log_size, daemon) writepac(True) licdays,licdate = trial.haskey() if licdays == 0 or (licdate - date.today()).days < 0: licdays,licdate = auth.haslic() if licdays == 0 or (licdate - date.today()).days < 0: writepac(False) logger.warning(u'试用授权到期或没有正式授权文件,系统启动失败!') return 0 else: webenv.istrial = False webenv.licdate = licdate else: webenv.istrial = True webenv.licdate = licdate writelicjs() settings = { "static_path": path + "/static", } app = tornado.web.Application([ (r"/", Hello), (r"/hello", Hello), (r"/getlic", Lic), (r"/repost", Repost), (r"/job", Job), (r"/testjob", ThreadJob), (r"/querynsr", Querynsr), (r"/querytrace", Querytrace), (r"/download",Downloader), (r"/importnsr",ImoportNsr), (r"/rquery",RemoteQuery), (r"/sysinfo",G3info), (r"/SaveRemoteQuery",SaveRemoteQuery), (r"/jsonp",JSONP), (r"/reget",Reget), (r"/czy",CZY), (r"/queryfreq",QueryFreq), (r"/savefreq",SaveFreq), (r"/nsrlistjsonp",NsrlistJsonp), (r"/nsrinfo",GetNsrDetail) ],**settings) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(8001) logger.warning("Servering HTTP on localhost port:%s",8001) #signal never work in windows system #signal.signal(signal.SIGTERM, sig_handler) #signal.signal(signal.SIGINT, sig_handler) try: tornado.ioloop.IOLoop.instance().start() #KeyboardInterrupt never work #except KeyboardInterrupt: # logger.log(logging.INFO,"KeyboardInterrupt") # shutdown() except Exception as e: print e logger.warning("exception")
def main (): path = sys.path[0] if os.path.isfile(path): path = os.path.dirname(path) #path = "F:\\release" gtdir = path myenv = Gtenv(path) path = myenv.getpath() cfgfile = path + '/config.json' logfile = "" try: cf = ConfigParser.ConfigParser() cf.read(path + "/service.ini") logfile = path + "/" + cf.get("log","proxy") except Exception as e: pass if logfile == '': logfile = path + '/proxy.log' daemon = False max_log_size = 2 port = 8000 allowed = [] run_event = threading.Event () local_hostname = socket.gethostname () ''' try: opts, args = getopt.getopt (sys.argv[1:], "l:dhp:", []) except getopt.GetoptError, e: usage (str (e)) return 1 for opt, value in opts: if opt == "-c": cfgfile = value if opt == "-p": port = int (value) if opt == "-l": logfile = value if opt == "-d": daemon = not daemon if opt == "-h": usage () return 0 ''' # setup the log file logger = logSetup (logfile, max_log_size, daemon) #logger.info("a..........") licdays,licdate = trial.haskey() if licdays == 0 or (licdate - date.today()).days < 0: licdays,licdate = auth.haslic() if licdays == 0 or (licdate - date.today()).days < 0: logger.warning('试用授权到期或没有正式授权文件,系统启动失败!') return 0 else: myenv.istrial = False myenv.licdate = licdate else: myenv.istrial = True myenv.licdate = licdate if daemon: pass #daemonize (logger) #signal.signal (signal.SIGINT, handler) #必须屏蔽 #logger.info("b..........") ''' if args: allowed = [] for name in args: client = socket.gethostbyname(name) allowed.append(client) logger.log (logging.INFO, "Accept: %s (%s)" % (client, name)) ProxyHandler.allowed_clients = allowed else: logger.log (logging.WARNING, "Any clients will be served...") ''' cfgcls = ProxyConfig.config(cfgfile) cfg = {} (cfg['Redirect'],cfg['Modify'],cfg['Repost']) = cfgcls.read() ProxyHandler.config = cfg rulematch = RuleMatch.RuleMatch(cfg['Redirect'],cfg['Modify'],cfg['Repost']) ProxyHandler.rulehandler = rulematch #server_address = (socket.gethostbyname (local_hostname), port) server_address = ('127.0.0.1', port) ProxyHandler.protocol = "HTTP/1.0" httpd = ThreadingHTTPServer (server_address, ProxyHandler, logger) sa = httpd.socket.getsockname () logger.warning("Servering HTTP Proxy on %s port %s", sa[0], sa[1]) req_count = 0 myenv.running = True myenv.checked = False while myenv.running and not run_event.isSet (): try: httpd.handle_request () req_count += 1 if req_count == 1000: logger.log (logging.INFO, "Number of active threads: %s", threading.activeCount ()) req_count = 0 if not myenv.running: httpd.__is_shut_down = True except select.error, e: if e[0] == 4: pass else: logger.log (logging.CRITICAL, "Errno: %d - %s", e[0], e[1])