• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python common.to_str函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中shadowsocks.common.to_str函数的典型用法代码示例。如果您正苦于以下问题:Python to_str函数的具体用法?Python to_str怎么用?Python to_str使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了to_str函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: getSimpleConfig

def getSimpleConfig():
    VERBOSE_LEVEL = 5
    config['password'] = to_bytes(config.get('password', b''))
    config['method'] = to_str(config.get('method', 'aes-256-cfb'))
    config['port_password'] = ssDict
    config['timeout'] = int(config.get('timeout', 300))
    config['fast_open'] = config.get('fast_open', False)
    config['workers'] = config.get('workers', 1)
    config['pid-file'] = config.get('pid-file', '/var/run/shadowsocks.pid')
    config['log-file'] = config.get('log-file', '/var/log/shadowsocks.log')
    config['verbose'] = config.get('verbose', False)
    config['local_address'] = to_str(config.get('local_address', '127.0.0.1'))
    config['local_port'] = config.get('local_port', 1080)
    config['server'] = to_str(config.get('server', '0.0.0.0'))

    logging.getLogger('').handlers = []
    logging.addLevelName(VERBOSE_LEVEL, 'VERBOSE')
    level = logging.INFO
    logging.basicConfig(level=level,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    try:
        config['forbidden_ip'] = \
        IPNetwork(config.get('forbidden_ip', '127.0.0.0/8,::1/128'))
    except Exception as e:
        logging.error(e)
        sys.exit(2)

    check_config(config, False)
    return config
开发者ID:rain10154,项目名称:ss,代码行数:31,代码来源:ss.py


示例2: _create_remote_socket

    def _create_remote_socket(self, ip, port):
        if self._remote_udp:
            addrs_v6 = socket.getaddrinfo("::", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
            addrs = socket.getaddrinfo("0.0.0.0", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
        else:
            addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP)
        if len(addrs) == 0:
            raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
        af, socktype, proto, canonname, sa = addrs[0]
        if self._forbidden_iplist:
            if common.to_str(sa[0]) in self._forbidden_iplist:
                raise Exception('IP %s is in forbidden list, reject' %
                                common.to_str(sa[0]))
        remote_sock = socket.socket(af, socktype, proto)
        self._remote_sock = remote_sock
        self._fd_to_handlers[remote_sock.fileno()] = self

        if self._remote_udp:
            af, socktype, proto, canonname, sa = addrs_v6[0]
            remote_sock_v6 = socket.socket(af, socktype, proto)
            self._remote_sock_v6 = remote_sock_v6
            self._fd_to_handlers[remote_sock_v6.fileno()] = self
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)

        remote_sock.setblocking(False)
        if self._remote_udp:
            pass
        else:
            remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        return remote_sock
开发者ID:konggil,项目名称:shadowsocks,代码行数:33,代码来源:tcprelay.py


示例3: _handle_stage_addr

 def _handle_stage_addr(self, data):
     try:
         if self._is_local:
             cmd = common.ord(data[1])
             if cmd == CMD_UDP_ASSOCIATE:
                 logging.debug('UDP associate')
                 if self._local_sock.family == socket.AF_INET6:
                     header = b'\x05\x00\x00\x04'
                 else:
                     header = b'\x05\x00\x00\x01'
                 addr, port = self._local_sock.getsockname()[:2]
                 addr_to_send = socket.inet_pton(self._local_sock.family,
                                                 addr)
                 port_to_send = struct.pack('>H', port)
                 self._write_to_sock(header + addr_to_send + port_to_send,
                                     self._local_sock)
                 self._stage = STAGE_UDP_ASSOC
                 # just wait for the client to disconnect
                 return
             elif cmd == CMD_CONNECT:
                 # just trim VER CMD RSV
                 data = data[3:]
             else:
                 logging.error('unknown command %d', cmd)
                 self.destroy()
                 return
         header_result = parse_header(data)
         if header_result is None:
             raise Exception('can not parse header')
         addrtype, remote_addr, remote_port, header_length = header_result
         logging.info('connecting %s:%d from %s:%d' %
                      (common.to_str(remote_addr), remote_port,
                       self._client_address[0], self._client_address[1]))
         self._remote_address = (common.to_str(remote_addr), remote_port)
         # pause reading
         self._update_stream(STREAM_UP, WAIT_STATUS_WRITING)
         self._stage = STAGE_DNS
         if self._is_local:
             # forward address to remote
             self._write_to_sock((b'\x05\x00\x00\x01'
                                  b'\x00\x00\x00\x00\x10\x10'),
                                 self._local_sock)
             data_to_send = self._encryptor.encrypt(data)
             self._data_to_write_to_remote.append(data_to_send)
             # notice here may go into _handle_dns_resolved directly
             self._dns_resolver.resolve(self._chosen_server[0],
                                        self._handle_dns_resolved)
         else:
             if len(data) > header_length:
                 self._data_to_write_to_remote.append(data[header_length:])
             # notice here may go into _handle_dns_resolved directly
             self._dns_resolver.resolve(remote_addr,
                                        self._handle_dns_resolved)
     except Exception as e:
         self._log_error(e)
         if self._config['verbose']:
             traceback.print_exc()
         # TODO use logging when debug completed
         self.destroy()
开发者ID:noblocknet,项目名称:shadowsocks,代码行数:59,代码来源:tcprelay.py


示例4: _create_remote_socket

    def _create_remote_socket(self, ip, port):
        if self._remote_udp:
            addrs_v6 = socket.getaddrinfo("::", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
            addrs = socket.getaddrinfo("0.0.0.0", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
        else:
            addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP)
        if len(addrs) == 0:
            raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
        af, socktype, proto, canonname, sa = addrs[0]
        if not self._remote_udp:
            if self._forbidden_iplist:
                if common.to_str(sa[0]) in self._forbidden_iplist:
                    if self._remote_address:
                        raise Exception('IP %s is in forbidden list, when connect to %s:%d via port %d' %
                            (common.to_str(sa[0]), self._remote_address[0], self._remote_address[1], self._server._listen_port))
                    raise Exception('IP %s is in forbidden list, reject' %
                                    common.to_str(sa[0]))
            if self._forbidden_portset:
                if sa[1] in self._forbidden_portset:
                    if self._remote_address:
                        raise Exception('Port %d is in forbidden list, when connect to %s:%d via port %d' %
                            (sa[1], self._remote_address[0], self._remote_address[1], self._server._listen_port))
                    raise Exception('Port %d is in forbidden list, reject' % sa[1])
        remote_sock = socket.socket(af, socktype, proto)
        self._remote_sock = remote_sock
        self._fd_to_handlers[remote_sock.fileno()] = self

        if self._remote_udp:
            af, socktype, proto, canonname, sa = addrs_v6[0]
            remote_sock_v6 = socket.socket(af, socktype, proto)
            self._remote_sock_v6 = remote_sock_v6
            self._fd_to_handlers[remote_sock_v6.fileno()] = self

        remote_sock.setblocking(False)
        if self._remote_udp:
            remote_sock_v6.setblocking(False)
        else:
            remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)

            if not self._is_local:
                bind_addr = ''
                if self._bind and af == socket.AF_INET:
                    bind_addr = self._bind
                elif self._bindv6 and af == socket.AF_INET6:
                    bind_addr = self._bindv6
                else:
                    bind_addr = self._accept_address[0]

                bind_addr = bind_addr.replace("::ffff:", "")
                if bind_addr in self._ignore_bind_list:
                    bind_addr = None
                if bind_addr:
                    local_addrs = socket.getaddrinfo(bind_addr, port, 0, socket.SOCK_STREAM, socket.SOL_TCP)
                    if local_addrs[0][0] == af:
                        logging.debug("bind %s" % (bind_addr,))
                        remote_sock.bind((bind_addr, 0))
        return remote_sock
开发者ID:xcracker,项目名称:autoss,代码行数:57,代码来源:tcprelay.py


示例5: _create_remote_socket

 def _create_remote_socket(self, ip, port):
     addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM,
                                socket.SOL_TCP)
     if len(addrs) == 0:
         raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
     af, socktype, proto, canonname, sa = addrs[0]
     if self._forbidden_iplist:
         if common.to_str(sa[0]) in self._forbidden_iplist:
             raise Exception('IP %s is in forbidden list, reject' %
                             common.to_str(sa[0]))
     remote_sock = socket.socket(af, socktype, proto)
     self._remote_sock = remote_sock
     self._fd_to_handlers[remote_sock.fileno()] = self
     remote_sock.setblocking(False)
     remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
     return remote_sock
