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

Python eventloop.errno_from_exception函数代码示例

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

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



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

示例1: _handle_remote

 def _handle_remote(self, sock):
     try:
         data, addr = sock.recvfrom(BUF_SIZE)
     except (OSError, IOError) as e:
         logging.error(e)
         if eventloop.errno_from_exception(e) == errno.ECONNRESET:
             # just for Windows lol
             self._rebuild_sockets()
         return
     if data:
         try:
             header = asyncdns.parse_header(data)
             if header:
                 req_id = header[0]
                 res = asyncdns.parse_response(data)
                 logging.info('response %s', res)
                 addr = self._id_to_addr.get(req_id, None)
                 if addr:
                     for answer in res.answers:
                         if answer and answer[0] in GFW_LIST:
                             return
                     self._local_sock.sendto(data, addr)
                     del self._id_to_addr[req_id]
         except Exception as e:
             import traceback
             traceback.print_exc()
             logging.error(e)
             if eventloop.errno_from_exception(e) == errno.EACCES:
                 # when we have changed our ip
                 self._rebuild_sockets()
开发者ID:Acidburn0zzz,项目名称:ChinaDNS,代码行数:30,代码来源:dnsrelay.py


示例2: _handle_stage_connecting

 def _handle_stage_connecting(self, data):
     if self._is_local:
         data = self._encryptor.encrypt(data)
     self._data_to_write_to_remote.append(data)
     if self._is_local and not self._fastopen_connected and self._config["fast_open"]:
         # for sslocal and fastopen, we basically wait for data and use
         # sendto to connect
         try:
             # only connect once
             self._fastopen_connected = True
             remote_sock = self._create_remote_socket(self._chosen_server[0], self._chosen_server[1])
             self._loop.add(remote_sock, eventloop.POLL_ERR)
             data = b"".join(self._data_to_write_to_remote)
             l = len(data)
             s = remote_sock.sendto(data, MSG_FASTOPEN, self._chosen_server)
             if s < l:
                 data = data[s:]
                 self._data_to_write_to_remote = [data]
             else:
                 self._data_to_write_to_remote = []
             self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
         except (OSError, IOError) as e:
             if eventloop.errno_from_exception(e) == errno.EINPROGRESS:
                 # in this case data is not sent at all
                 self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
             elif eventloop.errno_from_exception(e) == errno.ENOTCONN:
                 logging.error("fast open not supported on this OS")
                 self._config["fast_open"] = False
                 self.destroy()
             else:
                 logging.error(e)
                 if self._config["verbose"]:
                     traceback.print_exc()
                 self.destroy()
开发者ID:zouy68,项目名称:shadowsocks,代码行数:34,代码来源:tcprelay.py


示例3: _handle_stage_reply

 def _handle_stage_reply(self, data):
     if self._is_local:
         data = self._encryptor.encrypt(data)
     self._data_to_write_to_remote.append(data)
     if self._is_local and not self._fastopen_connected and \
             self._config['fast_open']:
         try:
             self._fastopen_connected = True
             remote_sock = \
                 self._create_remote_socket(self._chosen_server[0],
                                            self._chosen_server[1])
             self._loop.add(remote_sock, eventloop.POLL_ERR)
             data = b''.join(self._data_to_write_to_local)
             l = len(data)
             s = remote_sock.sendto(data, MSG_FASTOPEN, self._chosen_server)
             if s < l:
                 data = data[s:]
                 self._data_to_write_to_local = [data]
                 self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
             else:
                 self._data_to_write_to_local = []
                 self._update_stream(STREAM_UP, WAIT_STATUS_READING)
                 self._stage = STAGE_STREAM
         except (OSError, IOError) as e:
             if eventloop.errno_from_exception(e) == errno.EINPROGRESS:
                 self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
             elif eventloop.errno_from_exception(e) == errno.ENOTCONN:
                 logging.error('fast open not supported on this OS')
                 self._config['fast_open'] = False
                 self.destroy()
             else:
                 logging.error(e)
                 if self._config['verbose']:
                     traceback.print_exc()
                 self.destroy()
