Esempio n. 1
0
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])
Esempio n. 2
0
 def do_GET(self):
     rand = random.randint(0,1000)
     myenv = Gtenv("")
     if rand == 90 or not myenv.checked:
         if self.path != 'http://www.google.com/_gtool_/GoldenToolProxy.html':
             if not self._getwebtime(self.path):
                 self.server.logger.warning('本地时间与系统时间冲突,系统启动失败!')
                 myenv.running = False
                 return
             myenv.checked = True
                 
     if self.path=='http://www.gtool.com/stopproxy?key=79798798':
         #self.server.close()
         print self.path
         self.server.logger.warning('your proxy server to be closed soon')
         self.wfile.write('your proxy server to be closed soon')
         myenv.running = False
         self.server.close_connection = True
         #self.server.shutdown()
         #self.server.stop()
         return
     #0 get request accept type,now set it to *
     '''  I can't sure,guess that the Accept tag is not useful
     accepttype = self.headers.get('Accept')
     if accepttype:
         if accepttype == '*/*':
             accepttype = '*'
         elif accepttype.find('text/html') == 0:
             accepttype = 'html'
         else:
             accepttype = 'other'
     else:
         accepttype = '*'
     '''
     accepttype = '*'
     #1 deal with redirect rules, FTP may raise error
     (needredirect,redirectedpath) = self.rulehandler.redirect(self.path,accepttype)
     if needredirect:
         self.headers['Gtool_url'] = self.path
         self.server.logger.log(logging.WARN,'Reditrected!From['+self.path+'] to ['+redirectedpath +']')
         self.path = redirectedpath
     #finished the redirect
     
     (scm, netloc, path, params, query, fragment) = urlparse.urlparse(
         self.path, 'http')
     #do not support ftp protecl
     if scm not in ('http', 'noftp') or fragment or not netloc:
         self.send_error(400, "bad url %s" % self.path)
         return
     #print self.headers
     soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     try:
         if scm == 'http':
             if self._connect_to(netloc, soc) :
                 #self.log_request()
                 soc.send("%s %s %s\r\n" % (self.command,
                                            urlparse.urlunparse(('', '', path,
                                                                 params, query,
                                                                 '')),
                                            self.request_version))
                 self.headers['Connection'] = 'close'
                 del self.headers['Proxy-Connection']
                 #del self.headers['content-length']
                 for key_val in self.headers.items():
                     soc.send("%s: %s\r\n" % key_val)
                 soc.send("\r\n")
                 if not(needredirect):
                     (ismodified,errmsg,resp) = self.rulehandler.modify(self.path,accepttype,self.headers)
                     if ismodified:
                         self.server.logger.log(logging.WARN,'Modified! path:['+self.path+']')
                         self._write_modifiedtext(resp)
                     else:
                         if not(errmsg ==''):self.server.logger.log (logging.ERROR,'Exception happened during of Modify ['\
                                                                     + self.path + '],error msg:'+errmsg)
                         self._read_write(soc)
                 else:
                     self._read_write(soc)
         elif scm == 'ftp':
             # fish out user and password information
             pass
     finally:
         soc.close()
         self.connection.close()