开发者ID:EvilCult,项目名称:shadowsocks,代码行数:16,代码来源:tcprelay.py


示例6: write_pid_file

def write_pid_file(pid_file, pid):
    import fcntl
    import stat

    try:
        fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
                     stat.S_IRUSR | stat.S_IWUSR)
    except OSError as e:
        logging.error(e)
        return -1
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    assert flags != -1
    flags |= fcntl.FD_CLOEXEC
    r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
    assert r != -1
    # There is no platform independent way to implement fcntl(fd, F_SETLK, &fl)
    # via fcntl.fcntl. So use lockf instead
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
    except IOError:
        r = os.read(fd, 32)
        if r:
            logging.error('already started at pid %s' % common.to_str(r))
        else:
            logging.error('already started')
        os.close(fd)
        return -1
    os.ftruncate(fd, 0)
    os.write(fd, common.to_bytes(str(pid)))
    return 0
开发者ID:Kerwong,项目名称:shadowsocks,代码行数:30,代码来源:daemon.py


示例7: ssrlink

	def ssrlink(self, user, encode):
		protocol = user.get('protocol', '')
		obfs = user.get('obfs', '')
		protocol = protocol.replace("_compatible", "")
		obfs = obfs.replace("_compatible", "")
		link = "%s:%s:%s:%s:%s:%s" % (self.server_addr, user['port'], protocol, user['method'], obfs, common.to_str(base64.urlsafe_b64encode(common.to_bytes(user['passwd']))).replace("=", ""))
		return "ssr://" + ( encode and common.to_str(base64.urlsafe_b64encode(common.to_bytes(link))).replace("=", "") or link)