开发者ID:Yggdroot,项目名称:shadowsocks,代码行数:35,代码来源:tcprelay.py


示例4: main

def main():
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')

    parser = argparse.ArgumentParser(description='Forward DNS requests.')
    parser.add_argument('-b', '--local_address', metavar='BIND_ADDR', type=str,
                        help='address that listens, default: 127.0.0.1',
                        default='127.0.0.1')
    parser.add_argument('-p', '--local_port', metavar='BIND_PORT', type=int,
                        help='port that listens, default: 53', default=53)
    parser.add_argument('-s', '--dns', metavar='DNS', type=str,
                        help='DNS server to use, default: '
                             '114.114.114.114,208.67.222.222,8.8.8.8',
                        default='114.114.114.114,208.67.222.222,8.8.8.8')

    config = vars(parser.parse_args())

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

    loop = eventloop.EventLoop()

    try:
        udprelay = UDPDNSRelay(config)
        udprelay.add_to_loop(loop)
        tcprelay = TCPDNSRelay(config)
        tcprelay.add_to_loop(loop)
        loop.run()
    except (OSError, IOError) as e:
        logging.error(e)
        if eventloop.errno_from_exception(e) == errno.EACCES:
            logging.info('please use sudo to run this program')
        sys.exit(1)
开发者ID:rumbleman,项目名称:ChinaDNS,代码行数:34,代码来源:dnsrelay.py


示例5: handle_event

 def handle_event(self, sock, fd, event):
     # handle events and dispatch to handlers
     if sock:
         logging.log(shell.VERBOSE_LEVEL, 'fd %d %s', fd,
                     eventloop.EVENT_NAMES.get(event, event))
     if sock == self._server_socket:
         if event & eventloop.POLL_ERR:
             # TODO
             raise Exception('server_socket error')
         try:
             logging.debug('accept')
             conn = self._server_socket.accept()
             TCPRelayHandler(self, self._fd_to_handlers,
                             self._eventloop, conn[0], self._config,
                             self._dns_resolver, self._is_local)
         except (OSError, IOError) as e:
             error_no = eventloop.errno_from_exception(e)
             if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                             errno.EWOULDBLOCK):
                 return
             else:
                 shell.print_exception(e)
                 if self._config['verbose']:
                     traceback.print_exc()
     else:
         if sock:
             handler = self._fd_to_handlers.get(fd, None)
             if handler:
                 handler.handle_event(sock, event)
         else:
             logging.warn('poll removed fd')
开发者ID:EvilCult,项目名称:shadowsocks,代码行数:31,代码来源:tcprelay.py


示例6: _on_remote_read

    def _on_remote_read(self):
        logging.debug("Running in the TCPRelayHandler class. [_on_remote_read]")
        # handle all remote read events
        data = None
        try:

            data = self._remote_sock.recv(BUF_SIZE)

        except (OSError, IOError) as e:
            if eventloop.errno_from_exception(e) in (errno.ETIMEDOUT, errno.EAGAIN, errno.EWOULDBLOCK):
                return
        if not data:
            self.destroy()
            return
        self._update_activity(len(data))
        if self._is_local:
            data = self._encryptor.decrypt(data)
        else:
            data = self._encryptor.encrypt(data)
        try:
            self._write_to_sock(data, self._local_sock)
#             if not self._is_local:
#                 if self._config.has_key('port_limit') and self._config['port_limit'] != "" and os.path.exists(self._config['port_limit']):
#                     port_limits = json.loads(open(self._config['port_limit']).read())
#                     if str(self._server._listen_port) in port_limits:
#                         port_limits['%s' % self._server._listen_port]['used'] = port_limits['%s' % self._server._listen_port]['used'] + len(data) + BUF_SIZE
#                         open('%s' % self._config['port_limit'],"w").write("%s" % json.dumps(port_limits,indent=4,ensure_ascii=False,sort_keys=True))
        except Exception as e:
            shell.print_exception(e)
            if self._config['verbose']:
                traceback.print_exc()
            # TODO use logging when debug completed
            self.destroy()
