Python errno.ETIMEDOUT Examples

The following are 30 code examples of errno.ETIMEDOUT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module errno , or try the search function .
Example #1
Source File: test_clf_rcs956.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def test_listen_dep_not_atr_and_then_ioerror(self, device):
        atr_req = 'D4FF 30313233343536373839 00000000'
        atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
        device.chipset.transport.read.side_effect = [
            ACK(), RSP('19'),                           # ResetMode
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('33'),                           # RFConfiguration
            ACK(), RSP('13'),                           # SetParameters
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('8D 05 11' + atr_req),           # TgInitAsTarget
            ACK(), IOError(errno.ETIMEDOUT, ""),        # TgInitAsTarget
            ACK(), IOError(errno.EIO, ""),              # TgInitAsTarget
        ]
        target = nfc.clf.LocalTarget()
        target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
        target.sens_res = HEX("0101")
        target.sel_res = HEX("40")
        target.sdd_res = HEX("08010203")
        target.atr_res = HEX(atr_res)
        with pytest.raises(IOError):
            device.listen_dep(target, 1.0)
        assert device.chipset.transport.read.call_count == 16 
Example #2
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def init_database(self):
        """
        Initializes the database connection to MongoDB.
        Also pre-caches potentially heavy resources from the DB.
        :return:
        """
        self.log.info('Connecting to Database...')
        self.db = Database(self, self.cfg.db)
        try:
            await self.db[self.db.db_nam].collection.find_one({})
            if self.cfg.cache.type not in ['redis', 'mixed']:
                await self.db.precache_settings()
                await self.db.precache_profiles()
                await self.db.precache_resources()
            set_color_cache_coll(self.db[self.db.db_nam].ColorCache)
        except ServerSelectionTimeoutError:
            self.log.error('A Connection To The Database Host Failed!')
            exit(errno.ETIMEDOUT)
        except OperationFailure:
            self.log.error('Database Access Operation Failed!')
            exit(errno.EACCES)
        self.log.info('Successfully Connected to Database') 
Example #3
Source File: test_ssl.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_connect_ex_error(self):
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT)
            try:
                rc = s.connect_ex((REMOTE_HOST, 444))
                # Issue #19919: Windows machines or VMs hosted on Windows
                # machines sometimes return EWOULDBLOCK.
                errors = (
                    errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
                    errno.EWOULDBLOCK,
                )
                self.assertIn(rc, errors)
            finally:
                s.close() 
Example #4
Source File: semlock.py    From loky with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def acquire(self, block=True, timeout=None):
        if self.kind == RECURSIVE_MUTEX and self._is_mine():
            self.count += 1
            return True

        if block and timeout is None:
            res = pthread.sem_wait(self.handle)
        elif not block or timeout <= 0:
            res = pthread.sem_trywait(self.handle)
        else:
            res = _sem_timedwait(self.handle, timeout)
        if res < 0:
            e = ctypes.get_errno()
            if e == errno.EINTR:
                return None
            elif e in [errno.EAGAIN, errno.ETIMEDOUT]:
                return False
            raiseFromErrno()
        self.count += 1
        self.ident = get_ident()
        return True 
Example #5
Source File: udprelay.py    From ssr-ml with Apache License 2.0 6 votes vote down vote up
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
        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 data:
            return
        self._server.server_transfer_ul += len(data)
        #TODO ============================================================
        if self._stage == STAGE_STREAM:
            self._write_to_sock(data, self._remote_sock)
            return 
Example #6
Source File: test_ssl.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_connect_ex_error(self):
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT)
            try:
                rc = s.connect_ex((REMOTE_HOST, 444))
                # Issue #19919: Windows machines or VMs hosted on Windows
                # machines sometimes return EWOULDBLOCK.
                errors = (
                    errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
                    errno.EWOULDBLOCK,
                )
                self.assertIn(rc, errors)
            finally:
                s.close() 
