Exemplo n.º 1
0
 def conn_loop(self):
     self.is_running = True
     self.update_vars()
     self.file_handle = win32file.CreateFile(
         self.ipc_path, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0,
         None, win32file.OPEN_EXISTING, 0, None)
     while self.is_running:
         try:
             while not self.write_queue.empty():
                 win32file.WriteFile(self.file_handle,
                                     self.write_queue.get_nowait())
         except win32file.error:
             logger.debug('Exception while writing to pipe.', exc_info=True)
             self.is_running = False
             break
         size = win32file.GetFileSize(self.file_handle)
         if size > 0:
             while size > 0:
                 # pipe has data to read
                 _, data = win32file.ReadFile(self.file_handle, 4096)
                 self.on_data(data)
                 size = win32file.GetFileSize(self.file_handle)
         else:
             time.sleep(1)
     win32file.CloseHandle(self.file_handle)
     logger.debug('Pipe closed.')
Exemplo n.º 2
0
    def testMoreFiles(self):
        # Create a file in the %TEMP% directory.
        testName = os.path.join(win32api.GetTempPath(), "win32filetest.dat")
        desiredAccess = win32file.GENERIC_READ | win32file.GENERIC_WRITE
        # Set a flag to delete the file automatically when it is closed.
        fileFlags = win32file.FILE_FLAG_DELETE_ON_CLOSE
        h = win32file.CreateFile(testName, desiredAccess,
                                 win32file.FILE_SHARE_READ, None,
                                 win32file.CREATE_ALWAYS, fileFlags, 0)

        # Write a known number of bytes to the file.
        data = "z" * 1025

        win32file.WriteFile(h, data)

        self.failUnless(
            win32file.GetFileSize(h) == len(data),
            "WARNING: Written file does not have the same size as the length of the data in it!"
        )

        # Ensure we can read the data back.
        win32file.SetFilePointer(h, 0, win32file.FILE_BEGIN)
        hr, read_data = win32file.ReadFile(h,
                                           len(data) +
                                           10)  # + 10 to get anything extra
        self.failUnless(hr == 0, "Readfile returned %d" % hr)

        self.failUnless(read_data == data, "Read data is not what we wrote!")

        # Now truncate the file at 1/2 its existing size.
        newSize = len(data) / 2
        win32file.SetFilePointer(h, newSize, win32file.FILE_BEGIN)
        win32file.SetEndOfFile(h)
        self.failUnless(
            win32file.GetFileSize(h) == newSize,
            "Truncated file does not have the expected size!")

        # GetFileAttributesEx/GetFileAttributesExW tests.
        self.failUnless(
            win32file.GetFileAttributesEx(
                testName) == win32file.GetFileAttributesExW(testName),
            "ERROR: Expected GetFileAttributesEx and GetFileAttributesExW to return the same data"
        )

        attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName)
        self.failUnless(
            size == newSize,
            "Expected GetFileAttributesEx to return the same size as GetFileSize()"
        )
        self.failUnless(
            attr == win32file.GetFileAttributes(testName),
            "Expected GetFileAttributesEx to return the same attributes as GetFileAttributes"
        )

        h = None  # Close the file by removing the last reference to the handle!

        self.failUnless(not os.path.isfile(testName),
                        "After closing the file, it still exists!")
Exemplo n.º 3
0
    def __init__(self, base=None, filename=None, **kwargs):
        self.as_assert(base == None, 'Must be first Address Space')
        super(Win32FileAddressSpace, self).__init__(**kwargs)

        path = filename or self.session.GetParameter("filename")

        self.as_assert(
            path, "Filename must be specified in session (e.g. "
            "session.SetParameter('filename', 'MyFile.raw').")

        self.fname = path

        # The file is just a regular file, we open for reading.
        fhandle = self._OpenFileForRead(path)

        # If we can not get the file size it means this is not a regular file -
        # maybe a device.
        self.fhandle_as = Win32FileWrapper(fhandle)
        try:
            file_size = win32file.GetFileSize(fhandle)
            self.add_run(0, 0, file_size, self.fhandle_as)
        except pywintypes.error:
            # This may be a device, we just read the whole space.
            self.add_run(0, 0, 2**63, self.fhandle_as)
            self.volatile = True
