Python select.error() Examples

The following are 30 code examples of select.error(). 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 select , or try the search function .
Example #1
Source File: subprocess.py    From jawfish with MIT License 7 votes vote down vote up
def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
                _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD):
            """Check if child process has terminated.  Returns returncode
            attribute.

            This method is called by __del__, so it cannot reference anything
            outside of the local scope (nor can any methods it calls).

            """
            if self.returncode is None:
                try:
                    pid, sts = _waitpid(self.pid, _WNOHANG)
                    if pid == self.pid:
                        self._handle_exitstatus(sts)
                except _os_error as e:
                    if _deadstate is not None:
                        self.returncode = _deadstate
                    elif e.errno == _ECHILD:
                        # This happens if SIGCLD is set to be ignored or
                        # waiting for child processes has otherwise been
                        # disabled for our process.  This child is dead, we
                        # can't get the status.
                        # http://bugs.python.org/issue15756
                        self.returncode = 0
            return self.returncode 
Example #2
Source File: asyncore.py    From meddle with MIT License 6 votes vote down vote up
def set_reuse_addr(self):
        # try to re-use a server port if possible
        try:
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_REUSEADDR,
                self.socket.getsockopt(socket.SOL_SOCKET,
                                       socket.SO_REUSEADDR) | 1
                )
        except socket.error:
            pass

    # ==================================================
    # predicates for select()
    # these are used as filters for the lists of sockets
    # to pass to select().
    # ================================================== 
Example #3
Source File: wait.py    From gist-alfred with MIT License 6 votes vote down vote up
def _retry_on_intr(fn, timeout):
        if timeout is None:
            deadline = float("inf")
        else:
            deadline = monotonic() + timeout

        while True:
            try:
                return fn(timeout)
            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7
            except (OSError, select.error) as e:
                # 'e.args[0]' incantation works for both OSError and select.error
                if e.args[0] != errno.EINTR:
                    raise
                else:
                    timeout = deadline - monotonic()
                    if timeout < 0:
                        timeout = 0
                    if timeout == float("inf"):
                        timeout = None
                    continue 
Example #4
Source File: _socket_proxy.py    From oscrypto with MIT License 6 votes vote down vote up
def proxy(src, dst, callback=None):
    timeout = 10
    try:
        read_ready, _, _ = select.select([src], [], [], timeout)
        while len(read_ready):
            if callback:
                callback(src, dst)
            else:
                dst.send(src.recv(8192))
            read_ready, _, _ = select.select([src], [], [], timeout)
    except (socket.error, select.error, OSError, ValueError):
        pass
    try:
        src.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    src.close()
    try:
        dst.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    dst.close() 
Example #5
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example #6
Source File: UDP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example #7
Source File: UDP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example #8
Source File: websocketproxy.py    From zun with Apache License 2.0 6 votes vote down vote up
def _send_buffer(self, buff, target, send_all=False):
        size = len(buff)
        tosend = size
        already_sent = 0

        while tosend > 0:
            try:
                # i should be able to send a bytearray
                sent = target.send(buff[already_sent:])
                if sent == 0:
                    raise RuntimeError('socket connection broken')

                already_sent += sent
                tosend -= sent

            except socket.error as e:
                # if full buffers then wait for them to drain and try again
                if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]:
                    if send_all:
                        continue
                    return buff[already_sent:]
                else:
                    raise exception.SocketException(str(e))
        return None 
Example #9
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def send(self, channel_type, message, additional_data):
		if channel_type == common.CONTROL_CHANNEL_BYTE:
			transformed_message = self.transform(self.encryption, common.CONTROL_CHANNEL_BYTE+message, 1)
		else:
			transformed_message = self.transform(self.encryption, common.DATA_CHANNEL_BYTE+message, 1)

		common.internal_print("{0} sent: {1}".format(self.module_short, len(transformed_message)), 0, self.verbosity, common.DEBUG)

		# WORKAROUND?!
		# Windows: It looks like when the buffer fills up the OS does not do
		# congestion control, instead throws and exception/returns with
		# WSAEWOULDBLOCK which means that we need to try it again later.
		# So we sleep 100ms and hope that the buffer has more space for us.
		# If it does then it sends the data, otherwise tries it in an infinite
		# loop...
		while True:
			try:
				return self.comms_socket.send(struct.pack(">H", len(transformed_message))+transformed_message)
			except socket.error as se:
				if se.args[0] == 10035: # WSAEWOULDBLOCK
					time.sleep(0.1)
					pass
				else:
					raise 
Example #10
Source File: wait.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _retry_on_intr(fn, timeout):
        if timeout is None:
            deadline = float("inf")
        else:
            deadline = monotonic() + timeout

        while True:
            try:
                return fn(timeout)
            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7
            except (OSError, select.error) as e:
                # 'e.args[0]' incantation works for both OSError and select.error
                if e.args[0] != errno.EINTR:
                    raise
                else:
                    timeout = deadline - monotonic()
                    if timeout < 0:
                        timeout = 0
                    if timeout == float("inf"):
                        timeout = None
                    continue 
