Beispiel #1
0
    def __init__(self):
        shell.check_python()
        self.config = shell.get_config(False)
        self.dns_resolver = asyncdns.DNSResolver()
        if not self.config.get('dns_ipv6', False):
            asyncdns.IPV6_CONNECTION_SUPPORT = False

        self.mgr = None  # asyncmgr.ServerMgr()

        self.eventloop_pool = {}
        self.thread_pool = {}
        self.dns_resolver_pool = {}

        self.dns_resolver = asyncdns.DNSResolver()

        self.loop = eventloop.EventLoop()
        self.thread = MainThread((self.loop, self.dns_resolver, self.mgr))
        self.thread.start()

        self.tcp_servers_pool = {}
        self.tcp_ipv6_servers_pool = {}
        self.udp_servers_pool = {}
        self.udp_ipv6_servers_pool = {}
        self.stat_counter = {}

        self.uid_port_table = {}
Beispiel #2
0
 def __init__(self):
     self._config = {}
     self._relays = {}
     self._loop = eventloop.EventLoop()
     self._dns_resolver = asyncdns.DNSResolver()
     self._dns_resolver.add_to_loop(self._loop)
     self._statistics = collections.defaultdict(int)
Beispiel #3
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 deployProxy(configs, index):
    config = configs[index]
    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:
        raise
Beispiel #5
0
def main():
    shell.check_python()

    config = shell.get_config(False)

    daemon.daemon_exec(config)

    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')
    else:
        config['port_password'] = {}
        server_port = config['server_port']
        if type(server_port) == list:
            for a_server_port in server_port:
                config['port_password'][a_server_port] = config['password']
        else:
            config['port_password'][str(server_port)] = config['password']

    tcp_servers = []
    udp_servers = []
    dns_resolver = asyncdns.DNSResolver()
    for port, password in config['port_password'].items():
        a_config = config.copy()
        a_config['server_port'] = int(port)
        a_config['password'] = password
        logging.info("starting server at %s:%d" %
                     (a_config['server'], int(port)))
        tcp_servers.append(tcprelay.TCPRelay(a_config, dns_resolver, False))
        udp_servers.append(udprelay.UDPRelay(a_config, dns_resolver, False))

    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)

    run_server()
Beispiel #6
0
    def handler():
        config = {
            "password": password,
            "method": crypt_name,
            "server_port": port,
            "timeout": 60,
            "server": "::",
            "fast_open": False
        }

        try:
            loop = eventloop.EventLoop()

            dns_resolver = asyncdns.DNSResolver()
            tcp_server = tcprelay.TCPRelay(config,
                                           dns_resolver,
                                           False,
                                           stat_callback=call_back)
            udp_server = udprelay.UDPRelay(config, dns_resolver, False)

            dns_resolver.add_to_loop(loop)
            tcp_server.add_to_loop(loop)
            udp_server.add_to_loop(loop)

            loop.run()
        except IOError as e:
            if e.errno == 98:
                sys.exit(1)
        except Exception as e:
            shell.print_exception(e)
            sys.exit(1)
Beispiel #7
0
    def __init__(self):
        shell.check_python()
        self.config = shell.get_config(False)
        self.dns_resolver = asyncdns.DNSResolver()
        if not self.config.get('dns_ipv6', False):
            asyncdns.IPV6_CONNECTION_SUPPORT = False

        self.mgr = None  # asyncmgr.ServerMgr()

        self.tcp_servers_pool = {}
        self.tcp_ipv6_servers_pool = {}
        self.udp_servers_pool = {}
        self.udp_ipv6_servers_pool = {}
        self.stat_counter = {}

        self.loop = eventloop.EventLoop()
        self.logger = logging.getLogger(__name__)
        if get_config().debug:
            self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler('log.txt',
                                 mode='a',
                                 encoding=None,
                                 delay=False)
        formater = logging.Formatter(
            '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
        )
        fh.setFormatter(formater)
        self.logger.addHandler(fh)
        self.thread = MainThread((self.loop, self.dns_resolver, self.mgr))
        self.thread.start()
Beispiel #8
0
def main():
    dns_resolver = asyncdns.DNSResolver()
    myserv = MyServer(dns_resolver)
    loop = eventloop.EventLoop()
    myserv.add_to_loop(loop)
    dns_resolver.add_to_loop(loop)

    loop.run()