Exemplo n.º 4
0
    def __init__(self, base=None, filename=None, **kwargs):
        self.as_assert(base == None, 'Must be first Address Space')
        super(Win32FileAddressSpace, self).__init__(**kwargs)

        path = filename or (self.session and self.session.GetParameter(
                "filename"))

        self.as_assert(path, "Filename must be specified in session (e.g. "
                       "session.GetParameter('filename', 'MyFile.raw').")

        self.fname = path

        # If the file is a device we try to talk to the winpmem driver.
        if path.startswith("\\\\"):
            try:
                # First open for write in case the driver is in write mode.
                self._OpenFileForWrite(path)
            except IOError:
                self._OpenFileForRead(path)

            self.ParseMemoryRuns()

        else:
            # The file is just a regular file, we open for reading.
            self._OpenFileForRead(path)
            self.runs.insert((0, 0, win32file.GetFileSize(self.fhandle)))
Exemplo n.º 5
0
    def __init__(self, filename, mode='r', encoding=None):
        if mode in ('r', 'r+'):
            creationDisposition = win32file.OPEN_EXISTING
            desiredAccess = win32con.GENERIC_READ
        elif mode == 'w':
            creationDisposition = win32con.CREATE_ALWAYS
            desiredAccess = win32con.GENERIC_WRITE
        elif mode in ('rw', 'wr', 'r+', 'w+', 'a+'):
            creationDisposition = win32con.OPEN_ALWAYS
            desiredAccess = win32con.GENERIC_READ | win32con.GENERIC_WRITE
        elif mode == 'a':
            creationDisposition = win32con.OPEN_ALWAYS
            desiredAccess = win32con.GENERIC_WRITE
        else:
            raise ValueError('Invalid access mode')
        self.filename = filename
        # shareMode = (win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE |
        #              win32con.FILE_SHARE_DELETE)
        shareMode = win32con.shareMode = (win32con.FILE_SHARE_READ
                                          | win32con.FILE_SHARE_WRITE)
        attributes = win32security.SECURITY_ATTRIBUTES()
        # dwFlagsAndAttributes = win32con.FILE_ATTRIBUTE_NORMAL
        dwFlagsAndAttributes = win32con.FILE_FLAG_WRITE_THROUGH

        self.encoding = encoding or 'utf-8'
        self.handle = win32file.CreateFile(filename, desiredAccess, shareMode,
                                           attributes, creationDisposition,
                                           dwFlagsAndAttributes, 0)
        win32api.SetHandleInformation(self.handle,
                                      win32con.HANDLE_FLAG_INHERIT, 0)
        if mode in ('a', 'a+'):
            self.seek(0, 2)
        self.file_size = win32file.GetFileSize(self.handle)
        self.is_closed = False
Exemplo n.º 6
0
 def _read_all_data(self):
     """Read all the remaining data on the pipe"""
     data = b""
     read_buf = win32file.AllocateReadBuffer(512)
     while win32file.GetFileSize(self.file_handle):
         _, d = win32file.ReadFile(self.file_handle, read_buf)
         data += d
     return data
Exemplo n.º 7
0
    def run(self):
        import win32file
        self.file_handle = win32file.CreateFile(
            self.named_pipe_path,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None,
            win32file.OPEN_EXISTING, 0, None)

        log.info('Windows named pipe connected')
        self.fire_connected()

        while True:
            # The following code is cleaner, than waiting for an exception while writing to detect pipe closing,
            # but causes mpv to hang and crash while closing when closed at the wrong time.

            # if win32file.GetFileAttributes(self.named_pipe_path) != win32file.FILE_ATTRIBUTE_NORMAL:
            #     # pipe was closed
            #     break

            try:
                while not self.write_queue.empty():
                    win32file.WriteFile(self.file_handle,
                                        self.write_queue.get_nowait())
            except win32file.error:
                log.warning(
                    'Exception while writing to Windows named pipe. Assuming pipe closed.'
                )
                break

            size = win32file.GetFileSize(self.file_handle)
            if size > 0:
                while size > 0:
                    # pipe has data to read
                    data = win32file.ReadFile(self.file_handle, 512)
                    self.on_data(data[1])
                    size = win32file.GetFileSize(self.file_handle)
            else:
                time.sleep(1)

        log.info('Windows named pipe closed')
        win32file.CloseHandle(self.file_handle)
        self.file_handle = None

        self.fire_disconnected()
