Exemplo n.º 1
0
    def _win_thread_fn(read_side, write_side, buf_size):
        """This method serves as a server that connects a writer client
    to a reader client.
    
    This methods will run as a thread, and will only be called on Windows platforms.
    """

        import win32pipe, win32file, pywintypes  # type: ignore
        try:
            # Connect to both ends of the pipe before starting the transfer.
            # This funciton is blocking. If no process is connected yet, it will wait
            # indefinitely.
            win32pipe.ConnectNamedPipe(read_side)
            win32pipe.ConnectNamedPipe(write_side)
            while True:
                # Writer -> read_side -> write_side -> Reader
                _, data = win32file.ReadFile(read_side, buf_size)
                win32file.WriteFile(write_side, data)
        except Exception as ex:
            # Remove the pipes from the system.
            win32file.CloseHandle(read_side)
            win32file.CloseHandle(write_side)
            # If the error was due to one of the processes shutting down, just exit normally.
            if isinstance(ex, pywintypes.error) and ex.args[0] in [109, 232]:
                return 0
            # Otherwise, raise that error.
            raise ex
Exemplo n.º 2
0
    def connect(self, timeout=0, buf_sz=0):
        if self.transport == Pipe.Transport.ASYNCHRONOUS:
            if timeout == 0:
                event_timeout = w32ev.INFINITE
            stream = self.__getOverlappedStruct()
            # Asynchronous named pipes return immediately!
            status_code = w32p.ConnectNamedPipe(
                self.__hPipe, stream
            )
            if status_code != werr.ERROR_IO_PENDING:
                raise PipeError(
                    'Failed to create unsynchronous named pipe connection!',
                    'status_code',
                    status_code
                )
            self.__waitForEvent(stream, event_timeout)
        else:
            status_code = w32p.ConnectNamedPipe(self.__hPipe, None)
            if status_code != 0:
                raise PipeError(
                    'Failed to create synchronous named pipe connection!',
                    'status_code',
                    status_code
                )

        return 0
Exemplo n.º 3
0
def start_listen(pipe_name):
    pipe = win32pipe.CreateNamedPipe(
        pipe_name,
        win32pipe.PIPE_ACCESS_DUPLEX,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 65536, 65536, 0, None)

    # Waiting for client
    win32pipe.ConnectNamedPipe(pipe, None)
    win32pipe.SetNamedPipeHandleState(
        pipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)

    while True:
        # Got client
        try:
            # Trying to read the message received in the pipe
            get_command = win32file.ReadFile(pipe, 6)
            decoded_message = str(get_command[1].decode())

            # If the message is *STOP*, we break from the loop
            if decoded_message == "*STOP*":
                break
        except pywintypes.error as e:
            pass

        if pipe is not None:
            win32pipe.DisconnectNamedPipe(pipe)
            win32pipe.ConnectNamedPipe(pipe, None)

    win32file.CloseHandle(pipe)
    return
Exemplo n.º 4
0
 def connect(self):
     try:
         return win32pipe.ConnectNamedPipe(self.pipe, None) == 0
     except WinError as e:
         win32api.CloseHandle(self.pipe)
         self.create_pipe()
         return win32pipe.ConnectNamedPipe(self.pipe, None) == 0
Exemplo n.º 5
0
 def open(self, mode='read', pipe_wait=True):
     wait = win32pipe.PIPE_WAIT
     if pipe_wait:
         wait = win32pipe.PIPE_WAIT
     else:
         wait = win32pipe.PIPE_NOWAIT
     create_file = False
     try:
         self.__fifo = win32pipe.CreateNamedPipe(rf'\\.\pipe\{self.__pipe}', win32pipe.PIPE_ACCESS_DUPLEX,
                                                 win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE
                                                 | wait, 1, 65536, 65536, 0, None)
         print('Waiting for the client to connect')
         win32pipe.ConnectNamedPipe(self.__fifo, None)
         print('Client connected')
     except pywintypes.error as err:
         if mode == 'read':
             if err.args[0] == 231:
                 create_file = True
             else:
                 raise
         else:
             raise
     if mode == 'read' and create_file:
         self.__fifo = win32file.CreateFile(rf'\\.\pipe\{self.__pipe}',
                                            win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None,
                                            win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)
         result = win32pipe.SetNamedPipeHandleState(self.__fifo, win32pipe.PIPE_READMODE_MESSAGE, None, None)
         if result == 0:
             raise Exception('Could not connect to any PIPE')
     return True