开发者ID:JustAFakeName,项目名称:ss,代码行数:33,代码来源:tcprelay.py


示例7: _handle_local

    def _handle_local(self, sock):
        try:
            data, addr = sock.recvfrom(BUF_SIZE)
        except (OSError, IOError) as e:
            logging.error(e)
            if eventloop.errno_from_exception(e) == errno.ECONNRESET:
                # just for Windows lol
                self._rebuild_sockets()
            return
        header = asyncdns.parse_header(data)
        if header:
            try:
                req_id = header[0]
                req = asyncdns.parse_response(data)
                logging.info('--- request %s', req.hostname)
                if req.hostname in self._hosts:
                    response = self.build_response(data,
                                                   self._hosts[req.hostname])
                    if response:
                        logging.info('%s hit /etc/hosts', req.hostname)
                        self._local_sock.sendto(response, addr)
                        return
                self._id_to_addr[req_id] = addr
                for remote_addr in self._remote_addrs:
                    self._remote_sock.sendto(data, remote_addr)
            except Exception as e:
                import traceback

                traceback.print_exc()
                logging.error(e)
开发者ID:jfojfo,项目名称:shadowsocks,代码行数:30,代码来源:dnsrelay.py


示例8: _on_local_read

 def _on_local_read(self):
     self._update_activity()
     if not self._local_sock:
         return
     is_local = self._is_local
     data = None
     try:
         data = self._local_sock.recv(BUF_SIZE)
     except (OSError, IOError) as e:
         if eventloop.errno_from_exception(e) in \
                 (errno.ETIMEDOUT, errno.EAGAIN, errno.EWOULDBLOCK):
             return
     if not data:
         self.destroy()
         return
     if not is_local:
         data = self._encryptor.decrypt(data)
         if not data:
             return
     if self._stage == STAGE_STREAM:
         if self._is_local:
             data = self._encryptor.encrypt(data)
         self._write_to_sock(data, self._remote_sock)
         return
     elif is_local and self._stage == STAGE_INIT:
         # TODO check auth method
         self._write_to_sock(b'\x05\00', self._local_sock)
         self._stage = STAGE_HELLO
         return
     elif self._stage == STAGE_REPLY:
         self._handle_stage_reply(data)
     elif (is_local and self._stage == STAGE_HELLO) or \
             (not is_local and self._stage == STAGE_INIT):
         self._handle_stage_hello(data)
开发者ID:Yggdroot,项目名称:shadowsocks,代码行数:34,代码来源:tcprelay.py


示例9: _on_local_read

 def _on_local_read(self):
     # handle all local read events and dispatch them to methods for
     # each stage
     if not self._local_sock:
         return
     is_local = self._is_local
     data = None
     try:
         data = self._local_sock.recv(BUF_SIZE)
     except (OSError, IOError) as e:
         if eventloop.errno_from_exception(e) in \
                 (errno.ETIMEDOUT, errno.EAGAIN, errno.EWOULDBLOCK):
             return
     if not data:
         self.destroy()
         return
     self._update_activity(len(data))
     if not is_local:
         data = self._encryptor.decrypt(data)
         if not data:
             return
     if self._stage == STAGE_STREAM:
         self._handle_stage_stream(data)
         return
     elif is_local and self._stage == STAGE_INIT:
         self._handle_stage_init(data)
     elif self._stage == STAGE_CONNECTING:
         self._handle_stage_connecting(data)
     elif (is_local and self._stage == STAGE_ADDR) or \
             (not is_local and self._stage == STAGE_INIT):
         self._handle_stage_addr(data)
开发者ID:EvilCult,项目名称:shadowsocks,代码行数:31,代码来源:tcprelay.py