开发者ID:xcracker,项目名称:autoss,代码行数:7,代码来源:mujson_mgr.py


示例8: get_host_from_http_header

 def get_host_from_http_header(self, buf):
     ret_buf = b''
     lines = buf.split(b'\r\n')
     if lines and len(lines) > 1:
         for line in lines:
             if match_begin(line, b"Host: "):
                 return common.to_str(line[6:])
开发者ID:chasenn,项目名称:Shadowsowcks1Click,代码行数:7,代码来源:http_simple.py


示例9: __init__

 def __init__(self, method):
     method = common.to_str(method)
     self.method = method
     self._method_info = self.get_method_info(method)
     if self._method_info:
         self.obfs = self.get_obfs(method)
     else:
         raise Exception('obfs plugin [%s] not supported' % method)
开发者ID:luffySaw,项目名称:shadowsocks-R,代码行数:8,代码来源:obfs.py


示例10: ssrlink

	def ssrlink(self, user, encode, muid):
		protocol = user.get('protocol', '')
		obfs = user.get('obfs', '')
		protocol = protocol.replace("_compatible", "")
		obfs = obfs.replace("_compatible", "")
		protocol_param = ''
		if muid is not None:
			protocol_param_ = user.get('protocol_param', '')
			param = protocol_param_.split('#')
			if len(param) == 2:
				for row in self.data.json:
					if int(row['port']) == muid:
						param = str(muid) + ':' + row['passwd']
						protocol_param = '/?protoparam=' + common.to_str(base64.urlsafe_b64encode(common.to_bytes(param))).replace("=", "")
						break
		link = ("%s:%s:%s:%s:%s:%s" % (self.server_addr, user['port'], protocol, user['method'], obfs, common.to_str(base64.urlsafe_b64encode(common.to_bytes(user['passwd']))).replace("=", ""))) + protocol_param
		return "ssr://" + (encode and common.to_str(base64.urlsafe_b64encode(common.to_bytes(link))).replace("=", "") or link)
开发者ID:chasenn,项目名称:Shadowsowcks1Click,代码行数:17,代码来源:mujson_mgr.py


示例11: _parse_command

 def _parse_command(self, data):
     # commands:
     # add: {"server_port": 8000, "password": "foobar"}
     # remove: {"server_port": 8000"}
     data = common.to_str(data)
     parts = data.split(':', 1)
     if len(parts) < 2:
         return data, None
     command, config_json = parts
     try:
         config = shell.parse_json_in_str(config_json)
         if 'method' in config:
             config['method'] = common.to_str(config['method'])
         return command, config
     except Exception as e:
         logging.error(e)
         return None
