Exemplo n.º 1
0
	def run(self):
		try:
			while 1:
				rc,b,c,ol = win32file.GetQueuedCompletionStatus( self.hiocp, 1000 )
				if ol:
					#print rc,b,c,ol
					otype = len(ol.object)
					if otype == 2 :
						[userdata, fd] = ol.object
						if self.onresult : self.onresult( fd, rc, userdata, self.fds[fd][3], b )
					elif otype == 1:
						#print rc, b,c,ol
						assert rc == 0
						sock = ol.object[0]
						self.addsocket( self.infds[sock].insock )
						if self.onaccept : self.onaccept( sock,self.infds[sock].insock , 0, self.infds[sock].data )
	
						self.infds[sock].insock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
						win32file.AcceptEx( sock, self.infds[sock].insock, self.infds[sock].buffer,  self.infds[sock].ol )
					
					elif otype == 3:
						ol.object[1](*ol.object[2])
					elif otype == 4 :
						fd = ol.object[1]
						if self.ondata : self.ondata( fd, ol.object[2][:b], ol.object[0], self.fds[fd][3] )
						if b == 0:
							win32file.CloseHandle( fd.fileno() )
							del self.fds[fd]

		except KeyboardInterrupt, r:
			self.stop = 1
Exemplo n.º 2
0
 def read_events(self, timeout=None):
     timeout_ms = 0x7FFFFFFF
     if timeout is not None:
         timeout_ms = int(timeout * 1000)
         if timeout_ms < 0 or timeout_ms >= 0x7FFFFFFF:
             raise ValueError("Timeout value out of range")
     try:
         events = []
         rc, num, key, _ = win32file.GetQueuedCompletionStatus(
             self.__cphandle, timeout_ms)
         if rc == 0:
             with self.__lock:
                 watch = self.__key_to_watch.get(key)
                 if watch is not None and watch.enabled and not watch._removed:
                     events.extend(process_events(watch, num))
         elif rc == 5:
             with self.__lock:
                 watch = self.__key_to_watch.get(key)
                 if watch is not None and watch.enabled:
                     close_watch(watch)
                     del self.__key_to_watch[key]
                     events.append(FSEvent(watch, FSEvent.DeleteSelf))
         return events
     except pywintypes.error as e:
         raise FSMonitorWindowsError(*e.args)
 def testCompletionPortsQueued(self):
     class Foo: pass
     io_req_port = win32file.CreateIoCompletionPort(-1, None, 0, 0)
     overlapped = pywintypes.OVERLAPPED()
     overlapped.object = Foo()
     win32file.PostQueuedCompletionStatus(io_req_port, 0, 99, overlapped)
     errCode, bytes, key, overlapped = \
             win32file.GetQueuedCompletionStatus(io_req_port, win32event.INFINITE)
     self.failUnlessEqual(errCode, 0)
     self.failUnless(isinstance(overlapped.object, Foo))
Exemplo n.º 4
0
    def _IOCPServerThread(self, handle, port, drop_overlapped_reference):
        overlapped = pywintypes.OVERLAPPED()
        win32pipe.ConnectNamedPipe(handle, overlapped)
        if drop_overlapped_reference:
            # Be naughty - the overlapped object is now dead, but
            # GetQueuedCompletionStatus will still find it.  Our check of
            # reference counting should catch that error.
            overlapped = None
            # even if we fail, be sure to close the handle; prevents hangs
            # on Vista 64...
            try:
                with pytest.raises(RuntimeError):
                    win32file.GetQueuedCompletionStatus(port, -1)
            finally:
                handle.Close()
            return

        result = win32file.GetQueuedCompletionStatus(port, -1)
        ol2 = result[-1]
        assert ol2 is overlapped
        data = win32file.ReadFile(handle, 512)[1]
        win32file.WriteFile(handle, data)
    def _IOCPServerThread(self, handle, port, drop_overlapped_reference):
        overlapped = pywintypes.OVERLAPPED()
        win32pipe.ConnectNamedPipe(handle, overlapped)
        if drop_overlapped_reference:
            # Be naughty - the overlapped object is now dead, but
            # GetQueuedCompletionStatus will still find it.  Our check of
            # reference counting should catch that error.
            overlapped = None
            self.failUnlessRaises(RuntimeError,
                                  win32file.GetQueuedCompletionStatus, port, -1)
            handle.Close()
            return

        result = win32file.GetQueuedCompletionStatus(port, -1)
        ol2 = result[-1]
        self.failUnless(ol2 is overlapped)
        data = win32file.ReadFile(handle, 512)[1]
        win32file.WriteFile(handle, data)
Exemplo n.º 6
0
 def wait_event(self, timeout):
     """returns (size, overlapped) on success, None on timeout"""
     rc, size, _, overlapped = win32file.GetQueuedCompletionStatus(
         self._port, int(timeout * 1000))
     if rc == win32con.WAIT_TIMEOUT:
         return None
     elif rc == 0:
         if overlapped is self._post_overlapped:
             # ignore the overlapped -- it's was enqueued by post()
             return None
         else:
             return size, overlapped, None
     elif rc in IGNORED_ERRORS:
         return size, overlapped, None
     else:
         ex = ctypes.WinError(rc)
         if not overlapped:
             raise ex
         else:
             return size, overlapped, ex
Exemplo n.º 7
0
 def read_events(self):
     try:
         events = []
         rc, num, key, _ = win32file.GetQueuedCompletionStatus(
             self.__cphandle, 1000)
         if rc == 0:
             with self.__lock:
                 watch = self.__key_to_watch.get(key)
                 if watch is not None and watch.enabled and not watch._removed:
                     for evt in process_events(watch, num):
                         events.append(evt)
         elif rc == 5:
             with self.__lock:
                 watch = self.__key_to_watch.get(key)
                 if watch is not None and watch.enabled:
                     close_watch(watch)
                     del self.__key_to_watch[key]
                     events.append(FSEvent(watch, FSEvent.DeleteSelf))
         return events
     except pywintypes.error, e:
         raise FSMonitorWindowsError(*e.args)
Exemplo n.º 8
0
    completion_port = win32file.CreateIoCompletionPort(
        win32file.INVALID_HANDLE_VALUE, None, 0, 0)
    print win32file.CreateIoCompletionPort(handle, completion_port, 111, 0)
    print win32file.CreateIoCompletionPort(sock.fileno(), completion_port, 222,
                                           0)

    tun_recv = TunnelRecv()
    net_recv = NetworkRecv()

    timer = TimerThread(1)  # per second
    timer.start()

    while running:
        timeout = last_send + keepalive_interval - now
        rc, numberOfBytesTransferred, completionKey, overlapped = win32file.GetQueuedCompletionStatus(
            completion_port, int(1000 * timeout))
        if rc:
            if rc == win32event.WAIT_TIMEOUT:
                pass
            else:
                print "error %d" % rc
                break
        else:
            if overlapped and overlapped.object:
                overlapped.object.send(numberOfBytesTransferred)
            else:
                # timer
                now = time.time()

        if last_send + keepalive_interval <= now:
            keepalive()
Exemplo n.º 9
0
 def wait(self, timeout):
     res = win32file.GetQueuedCompletionStatus(self._port,
                                               int(timeout * 1000))
     return res
Exemplo n.º 10
0
def pipe_server():
    pipe = win32pipe.CreateNamedPipe(
        r'\\.\pipe\my_pipe',
        win32pipe.PIPE_ACCESS_INBOUND | win32file.FILE_FLAG_OVERLAPPED,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE
        | win32pipe.PIPE_WAIT, 1, 65536, 65536, 0, None)
    quit = False
    overlapped_obj1 = pywintypes.OVERLAPPED()

    completion_port = win32file.CreateIoCompletionPort(pipe, None, 0, 0)

    while not quit:
        try:
            win32pipe.ConnectNamedPipe(pipe, overlapped_obj1)

            while True:  # Doing some sleep (2 seconds): Actually, other things could be done in this time
                for i in range(10):
                    time.sleep(0.2)

                # If the function succeeds, rc will be set to 0, otherwise it will be set to the win32 error code (258).
                (rc, byte_num, key,
                 ovrlpd) = win32file.GetQueuedCompletionStatus(
                     completion_port, 50)  #1000)

                if rc == 0:  # The message can be retrieved
                    msg = ''  # Will contain the whole message at the end
                    """
                    in order to read the characters we need to distinguish two cases:
                        -the character is a normal (unicode) character, which takes 1 byte
                        -the character is non_unicode (German, Russian...), which takes 2 bytes
                    as we are reading 1 byte at a time, the above-mentioned discussion is essential.
                    When a 1 byte character is coming, its decoding is done without problems.
                    Let's see what happens, when a 2-byte character is coming. In this case, we read
                    1 byte, try to decode, get an error. Now we know that the character takes 2-bytes.
                    Then, we read 1 byte again, combine them and decode.
                    """
                    # 1-byte character case
                    try:
                        rtnvalue, data = win32file.ReadFile(
                            pipe, 1, overlapped_obj1)
                        msg = msg + bytes(data).decode("utf-8")
                    # 2-bytes character case
                    except:
                        rtnvalue, data1 = win32file.ReadFile(
                            pipe, 1, overlapped_obj1)
                        non_unicode = data.tobytes() + data1.tobytes()
                        msg = msg + non_unicode.decode("utf-8")

                    while rtnvalue == 234:  # more data is available

                        try:  # 1-byte character case
                            rtnvalue, data = win32file.ReadFile(
                                pipe, 1, overlapped_obj1)
                            msg = msg + bytes(data).decode("utf-8")

                        except:  # 2-bytes character case
                            rtnvalue, data1 = win32file.ReadFile(
                                pipe, 1, overlapped_obj1)
                            non_unicode = data.tobytes() + data1.tobytes()
                            msg = msg + non_unicode.decode("utf-8")

                    # the next line helps with writing Russian and Armenian characters into a text file
                    with codecs.open('test.txt', 'w', encoding='utf-8') as f:
                        f.write(msg)
                    f.close()
                    print("Successfully received and written")
                    print("Closing Handle")
                    exit(0)

        except pywintypes.error as e:
            if e.args[0] == 109:
                print("broken pipe")
                quit = True
            else:
                print(e)
                quit = True
    win32file.CloseHandle(pipe)
Exemplo n.º 11
0
 def wait(self, timeout):
     rc, size, key, overlapped = win32file.GetQueuedCompletionStatus(self._port, int(timeout * 1000))
     if rc == 0:
         pass
     else:
         pass
Exemplo n.º 12
0
 def wait_good(self):
     # keep a reference to the overlapped object
     self.result = win32file.GetQueuedCompletionStatus(self.port, -1)[3]
Exemplo n.º 13
0
 def wait_buggy(self):
     win32file.GetQueuedCompletionStatus(self.port, -1)