def test(): loop = eventloop.EventLoop() # 创建 loop 实例 dns_resolver = DNSResolver(loop) # 创建实例 def make_callback(): # 返回一个 callback def callback(result, error): pass # print(result, error) a_callback = callback return a_callback assert (make_callback() != make_callback()) dns_resolver.resolve('google.com', make_callback()) dns_resolver.resolve('google.com', make_callback()) dns_resolver.resolve('example.com', make_callback()) dns_resolver.resolve('ipv6.google.com', make_callback()) dns_resolver.resolve('www.facebook.com', make_callback()) dns_resolver.resolve('ns2.google.com', make_callback()) dns_resolver.resolve('invalid.@!#$%^&[email protected]', make_callback()) dns_resolver.resolve('baidu.com', make_callback()) dns_resolver.resolve('i0.hdslb.com', make_callback()) # dns_resolver.resolve('bstatic.hdslb.com', make_callback()) # dns_resolver.resolve('s1.hdslb.com.w.kunlunar.com', make_callback()) loop.run() # rua!
def test(): logging.getLogger('').handlers = [] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filemode='a+') def _callback(address, error): print error, address loop = eventloop.EventLoop() resolver = DNSResolver() resolver.add_to_loop(loop) for hostname in ['www.google.com', '8.8.8.8', 'localhost', 'activate.adobe.com', 'www.twitter.com', 'ipv6.google.com', 'ipv6.l.google.com', 'www.gmail.com', 'r4---sn-3qqp-ioql.googlevideo.com', 'www.baidu.com', 'www.a.shifen.com', 'm.baidu.jp', 'www.youku.com', 'www.twitter.com', 'ipv6.google.com']: resolver.resolve(hostname, _callback) loop.run()
def run_server(): def child_handler(signum, _): logging.warn('received SIGQUIT, doing graceful shutting down..') list( map(lambda s: s.close(next_tick=True), tcp_servers + udp_servers)) signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), child_handler) def int_handler(signum, _): sys.exit(1) signal.signal(signal.SIGINT, int_handler) try: loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) list(map(lambda s: s.add_to_loop(loop), tcp_servers + udp_servers)) daemon.set_user(config.get('user', None)) loop.run() except Exception as e: shell.print_exception(e) sys.exit(1)
def _run(self): server_socket = self._server_socket self._eventloop = eventloop.EventLoop() self._eventloop.add(server_socket, eventloop.POLL_IN) last_time = time.time() while not self._closed: try: events = self._eventloop.poll(10) except (OSError, IOError) as e: if eventloop.errno_from_exception(e) == errno.EPIPE: # Happens when the client closes the connection continue else: logging.error(e) continue for sock, event in events: if sock == self._server_socket: self._handle_server() else: self._handle_client(sock) now = time.time() if now - last_time > 3.5: self._cache.sweep() if now - last_time > 7: self._client_fd_to_server_addr.sweep() last_time = now
def test(): dns_resolver = DNSResolver() loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) global counter counter = 0 def make_callback(): global counter def callback(result, error): global counter # TODO: what can we assert? print(result, error) counter += 1 if counter == 9: dns_resolver.close() loop.stop() a_callback = callback return a_callback assert (make_callback() != make_callback()) dns_resolver.resolve(b'google.com', make_callback()) dns_resolver.resolve('google.com', make_callback()) dns_resolver.resolve('example.com', make_callback()) dns_resolver.resolve('ipv6.google.com', make_callback()) dns_resolver.resolve('www.facebook.com', make_callback()) dns_resolver.resolve('ns2.google.com', make_callback()) loop.run()
def main(): utils.check_python() # fix py2exe if hasattr(sys, "frozen") and sys.frozen in \ ("windows_exe", "console_exe"): p = os.path.dirname(os.path.abspath(sys.executable)) os.chdir(p) config = utils.get_config(True) utils.print_shadowsocks() encrypt.init_table(config['password'], config['method']) try: logging.info("starting local at %s:%d" % (config['local_address'], config['local_port'])) tcp_server = tcprelay.TCPRelay(config, True) udp_server = udprelay.UDPRelay(config, True) loop = eventloop.EventLoop() tcp_server.add_to_loop(loop) udp_server.add_to_loop(loop) loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) os._exit(0)
def main(): shell.check_python() # fix py2exe if hasattr(sys, "frozen") and sys.frozen in \ ("windows_exe", "console_exe"): p = os.path.dirname(os.path.abspath(sys.executable)) os.chdir(p) config = shell.get_config(True) daemon.daemon_exec(config) logging.info("starting local at %s:%d" % (config['local_address'], config['local_port'])) dns_resolver = asyncdns.DNSResolver() tcp_server = tcprelay.TCPRelay(config, dns_resolver, True) udp_server = udprelay.UDPRelay(config, dns_resolver, True) loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) tcp_server.add_to_loop(loop) udp_server.add_to_loop(loop) def handler(signum, _): logging.warn('received SIGQUIT, doing graceful shutting down..') tcp_server.close(next_tick=True) udp_server.close(next_tick=True) signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler) def int_handler(signum, _): sys.exit(1) signal.signal(signal.SIGINT, int_handler) daemon.set_user(config.get('user', None)) loop.run()
def main_loop(bindaddr, dnslist, proxy): dns = UDPRelay(proxy, dnslist) loop = eventloop.EventLoop() if dns.bind(bindaddr[0], bindaddr[1]): dns.add_to_loop(loop) loop.run() else: logging.error("bind failed")
class ModuleVars: agent = None agentName = "MasterAgentSimulator" thread = threading.Thread(target=_exec) lock = threading.Lock() evt_loop = eventloop.EventLoop() pipe_w = None pipe_r = None
def __init__(self): self.init_server_socket() # add to event loop loop = eventloop.EventLoop() self._eventloop = loop self._eventloop.add(self._server_socket, eventloop.POLL_IN | eventloop.POLL_ERR, self) self._fd_to_handlers = {}
def __init__(self): self.config = shell.config_info() shell.print_shadowsocks() self.dns_resolver = asyncdns.DNSResolver() self.mgr = asyncmgr.ServerMgr() self.tcp_servers_pool = {} self.udp_servers_pool = {} self.loop = eventloop.EventLoop() thread.start_new_thread(ServerPool._loop, (self.loop, self.dns_resolver, self.mgr))
def run_server(): try: loop = eventloop.EventLoop() for tcp_server in tcp_servers: tcp_server.add_to_loop(loop) for udp_server in udp_servers: udp_server.add_to_loop(loop) loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) os._exit(0)
def __init__(self): utils.check_python() self.config = utils.get_config(False) utils.print_shadowsocks() self.dns_resolver = asyncdns.DNSResolver() self.mgr = asyncmgr.ServerMgr() self.tcp_servers_pool = {} #self.udp_servers_pool = {} self.loop = eventloop.EventLoop() thread.start_new_thread(ServerPool._loop, (self.loop, self.dns_resolver, self.mgr))
def run_server(): try: loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) for tcp_server in tcp_servers: tcp_server.add_to_loop(loop) for udp_server in udp_servers: udp_server.add_to_loop(loop) loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) import traceback traceback.print_exc() os._exit(0)
def main(): shell.check_python() # fix py2exe if hasattr(sys, "frozen") and sys.frozen in \ ("windows_exe", "console_exe"): p = os.path.dirname(os.path.abspath(sys.executable)) os.chdir(p) config = shell.get_config(True) if not config.get('dns_ipv6', False): asyncdns.IPV6_CONNECTION_SUPPORT = False daemon.daemon_exec(config) logging.info( "local start with protocol[%s] password [%s] method [%s] obfs [%s] obfs_param [%s]" % (config['protocol'], config['password'], config['method'], config['obfs'], config['obfs_param'])) try: logging.info("starting local at %s:%d" % (config['local_address'], config['local_port'])) dns_resolver = asyncdns.DNSResolver() tcp_server = tcprelay.TCPRelay(config, dns_resolver, True) udp_server = udprelay.UDPRelay(config, dns_resolver, True) loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) tcp_server.add_to_loop(loop) udp_server.add_to_loop(loop) def handler(signum, _): logging.warn('received SIGQUIT, doing graceful shutting down..') tcp_server.close(next_tick=True) udp_server.close(next_tick=True) signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler) def int_handler(signum, _): sys.exit(1) signal.signal(signal.SIGINT, int_handler) daemon.set_user(config.get('user', None)) loop.run() except Exception as e: shell.print_exception(e) sys.exit(1)
def test(): dns_resolver = DNSResolver() loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop, ref=True) global counter counter = 0 def make_callback(): global counter def callback(result, error): global counter # TODO: what can we assert? print(result, error) counter += 1 if counter == 9: loop.remove_handler(dns_resolver.handle_events) dns_resolver.close() a_callback = callback return a_callback assert (make_callback() != make_callback()) dns_resolver.resolve(b'google.com', make_callback()) dns_resolver.resolve('google.com', make_callback()) dns_resolver.resolve('example.com', make_callback()) dns_resolver.resolve('ipv6.google.com', make_callback()) dns_resolver.resolve('www.facebook.com', make_callback()) dns_resolver.resolve('ns2.google.com', make_callback()) dns_resolver.resolve('invalid.@!#$%^&[email protected]', make_callback()) dns_resolver.resolve( 'toooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'long.hostname', make_callback()) dns_resolver.resolve( 'toooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'ooooooooooooooooooooooooooooooooooooooooooooooooooo' 'long.hostname', make_callback()) loop.run()
def run_server(): def child_handler(signum, _): logging.warn('received SIGQUIT, doing graceful shutting down..') map(lambda s: s.close(next_tick=True), tcp_servers + udp_servers) signal.signal(signal.SIGQUIT, child_handler) try: loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) map(lambda s: s.add_to_loop(loop), tcp_servers + udp_servers) loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) if config['verbose']: import traceback traceback.print_exc() os._exit(1)
def main(): loop = eventloop.EventLoop() dns_resolver = asyncdns.DNSResolver(loop) tcp_server = tcprelay.TCPRelay(dns_resolver, loop) udp_server = udprelay.UDPRelay(dns_resolver, loop) def handler(signum, _): logging.warning('received SIGQUIT, doing graceful shutting down..') tcp_server.close() udp_server.close() signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler) def int_handler(signum, _): sys.exit(1) signal.signal(signal.SIGINT, int_handler) loop.run()
def __init__(self, config): self._config = config self._relays = {} # (tcprelay, udprelay) self._loop = eventloop.EventLoop() self._dns_resolver = asyncdns.DNSResolver() self._dns_resolver.add_to_loop(self._loop) self._statistics = collections.defaultdict(int) self._control_client_addr = None try: manager_address = config['manager_address'] if ':' in manager_address: addr = manager_address.rsplit(':', 1) addr = addr[0], int(addr[1]) addrs = socket.getaddrinfo(addr[0], addr[1]) if addrs: family = addrs[0][0] else: logging.error('invalid address: %s', manager_address) exit(1) else: addr = manager_address family = socket.AF_UNIX self._control_socket = socket.socket(family, socket.SOCK_DGRAM) self._control_socket.bind(addr) self._control_socket.setblocking(False) except (OSError, IOError) as e: logging.error(e) logging.error('can not bind to manager address') exit(1) self._loop.add(self._control_socket, eventloop.POLL_IN, self) self._loop.add_periodic(self.handle_periodic) port_password = config['port_password'] del config['port_password'] for port, password in port_password.items(): a_config = config.copy() a_config['server_port'] = int(port) a_config['password'] = password self.add_port(a_config)
def __init__(self, listen_addr='127.0.0.1', listen_port=1080, remote_addr='127.0.0.1', remote_port=8387, password=None, method='table', timeout=300, is_local=True): self._listen_addr = listen_addr self._listen_port = listen_port self._remote_addr = remote_addr self._remote_port = remote_port self._password = password self._method = method self._timeout = timeout self._is_local = is_local self._eventloop = eventloop.EventLoop() self._cache = lru_cache.LRUCache(timeout=timeout, close_callback=self._close_client) self._client_fd_to_server_addr = lru_cache.LRUCache(timeout=timeout)
def main(): # 获取配置 config = shell.get_config() # 设置日志 debug/info/warning/error/critical logging.basicConfig( level=logging.INFO, filename='./log.txt', filemode='w', format= '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s' ) try: tcp_server = controller.Controller(config) loop = eventloop.EventLoop() tcp_server.add_to_loop(loop) except Exception as e: print(e) logging.error(e) sys.exit(-1) loop.run()
def main(): utils.check_python() # fix py2exe if hasattr(sys, "frozen") and sys.frozen in \ ("windows_exe", "console_exe"): p = os.path.dirname(os.path.abspath(sys.executable)) os.chdir(p) config = utils.get_config(True) utils.print_shadowsocks() encrypt.init_table(config['password'], config['method']) try: logging.info("starting local at %s:%d" % (config['local_address'], config['local_port'])) dns_resolver = asyncdns.DNSResolver() tcp_server = tcprelay.TCPRelay(config, dns_resolver, True) udp_server = udprelay.UDPRelay(config, dns_resolver, True) loop = eventloop.EventLoop() dns_resolver.add_to_loop(loop) tcp_server.add_to_loop(loop) udp_server.add_to_loop(loop) def handler(signum, _): logging.warn('received SIGQUIT, doing graceful shutting down..') tcp_server.close(next_tick=True) udp_server.close(next_tick=True) signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler) loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) if config['verbose']: import traceback traceback.print_exc() os._exit(1)
def __init__(self): self.eventloop = eventloop.EventLoop() self.running_tasks = {} self.failed_tasks = [] self.socket2task = {} self.concurrent_tasks = 0 self.helper = HttpHelper() self.METHOD_GET = "GET" self.HEADER_END = "\x0d\x0a\x0d\x0a" self.HTTPSTATUS = { "STATUS_CONNECT": 0x1 << 3, "STATUS_CONNECTED": 0x1 << 4, "STATUS_FAILED": 0x1 << 6, "STATUS_SEND": 0x1 << 7, "STATUS_RECV": 0x1 << 8, "STATUS_HEADER": 0x1 << 9, "STATUS_DONE": 0x1 << 10 } self.conf = { "buf_size": 32 * 1024, "verbose": False, "task_timeout": 5, "max_concurrent_tasks": 1000, }
def __init__(self): self.loop = eventloop.EventLoop() self.thread = MainThread(self.loop) self.thread.start()
def main(): import logging # -- import from shadowsockesr-v import conf import exit import shell import eventloop import tcprelay import udprelay import asyncdns # -- init logging -- conf.logger_init() # show version logging.info(conf.version()) # -- starting ssr -- # get ssr configurations ssr_conf = shell.get_ssr_conf(ssr_conf_path=conf.ssr_conf_path()) if not ssr_conf.get('dns_ipv6', False): asyncdns.IPV6_CONNECTION_SUPPORT = False password = ssr_conf['password'] method = ssr_conf['method'] protocol = ssr_conf['protocol'] protocol_param = ssr_conf['protocol_param'] obfs = ssr_conf['obfs'] obfs_param = ssr_conf['obfs_param'] udp_enable = ssr_conf['udp_enable'] dns_list = ssr_conf['dns'] logging.info(f'Server start with ' f'password [{password}] ' f'method [{method}] ' f'protocol[{protocol}] ' f'protocol_param[{protocol_param}] ' f'obfs [{obfs}] ' f'obfs_param [{obfs_param}]') server = ssr_conf['server'] port = ssr_conf['server_port'] logging.info(f'Starting server at [{server}]:{port}') try: ssr_conf['out_bind'] = '' ssr_conf['out_bindv6'] = '' # create epoll (singleton) loop = eventloop.EventLoop() # dns server (singleton) dns_resolver = asyncdns.DNSResolver(dns_list) dns_resolver.add_to_loop(loop) stat_counter_dict = {} # listen tcp && register socket tcp = tcprelay.TCPRelay(ssr_conf, dns_resolver, stat_counter=stat_counter_dict) tcp.add_to_loop(loop) if udp_enable: # listen udp && register socket udp = udprelay.UDPRelay(ssr_conf, dns_resolver, False, stat_counter=stat_counter_dict) udp.add_to_loop(loop) # run epoll to handle socket loop.run() except Exception as e: exit.error(e)
def main(): shell.check_python() # fix py2exe if hasattr(sys, "frozen") and sys.frozen in ("windows_exe", "console_exe"): p = os.path.dirname(os.path.abspath(sys.executable)) os.chdir(p) config = shell.get_config(True) #added by cloud for local random choose a server and the port and the port_password if config['port_password']: if config['password']: logging.warn( 'warning: port_password should not be used with server_port and password. server_port and password will be ignored' ) # config['server_port'] = int(random.choice(config['port_password'].items())[0]) if config.has_key('server_port'): if type(config['server_port']) == list and config['server_port']: config['server_port'] = random.choice( config.get('server_port', 8388)) elif config['server_port']: config['server_port'] == int( common.to_str(config.get('server_port', 8388))) else: config['server_port'] = int( random.choice(config['port_password'].items())[0]) else: config['server_port'] = int( random.choice(config['port_password'].items())[0]) if not config['password'] or str(config['password']) == "": config['password'] = common.to_str( config['port_password']["%s" % config['server_port']]) else: if type(config['server_port']) == list and config['server_port']: config['server_port'] = random.choice( config.get('server_port', 8388)) else: config['server_port'] == int( common.to_str(config.get('server_port', 8388))) config["password"] = str( config["port_password"]["%s" % config["server_port"]]).strip() logging.warn('!' * 30) logging.info( "OK.. I choose this guy to help me f**k the GFW.. [ %s : %s : %s : %s : %s]" % (config['server'], config['server_port'], config['password'], config['server_info']["%s" % config['server']], config['method'])) logging.warn('!' * 30) time.sleep(1) daemon.daemon_exec(config) try: logging.info("starting local at %s:%d" % (config['local_address'], config['local_port'])) dns_resolver = asyncdns.DNSResolver(config) tcp_server = tcprelay.TCPRelay(config, dns_resolver, True) udp_server = udprelay.UDPRelay(config, dns_resolver, True) loop = eventloop.EventLoop(config) dns_resolver.add_to_loop(loop) tcp_server.add_to_loop(loop) udp_server.add_to_loop(loop) def handler(signum, _): logging.warn('received SIGQUIT, doing graceful shutting down..') tcp_server.close(next_tick=True) udp_server.close(next_tick=True) signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler) def int_handler(signum, _): sys.exit(1) signal.signal(signal.SIGINT, int_handler) daemon.set_user(config.get('user', None)) loop.run() except Exception as e: shell.print_exception(e) sys.exit(1)
.-'-.-'-. / \\ #### #### ##### # # ##### #### # # | | # # # # # # # # # # # # | .-------'._ #### #### ### # # # ### #### # # | / / '.' '. \\ # # # # # # # # # # # # | \\ \\ @ @ / / #### # # ##### # # ##### # # # | '---------' | _______| = 2015 = | .'-+-+-+| | '.-+-+-+| | """""" | '-.__ __.-' """''') import eventloop import logger import leds logger.initialize(args) loop = eventloop.EventLoop(args.statemachine, args.webserver_port, not args.disable_interbot) leds.initialize(loop) loop.start() logger.close() if args.pydev_debug: pydevd.stoptrace() sys.exit(loop.exit_value)