Exemplo n.º 6
0
    def open(self):
        self._olapped_io = win32file.OVERLAPPED()
        if 'w' in self.mode:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, False, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeWrite')
        else:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, True, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeRead')

        self._olapped_connect = win32file.OVERLAPPED()
        self._olapped_connect.hEvent = win32event.CreateEvent(
            None, True, False, None)

        self._connect_deferred = defer.Deferred()
        win32pipe.ConnectNamedPipe(self._handle, self._olapped_connect)
        self.reactor.addEvent(self._olapped_connect.hEvent, self, '_connected')
        yield self._connect_deferred
        self.reactor.removeEvent(self._olapped_connect.hEvent)

        if 'r' in self.mode:
            self._read_buffer = win32file.AllocateReadBuffer(8192)
            win32file.ReadFile(self._handle, self._read_buffer,
                               self._olapped_io)
Exemplo n.º 7
0
 def heart(self, lock):
     try:
         while self.flag:
             print("心跳")
             try:
                 conn = win32pipe.ConnectNamedPipe(self.named_pipe, None)
                 if conn:
                     _str = tobuff(8, 202, b'{}')
                     print(f'写入ipc管道的信息为== {_str}')
                     with lock:
                         win32file.WriteFile(self.named_pipe, _str)
                     print("写入心跳结束")
                     time.sleep(5)
                 else:
                     time.sleep(0.1)
                     print("心跳命名管道还未连接")
                     continue
             except BaseException as e:
                 print("read1 exception:", e)
                 break
         print("命名管道要关闭通道啦")
     finally:
         try:
             print('关闭通道')
             win32pipe.DisconnectNamedPipe(self.named_pipe)
         except:
             pass
Exemplo n.º 8
0
        def accept_client(self, timeout=None):
            """Blocks until a client connects to the server.

            One the client has connected, then the `write` method can be used to write to it.

            @param timeout: The maximum number of seconds to wait for the client to connect before raising an
                `RedirectorError` exception.
            @type timeout: float|None

            @return:  True if a client has been connected, otherwise False.
            @rtype: bool
            """
            scaled_timeout = None
            if timeout is not None:
                scaled_timeout = int(timeout * 1000)
            self.__pipe_handle = win32pipe.CreateNamedPipe(
                self.__full_pipe_name,
                win32pipe.PIPE_ACCESS_OUTBOUND,
                win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_WAIT,
                1,
                65536,
                65536,
                scaled_timeout,
                None,
            )

            return win32pipe.ConnectNamedPipe(self.__pipe_handle, None) == 0