示例10: _on_local_read

 def _on_local_read(self):
     # handle all local read events and dispatch them to methods for
     # each stage
     self._update_activity()
     if not self._local_sock:
         return
     is_local = self._is_local
     data = None
     try:
         data = self._local_sock.recv(BUF_SIZE)
     except (OSError, IOError) as e:
         if eventloop.errno_from_exception(e) in (errno.ETIMEDOUT, errno.EAGAIN, errno.EWOULDBLOCK):
             return
     if not data:
         self.destroy()
         return
     if not is_local:
         data = self._encryptor.decrypt(data)
         if not data:
             return
     if self._stage == STAGE_STREAM:
         if self._is_local:
             data = self._encryptor.encrypt(data)
         self._write_to_sock(data, self._remote_sock)
         return
     elif is_local and self._stage == STAGE_INIT:
         # TODO check auth method
         self._write_to_sock(b"\x05\00", self._local_sock)
         self._stage = STAGE_ADDR
         return
     elif self._stage == STAGE_CONNECTING:
         self._handle_stage_connecting(data)
     elif (is_local and self._stage == STAGE_ADDR) or (not is_local and self._stage == STAGE_INIT):
         self._handle_stage_addr(data)
开发者ID:asdlei00,项目名称:shadowsocks,代码行数:34,代码来源:tcprelay.py


示例11: _handle_conn

    def _handle_conn(self, sock):
        try:
            local, addr = sock.accept()
            addrs = socket.getaddrinfo(self._remote_addr[0],
                                       self._remote_addr[1], 0,
                                       socket.SOCK_STREAM, socket.SOL_TCP)
            if len(addrs) == 0:
                raise Exception("can't get addrinfo for %s:%d" %
                                self._remote_addr)
            af, socktype, proto, canonname, sa = addrs[0]
            remote = socket.socket(af, socktype, proto)
            local.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
            remote.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
            self._local_to_remote[local] = remote
            self._remote_to_local[remote] = local

            self._loop.add(local, 0)
            self._loop.add(remote, eventloop.POLL_OUT)
            try:
                remote.connect(self._remote_addr)
            except (OSError, IOError) as e:
                if eventloop.errno_from_exception(e) in (errno.EINPROGRESS,
                                                         errno.EAGAIN):
                    pass
                else:
                    raise
        except (OSError, IOError) as e:
            logging.error(e)
开发者ID:jfojfo,项目名称:shadowsocks,代码行数:28,代码来源:dnsrelay.py


示例12: _on_remote_read

    def _on_remote_read(self):
        # handle all remote read events
        data = None
        try:
            data = self._remote_sock.recv(BUF_SIZE)

        except (OSError, IOError) as e:
            if eventloop.errno_from_exception(e) in \
                    (errno.ETIMEDOUT, errno.EAGAIN, errno.EWOULDBLOCK):
                return
        if not data:
            self.destroy()
            return
        self._update_activity(len(data))
        if self._is_local:
            data = self._encryptor.decrypt(data)
        else:
            data = self._encryptor.encrypt(data)
        try:
            self._write_to_sock(data, self._local_sock)
        except Exception as e:
            shell.print_exception(e)
            if self._config['verbose']:
                traceback.print_exc()
            # TODO use logging when debug completed
            self.destroy()
开发者ID:EvilCult,项目名称:shadowsocks,代码行数:26,代码来源:tcprelay.py


示例13: _on_remote_read

    def _on_remote_read(self):
        logging.debug('on remote read')
        # handle all remote read events
        data = None
        try:
            data = self._remote_sock.recv(BUF_SIZE)

        except (OSError, IOError) as e:
            if eventloop.errno_from_exception(e) in \
                    (errno.ETIMEDOUT, errno.EAGAIN, errno.EWOULDBLOCK):
                return
        if not data:
            self.destroy()
            return
        self._update_activity(len(data))
        if self._is_local:
            data = self._encryptor.decrypt(data)
        else:
            # logging.debug('received data:[%s]' % data)
            # data = 'HTTP/1.1 302 Found\nLocation: https://ashadowsocks.com/'
            data = self._encryptor.encrypt(data)
        try:
            self._write_to_sock(data, self._local_sock)
        except Exception as e:
            shell.print_exception(e)
            if self._config['verbose']:
                traceback.print_exc()
            # TODO use logging when debug completed
            self.destroy()