Exemplo n.º 8
0
def windows_get_size(path):
    ''' On windows file sizes are only accurately stored in the actual file,
    not in the directory entry (which could be out of date). So we open the
    file, and get the actual size. '''
    import win32file
    h = win32file.CreateFile(
        path, 0, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE
        | win32file.FILE_SHARE_DELETE, None, win32file.OPEN_EXISTING, 0, None)
    try:
        return win32file.GetFileSize(h)
    finally:
        win32file.CloseHandle(h)
Exemplo n.º 9
0
 def read(self, bytes=-1):
     import win32file as w
     sz = w.GetFileSize(self._handle)
     max = sz - self.tell()
     if bytes < 0: bytes = max
     bytes = min(max, bytes)
     if bytes < 1:
         return ''
     hr, ans = w.ReadFile(self._handle, bytes, None)
     if hr != 0:
         raise IOError('Error reading file: %s' % hr)
     return ans
Exemplo n.º 10
0
 def get_file_pos(self, path=None):
     if path is None:
         self.raise_if_notarget()
         tpath = self.target_path
     else:
         tpath = path
     self.ldebug("get_file_pos", "for {}".format(tpath))
     try:
         with OpenNoLock(tpath) as fh:
             return win32file.GetFileSize(fh)
     except pywintypes.error as e:
         err = e[2]
         if self.encoding:
             err = err.decode(self.encoding).encode('utf8')
         self.lerror("get_file_pos", "{} - {}".format(err, tpath))
         raise
Exemplo n.º 11
0
 def __init__(self, path, mode=0, access=win32con.GENERIC_ALL):
     self.name = path
     access = 0
     winmode = 0
     if 'r' in mode:
         winmode = win32con.OPEN_EXISTING
         access |= win32con.GENERIC_READ
     if 'w' in mode:
         winmode |= win32con.CREATE_ALWAYS
         access |= win32con.GENERIC_WRITE
     if path.startswith("\\\\"):
         self.size = _self.get_device_size(path) * 512
         self.handle = win32file.CreateFile(
             path, access,
             win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
             None, winmode, win32con.FILE_FLAG_RANDOM_ACCESS, None)
     else:
         self.handle = win32file.CreateFile(path, access, 0, None,
                                            winmode, 0, None)
         self.size = win32file.GetFileSize(self.handle)
Exemplo n.º 12
0
def read_with_share_delete(filepath):
    h = win32file.CreateFile(filepath,
                             win32file.GENERIC_READ,
                             win32file.FILE_SHARE_READ |
                             win32file.FILE_SHARE_WRITE |
                             win32file.FILE_SHARE_DELETE,
                             None,
                             win32file.OPEN_EXISTING,
                             0,
                             0)

    if h != win32file.INVALID_HANDLE_VALUE:
        try:
            size = win32file.GetFileSize(h)
            hr, contents = win32file.ReadFile(h, size, None)
            if hr != 0:
                raise Exception("Failed to ReadFile")
            return contents.decode('utf-8').splitlines()
        except:
            win32file.CloseHandle(h)
    else:
        raise Exception("Failed to CreateFile")
Exemplo n.º 13
0
    def __init__(self, base=None, filename=None, **kwargs):
        self.as_assert(base == None, 'Must be first Address Space')
        super(Win32FileAddressSpace, self).__init__(**kwargs)
        self.phys_base = self

        path = filename or self.session.GetParameter("filename")

        self.as_assert(
            path, "Filename must be specified in session (e.g. "
            "session.SetParameter('filename', 'MyFile.raw').")

        self.fname = path

        # The file is just a regular file, we open for reading.
        self._OpenFileForRead(path)

        # If we can not get the file size it means this is not a regular file -
        # maybe a device.
        try:
            self.runs.insert((0, 0, win32file.GetFileSize(self.fhandle)))
        except pywintypes.error:
            raise addrspace.ASAssertionError("Not a regular file.")
Exemplo n.º 14
0
 def AdGetSize(self):
     return win32file.GetFileSize(self.fhandle)