Exemplo n.º 9
0
    def connect_pipe(pipe, pipeName):
        overLap = pywintypes.OVERLAPPED()
        overLap.hEvent = win32event.CreateEvent(None, 1, 0, None)
        if overLap.hEvent == 0:
            raise PipeError('Could not create hEvent')

        try:
            # Wait for a pipe client connection
            ret = win32pipe.ConnectNamedPipe(pipe, overLap)
            if not ret in (0, ERROR_PIPE_CONNECTED):
                if ret == ERROR_IO_PENDING:
                    ret = win32event.WaitForSingleObject(
                        overLap.hEvent, 1000 * CONNECT_TIMEOUT_SECS)
                    if ret != win32event.WAIT_OBJECT_0:
                        # Timeout error
                        raise PipeError('Timeout error')
                else:
                    # API error
                    raise PipeError('API error')

                ret = win32pipe.GetOverlappedResult(pipe, overLap, True)
            if not ret in (0, ERROR_PIPE_CONNECTED):
                # API Error
                raise PipeError('API error 2')
        except PipeError:
            # Named pipe exception
            win32file.CancelIo(pipe)
            pipe.close()
            raise
        except BaseException, err:
            win32file.CancelIo(pipe)
            pipe.close()
            pipe = None
            raise PipeError('BaseException : ' + str(err))
    def open_pipe(self, pipe_name=None, num_allowed_instances=1):
        if pipe_name is None:
            pipe_name = CommunicationHandler.RLGYM_GLOBAL_PIPE_NAME

        if self.is_connected():
            self.close_pipe()

        self._connected = False

        pool = ThreadPool(processes=1)
        pool.apply_async(CommunicationHandler.handle_diemwin_potential,
                         args=[self.is_connected])

        #win32pipe.PIPE_UNLIMITED_INSTANCES
        self._pipe = win32pipe.CreateNamedPipe(
            pipe_name,
            win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED,
            win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE
            | win32pipe.PIPE_WAIT, num_allowed_instances,
            CommunicationHandler.RLGYM_DEFAULT_PIPE_SIZE,
            CommunicationHandler.RLGYM_DEFAULT_PIPE_SIZE, 0, None)

        win32pipe.ConnectNamedPipe(self._pipe)

        self._current_pipe_name = pipe_name
        self._connected = True

        pool.terminate()
        pool.join()
Exemplo n.º 11
0
def pipe_server(name):

    pipe = win32pipe.CreateNamedPipe(
        name, win32pipe.PIPE_ACCESS_DUPLEX,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE, 1,
        65536, 65536, 0, None)
    win32pipe.ConnectNamedPipe(pipe, None)
Exemplo n.º 12
0
 def write_to_ipc(self, data):
     #print (f'socket服务端收到的信息为=={data}')
     try:
         conn = win32pipe.ConnectNamedPipe(self.named_pipe, None)
         if conn:
             print("write_to_ipc 的信息为%s" % data)
             # print(data)
             if (len(data) > 0):
                 _str = tobuff(2018, 2018, data)
                 try:
                     with lock:
                         print(
                             f'ipc管道发给互动端的信息为=={_str+bytes(data,encoding="utf-8")}'
                         )
                         win32file.WriteFile(
                             self.named_pipe,
                             _str + bytes(data, encoding="utf-8"))
                         print("writefile finish")
                 except Exception as e:
                     print("答题信息出错:%s" % e)
             else:
                 _str = tobuff(8, 202, b'{}')
                 print(f'写入ipc管道的信息为== {_str}')
                 try:
                     with lock:
                         print('heart begin')
                         win32file.WriteFile(self.named_pipe, _str)
                         print("heart finish")
                 except Exception as e:
                     print("心跳出错:%s" % e)
     except BaseException as e:
         print("write_to_ipc 出错了:", e)
Exemplo n.º 13
0
    def Initialize(self):
        """
        入力パイプを初期化します。
            :param self: 
        """

        ### コマンド未登録チェック
        if self.__comm_list__ == None:
            raise IpcException.IpcCommInvalidException()

        try:
            if (not (self.__is_initialize__) and not (self.__is_finalize__)):
                # パイプ作成
                self.__pipe_in__ = win32pipe.CreateNamedPipe(
                    r'\\.\pipe\biassys_pipeout', win32pipe.PIPE_ACCESS_INBOUND,
                    win32pipe.PIPE_WAIT | win32pipe.PIPE_TYPE_BYTE, 1, 65536,
                    0, 10000, None)

                if self.__pipe_in__ != None:
                    if win32pipe.ConnectNamedPipe(
                            self.__pipe_in__) == 0:  # パイプ接続確認
                        self.__is_initialize__ = True
                        return True
        except pywintypes.error:
            return False

        return False