Example #7
Source File: transport.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def read(self, timeout=0):
        if self.usb_inp is not None:
            try:
                ep_addr = self.usb_inp.getAddress()
                frame = self.usb_dev.bulkRead(ep_addr, 300, timeout)
            except libusb.USBErrorTimeout:
                raise IOError(errno.ETIMEDOUT, os.strerror(errno.ETIMEDOUT))
            except libusb.USBErrorNoDevice:
                raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
            except libusb.USBError as error:
                log.error("%r", error)
                raise IOError(errno.EIO, os.strerror(errno.EIO))

            if len(frame) == 0:
                log.error("bulk read returned zero data")
                raise IOError(errno.EIO, os.strerror(errno.EIO))

            frame = bytearray(frame)
            log.log(logging.DEBUG-1, "<<< %s", hexlify(frame).decode())
            return frame 
Example #8
Source File: pn53x.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def send_rsp_recv_cmd(self, target, data, timeout):
        # print("\n".join(self._print_ciu_register_page(0, 1)))
        if target.tt3_cmd:
            return self._tt3_send_rsp_recv_cmd(target, data, timeout)
        try:
            if data:
                self.chipset.tg_response_to_initiator(data)
            return self.chipset.tg_get_initiator_command(timeout)
        except Chipset.Error as error:
            if error.errno in (0x0A, 0x29, 0x31):
                self.log.debug("Error: %s", error)
                raise nfc.clf.BrokenLinkError(str(error))
            else:
                self.log.warning(error)
                raise nfc.clf.TransmissionError(str(error))
        except IOError as error:
            if error.errno == errno.ETIMEDOUT:
                info = "no data received within %.3f s" % timeout
                self.log.debug(info)
                raise nfc.clf.TimeoutError(info)
            else:
                # host-controller communication broken
                self.log.error(error)
                raise error 
Example #9
Source File: udprelay.py    From shadowsocksr with Apache License 2.0 6 votes vote down vote up
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
        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 data:
            return
        self._server.server_transfer_ul += len(data)
        #TODO ============================================================
        if self._stage == STAGE_STREAM:
            self._write_to_sock(data, self._remote_sock)
            return 
Example #10
Source File: base_clf_pn53x.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def test_listen_tta_as_tt4_rcvd_deselect(self, device):
        device.chipset.transport.read.side_effect = [
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('8D 00 E0 80'),                  # TgInitAsTarget
            ACK(), RSP('91 00'),                        # TgResponseToInitiator
            ACK(), RSP('89 00 C03233'),                 # TgGetInitiatorCommand
            ACK(), RSP('91 00'),                        # TgResponseToInitiator
            ACK(), IOError(errno.ETIMEDOUT, ""),        # TgInitAsTarget
        ]
        target = nfc.clf.LocalTarget('106A')
        target.sens_res = HEX("4400")
        target.sel_res = HEX("20")
        target.sdd_res = HEX("08010203")
        assert device.listen_tta(target, 1.0) is None
        assert device.chipset.transport.read.call_count == 12
        device.chipset.transport.write.assert_any_call(CMD('90 0578807002')) 
Example #11
Source File: base_clf_pn53x.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def test_listen_dep_ioerror_timeout_after_psl(self, device):
        atr_req = 'D400 30313233343536373839 00000000'
        atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
        psl_req = 'D404 00 12 03'
        device.chipset.transport.read.side_effect = [
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('8D 05 11' + atr_req),           # TgInitAsTarget
            ACK(), RSP('91 00'),                        # TgResponseToInitiator
            ACK(), RSP('89 00 06' + psl_req),           # TgGetInitiatorCommand
            ACK(), self.reg_rsp('FD'),                  # ReadRegister
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('91 00'),                        # TgResponseToInitiator
            ACK(), self.reg_rsp('FD'),                  # ReadRegister
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), IOError(errno.ETIMEDOUT, ""),        # TgGetInitiatorCommand
        ]
        target = nfc.clf.LocalTarget()
        target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
        target.sens_res = HEX("0101")
        target.sel_res = HEX("40")
        target.sdd_res = HEX("08010203")
        target.atr_res = HEX(atr_res)
        assert device.listen_dep(target, 1.0) is None
        assert device.chipset.transport.read.call_count == 20 
Example #12
Source File: base_clf_pn53x.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def test_listen_dep_ioerror_timeout_after_atr(self, device):
        atr_req = 'D400 30313233343536373839 00000000'
        atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
        device.chipset.transport.read.side_effect = [
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('8D 05 11' + atr_req),           # TgInitAsTarget
            ACK(), RSP('91 00'),                        # TgResponseToInitiator
            ACK(), IOError(errno.ETIMEDOUT, ""),        # TgGetInitiatorCommand
        ]
        target = nfc.clf.LocalTarget()
        target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
        target.sens_res = HEX("0101")
        target.sel_res = HEX("40")
        target.sdd_res = HEX("08010203")
        target.atr_res = HEX(atr_res)
        assert device.listen_dep(target, 1.0) is None
        assert device.chipset.transport.read.call_count == 8 
Example #13
Source File: base_clf_pn53x.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def test_send_cmd_recv_rsp_transport_error(self, device, err, exc):
        device.chipset.transport.read.side_effect = [
            ACK(), self.reg_rsp('00 00 00'),              # ReadRegister
            ACK(), RSP('09 00'),                          # WriteRegister
            ACK(), RSP('33'),                             # RFConfiguration
            ACK(), IOError(err, "test"),                  # InCommunicateThru
        ]
        target = nfc.clf.RemoteTarget('106A')
        with pytest.raises(exc):
            device.send_cmd_recv_rsp(target, b'123', 1.0)
        assert device.chipset.transport.write.mock_calls == [call(_) for _ in [
            CMD('06 6302 6303 6305'),                     # ReadRegister
            CMD('08 630200 630300 630540'),               # WriteRegister
            CMD('32 020a0b0f'),                           # RFConfiguration
            CMD('42 313233'),                             # InCommunicateThru
        ] + ([ACK()] if err == errno.ETIMEDOUT else [])] 
Example #14
Source File: base_clf_pn53x.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def test_listen_dep_not_atr_and_then_ioerror(self, device):
        atr_req = 'D4FF 30313233343536373839 00000000'
        atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
        device.chipset.transport.read.side_effect = [
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('8D 05 11' + atr_req),           # TgInitAsTarget
            ACK(), IOError(errno.ETIMEDOUT, ""),        # TgInitAsTarget
            ACK(), IOError(errno.EIO, ""),              # TgInitAsTarget
        ]
        target = nfc.clf.LocalTarget()
        target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
        target.sens_res = HEX("0101")
        target.sel_res = HEX("40")
        target.sdd_res = HEX("08010203")
        target.atr_res = HEX(atr_res)
        with pytest.raises(IOError):
            device.listen_dep(target, 1.0)
        assert device.chipset.transport.read.call_count == 8 
Example #15
Source File: test_clf_rcs956.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def test_listen_dep_ioerror_timeout_after_atr(self, device):
        atr_req = 'D400 30313233343536373839 00000000'
        atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
        device.chipset.transport.read.side_effect = [
            ACK(), RSP('19'),                           # ResetMode
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('33'),                           # RFConfiguration
            ACK(), RSP('13'),                           # SetParameters
            ACK(), RSP('09 00'),                        # WriteRegister
            ACK(), RSP('8D 05 11' + atr_req),           # TgInitAsTarget
            ACK(), RSP('93 00'),                        # TgSetGeneralBytes
            ACK(), IOError(errno.ETIMEDOUT, ""),        # TgGetInitiatorCommand
        ]
        target = nfc.clf.LocalTarget()
        target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
        target.sens_res = HEX("0101")
        target.sel_res = HEX("40")
        target.sdd_res = HEX("08010203")
        target.atr_res = HEX(atr_res)
        assert device.listen_dep(target, 1.0) is None
        assert device.chipset.transport.read.call_count == 16 
Example #16
Source File: transport.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
def read(self, timeout):
        if self.tty is not None:
            self.tty.timeout = max(timeout/1E3, 0.05)
            frame = bytearray(self.tty.read(6))
            if frame is None or len(frame) == 0:
                raise IOError(errno.ETIMEDOUT, os.strerror(errno.ETIMEDOUT))
            if frame.startswith(b"\x00\x00\xff\x00\xff\x00"):
                log.log(logging.DEBUG-1, "<<< %s", hexlify(frame).decode())
                return frame
            LEN = frame[3]
            if LEN == 0xFF:
                frame += self.tty.read(3)
                LEN = frame[5] << 8 | frame[6]
            frame += self.tty.read(LEN + 1)
            log.log(logging.DEBUG-1, "<<< %s", hexlify(frame).decode())
            return frame 
Example #17
Source File: tcp.py    From bacpypes with MIT License 5 votes vote down vote up
def handle_write_event(self):
        if _debug: TCPClient._debug("handle_write_event")

        # there might be an error
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if _debug: TCPClient._debug("    - err: %r", err)

        # check for connection refused
        if err == 0:
            if not self.connected:
                if _debug: TCPClient._debug("    - connected")
                self.handle_connect()
        else:
            if _debug: TCPClient._debug("    - peer: %r", self.peer)

            if (err == errno.ECONNREFUSED):
                socket_error = socket.error(err, "connection refused")
            elif (err == errno.ETIMEDOUT):
                socket_error = socket.error(err, "timed out")
            elif (err == errno.EHOSTUNREACH):
                socket_error = socket.error(err, "host unreachable")
            else:
                socket_error = socket.error(err, "other unknown: %r" % (err,))
            if _debug: TCPClient._debug("    - socket_error: %r", socket_error)

            self.handle_error(socket_error)
            return

        # pass along
        asyncore.dispatcher.handle_write_event(self) 
Example #18
Source File: tcprelay.py    From ShadowsocksFork with Apache License 2.0 5 votes vote down vote up
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:
            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) 
Example #19
Source File: tcprelay.py    From ShadowsocksFork with Apache License 2.0 5 votes vote down vote up
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() 
Example #20
Source File: test_error.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_errno(self):
        """
        L{error.getConnectError} converts based on errno for C{socket.error}.
        """
        self.assertErrnoException(errno.ENETUNREACH, error.NoRouteError)
        self.assertErrnoException(errno.ECONNREFUSED, error.ConnectionRefusedError)
        self.assertErrnoException(errno.ETIMEDOUT, error.TCPTimedOutError)
        if platformType == "win32":
            self.assertErrnoException(errno.WSAECONNREFUSED, error.ConnectionRefusedError)
            self.assertErrnoException(errno.WSAENETUNREACH, error.NoRouteError) 
Example #21
Source File: test_error.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_errno(self):
        """
        L{error.getConnectError} converts based on errno for C{socket.error}.
        """
        self.assertErrnoException(errno.ENETUNREACH, error.NoRouteError)
        self.assertErrnoException(errno.ECONNREFUSED, error.ConnectionRefusedError)
        self.assertErrnoException(errno.ETIMEDOUT, error.TCPTimedOutError)
        if platformType == "win32":
            self.assertErrnoException(errno.WSAECONNREFUSED, error.ConnectionRefusedError)
            self.assertErrnoException(errno.WSAENETUNREACH, error.NoRouteError) 