Example #11
Source File: wait.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _retry_on_intr(fn, timeout):
        if timeout is None:
            deadline = float("inf")
        else:
            deadline = monotonic() + timeout

        while True:
            try:
                return fn(timeout)
            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7
            except (OSError, select.error) as e:
                # 'e.args[0]' incantation works for both OSError and select.error
                if e.args[0] != errno.EINTR:
                    raise
                else:
                    timeout = deadline - monotonic()
                    if timeout < 0:
                        timeout = 0
                    if timeout == float("inf"):
                        timeout = None
                    continue 
Example #12
Source File: websocket.py    From cproto with MIT License 6 votes vote down vote up
def _read_messages(self):
        while self.connected:
            try:
                r, w, e = select.select([self.sock], [], [])
            except select.error:
                break

            if r and self.connected:
                with self.cLock:
                    data = self.recv()
                    message = json.loads(data)

                    # If id is present -> notifies main thread to return this message as a reply
                    # Otherwise puts message into events queue so it will be dispatched as event
                    if 'id' in message:
                        self.replies[message['id']] = message
                        self.cLock.notify()
                    else:
                        self.events.put(message) 
Example #13
Source File: ssl_wrap_util.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def unregister(self, fileobj):
        """Unregisters a file object from being monitored."""
        try:
            key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
        except KeyError:
            raise KeyError("{!r} is not registered".format(fileobj))

        # Getting the fileno of a closed socket on Windows errors with EBADF.
        except socket.error as e:  # Platform-specific: Windows.
            if e.errno != errno.EBADF:
                raise
            else:
                for key in self._fd_to_key.values():
                    if key.fileobj is fileobj:
                        self._fd_to_key.pop(key.fd)
                        break
                else:
                    raise KeyError("{!r} is not registered".format(fileobj))
        return key 
Example #14
Source File: selectors.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
def unregister(self, fileobj):
        """ Unregister a file object from being monitored. """
        try:
            key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))

        # Getting the fileno of a closed socket on Windows errors with EBADF.
        except socket.error as e:  # Platform-specific: Windows.
            if e.errno != errno.EBADF:
                raise
            else:
                for key in self._fd_to_key.values():
                    if key.fileobj is fileobj:
                        self._fd_to_key.pop(key.fd)
                        break
                else:
                    raise KeyError("{0!r} is not registered".format(fileobj))
        return key 
Example #15
Source File: _compat.py    From jbox with MIT License 6 votes vote down vote up
def wrap_error(func, *args, **kw):
        """
        Wrap socket.error, IOError, OSError, select.error to raise new specialized
        exceptions of Python 3.3 like InterruptedError (PEP 3151).
        """
        try:
            return func(*args, **kw)
        except (socket.error, IOError, OSError) as exc:
            if hasattr(exc, 'winerror'):
                _wrap_error(exc, _MAP_ERRNO, exc.winerror)
                # _MAP_ERRNO does not contain all Windows errors.
                # For some errors like "file not found", exc.errno should
                # be used (ex: ENOENT).
            _wrap_error(exc, _MAP_ERRNO, exc.errno)
            raise
        except select.error as exc:
            if exc.args:
                _wrap_error(exc, _MAP_ERRNO, exc.args[0])
            raise 
Example #16
Source File: subprocess.py    From meddle with MIT License 6 votes vote down vote up
def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
                _WNOHANG=os.WNOHANG, _os_error=os.error):
            """Check if child process has terminated.  Returns returncode
            attribute.

            This method is called by __del__, so it cannot reference anything
            outside of the local scope (nor can any methods it calls).

            """
            if self.returncode is None:
                try:
                    pid, sts = _waitpid(self.pid, _WNOHANG)
                    if pid == self.pid:
                        self._handle_exitstatus(sts)
                except _os_error:
                    if _deadstate is not None:
                        self.returncode = _deadstate
            return self.returncode 
Example #17
Source File: nmb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def non_polling_read(self, read_length, timeout):
        data = ''
        bytes_left = read_length

        while bytes_left > 0:
            try:
                ready, _, _ = select.select([self._sock.fileno()], [], [], timeout)

                if not ready:
                    raise NetBIOSTimeout

                received = self._sock.recv(bytes_left)
                if len(received) == 0:
                    raise NetBIOSError, ('Error while reading from remote', ERRCLASS_OS, None)

                data = data + received
                bytes_left = read_length - len(data)
            except select.error, ex:
                if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN:
                    raise NetBIOSError, ('Error occurs while reading from remote', ERRCLASS_OS, ex[0]) 