Exemplo n.º 14
0
 def connect_pipe(self):
     '''
     struct pcap_file_header
     {
         uint32_t magic_number;  /* magic number */
         uint16_t version_major; /* major version number */
         uint16_t version_minor; /* minor version number */
         int32_t  thiszone;      /* GMT to local correction */
         uint32_t sigfigs;       /* accuracy of timestamps */
         uint32_t snaplen;       /* max length of captured packets, in octets */
         uint32_t linktype;      /* data link type */
     }
     '''
     win32pipe.ConnectNamedPipe(self.pipe, None)
     global_header = struct.pack(
         'IHHiIII',
         self.magic_num,  # magic number 4
         self.major_ver,  # major version number 2
         self.minor_ver,  # minor version number 2
         0,  # GMT to local correction 4
         0,  # accuracy of timestamps 4
         0,  # max length of captured packets, in octets 4
         self.link_type  # data link type 4
     )
     win32file.WriteFile(self.pipe, global_header)
Exemplo n.º 15
0
 def create(cls,
            name,
            path='',
            host=PIPE_LOCALHOST,
            blocking=True,
            msgLimit=0,
            logger=logging.getLogger("k_os.ipc"),
            level=logging.INFO):
     pname = cls.getCanoicalName(host, path, name)
     sa = pywintypes.SECURITY_ATTRIBUTES()
     instance = cls(logger, level)
     blockingMode = win32pipe.PIPE_WAIT if blocking else win32pipe.PIPE_NOWAIT
     pmode = win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | blockingMode
     instance.name = name
     instance.handle = win32pipe.CreateNamedPipe(
         pname, win32pipe.PIPE_ACCESS_DUPLEX, pmode,
         win32pipe.PIPE_UNLIMITED_INSTANCES, 100, 100,
         win32pipe.NMPWAIT_USE_DEFAULT_WAIT, sa)
     NamedPipeServer.numberOfInstances += 1
     instance._logger.debug("Created NamedPipe '%s'." % pname)
     instance._logger.debug("Current # of instances = %u." %
                            NamedPipeServer.numberOfInstances)
     res = win32pipe.ConnectNamedPipe(instance.handle, None)
     instance._logger.debug("Client connected to NamedPipe.")
     return instance
Exemplo n.º 16
0
def send_event_thread():

    event_buffer = [str(i) + "\n" for i in range(300)]
    event_buffer[-1] = event_buffer[-1][:-1]

    pipe = win32pipe.CreateNamedPipe(

        "\\\\.\\pipe\\" + PIPE_NAME,
        win32pipe.PIPE_ACCESS_DUPLEX,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 65536, 65536,
        0,
        None

    )

    try:

        print("Waiting for client...\n")
        win32pipe.ConnectNamedPipe(pipe, None)
        print("Client connected.\n")

        while True:

            text = win32file.ReadFile(pipe, 64*1024)
            print(text)

    finally:

        win32file.CloseHandle(pipe)
Exemplo n.º 17
0
def open(name, options):
    if options == os.O_WRONLY:
        opt = win32file.GENERIC_WRITE
        dbg("open %s GENERIC_WRITE" % (name))
    else:
        opt = win32file.GENERIC_READ
        dbg("open %s GENERIC_READ" % (name))
    fileName = PIPE_PREFIX % name
    fileName = fileName.replace("\\", "/")
    fileName = fileName.replace(":", "_")
    try:
        overlapped = pywintypes.OVERLAPPED()
        #TODO: this check is more a workaround than a real solution!
        if name in PIPE_HANDLES:
            pipe_handle = PIPE_HANDLES[name]
            overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
            rc = win32pipe.ConnectNamedPipe(pipe_handle, overlapped)
            if rc == winerror.ERROR_PIPE_CONNECTED:
                win32event.SetEvent(overlapped.hEvent)
            return FileIO(pipe_handle, fileName, overlapped, opt, True)
        else:
            wh = win32file.CreateFile(fileName, opt, 0, None,
                                      win32file.OPEN_EXISTING,
                                      win32file.FILE_FLAG_OVERLAPPED, None)
            #dbg("SetNamedPipeHandleState %s" % wh)
            #win32pipe.SetNamedPipeHandleState(wh,
            #                  win32pipe.PIPE_READMODE_BYTE, None, None)
            overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
        return FileIO(wh, fileName, overlapped, opt, False)
    except:
        raise
Exemplo n.º 18
0
    def run(self):
        import win32pipe, win32file, winerror, win32api
        def as_unicode(err):
            try:
                self.err_msg = type('')(err)
            except Exception:
                self.err_msg = repr(err)
        try:
            try:
                rc = win32pipe.ConnectNamedPipe(self.pipe_handle)
            except Exception as err:
                as_unicode(err)
                return

            if rc != 0:
                self.err_msg = 'Failed to connect to client over named pipe: 0x%x' % rc
                return

            while True:
                try:
                    hr, data = win32file.ReadFile(self.pipe_handle, 1024 * 50, None)
                except Exception as err:
                    if getattr(err, 'winerror', None) == winerror.ERROR_BROKEN_PIPE:
                        break  # pipe was closed at the other end
                    as_unicode(err)
                    break
                if hr not in (winerror.ERROR_MORE_DATA, 0):
                    self.err_msg = 'ReadFile on pipe failed with hr=%d' % hr
                    break
                if not data:
                    break
                self.data += data
        finally:
            win32api.CloseHandle(self.pipe_handle)
            self.pipe_handle = None
Exemplo n.º 19
0
    def __send_buffer_thread_windows(self):

        event_queue_pipe = win32pipe.CreateNamedPipe(
            "\\\\.\\pipe\\" + self.__EVENT_QUEUE_PIPE_NAME,
            win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE
            | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT, 1, 65536,
            65536, 0, None)

        win32pipe.ConnectNamedPipe(event_queue_pipe, None)

        self.__connection_lock.acquire()
        self.__send_connected = True
        self.__connection_lock.notify_all()
        self.__connection_lock.release()

        while len(self.__event_buffer) > 0 or not self.__should_destroy:

            with self.__event_buffer_lock:

                message = self.__EVENT_SEPARATOR.join(
                    self.__event_buffer) + "\n"
                self.__event_buffer = []

            if message != "\n":

                win32file.WriteFile(event_queue_pipe, bytes(message, "ascii"))

            time.sleep(self.__SEND_INTERVAL)
Exemplo n.º 20
0
    def __get_robot_state_thread_windows(self):

        info_pipe = win32pipe.CreateNamedPipe(
            "\\\\.\\pipe\\" + self.__INFO_PIPE_NAME,
            win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE
            | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT, 1, 65536,
            65536, 0, None)

        win32pipe.ConnectNamedPipe(info_pipe, None)

        while not self.__should_destroy:

            info_text = utility.get_most_recent_message_windows(info_pipe)

            tmp_dict = json.loads(info_text)
            self.__info_dict = tmp_dict

            tmp_info = RobotInfo(self.__info_dict)

            if self.info:
                tmp_info.coordinates_are_inverted = self.info.coordinates_are_inverted

            self.info = tmp_info

            if not self.__get_connected:

                self.__connection_lock.acquire()
                self.__get_connected = True
                self.__connection_lock.notify_all()
                self.__connection_lock.release()

            time.sleep(self.__GET_INTERVAL)
Exemplo n.º 21
0
def pipe_ws(string):
    print("pipe server")
    pipe = win32pipe.CreateNamedPipe(
        r'\\.\pipe\Foo',  # name of pipe
        win32pipe.PIPE_ACCESS_DUPLEX,  # openmode
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE
        | win32pipe.PIPE_WAIT,  #pipe mode
        1,
        65536,
        65536,  # nMaxinstances , nOutBufferSize , nInbufferSize
        0,  # nDrfaultTimeOut
        None)  # pysecurity attributes
    try:
        print("waiting for client")
        win32pipe.ConnectNamedPipe(
            pipe,  # handle
            None)  # overlapped
        print("got client")

        #print(f"writing message {count}")
        # convert to bytes

        data = header.yHdr_ws(string)

        #print(f"data to send : {data}")

        win32file.WriteFile(pipe, data)
        #win32file.WriteFile(pipe, b'hello pipe...!')
        time.sleep(1)

        print("finished now")

    finally:
        win32file.CloseHandle(pipe)
Exemplo n.º 22
0
def get_mouse_data():
    import win32file
    import win32pipe

    PIPE_NAME = r'\\.\pipe\test_pipe'
    PIPE_BUFFER_SIZE = 1

    while True:
        named_pipe = win32pipe.CreateNamedPipe(
            PIPE_NAME, win32pipe.PIPE_ACCESS_DUPLEX,
            win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT
            | win32pipe.PIPE_READMODE_MESSAGE,
            win32pipe.PIPE_UNLIMITED_INSTANCES, PIPE_BUFFER_SIZE,
            PIPE_BUFFER_SIZE, 500, None)

        while True:
            try:
                win32pipe.ConnectNamedPipe(named_pipe, None)
                data = win32file.ReadFile(named_pipe, PIPE_BUFFER_SIZE, None)

                # if data is None or len(data) < 2:
                #     continue

                print('receive msg:', int.from_bytes(data[1], 'big'))
            except BaseException as e:
                print("exception:", e)
                break
        win32pipe.DisconnectNamedPipe(named_pipe)
Exemplo n.º 23
0
def main():
    while True:
        #create pipe in windows
        pipe = create_winpipe()
        
        #wait until client(game) is started
        print(">>waiting for client")
        win32pipe.ConnectNamedPipe(pipe, None)
        
        print(">>got client, connecting to host")
        #connect to socat host
        try:
            sock = socket.create_connection((HOST,PORT))
        except (ConnectionRefusedError, socket.gaierror):
            print(">>couldn't connect to host, check config")
            sys.exit()
            
        print(">>connected, starting loop")
        
        #start the connection loop
        request_loop(pipe, sock)
        
        #close the windows pipe and socket so new ones can be created
        win32file.CloseHandle(pipe)
        sock.close()
Exemplo n.º 24
0
def pipe_server():
    """
    create a server pipe to read and write file from and to the client
    """
    print("pipe server")
    pipe = win32pipe.CreateNamedPipe(
        r'\\.\pipe\Foo',
        win32pipe.PIPE_ACCESS_DUPLEX,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 65536, 65536,
        0,
        None)
    try:
        print("waiting for client")
        win32pipe.ConnectNamedPipe(pipe, None)
        print("got client")
        while True:
            # convert to bytes
            answer = random.choice(responses)
            print(f"The Magic 8 Ball says: {answer}")
            some_data = str.encode(f"{answer}")
            win32file.WriteFile(pipe, some_data)
            time.sleep(1)
    finally:
        win32file.CloseHandle(pipe)
Exemplo n.º 25
0
 def server(name, callback_func):
     buffer = 4096
     timeout = 1000
     error = False
     while True:
         if error:
             time.sleep(1)
             error = False
         handle = win32pipe.CreateNamedPipe(
             name, win32pipe.PIPE_ACCESS_INBOUND, win32pipe.PIPE_TYPE_BYTE
             | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT,
             win32pipe.PIPE_UNLIMITED_INSTANCES, buffer, buffer, timeout,
             None)
         if handle == win32file.INVALID_HANDLE_VALUE:
             error = True
             continue
         try:
             if win32pipe.ConnectNamedPipe(handle) != 0:
                 error = True
             else:
                 code, message = win32file.ReadFile(handle, buffer, None)
                 if code == 0:
                     callback_func(message)
                 else:
                     error = True
         except Exception:
             error = True
         finally:
             win32pipe.DisconnectNamedPipe(handle)
             win32file.CloseHandle(handle)
Exemplo n.º 26
0
def send_pipe():
    print("pipe server")
    count = 0
    pipe = win32pipe.CreateNamedPipe(
        r'\\.\pipe\Foo',  # name of pipe
        win32pipe.PIPE_ACCESS_DUPLEX,  # openmode
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,  # pipe mode
        1, 65536, 65536,  # nMaxinstances , nOutBufferSize , nInbufferSize
        0,  # nDrfaultTimeOut
        None)  # pysecurity attributes
    try:
        print("waiting for client")
        win32pipe.ConnectNamedPipe(pipe,  # handle
                                   None)  # overlapped
        print("got client")

        while count < 10:
            print(f"writing message {count}")
            some_data = str.encode(f"{count}")  # byte로 인코딩
            win32file.WriteFile(pipe, some_data)
            time.sleep(1)
            count += 1

        print("finished now")
    finally:
        win32file.CloseHandle(pipe)
Exemplo n.º 27
0
  def _StartMsrServerIfNeeded(self):
    if self._msr_server_handle:
      return

    _InstallWinRing0()

    pipe_name = r"\\.\pipe\msr_server_pipe_{}".format(os.getpid())
    # Try to open a named pipe to receive a msr port number from server process.
    pipe = win32pipe.CreateNamedPipe(
        pipe_name,
        win32pipe.PIPE_ACCESS_INBOUND,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 32, 32, 300, None)
    parameters = (
        os.path.join(os.path.dirname(__file__), 'msr_server_win.py'),
        pipe_name,
    )
    self._msr_server_handle = self.LaunchApplication(
        sys.executable, parameters, elevate_privilege=True)
    if pipe != win32file.INVALID_HANDLE_VALUE:
      if win32pipe.ConnectNamedPipe(pipe, None) == 0:
        self._msr_server_port = int(win32file.ReadFile(pipe, 32)[1])
      win32api.CloseHandle(pipe)
    # Wait for server to start.
    try:
      socket.create_connection(('127.0.0.1', self._msr_server_port), 5).close()
    except socket.error:
      self.CloseMsrServer()
    atexit_with_log.Register(TerminateProcess, self._msr_server_handle)
Exemplo n.º 28
0
 def start(self):
     '''Start the handler'''
     win32pipe.ConnectNamedPipe(self.pipe, None)
     if not self.link_type_tap:
         win32file.WriteFile(self.pipe, PCAP_HDR_BYTES_1)
     else:
         win32file.WriteFile(self.pipe, PCAP_HDR_BYTES_2)
def pipe_server():
    print("pipe server")
    reader = win32pipe.CreateNamedPipe(
        r'\\.\pipe\setPassword',
        win32pipe.PIPE_ACCESS_DUPLEX,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 65536, 65536,
        0,
        None)

    try:
        print("waiting for client")
        sys.stdout.flush()
        win32pipe.ConnectNamedPipe(reader, None)

        print("got client")

        resp = win32file.ReadFile(reader, 64 * 1024)
        my_json = resp[1].decode('utf8').replace("'", '"')

        result = client.execute(my_json)
        json_obj = json.loads(result)
        print(json_obj)
        res = json_obj['data']['update_user']
        some_data = str.encode(f"{res}")
        win32file.WriteFile(reader, some_data)
        print("finished now")
    finally:
        win32file.CloseHandle(reader)
Exemplo n.º 30
0
    def open(self):
        """
        Open named-pipe, starts up reading/writing

        :return: a deferred firing when the named pipe is opened
        :rtype: twisted.internet.deferred.Deferred
        """
        self._olapped_io = win32file.OVERLAPPED()
        if 'w' in self.mode:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, False, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeWrite')
        else:
            self._olapped_io.hEvent = win32event.CreateEvent(
                None, True, False, None)
            self.reactor.addEvent(self._olapped_io.hEvent, self, 'pipeRead')

        self._olapped_connect = win32file.OVERLAPPED()
        self._olapped_connect.hEvent = win32event.CreateEvent(
            None, True, False, None)

        self._connect_deferred = defer.Deferred()
        win32pipe.ConnectNamedPipe(self._handle, self._olapped_connect)
        self.reactor.addEvent(self._olapped_connect.hEvent, self, '_connected')
        yield self._connect_deferred
        self.reactor.removeEvent(self._olapped_connect.hEvent)

        if 'r' in self.mode:
            self._read_buffer = win32file.AllocateReadBuffer(8192)
            win32file.ReadFile(self._handle, self._read_buffer,
                               self._olapped_io)