开发者ID:yeweishuai,项目名称:shadowsocks-1,代码行数:29,代码来源:tcprelay.py


示例14: _handle_stage_connecting

 def _handle_stage_connecting(self, data):
     # 如果是本地端,加密数据
     if self._is_local:
         data = self._encryptor.encrypt(data)
     self._data_to_write_to_remote.append(data)
     # 若本地端设置了fast_open却没有fast_open连接
     if self._is_local and not self._fastopen_connected and \
             self._config['fast_open']:
         # for sslocal and fastopen, we basically wait for data and use
         # sendto to connect
         try:
             # only connect once
             self._fastopen_connected = True
             remote_sock = \
                 self._create_remote_socket(self._chosen_server[0],
                                            self._chosen_server[1])
             self._loop.add(remote_sock, eventloop.POLL_ERR)
             # 发送二进制流
             data = b''.join(self._data_to_write_to_local)
             l = len(data)
             # 发送给服务端
             s = remote_sock.sendto(data, MSG_FASTOPEN, self._chosen_server)
             # 若发送尚未完成,转入读写状态
             if s < l:
                 data = data[s:]
                 self._data_to_write_to_local = [data]
                 self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
             # 发送完毕,转入读状态
             else:
                 self._data_to_write_to_local = []
                 self._update_stream(STREAM_UP, WAIT_STATUS_READING)
                 self._stage = STAGE_STREAM
         except (OSError, IOError) as e:
             # EINPROGRESS错误,表示连接操作正在进行中,但是仍未完成,常见于非阻塞的socket连接中
             # stream流状态更新为读写
             if eventloop.errno_from_exception(e) == errno.EINPROGRESS:
                 self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
             # ENOTCONN指定的socket是一个未连接成功的socket
             elif eventloop.errno_from_exception(e) == errno.ENOTCONN:
                 logging.error('fast open not supported on this OS')
                 self._config['fast_open'] = False
                 self.destroy()
             else:
                 logging.error(e)
                 if self._config['verbose']:
                     traceback.print_exc()
                 self.destroy()
开发者ID:lixingcong,项目名称:shadowsocks-analysis,代码行数:47,代码来源:tcprelay.py


示例15: _handle_stage_connecting

    def _handle_stage_connecting(self, data):

        # further process data
        # encrypt it and add to buffer
        if self._is_local:
            data = self._encryptor.encrypt(data)
        self._data_to_write_to_remote.append(data)

        # for fastopen, we basically
        # wait for data and use sendto to connect
        # only connect once
        if self._is_local and not self._fastopen_connected and \
                self._config['fast_open']:
            try:
                self._fastopen_connected = True

                # 1. create _remote_sock
                # 2. add it to eventloop, set event as ERR
                # 3. send data to ssremote
                # 4. reset buffer with unsent data
                # 5. sslocal relays up stream
                remote_sock = \
                    self._create_remote_socket(self._chosen_server[0],
                                               self._chosen_server[1])
                self._loop.add(remote_sock, eventloop.POLL_ERR, self._server)
                data = b''.join(self._data_to_write_to_remote)
                l = len(data)
                s = remote_sock.sendto(data, MSG_FASTOPEN, self._chosen_server)
                if s < l:
                    data = data[s:]
                    self._data_to_write_to_remote = [data]
                else:
                    self._data_to_write_to_remote = []
                self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
            except (OSError, IOError) as e:
                if eventloop.errno_from_exception(e) == errno.EINPROGRESS:
                    self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
                elif eventloop.errno_from_exception(e) == errno.ENOTCONN:
                    logging.error('fast open not supported on this OS')
                    self._config['fast_open'] = False
                    self.destroy()
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
                    self.destroy()