Example #18
Source File: nmb.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def _setup_connection(self, dstaddr, timeout=None):
        port = randint(10000, 60000)
        af, socktype, proto, _canonname, _sa = socket.getaddrinfo(dstaddr, port, socket.AF_INET, socket.SOCK_DGRAM)[0]
        s = socket.socket(af, socktype, proto)
        has_bind = 1
        for _i in range(0, 10):
            # We try to bind to a port for 10 tries
            try:
                s.bind((INADDR_ANY, randint(10000, 60000)))
                s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
                has_bind = 1
            except socket.error:
                pass
        if not has_bind:
            raise NetBIOSError, ('Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN)
        self.__sock = s 
Example #19
Source File: Hypervisor.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
def fsfreeze(self, vm, port=QEMU_GUEST_AGENT_PORT, timeout=0):
        s_ctl = self._get_agent_ctl_safe(vm, port, timeout)
        s_ctl.stdin.write('{"execute":"guest-fsfreeze-freeze"}')
        data = os.read(s_ctl.stdout.fileno(), QMP_READ_SIZE)
        try:
            ret = json.loads(data)
        except:
            raise AgentError("Failed to parse agent output")

        if "error" in ret:
            raise AgentError("Error while freezing VM: " + ret["error"]["desc"])

        ret = json.loads(data)["return"]
        if  ret <= 0:
            raise AgentError("No filesystem frozen")

        s_ctl.terminate() 
Example #20
Source File: Hypervisor.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
def _read_a_command(self):
        """
        Read data from the VM until a complete command is read
        """
        while not '\n' in self.databuff:
            rdr, _, _ = select.select([self.sp_r, self.sock], [], [])
            if self.sp_r in rdr:
                # The host agent is shutting down
                # so we interrupt our read
                return None
            elif rdr:
                try:
                    tdata = self.sock.recv(32768)
                except socket.error:
                    tdata = None

                if not tdata:
                    return None
                else:
                    self.databuff = self.databuff + tdata

        sret = self.databuff.split("\n")
        self.databuff = "\n".join(sret[1:])
        ret = sret[0]
        return ret 
Example #21
Source File: screen.py    From asciimatics with Apache License 2.0 6 votes vote down vote up
def _print_at(self, text, x, y, width):
            """
            Print string at the required location.

            :param text: The text string to print.
            :param x: The x coordinate
            :param y: The Y coordinate
            :param width: The width of the character (for dual-width glyphs in CJK languages).
            """
            # We can throw temporary errors on resizing, so catch and ignore
            # them on the assumption that we'll resize shortly.
            try:
                # Move the cursor if necessary
                if x != self._cur_x or y != self._cur_y:
                    self._stdout.SetConsoleCursorPosition(
                        win32console.PyCOORDType(x, y))

                # Print the text at the required location and update the current
                # position.
                self._stdout.WriteConsole(text)
                self._cur_x = x + width
                self._cur_y = y
            except pywintypes.error:
                pass 
Example #22
Source File: arbiter.py    From jbox with MIT License 6 votes vote down vote up
def sleep(self):
        """\
        Sleep until PIPE is readable or we timeout.
        A readable PIPE means a signal occurred.
        """
        try:
            ready = select.select([self.PIPE[0]], [], [], 1.0)
            if not ready[0]:
                return
            while os.read(self.PIPE[0], 1):
                pass
        except select.error as e:
            if e.args[0] not in [errno.EAGAIN, errno.EINTR]:
                raise
        except OSError as e:
            if e.errno not in [errno.EAGAIN, errno.EINTR]:
                raise
        except KeyboardInterrupt:
            sys.exit() 
Example #23
Source File: sync.py    From jbox with MIT License 6 votes vote down vote up
def wait(self, timeout):
        try:
            self.notify()
            ret = select.select(self.wait_fds, [], [], timeout)
            if ret[0]:
                if self.PIPE[0] in ret[0]:
                    os.read(self.PIPE[0], 1)
                return ret[0]

        except select.error as e:
            if e.args[0] == errno.EINTR:
                return self.sockets
            if e.args[0] == errno.EBADF:
                if self.nr < 0:
                    return self.sockets
                else:
                    raise StopWaiting
            raise 
Example #24
Source File: selectors.py    From ServerlessCrawler-VancouverRealState with MIT License 6 votes vote down vote up
def unregister(self, fileobj):
        """ Unregister a file object from being monitored. """
        try:
            key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))

        # Getting the fileno of a closed socket on Windows errors with EBADF.
        except socket.error as e:  # Platform-specific: Windows.
            if e.errno != errno.EBADF:
                raise
            else:
                for key in self._fd_to_key.values():
                    if key.fileobj is fileobj:
                        self._fd_to_key.pop(key.fd)
                        break
                else:
                    raise KeyError("{0!r} is not registered".format(fileobj))
        return key 
Example #25
Source File: selectors.py    From core with MIT License 6 votes vote down vote up
def unregister(self, fileobj):
        """ Unregister a file object from being monitored. """
        try:
            key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))

        # Getting the fileno of a closed socket on Windows errors with EBADF.
        except socket.error as e:  # Platform-specific: Windows.
            if e.errno != errno.EBADF:
                raise
            else:
                for key in self._fd_to_key.values():
                    if key.fileobj is fileobj:
                        self._fd_to_key.pop(key.fd)
                        break
                else:
                    raise KeyError("{0!r} is not registered".format(fileobj))
        return key 
Example #26
Source File: ICMP.py    From XFLTReaT with MIT License 5 votes vote down vote up
def send(self, channel_type, message, additional_data):
		addr = additional_data[0]
		identifier = additional_data[1]
		sequence = additional_data[2]
		queue_length = additional_data[3]

		if queue_length < 256:
			ql = chr(queue_length)
		else:
			ql = chr(255)

		if channel_type == common.CONTROL_CHANNEL_BYTE:
			transformed_message = self.transform(self.get_client_encryption(additional_data), ql+common.CONTROL_CHANNEL_BYTE+message, 1)
		else:
			transformed_message = self.transform(self.get_client_encryption(additional_data), ql+common.DATA_CHANNEL_BYTE+message, 1)

		common.internal_print("ICMP sent: {0} seq: {1} id: {2}".format(len(transformed_message), sequence, identifier), 0, self.verbosity, common.DEBUG)

		packet = self.icmp.create_packet(self.ICMP_send, identifier, sequence,
			self.ICMP_prefix+struct.pack(">H", len(transformed_message))+transformed_message)

		# WORKAROUND?!
		# Windows: It looks like when the buffer fills up the OS does not do
		# congestion control, instead throws and exception/returns with
		# WSAEWOULDBLOCK which means that we need to try it again later.
		# So we sleep 100ms and hope that the buffer has more space for us.
		# If it does then it sends the data, otherwise tries it in an infinite
		# loop...
		while True:
			try:
				return self.comms_socket.sendto(packet, addr)
			except socket.error as se:
				if se.args[0] == 10035: # WSAEWOULDBLOCK
					time.sleep(0.1)
					pass
				else:
					raise 
Example #27
Source File: Hypervisor.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, error):
        super(AgentError, self).__init__('Guest agent failure: '
                                              + error) 
Example #28
Source File: asyncore.py    From meddle with MIT License 5 votes vote down vote up
def poll2(timeout=0.0, map=None):
    # Use the poll() support added to the select module in Python 2.0
    if map is None:
        map = socket_map
    if timeout is not None:
        # timeout is in milliseconds
        timeout = int(timeout*1000)
    pollster = select.poll()
    if map:
        for fd, obj in map.items():
            flags = 0
            if obj.readable():
                flags |= select.POLLIN | select.POLLPRI
            if obj.writable():
                flags |= select.POLLOUT
            if flags:
                # Only check for exceptions if object was either readable
                # or writable.
                flags |= select.POLLERR | select.POLLHUP | select.POLLNVAL
                pollster.register(fd, flags)
        try:
            r = pollster.poll(timeout)
        except select.error, err:
            if err.args[0] != EINTR:
                raise
            r = []
        for fd, flags in r:
            obj = map.get(fd)
            if obj is None:
                continue
            readwrite(obj, flags) 
Example #29
Source File: Hypervisor.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def _handle_monitor(self, monitor_data):
        """
        Run the callback for a given Qemu Monitor answer or async notification
        """
        logging.debug("Qemu monitor: received %s",
                      str(monitor_data))

        try:
            json_msg = json.loads(monitor_data)
        except Exception as e:
            # TODO: We should implement a better recovery strategy
            # from leftover garbage in the serial port
            logging.error("Host agent: cannot decode data from Qemu monitor: %s",
                          str(e))
            return

        if 'event' in json_msg:
            kept_cbs = []
            for cb in self.async_cb:
                keep = cb(json_msg)
                if keep:
                    kept_cbs.append(cb)
            self.async_cb = kept_cbs
        else:
            try:
                cb = self.sync_cb.get(False)
            except Queue.Empty:
                logging.error("Qemu monitor sent unexpected reply: %s", json_msg)
                return
            cb(json_msg) 
Example #30
Source File: Hypervisor.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def validate_reply(self, data):
        if data is None:
            raise PcoccError('Qemu monitor disconnected')

        if 'error' in data:
            if 'desc' in data['error']:
                raise PcoccError('Qemu monitor command failed: {}'.format(
                                 str(data['error']['desc'])))
            else:
                raise PcoccError('Qemu monitor command failed')

        return data