Beispiel #9
0
def main():
    # Python 2.6+ or Python3.3+
    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

    # only
    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分解器
        dns_resolver = asyncdns.DNSResolver()
        # TCP服务
        tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)
        # UDP服务
        udp_server = udprelay.UDPRelay(config, dns_resolver, True)

        # 将DNS服务、TCP服务、UDP服务加入事件循环
        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)

        # SIGINT是键盘ctrl + c
        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)
Beispiel #10
0
 def __init__(self, ssconfig, thread_num=0, timeout=1.0):
     super(SSThread, self).__init__()
     self.ssconfig = ssconfig
     self.loop = eventloop.EventLoop()
     self.dns_resolver = asyncdns.DNSResolver()
     self.tcp_server = tcprelay.TCPRelay(self.ssconfig, self.dns_resolver,
                                         True)
     self.udp_server = udprelay.UDPRelay(self.ssconfig, self.dns_resolver,
                                         True)
    def __init__(self, config):
        self._config = config
        self._port_info = {}
        self._relays = {}  # (tcprelay, udprelay)
        self._loop = eventloop.EventLoop()
        self._dns_resolver = asyncdns.DNSResolver()
        self._dns_resolver.add_to_loop(self._loop)

        self._last_day = datetime.date.today().day
        self._statistics = collections.defaultdict(int)
        # 使用 _statistics_sum 来记录每天使用的流量的总量,每天凌晨刷新
        self._statistics_sum = collections.defaultdict(int)

        self._control_client_addr = None
        self._control_client_url = 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
                self._control_client_url = addr
                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']
        port_limit = config['port_limit']

        del config['port_password']
        del config['port_limit']
        del config['server_port']

        if port_limit is None:
            port_limit = {}

        for port, password in port_password.items():
            a_config = config.copy()
            a_config['server_port'] = int(port)
            a_config['password'] = password
            if port in port_limit:
                a_config['limit'] = int(port_limit[port]) * LIMIT_MULTIPLE
            self.add_user(a_config)
Beispiel #12
0
 def __init__(self):
     shell.check_python()
     self.config = shell.get_config(False)
     self.dns_resolver = asyncdns.DNSResolver()
     self.tcp_servers_pool = {}
     self.udp_servers_pool = {}
     self.loop = eventloop.EventLoop()
     self.thread = MainThread((self.loop, self.dns_resolver))
     self.thread.start()
Beispiel #13
0
def main():
    global loop
    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)

    daemon.daemon_exec(config)

    utils.print_shadowsocks()

    encrypt.try_cipher(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)

        def int_handler(signum, _):
            sys.exit(1)

        # signal.signal(signal.SIGINT, int_handler)

        loop.run()
        try:
            tcp_server.close(next_tick=True)
            udp_server.close(next_tick=True)
        except:
            pass
    except (KeyboardInterrupt, IOError, OSError) as e:
        import traceback
        traceback.print_exc()
        logging.error(e)
        if config['verbose']:
            import traceback
            traceback.print_exc()
        os._exit(1)
Beispiel #14
0
    def __init__(self):
        self._config = None
        self._relays = {}  # (tcprelay, udprelay, username, password, method)
        self._loop = eventloop.EventLoop()
        self._dns_resolver = asyncdns.DNSResolver()
        self._dns_resolver.add_to_loop(self._loop)

        self._statistics = collections.defaultdict(dict)
        self._control_client_addr = None
        self._loop.add_periodic(self.handle_periodic)
Beispiel #15
0
    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)

        dbconfig = {
            'host': config['db_host'],
            'port': config['db_port'],
            'user': config['db_user'],
            'passwd': config['db_passwd'],
            'db': config['db_name'],
            'charset': 'utf8'
        }

        self._db = LightMysql.LightMysql(dbconfig)

        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)

        del config['port_password']
        port_passwords = self._db.select(
            'select port,passwd from t_ss_port where enable=1')
        for port_password in port_passwords:
            a_config = config.copy()
            a_config['server_port'] = int(port_password['port'])
            a_config['password'] = port_password['passwd']
            self.add_port(a_config)
Beispiel #16
0
    def _start_ss(self):
        logging.info("starting local at %s:%d" %
                     (self.config['local_address'], self.config['local_port']))
        print("starting local at %s:%d" %
              (self.config['local_address'], self.config['local_port']))
        dns_resolver = asyncdns.DNSResolver()
        tcp_server = tcprelay.TCPRelay(self.config, dns_resolver, True)
        udp_server = udprelay.UDPRelay(self.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)

        loop.run()
Beispiel #17
0
    def __init__(self, config):

        """
        初始化Manager的配置参数,进入循环事件

        :param 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)
Beispiel #18
0
    def __init__(self, config):
        atexit.register(self.cleanup)
        self._is_unix = False
        self._mngr_address = None
        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 hasattr(manager_address, 'decode'):
                manager_address = manager_address.decode('utf-8')
            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._is_unix = True
                self._mngr_address = manager_address
            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']
        config['crypto_path'] = config.get('crypto_path', dict())
        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)
Beispiel #19
0
def main():
    shell.check_python()  # 判断python版本

    # fix py2exe
    # hasattr(object, name) 判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        # sys.executable python可执行文件的绝对路径
        # os.path.abspath(path) 返回绝对路径
        # os.path.dirname(path) 返回文件路径
        # os.chdir() 用于改变当前工作目录到指定的路径
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)

    # 获取配置字典,包含每个配置项的具体配置值
    config = shell.get_config(True)
    # 根据配置文件当中的关键字daemon决定程序是启动/停止/重启
    daemon.daemon_exec(config)

    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)
Beispiel #20
0
def main():
    # 检查当前的运行环境 是否支持, 如果不支持, sys.exit(1) 退出
    shell.check_python()

    config = shell.get_config(True)
    # deamon.deamon_exec(config)

    logging.info('start local at %s:%d' %
                (config['local_address'], config['local_port']))
    dns_resolver = asyncdns.DNSResolver()
    tcp_server = tcprelay.TCPRelay(config, dns_resolver)
    loop = eventloop.EventLoop()

    tcp_server.add_to_loop(loop)

    loop.run()
Beispiel #21
0
def main():
    # 检查 python 版本
    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)  # 读取配置文件是否开启进程守护, 仅在UNIX ,Linux 上有效

    try:
        logging.info("starting local at %s:%d" %
                     (config['local_address'], config['local_port']))

        dns_resolver = asyncdns.DNSResolver()   # 创建dns 查询对象
        tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)  # 创建 TCP 代理转发对象
        udp_server = udprelay.UDPRelay(config, dns_resolver, True)  # 创建 UDP 代理转发对象
        loop = eventloop.EventLoop()    # 创建事件处理对象
        # 将dns查询、tcp代理方式转发、udp代理方式转发绑定到事件循环
        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)  # "Ctrl + C" 中断指令

        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)
Beispiel #22
0
    def __init__(self, config):
        self._config = config
        self._relays = {}  # (tcprelay, udprelay)
        self._loop = eventloop.EventLoop()
        self._dns_resolver = asyncdns.DNSResolver(
            server_list=config.get('dns_server'),
            prefer_ipv6=config['prefer_ipv6'],
        )
        self._dns_resolver.add_to_loop(self._loop)

        self._statistics = collections.defaultdict(lambda: [0, 0])
        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 Exception as e:
            logging.error('Can not bind to manager address: %s' % e)
            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)
Beispiel #23
0
def run(config):
    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)

    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)

    loop.run()
Beispiel #24
0
    def stopOnUnix(self, ssrDict, *args):
        ssrDict['daemon'] = 'stop'
        ssrDict['local_address'] = args[0]
        ssrDict['local_port'] = args[1]
        ssrDict['timeout'] = args[2]
        ssrDict['workers'] = args[3]
        ssrDict['pid-file'] = args[4]
        ssrDict['log-file'] = args[5]
        if not ssrDict.get('dns_ipv6', False):
            asyncdns.IPV6_CONNECTION_SUPPORT = False
        try:
            daemon.daemon_exec(ssrDict)
            dns_resolver = asyncdns.DNSResolver()
            tcp_server = tcprelay.TCPRelay(ssrDict, dns_resolver, True)
            udp_server = udprelay.UDPRelay(ssrDict, 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, _):
                logger.info('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, _):
                logger.info("ShadowsocksR is stop")
                sys.exit(1)

            signal.signal(signal.SIGINT, int_handler)
            daemon.set_user(ssrDict.get('user', None))
            logger.info('ShadowsocksR is start on {0}:{1}'.format(args[0], args[1]))
            loop.run()
        except Exception as e:
            logger.error(e)
            sys.exit(1)
Beispiel #25
0
    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.split(':')
                addr = addr[0], int(addr[1])
                family = socket.AF_INET
            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')
            common.error_to_file('can not bind to manager address',
                                 self._config)
            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)
Beispiel #26
0
def daemon_embeded(config):

    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)
    print(config)
    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)

    daemon.set_user(config.get('user', None))
    loop.run()
Beispiel #27
0
def main():
    shell.check_python()

    config = shell.get_config(False)

    daemon.daemon_exec(config)

    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')
    else:
        config['port_password'] = {}
        server_port = config.get('server_port', None)
        if server_port:
            if type(server_port) == list:
                for a_server_port in server_port:
                    config['port_password'][a_server_port] = config['password']
            else:
                config['port_password'][str(server_port)] = config['password']

    if config.get('manager_address', 0):
        logging.info('entering manager mode')
        manager.run(config)
        return

    tcp_servers = []
    udp_servers = []

    if 'dns_server' in config:  # allow override settings in resolv.conf
        dns_resolver = asyncdns.DNSResolver(config['dns_server'])
    else:
        dns_resolver = asyncdns.DNSResolver()

    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
        logging.info("starting server at %s:%d" %
                     (a_config['server'], int(port)))
        tcp_servers.append(tcprelay.TCPRelay(a_config, dns_resolver, False))
        udp_servers.append(udprelay.UDPRelay(a_config, dns_resolver, False))

    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)

    if int(config['workers']) > 1:
        if os.name == 'posix':
            children = []
            is_child = False
            for i in range(0, int(config['workers'])):
                r = os.fork()
                if r == 0:
                    logging.info('worker started')
                    is_child = True
                    run_server()
                    break
                else:
                    children.append(r)
            if not is_child:
                def handler(signum, _):
                    for pid in children:
                        try:
                            os.kill(pid, signum)
                            os.waitpid(pid, 0)
                        except OSError:  # child may already exited
                            pass
                    sys.exit()
                signal.signal(signal.SIGTERM, handler)
                signal.signal(signal.SIGQUIT, handler)
                signal.signal(signal.SIGINT, handler)

                # master
                for a_tcp_server in tcp_servers:
                    a_tcp_server.close()
                for a_udp_server in udp_servers:
                    a_udp_server.close()
                dns_resolver.close()

                for child in children:
                    os.waitpid(child, 0)
        else:
            logging.warn('worker is only available on Unix/Linux')
            run_server()
    else:
        run_server()
Beispiel #28
0
def main():
    shell.check_python3()

    config = shell.get_config(False)

    shell.log_shadowsocks_version()

    daemon.daemon_exec(config)

    try:
        import resource
        logging.info(
            'current process RLIMIT_NOFILE resource: soft %d hard %d' %
            resource.getrlimit(resource.RLIMIT_NOFILE))
    except ImportError:
        pass

    if config['port_password']:
        pass
    else:
        config['port_password'] = {}
        server_port = config['server_port']
        if type(server_port) == list:
            for a_server_port in server_port:
                config['port_password'][a_server_port] = config['password']
        else:
            config['port_password'][str(server_port)] = config['password']

    if not config.get('dns_ipv6', False):
        asyncdns.IPV6_CONNECTION_SUPPORT = False

    if config.get('manager_address', 0):
        logging.info('entering manager mode')
        manager.run(config)
        return

    tcp_servers = []
    udp_servers = []
    dns_resolver = asyncdns.DNSResolver()
    if int(config['workers']) > 1:
        stat_counter_dict = None
    else:
        stat_counter_dict = {}
    port_password = config['port_password']
    config_password = config.get('password', 'm')
    del config['port_password']
    for port, password_obfs in port_password.items():
        method = config["method"]
        protocol = config.get("protocol", 'origin')
        protocol_param = config.get("protocol_param", '')
        obfs = config.get("obfs", 'plain')
        obfs_param = config.get("obfs_param", '')
        bind = config.get("out_bind", '')
        bindv6 = config.get("out_bindv6", '')
        if type(password_obfs) == list:
            password = password_obfs[0]
            obfs = common.to_str(password_obfs[1])
            if len(password_obfs) > 2:
                protocol = common.to_str(password_obfs[2])
        elif type(password_obfs) == dict:
            password = password_obfs.get('password', config_password)
            method = common.to_str(password_obfs.get('method', method))
            protocol = common.to_str(password_obfs.get('protocol', protocol))
            protocol_param = common.to_str(
                password_obfs.get('protocol_param', protocol_param))
            obfs = common.to_str(password_obfs.get('obfs', obfs))
            obfs_param = common.to_str(
                password_obfs.get('obfs_param', obfs_param))
            bind = password_obfs.get('out_bind', bind)
            bindv6 = password_obfs.get('out_bindv6', bindv6)
        else:
            password = password_obfs
        a_config = config.copy()
        ipv6_ok = False
        logging.info(
            "server start with protocol[%s] password [%s] method [%s] obfs [%s] obfs_param [%s]"
            % (protocol, password, method, obfs, obfs_param))
        if 'server_ipv6' in a_config:
            try:
                if len(a_config['server_ipv6']
                       ) > 2 and a_config['server_ipv6'][
                           0] == "[" and a_config['server_ipv6'][-1] == "]":
                    a_config['server_ipv6'] = a_config['server_ipv6'][1:-1]
                a_config['server_port'] = int(port)
                a_config['password'] = password
                a_config['method'] = method
                a_config['protocol'] = protocol
                a_config['protocol_param'] = protocol_param
                a_config['obfs'] = obfs
                a_config['obfs_param'] = obfs_param
                a_config['out_bind'] = bind
                a_config['out_bindv6'] = bindv6
                a_config['server'] = a_config['server_ipv6']
                logging.info("starting server at [%s]:%d" %
                             (a_config['server'], int(port)))
                tcp_servers.append(
                    tcprelay.TCPRelay(a_config,
                                      dns_resolver,
                                      False,
                                      stat_counter=stat_counter_dict))
                udp_servers.append(
                    udprelay.UDPRelay(a_config,
                                      dns_resolver,
                                      False,
                                      stat_counter=stat_counter_dict))
                if a_config['server_ipv6'] == b"::":
                    ipv6_ok = True
            except Exception as e:
                shell.print_exception(e)

        try:
            a_config = config.copy()
            a_config['server_port'] = int(port)
            a_config['password'] = password
            a_config['method'] = method
            a_config['protocol'] = protocol
            a_config['protocol_param'] = protocol_param
            a_config['obfs'] = obfs
            a_config['obfs_param'] = obfs_param
            a_config['out_bind'] = bind
            a_config['out_bindv6'] = bindv6
            logging.info("starting server at %s:%d" %
                         (a_config['server'], int(port)))
            tcp_servers.append(
                tcprelay.TCPRelay(a_config,
                                  dns_resolver,
                                  False,
                                  stat_counter=stat_counter_dict))
            udp_servers.append(
                udprelay.UDPRelay(a_config,
                                  dns_resolver,
                                  False,
                                  stat_counter=stat_counter_dict))
        except Exception as e:
            if not ipv6_ok:
                shell.print_exception(e)

    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)

    if int(config['workers']) > 1:
        if os.name == 'posix':
            children = []
            is_child = False
            for i in range(0, int(config['workers'])):
                r = os.fork()
                if r == 0:
                    logging.info('worker started')
                    is_child = True
                    run_server()
                    break
                else:
                    children.append(r)
            if not is_child:

                def handler(signum, _):
                    for pid in children:
                        try:
                            os.kill(pid, signum)
                            os.waitpid(pid, 0)
                        except OSError:  # child may already exited
                            pass
                    sys.exit()

                signal.signal(signal.SIGTERM, handler)
                signal.signal(signal.SIGQUIT, handler)
                signal.signal(signal.SIGINT, handler)

                # master
                for a_tcp_server in tcp_servers:
                    a_tcp_server.close()
                for a_udp_server in udp_servers:
                    a_udp_server.close()
                dns_resolver.close()

                for child in children:
                    os.waitpid(child, 0)
        else:
            logging.warn('worker is only available on Unix/Linux')
            run_server()
    else:
        run_server()
Beispiel #29
0
def main():
    shell.check_python()  #检查python版本

    config = shell.get_config(False)  #从配置文件,命令行等获取参数

    daemon.daemon_exec(config)  #根据'daemon'参数来start,stop或restart ssserver

    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')
    else:
        config['port_password'] = {}
        server_port = config['server_port']
        if type(server_port) == list:
            for a_server_port in server_port:
                config['port_password'][a_server_port] = config['password']
        else:
            config['port_password'][str(server_port)] = config['password']

    if config.get('manager_address', 0):
        logging.info('entering manager mode')
        manager.run(config)
        return

    tcp_servers = []
    udp_servers = []
    # 类DNSResolver初始化时会从/etc/hosts和/etc/resolv.conf中获取hostname和dns
    dns_resolver = asyncdns.DNSResolver()
    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
        logging.info("starting server at %s:%d" %
                     (a_config['server'], int(port)))
        tcp_servers.append(tcprelay.TCPRelay(a_config, dns_resolver, False))
        udp_servers.append(udprelay.UDPRelay(a_config, dns_resolver, False))

    def run_server():
        def child_handler(signum, _):
            logging.warn('received SIGQUIT, doing graceful shutting down..')
            # map(function, sequence[, sequence, ...]) -> list 将function函数作用到
            # sequence中的每一个元素,也就是关掉上面打开的所有的socket
            list(
                map(lambda s: s.close(next_tick=True),
                    tcp_servers + udp_servers))

        # 注册SIGQUIT或SIGTERM的信号处理函数,Windows不支持SIGQUIT而Linux支持,所以为了
        # 跨平台兼容,此处使用了getattr函数
        # 在调用exec前,子进程会继承父进程注册的信号处理action,这里在子进程中重新注册
        # 了SIGTERM信号的处理action,不出意外,signal函数会返回上一次注册的action
        signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM),
                      child_handler)

        # 为SIGINT注册信号处理函数
        def int_handler(signum, _):
            sys.exit(1)

        signal.signal(signal.SIGINT, int_handler)

        try:
            loop = eventloop.EventLoop()
            # 将dns以及之前tcp, udp的socket都注册到epoll事件表中
            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)

    if int(config['workers']) > 1:
        if os.name == 'posix':
            children = []
            is_child = False
            for i in range(0, int(config['workers'])):
                r = os.fork()
                if r == 0:
                    logging.info('worker started')
                    is_child = True
                    run_server()
                    break
                else:
                    children.append(r)
            if not is_child:

                def handler(signum, _):
                    for pid in children:
                        try:
                            os.kill(pid, signum)
                            os.waitpid(pid, 0)
                        except OSError:  # child may already exited
                            pass
                    sys.exit()

                signal.signal(signal.SIGTERM, handler)
                signal.signal(signal.SIGQUIT, handler)
                signal.signal(signal.SIGINT, handler)

                # master
                for a_tcp_server in tcp_servers:
                    a_tcp_server.close()
                for a_udp_server in udp_servers:
                    a_udp_server.close()
                dns_resolver.close()

                for child in children:
                    os.waitpid(child, 0)
        else:
            logging.warn('worker is only available on Unix/Linux')
            run_server()
    else:
        run_server()
Beispiel #30
0
def main():
    # 检查python版本
    utils.check_python()

    # fix py2exe
    # 应该是专门为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)

    # 形参是is_local=True
    config = utils.get_config(True)

    # linux系统:执行守护进程
    daemon.daemon_exec(config)
    # 显示当前的ss版本号
    utils.print_shadowsocks()
    # 创建加密器类的实例
    encrypt.try_cipher(config['password'], config['method'])

    try:
        logging.info("starting local at %s:%d" %
                     (config['local_address'], config['local_port']))

        # dns只是tcp上面的一个应用,所以没有自己的bind
        # 新建dns_resolver
        dns_resolver = asyncdns.DNSResolver()
        tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)
        udp_server = udprelay.UDPRelay(config, dns_resolver, True)
        # 创建时间循环的类实例
        loop = eventloop.EventLoop()
        # dns请求报文发出去了之后要监测响应报文
        dns_resolver.add_to_loop(loop)  # client发远程网站地址给proxy,proxy去查找DNS
        tcp_server.add_to_loop(loop)  # 递送tcp数据
        udp_server.add_to_loop(loop)  # 递送udp数据

        # 定义退出信号捕获处理函数
        def handler(signum, _):
            logging.warn('received SIGQUIT, doing graceful shutting down..')
            #  连带关闭socket(因为next = true)
            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)

        # 运行事件循环,思想还是挺高端的
        loop.run()

    # 按下 Ctrl+c 退出
    except (KeyboardInterrupt, IOError, OSError) as e:
        logging.error(e)
        if config['verbose']:
            import traceback
            traceback.print_exc()
        os._exit(1)