Example #22
Source File: wait_for.py    From intera_sdk with Apache License 2.0 5 votes vote down vote up
def wait_for(test, timeout=1.0, raise_on_error=True, rate=100,
             timeout_msg="timeout expired", body=None):
    """
    Waits until some condition evaluates to true.

    @param test: zero param function to be evaluated
    @param timeout: max amount of time to wait. negative/inf for indefinitely
    @param raise_on_error: raise or just return False
    @param rate: the rate at which to check
    @param timout_msg: message to supply to the timeout exception
    @param body: optional function to execute while waiting
    """
    end_time = rospy.get_time() + timeout
    rate = rospy.Rate(rate)
    notimeout = (timeout < 0.0) or timeout == float("inf")
    while not test():
        if rospy.is_shutdown():
            if raise_on_error:
                raise OSError(errno.ESHUTDOWN, "ROS Shutdown")
            return False
        elif (not notimeout) and (rospy.get_time() >= end_time):
            if raise_on_error:
                raise OSError(errno.ETIMEDOUT, timeout_msg)
            return False
        if callable(body):
            body()
        rate.sleep()
    return True 
Example #23
Source File: ustreamtv.py    From streamlink with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
            while not self.stopped.wait(0):
                try:
                    cmd_args = self.api.recv()
                except (SocketError,
                        websocket._exceptions.WebSocketConnectionClosedException) as err:
                    cmd_args = None
                    if (hasattr(err, "errno") and err.errno in (errno.ECONNRESET, errno.ETIMEDOUT)
                            or "Connection is already closed." in str(err)):
                        while True:
                            # --stream-timeout will handle the timeout
                            try:
                                # reconnect on network issues
                                self.api.reconnect()
                                break
                            except websocket._exceptions.WebSocketAddressException:
                                # no connection available
                                reconnect_time_ws = 5
                                log.error("Local network issue, websocket reconnecting in {0}s".format(reconnect_time_ws))
                                sleep(reconnect_time_ws)
                    else:
                        raise
                except PluginError:
                    continue

                if not cmd_args:
                    continue
                if cmd_args["cmd"] == "warning":
                    log.warning("{code}: {message}", **cmd_args["args"])
                if cmd_args["cmd"] == "moduleInfo":
                    data = self.handle_module_info(cmd_args["args"])
                    if data:
                        self.data_chunks.append(data)
            log.debug("Stopped API polling") 
Example #24
Source File: file_util_test.py    From google-apputils with Apache License 2.0 5 votes vote down vote up
def testNonExistsError(self):
    non_exist_error = OSError(errno.ETIMEDOUT, 'This string not used')
    path = self.dir_tree[0]
    # record, replay
    os.mkdir(path).AndRaise(non_exist_error)
    self.mox.ReplayAll()
    # test, verify
    self.assertRaises(OSError, file_util.MkDirs, os.path.join(*self.dir_tree))
    self.mox.VerifyAll() 
Example #25
Source File: tcprelay.py    From shadowsocks-analysis with Apache License 2.0 5 votes vote down vote up
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))
        # ssserver接收到数据,则对其进行解密
        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:
            # 若未确认服务器,则先返回SOCKS代理的确认信息
            # '\x05' 为版本号 SOCKS5;'\x00' 表示无验证需求(即不用提供用户名以及密码)
            # 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):
            # 已给客户端回复确认信息 或 为ssserver且正处于初始化状态。
            self._handle_stage_addr(data) 
Example #26
Source File: tcprelay.py    From shadowsocks-analysis with Apache License 2.0 5 votes vote down vote up
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:
            # 发送给local_sock
            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() 
Example #27
Source File: test_clf_transport.py    From nfcpy with European Union Public License 1.1 5 votes vote down vote up
def test_read(self, usb):
        usb.usb_dev.bulkRead.side_effect = [
            b'12',
            b'34',
            nfc.clf.transport.libusb.USBErrorTimeout,
            nfc.clf.transport.libusb.USBErrorNoDevice,
            nfc.clf.transport.libusb.USBError,
            b'',
        ]
        assert usb.read() == b'12'
        usb.usb_dev.bulkRead.assert_called_with(0x84, 300, 0)

        assert usb.read(100) == b'34'
        usb.usb_dev.bulkRead.assert_called_with(0x84, 300, 100)

        with pytest.raises(IOError) as excinfo:
            usb.read()
        assert excinfo.value.errno == errno.ETIMEDOUT

        with pytest.raises(IOError) as excinfo:
            usb.read()
        assert excinfo.value.errno == errno.ENODEV

        with pytest.raises(IOError) as excinfo:
            usb.read()
        assert excinfo.value.errno == errno.EIO

        with pytest.raises(IOError) as excinfo:
            usb.read()
        assert excinfo.value.errno == errno.EIO

        usb.usb_inp = None
        assert usb.read() is None 
Example #28
Source File: test_clf_transport.py    From nfcpy with European Union Public License 1.1 5 votes vote down vote up
def test_read(self, serial, tty):
        serial.return_value.read.side_effect = [
            HEX('0000ff00ff00'),
        ]
        assert tty.read(0) == b'\x00\x00\xff\x00\xff\x00'
        assert serial.return_value.read.mock_calls == [call(6)]
        assert tty.tty.timeout == 0.05

        serial.return_value.read.reset_mock()
        serial.return_value.read.side_effect = [
            HEX('0000ff03fbd5'), HEX('01020000'),
        ]
        assert tty.read(51) == b'\x00\x00\xff\x03\xfb\xd5\x01\x02\x00\x00'
        assert serial.return_value.read.mock_calls == [call(6), call(4)]
        assert tty.tty.timeout == 0.051

        serial.return_value.read.reset_mock()
        serial.return_value.read.side_effect = [
            HEX('0000ffffff01'), HEX('01fed5'), bytearray(256) + HEX('2b00'),
        ]
        tty.read(100)
        assert serial.return_value.read.mock_calls == [
            call(6), call(3), call(258),
        ]
        assert tty.tty.timeout == 0.1

        serial.return_value.read.reset_mock()
        serial.return_value.read.side_effect = [HEX('')]
        with pytest.raises(IOError) as excinfo:
            tty.read(1100)
        assert excinfo.value.errno == errno.ETIMEDOUT
        assert serial.return_value.read.mock_calls == [call(6)]
        assert tty.tty.timeout == 1.1

        tty.tty = None
        assert tty.read(1000) is None 
Example #29
Source File: crypt_socket.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def receive(self, request=0, timeoutms=None):
        # receive into network buffer,
        # fill buffer once and decrypt
        # if request>0 wait blocking for request number of bytes (if timeout
        # given interrupt after timeoutms ms)
        # timeout==None: block
        # timeout==0: return immediately after trying to read something from
        #             network buffer
        # timeout>0: try for time specified to read something before returning
        #            this function always returns a pointer to the buffer and
        #            number of bytes read (could be 0)
        data = self.netbuf_in
        data_mv = self.netbuf_in_mv
        readbytes = 0
        start_t = ticks_ms()
        while readbytes < self.netbuf_size:
            try:
                if self.sock_read(data_mv[readbytes:readbytes + 1]):
                    readbytes += 1  # result was not 0 or none
                else:
                    if readbytes >= request:
                        break  # break if not blocking to request size
            except OSError as e:
                if len(e.args) > 0 \
                        and (e.args[0] == errno.EAGAIN
                             or e.args[0] == errno.ETIMEDOUT):
                    if readbytes >= request:
                        break  # break if not blocking to request size
                else:
                    raise
            if timeoutms is not None \
                    and ticks_diff(ticks_ms(), start_t) >= timeoutms:
                break
            sleep_ms(1)  # prevent busy waiting
        if readbytes > 0: self.crypt_in.decrypt(data, length=readbytes)
        return data, readbytes 
Example #30
Source File: tcprelay.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
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()