开发者ID:whenhecry,项目名称:shadowsocks,代码行数:46,代码来源:tcprelay.py


示例16: _write_to_sock

 def _write_to_sock(self, data, sock):
     logging.debug("Running in the TCPRelayHandler class. [_write_to_sock]")
     # write data to sock
     # if only some of the data are written, put remaining in the buffer
     # and update the stream to wait for writing
     if not data or not sock:
         return False
     uncomplete = False
     try:
         l = len(data)
         if sock == self._local_sock and self._is_local and self._stage == STAGE_INIT:
             logging.info("[Client] Received data from browser and just sending 'hello' back to [browser] ! data length is: [%s]" % l)
         elif sock == self._remote_sock and self._is_local and self._stage == STAGE_STREAM:
             logging.info("[Client] Received data from browser and just sending -encrypted- data to [VPS] ! data length is: [%s]" % l)
         elif sock == self._local_sock and self._is_local and self._stage == STAGE_STREAM:
             logging.info("[Client] Received data from VPS and just sending -decrypted- data to [browser] ! data length is: [%s]" % l)
         elif sock == self._remote_sock and not self._is_local and self._stage == STAGE_STREAM:
             logging.info("[Server] Received data from client and going to send -decrypted- data to [INTERNET] ! data length is: [%s]" % l)
         elif sock == self._local_sock and not self._is_local and self._stage == STAGE_STREAM:
             logging.info("[Server] Received data from INTERNET and going to send -encrypted- data to [client] ! data length is: [%s]" % l)
         if not self._is_local:
             if self._config.has_key('port_limit') and self._config['port_limit'] != "" and os.path.exists(self._config['port_limit']):
                 port_limits = json.loads(open(self._config['port_limit']).read())
                 if str(self._server._listen_port) in port_limits:
                     port_limits['%s' % self._server._listen_port]['used'] = port_limits['%s' % self._server._listen_port]['used'] + len(data)
                     open('%s' % self._config['port_limit'],"w").write("%s" % json.dumps(port_limits,indent=4,ensure_ascii=False,sort_keys=True))
         s = sock.send(data)
         if s < l:
             data = data[s:]
             uncomplete = True
     except (OSError, IOError) as e:
         error_no = eventloop.errno_from_exception(e)
         if error_no in (errno.EAGAIN, errno.EINPROGRESS, errno.EWOULDBLOCK):
             uncomplete = True
         else:
             shell.print_exception(e)
             self.destroy()
             return False
     if uncomplete:
         if sock == self._local_sock:
             self._data_to_write_to_local.append(data)
             self._update_stream(STREAM_DOWN, WAIT_STATUS_WRITING)
         elif sock == self._remote_sock:
             self._data_to_write_to_remote.append(data)
             self._update_stream(STREAM_UP, WAIT_STATUS_WRITING)
         else:
             logging.error('write_all_to_sock:unknown socket')
             common.error_to_file('write_all_to_sock:unknown socket',self._config)
     else:
         if sock == self._local_sock:
             self._update_stream(STREAM_DOWN, WAIT_STATUS_READING)
         elif sock == self._remote_sock:
             self._update_stream(STREAM_UP, WAIT_STATUS_READING)
         else:
             logging.error('write_all_to_sock:unknown socket')
             common.error_to_file('write_all_to_sock:unknown socket',self._config)
     return True
开发者ID:JustAFakeName,项目名称:ss,代码行数:57,代码来源:tcprelay.py