开发者ID:Cloud0219,项目名称:shadowsocks,代码行数:17,代码来源:manager.py


示例12: write_pid_file

def write_pid_file(pid_file, pid):
    """
    pidfile

    通常在 /var/run 目录中会看到很多进程的 pid 文件, 其实这些文件就是一个记录着进程的 PID 号的文本文件。
    它的作用是防止程序启动多个副本,只有获得 pid 文件写入权限的进程才能正常启动并把进程 PID 写入到该文件,
    而同一程序的其他进程则会检测到该文件无法写入退出。

    """
    # 文件描述符控制
    import fcntl
    # 获取文件信息
    import stat

    try:
        # O_RDWR | O_CREAT 如果文件存在,打开文件以读取写入,否则创建该文件,并使其拥有以下权限
        # S_IRUSR 文件所有者具可读取权限
        # S_IWUSR 文件所有者具可写入权限
        fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
                     stat.S_IRUSR | stat.S_IWUSR)
    except OSError as e:
        shell.print_exception(e)
        return -1
    # F_GETFD 获取文件描述符标记
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    assert flags != -1
    flags |= fcntl.FD_CLOEXEC
    r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
    assert r != -1
    # There is no platform independent way to implement fcntl(fd, F_SETLK, &fl)
    # via fcntl.fcntl. So use lockf instead
    try:
        """
        文件锁
        LOCK_EX exclusive 独占锁
        LOCK_NB non-blocking 非阻塞锁
        在独占锁的情况下,同一时间只有一个进程可以锁住这个文件。
        在有其他进程占有该锁时,
        如果是阻塞锁,lockf 函数会一直阻塞,直到获得锁,而非阻塞锁使 lockf 函数直接返回 IOError。
        fcntl.lockf(fd, operation[, length[, start[, whence]]])
        start 和 length 标记了要锁住的区域的起始位置和长度,而 whence 标记了整个锁区域的偏移量。
        SEEK_SET SEEK_CUR SEEK_END 分别表示文件开头,当前指针位置和文件结尾
        """
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
    except IOError:
        # pidfile 被其他进程锁住的情况,读取该 pidfile 内容
        r = os.read(fd, 32)
        if r:
            logging.error('already started at pid %s' % common.to_str(r))
        else:
            logging.error('already started')
        os.close(fd)
        return -1
    # 把 fd 对应文件修剪为长度为 0,即清空该文件
    os.ftruncate(fd, 0)
    # 将当前进程的 pid 文件写入到 fd 对应文件中
    os.write(fd, common.to_bytes(str(pid)))
    return 0
开发者ID:7uk0n,项目名称:decode_ss,代码行数:58,代码来源:daemon.py


示例13: push

 def push(self, ch):
     ch = ord(ch)
     if self.state == 0:
         if ch == ord('"'):
             self.state = 1
             return to_str(chr(ch))
         elif ch == ord('/'):
             self.state = 3
         else:
             return to_str(chr(ch))
     elif self.state == 1:
         if ch == ord('"'):
             self.state = 0
             return to_str(chr(ch))
         elif ch == ord('\\'):
             self.state = 2
         return to_str(chr(ch))
     elif self.state == 2:
         self.state = 1
         if ch == ord('"'):
             return to_str(chr(ch))
         return "\\" + to_str(chr(ch))
     elif self.state == 3:
         if ch == ord('/'):
             self.state = 4
         else:
             return "/" + to_str(chr(ch))
     elif self.state == 4:
         if ch == ord('\n'):
             self.state = 0
             return "\n"
     return ""
开发者ID:days72115,项目名称:lede,代码行数:32,代码来源:shell.py