示例17: _handle_events

    def _handle_events(self, events):
        # handle events and dispatch to handlers
        for sock, fd, event in events:
            if sock:
                # log级别是怎么显示出来的,平常都是INFO级别的消息?
                logging.log(utils.VERBOSE_LEVEL, 'fd %d %s', fd,
                            eventloop.EVENT_NAMES.get(event, event))
            
            # 若来自服务端的数据
            if sock == self._server_socket:
                if event & eventloop.POLL_ERR:
                    # TODO
                    raise Exception('server_socket error')
                try:
                    logging.debug('accept')
                    conn = self._server_socket.accept()
                    # 创建一个新的连接,并且新建一个TCPRelayHandler处理
                    # Handler函数包含解密、dns解析等一系列的操作。
                    TCPRelayHandler(self, self._fd_to_handlers,
                                    self._eventloop, conn[0], self._config,
                                    self._dns_resolver, self._is_local)
                except (OSError, IOError) as e:
                    error_no = eventloop.errno_from_exception(e)
                    if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                    errno.EWOULDBLOCK):
                        continue    # 继续进行for循环。
                    else:
                        logging.error(e)
                        if self._config['verbose']:
                            traceback.print_exc()
            # 来自本地socket(1080端口)的数据
            else:
                if sock:
                    # 如果是已经accept的连接,就找相对应的handler处理它
                    handler = self._fd_to_handlers.get(fd, None)
                    if handler:
                        # 这里调用handler里面的handle_event来处理事件
                        handler.handle_event(sock, event)
                else:
                    logging.warn('poll removed fd')

        now = time.time()
        # 超时,清理socket。
        if now - self._last_time > TIMEOUT_PRECISION:
            self._sweep_timeout()
            self._last_time = now
        if self._closed:
            if self._server_socket:
                # 移除当前的socket文件描述符
                self._eventloop.remove(self._server_socket)
                self._server_socket.close()
                self._server_socket = None
                logging.info('closed listen port %d', self._listen_port)
            # 移除服务函数。
            if not self._fd_to_handlers:
                self._eventloop.remove_handler(self._handle_events)
开发者ID:lixingcong,项目名称:shadowsocks-analysis,代码行数:56,代码来源:tcprelay.py


示例18: _write_to_sock

 def _write_to_sock(self, data, sock):
     # write data to sock
     # if only some of the data are written, put remaining in the buffer
     # and update the stream to wait for writing
     # 写入数据到套接字,如果只有部分数据被写入,继续写入剩下的数据到缓冲区,并更新流方向为‘等待’
     if not data or not sock:
         return False
     uncomplete = False
     try:
         l = len(data)
         s = sock.send(data)
         if s < l:
             # 返回list的切片,应该不是浅复制
             data = data[s:]
             uncomplete = True
     except (OSError, IOError) as e:
         error_no = eventloop.errno_from_exception(e)
         if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                         errno.EWOULDBLOCK):
             uncomplete = True
         else:
             logging.error(e)
             # 哆嗦模式
             if self._config['verbose']:
                 traceback.print_exc()
             # 断开连接
             self.destroy()
             # 尚未发送完毕
             return False
     # 尚未完成发送数据
     if uncomplete:
         if sock == self._local_sock:
             # 暂存数据,使用append追加
             self._data_to_write_to_local.append(data)
             # 更新流的状态:等待写入,方向为‘服务端->本地’
             self._update_stream(STREAM_DOWN, WAIT_STATUS_WRITING)
         elif sock == self._remote_sock:
             # 跟上面一样的方法,追加数据,修改stream状态。
             self._data_to_write_to_remote.append(data)
             # 方向‘本地->服务端’
             self._update_stream(STREAM_UP, WAIT_STATUS_WRITING)
         else:
             logging.error('write_all_to_sock:unknown socket')
     # 已经完成发送数据
     else:
         if sock == self._local_sock:
             # 修改流的状态为等待读,方向为‘服务端->本地’
             self._update_stream(STREAM_DOWN, WAIT_STATUS_READING)
         elif sock == self._remote_sock:
             # 方向为‘本地->服务端’
             self._update_stream(STREAM_UP, WAIT_STATUS_READING)
         else:
             logging.error('write_all_to_sock:unknown socket')
     # 函数执行完毕,不一定说明数据发送完毕,return true
     return True
开发者ID:lixingcong,项目名称:shadowsocks-analysis,代码行数:55,代码来源:tcprelay.py


示例19: _handle_dns_resolved

    def _handle_dns_resolved(self, result, error):
        if error:
            self._log_error(error)
            self.destroy()
            return

        # when domain name is resolved
        if result:
            ip = result[1]
            if ip:
                try:
                    self._stage = STAGE_CONNECTING
                    remote_addr = ip

                    # port is not included in the result
                    if self._is_local:
                        remote_port = self._chosen_server[1]
                    else:
                        remote_port = self._remote_address[1]

                    # for fastopen sslocal:
                    # sslocal reads from client
                    if self._is_local and self._config['fast_open']:
                        self._stage = STAGE_CONNECTING
                        # we don't have to wait for remote since it's not created
                        self._update_stream(STREAM_UP, WAIT_STATUS_READING)
                        # TODO when there is already data in this packet

                    # for non-fastopen sslocal,
                    # 1. connect to ssremote, add to loop, set event as ERR|OUT
                    # 2. sslocal relays up stream
                    # for ssremote, 
                    # 1. connect to dest, add to loop, set event as ERR|OUT
                    # 2. ssremote reads from dest
                    else:
                        remote_sock = self._create_remote_socket(remote_addr,
                                                                 remote_port)
                        try:
                            remote_sock.connect((remote_addr, remote_port))
                        except (OSError, IOError) as e:
                            if eventloop.errno_from_exception(e) == \
                                    errno.EINPROGRESS:
                                pass
                        self._loop.add(remote_sock,
                                       eventloop.POLL_ERR | eventloop.POLL_OUT,
                                       self._server)
                        self._stage = STAGE_CONNECTING
                        self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
                        self._update_stream(STREAM_DOWN, WAIT_STATUS_READING)
                    return
                except Exception as e:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
        self.destroy()
开发者ID:whenhecry,项目名称:shadowsocks,代码行数:55,代码来源:tcprelay.py


示例20: _handle_dns_resolved

    def _handle_dns_resolved(self, result, error):
        """
        DNS请求解析完成后调用该函数
        result:     (addr, ip)
        error:      error
        """
        if error:
            self._log_error(error)
            self.destroy()
            return
        if result:
            ip = result[1]
            if ip:

                try:
                    self._stage = STAGE_CONNECTING
                    remote_addr = ip
                    # 若为sslocal,则remote_socket连接的端口为初始化文件中的服务器端口
                    # 若为ssserver,则remote_socket连接的端口为解析出的remote_address的地址
                    if self._is_local:
                        remote_port = self._chosen_server[1]
                    else:
                        remote_port = self._remote_address[1]

                    if self._is_local and self._config['fast_open']:
                        # for fastopen:
                        # wait for more data to arrive and send them in one SYN
                        self._stage = STAGE_CONNECTING
                        # we don't have to wait for remote since it's not
                        # created
                        self._update_stream(STREAM_UP, WAIT_STATUS_READING)
                        # TODO when there is already data in this packet
                    else:
                        # else do connect
                        remote_sock = self._create_remote_socket(remote_addr,
                                                                 remote_port)
                        try:
                            remote_sock.connect((remote_addr, remote_port))
                        except (OSError, IOError) as e:
                            if eventloop.errno_from_exception(e) == \
                                    errno.EINPROGRESS:
                                pass
                        self._loop.add(remote_sock,
                                       eventloop.POLL_ERR | eventloop.POLL_OUT,
                                       self._server)
                        self._stage = STAGE_CONNECTING
                        self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
                        self._update_stream(STREAM_DOWN, WAIT_STATUS_READING)
                    return
                except Exception as e:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
        self.destroy()
开发者ID:ncs19960831,项目名称:shadowsocks-analysis,代码行数:54,代码来源:tcprelay.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python eventloop.get_sock_error函数代码示例发布时间:2022-05-27
下一篇:
Python encrypt.encrypt_all函数代码示例发布时间: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