示例14: _create_remote_socket

    def _create_remote_socket(self, ip, port):
        if self._remote_udp:
            addrs_v6 = socket.getaddrinfo("::", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
            addrs = socket.getaddrinfo("0.0.0.0", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
        else:
            addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP)
        if len(addrs) == 0:
            raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
        af, socktype, proto, canonname, sa = addrs[0]
        if not self._remote_udp:
            if self._forbidden_iplist:
                if common.to_str(sa[0]) in self._forbidden_iplist:
                    if self._remote_address:
                        raise Exception('IP %s is in forbidden list, when connect to %s:%d via port %d' %
                            (common.to_str(sa[0]), self._remote_address[0], self._remote_address[1], self._server._listen_port))
                    raise Exception('IP %s is in forbidden list, reject' %
                                    common.to_str(sa[0]))
            if self._forbidden_portset:
                if sa[1] in self._forbidden_portset:
                    if self._remote_address:
                        raise Exception('Port %d is in forbidden list, when connect to %s:%d via port %d' %
                            (sa[1], self._remote_address[0], self._remote_address[1], self._server._listen_port))
                    raise Exception('Port %d is in forbidden list, reject' % sa[1])
        remote_sock = socket.socket(af, socktype, proto)
        self._remote_sock = remote_sock
        self._fd_to_handlers[remote_sock.fileno()] = self

        if self._remote_udp:
            af, socktype, proto, canonname, sa = addrs_v6[0]
            remote_sock_v6 = socket.socket(af, socktype, proto)
            self._remote_sock_v6 = remote_sock_v6
            self._fd_to_handlers[remote_sock_v6.fileno()] = self

        remote_sock.setblocking(False)
        if self._remote_udp:
            remote_sock_v6.setblocking(False)

            if not self._is_local:
                self._socket_bind_addr(remote_sock, af)
                self._socket_bind_addr(remote_sock_v6, af)
        else:
            remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
            if not self._is_local:
                self._socket_bind_addr(remote_sock, af)
        return remote_sock
开发者ID:xieshenglin,项目名称:shadowsocks,代码行数:45,代码来源:tcprelay.py


示例15: check_config

def check_config(config, is_local):
    """
    校验配置文件正确性
    :param config:
    :param is_local: 是否为本地启动(也就是客户端)
    :return:
    """
    if config.get('daemon', None) == 'stop':
        # no need to specify configuration for daemon stop
        return
    # 本地需要密码
    if is_local and not config.get('password', None):
        logging.error('password not specified')
        print_help(is_local)
        sys.exit(2)
    # 服务器,需要密码 端口密码, 管理地址
    if not is_local and not config.get('password', None) \
            and not config.get('port_password', None) \
            and not config.get('manager_address'):
        logging.error('password or port_password not specified')
        print_help(is_local)
        sys.exit(2)
    # 格式转化
    if 'local_port' in config:
        config['local_port'] = int(config['local_port'])

    if config.get('server_port', None) and type(config['server_port']) != list:
        config['server_port'] = int(config['server_port'])

    if config.get('local_address', '') in [b'0.0.0.0']:
        logging.warn('warning: local set to listen on 0.0.0.0, it\'s not safe')
    if config.get('server', '') in ['127.0.0.1', 'localhost']:
        logging.warn('warning: server set to listen on %s:%s, are you sure?' %
                     (to_str(config['server']), config['server_port']))
    if (config.get('method', '') or '').lower() == 'table':
        logging.warn('warning: table is not safe; please use a safer cipher, '
                     'like AES-256-CFB')
    if (config.get('method', '') or '').lower() == 'rc4':
        logging.warn('warning: RC4 is not safe; please use a safer cipher, '
                     'like AES-256-CFB')
    if config.get('timeout', 300) < 100:
        logging.warn('warning: your timeout %d seems too short' %
                     int(config.get('timeout')))
    if config.get('timeout', 300) > 600:
        logging.warn('warning: your timeout %d seems too long' %
                     int(config.get('timeout')))
    if config.get('password') in [b'mypassword']:
        logging.error('DON\'T USE DEFAULT PASSWORD! Please change it in your '
                      'config.json!')
        sys.exit(1)
    if config.get('user', None) is not None:
        if os.name != 'posix':
            logging.error('user can be used only on Unix')
            sys.exit(1)
    # 设定底层加密算法
    encrypt.try_cipher(config['password'], config['method'])
开发者ID:t3573393,项目名称:shadowsocks,代码行数:56,代码来源:shell.py


示例16: new_server

	def new_server(self, port, user_config):
		ret = True
		port = int(port)
		ipv6_ok = False

		if 'server_ipv6' in self.config:
			if port in self.tcp_ipv6_servers_pool:
				logging.info("server already at %s:%d" % (self.config['server_ipv6'], port))
				return 'this port server is already running'
			else:
				a_config = self.config.copy()
				a_config.update(user_config)
				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'] = a_config['server_ipv6']
				a_config['server_port'] = port
				a_config['max_connect'] = 128
				a_config['method'] = common.to_str(a_config['method'])
				try:
					logging.info("starting server at [%s]:%d" % (common.to_str(a_config['server']), port))

					tcp_server = tcprelay.TCPRelay(a_config, self.dns_resolver, False, stat_counter=self.stat_counter)
					tcp_server.add_to_loop(self.loop)
					self.tcp_ipv6_servers_pool.update({port: tcp_server})

					udp_server = udprelay.UDPRelay(a_config, self.dns_resolver, False, stat_counter=self.stat_counter)
					udp_server.add_to_loop(self.loop)
					self.udp_ipv6_servers_pool.update({port: udp_server})

					if common.to_str(a_config['server_ipv6']) == "::":
						ipv6_ok = True
				except Exception as e:
					logging.warn("IPV6 %s " % (e,))

		if 'server' in self.config:
			if port in self.tcp_servers_pool:
				logging.info("server already at %s:%d" % (common.to_str(self.config['server']), port))
				return 'this port server is already running'
			else:
				a_config = self.config.copy()
				a_config.update(user_config)
				a_config['server_port'] = port
				a_config['max_connect'] = 128
				a_config['method'] = common.to_str(a_config['method'])
				try:
					logging.info("starting server at %s:%d" % (common.to_str(a_config['server']), port))

					tcp_server = tcprelay.TCPRelay(a_config, self.dns_resolver, False)
					tcp_server.add_to_loop(self.loop)
					self.tcp_servers_pool.update({port: tcp_server})

					udp_server = udprelay.UDPRelay(a_config, self.dns_resolver, False)
					udp_server.add_to_loop(self.loop)
					self.udp_servers_pool.update({port: udp_server})

				except Exception as e:
					if not ipv6_ok:
						logging.warn("IPV4 %s " % (e,))

		return True
开发者ID:wlhost,项目名称:LegendSock-Server,代码行数:60,代码来源:server_pool.py


示例17: check_config

def check_config(config, is_local):
    if config.get("daemon", None) == "stop":
        # no need to specify configuration for daemon stop
        return

    if is_local and not config.get("password", None):
        logging.error("password not specified")
        print_help(is_local)
        sys.exit(2)

    if (
        not is_local
        and not config.get("password", None)
        and not config.get("port_password", None)
        and not config.get("manager_address")
    ):
        logging.error("password or port_password not specified")
        print_help(is_local)
        sys.exit(2)

    if "local_port" in config:
        config["local_port"] = int(config["local_port"])

    if config.get("server_port", None) and type(config["server_port"]) != list:
        config["server_port"] = int(config["server_port"])

    if config.get("local_address", "") in [b"0.0.0.0"]:
        logging.warn("warning: local set to listen on 0.0.0.0, it's not safe")
    if config.get("server", "") in ["127.0.0.1", "localhost"]:
        logging.warn(
            "warning: server set to listen on %s:%s, are you sure?" % (to_str(config["server"]), config["server_port"])
        )
    if (config.get("method", "") or "").lower() == "table":
        logging.warn("warning: table is not safe; please use a safer cipher, " "like AES-256-CFB")
    if (config.get("method", "") or "").lower() == "rc4":
        logging.warn("warning: RC4 is not safe; please use a safer cipher, " "like AES-256-CFB")
    if config.get("timeout", 300) < 100:
        logging.warn("warning: your timeout %d seems too short" % int(config.get("timeout")))
    if config.get("timeout", 300) > 600:
        logging.warn("warning: your timeout %d seems too long" % int(config.get("timeout")))
    if config.get("password") in [b"mypassword"]:
        logging.error("DON'T USE DEFAULT PASSWORD! Please change it in your " "config.json!")
        sys.exit(1)
    if "cc_algo" in config and not sys.platform.startswith("linux"):
        logging.warn("pluggable congestion control algorithm requires linux!")
    if config.get("user", None) is not None:
        if os.name != "posix":
            logging.error("user can be used only on Unix")
            sys.exit(1)
    if "cc_algo" in config and sys.platform.startswith("linux"):
        logging.info("use %s as socket congestion control algorithm" % config.get("cc_algo", None))
    encrypt.try_cipher(config["password"], config["method"])
开发者ID:jiangxianliang,项目名称:shadowsocks,代码行数:52,代码来源:shell.py


示例18: check_config

def check_config(config, is_local):
    if config.get('daemon', None) == 'stop':
        # no need to specify configuration for daemon stop
        return

    if is_local and not config.get('password', None) and not config.get('port_password',None):
        logging.error('password or port_password not specified')
        print_help(is_local)
        sys.exit(2)

    if not is_local and not config.get('password', None)  and not config.get('port_password', None):
        logging.error('password or port_password not specified')
        print_help(is_local)
        sys.exit(2)

    if 'local_port' in config:
        config['local_port'] = int(config['local_port'])

    if 'server_port' in config and type(config['server_port']) != list:
        config['server_port'] = int(config['server_port'])

    if config.get('local_address', '') in [b'0.0.0.0']:
        logging.warn('warning: local set to listen on 0.0.0.0, it\'s not safe')
    if config.get('server', '') in ['127.0.0.1', 'localhost']:
        logging.warn('warning: server set to listen on %s:%s, are you sure?' % (to_str(config['server']), config['server_port']))
    if (config.get('method', '') or '').lower() == 'table':
        logging.warn('warning: table is not safe; please use a safer cipher, like AES-256-CFB')
    if (config.get('method', '') or '').lower() == 'rc4':
        logging.warn('warning: RC4 is not safe; please use a safer cipher,like AES-256-CFB')
    if config.get('timeout', 300) < 100:
        logging.warn('warning: your timeout %d seems too short' % int(config.get('timeout')))
    if config.get('timeout', 300) > 600:
        logging.warn('warning: your timeout %d seems too long' % int(config.get('timeout')))
    if config.get('password') in [b'mypassword']:
        logging.error('DON\'T USE DEFAULT PASSWORD! Please change it in your config.json!')
        sys.exit(1)
    if config['log'].has_key('log_enable') is False:
        config['log'] = {}
        config['log']['log_enable'] = False
    if config['log'].has_key('log_path') is False:
        config['log']['log_path'] = "%s" % os.path.expanduser("~/ss.log")
    if config['forbid'].has_key('site') is False:
        config['forbid'] = {}
        config['forbid']['site'] = []
    if config['forbid'].has_key('port') is False:
        config['forbid']['port'] = []
    if config.get('user', None) is not None:
        if os.name != 'posix':
            logging.error('user can be used only on Unix')
            sys.exit(1)
    encrypt.try_cipher(config['password'], config['method'])
开发者ID:JustAFakeName,项目名称:ss,代码行数:51,代码来源:shell.py


示例19: daemon_exec

def daemon_exec(config):
    if 'daemon' in config:
        if os.name != 'posix':
            raise Exception('daemon mode is only supported on Unix')
        command = config['daemon']
        if not command:
            command = 'start'
        pid_file = config['pid-file']
        log_file = config['log-file']
        command = common.to_str(command)
        pid_file = common.to_str(pid_file)
        log_file = common.to_str(log_file)
        if command == 'start':
            daemon_start(pid_file, log_file)
        elif command == 'stop':
            daemon_stop(pid_file)
            # always exit after daemon_stop
            sys.exit(0)
        elif command == 'restart':
            daemon_stop(pid_file)
            daemon_start(pid_file, log_file)
        else:
            raise Exception('unsupported daemon command %s' % command)
开发者ID:Kerwong,项目名称:shadowsocks,代码行数:23,代码来源:daemon.py


示例20: _parse_command

 def _parse_command(self, data):
     # commands:
     # add: {'server_port': 8000, 'password': 'foobar'}
     # remove: {'server_port': 8000'}
     data = common.to_str(data)
     parts = data.split(':', 1)
     if len(parts) < 2:
         return data, None
     command, config_json = parts
     try:
         config = shell.parse_json_in_str(config_json)
         return command, config
     except Exception as e:
         logging.error(e)
         return None
开发者ID:Liwink,项目名称:shadowsocks,代码行数:15,代码来源:manager.py



注:本文中的shadowsocks.common.to_str函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.run_cipher函数代码示例发布时间:2022-05-27
下一篇:
Python common.to_bytes函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap