Search in sources :

Example 6 with BYTE

use of com.sun.jna.platform.win32.WinDef.BYTE in project jna by java-native-access.

the class Advapi32Util method convertStringSidToSid.

/**
	 * Convert a string representation of a security identifier (SID) to a
	 * binary format.
	 *
	 * @param sidString
	 *            String SID.
	 * @return SID bytes.
	 */
public static byte[] convertStringSidToSid(String sidString) {
    PSIDByReference pSID = new PSIDByReference();
    if (!Advapi32.INSTANCE.ConvertStringSidToSid(sidString, pSID)) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    PSID value = pSID.getValue();
    try {
        return value.getBytes();
    } finally {
        Kernel32Util.freeLocalMemory(value.getPointer());
    }
}
Also used : PSIDByReference(com.sun.jna.platform.win32.WinNT.PSIDByReference) PSID(com.sun.jna.platform.win32.WinNT.PSID)

Example 7 with BYTE

use of com.sun.jna.platform.win32.WinDef.BYTE in project jna by java-native-access.

the class Advapi32Util method backupEncryptedFile.

/**
     * Backup an encrypted file or folder without decrypting it. A file named
     * "bar/sample.text" will be backed-up to "destDir/sample.text". A directory
     * named "bar" will be backed-up to "destDir/bar". This method is NOT
     * recursive. If you have an encrypted directory with encrypted files, this
     * method must be called once for the directory, and once for each encrypted
     * file to be backed-up.
     *
     * @param src
     *         The encrypted file or directory to backup.
     * @param destDir
     *         The directory where the backup will be saved.
     */
public static void backupEncryptedFile(File src, File destDir) {
    if (!destDir.isDirectory()) {
        throw new IllegalArgumentException("destDir must be a directory.");
    }
    // Open the file for export (backup)
    ULONG readFlag = new ULONG(0);
    // Import (restore) file
    ULONG writeFlag = new ULONG(CREATE_FOR_IMPORT);
    if (src.isDirectory()) {
        writeFlag.setValue(CREATE_FOR_IMPORT | CREATE_FOR_DIR);
    }
    // open encrypted file for export
    String srcFileName = src.getAbsolutePath();
    PointerByReference pvContext = new PointerByReference();
    if (Advapi32.INSTANCE.OpenEncryptedFileRaw(srcFileName, readFlag, pvContext) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // read encrypted file
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    FE_EXPORT_FUNC pfExportCallback = new FE_EXPORT_FUNC() {

        @Override
        public DWORD callback(Pointer pbData, Pointer pvCallbackContext, ULONG ulLength) {
            byte[] arr = pbData.getByteArray(0, ulLength.intValue());
            try {
                outputStream.write(arr);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return new DWORD(W32Errors.ERROR_SUCCESS);
        }
    };
    if (Advapi32.INSTANCE.ReadEncryptedFileRaw(pfExportCallback, null, pvContext.getValue()) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // close
    try {
        outputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Advapi32.INSTANCE.CloseEncryptedFileRaw(pvContext.getValue());
    // open file for import
    String destFileName = destDir.getAbsolutePath() + File.separator + src.getName();
    pvContext = new PointerByReference();
    if (Advapi32.INSTANCE.OpenEncryptedFileRaw(destFileName, writeFlag, pvContext) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // write encrypted file
    final IntByReference elementsReadWrapper = new IntByReference(0);
    FE_IMPORT_FUNC pfImportCallback = new FE_IMPORT_FUNC() {

        @Override
        public DWORD callback(Pointer pbData, Pointer pvCallbackContext, ULONGByReference ulLength) {
            int elementsRead = elementsReadWrapper.getValue();
            int remainingElements = outputStream.size() - elementsRead;
            int length = Math.min(remainingElements, ulLength.getValue().intValue());
            pbData.write(0, outputStream.toByteArray(), elementsRead, length);
            elementsReadWrapper.setValue(elementsRead + length);
            ulLength.setValue(new ULONG(length));
            return new DWORD(W32Errors.ERROR_SUCCESS);
        }
    };
    if (Advapi32.INSTANCE.WriteEncryptedFileRaw(pfImportCallback, null, pvContext.getValue()) != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    // close
    Advapi32.INSTANCE.CloseEncryptedFileRaw(pvContext.getValue());
}
Also used : ULONG(com.sun.jna.platform.win32.WinDef.ULONG) IntByReference(com.sun.jna.ptr.IntByReference) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) Pointer(com.sun.jna.Pointer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ULONGByReference(com.sun.jna.platform.win32.WinDef.ULONGByReference) PointerByReference(com.sun.jna.ptr.PointerByReference) FE_EXPORT_FUNC(com.sun.jna.platform.win32.WinBase.FE_EXPORT_FUNC) FE_IMPORT_FUNC(com.sun.jna.platform.win32.WinBase.FE_IMPORT_FUNC)

Example 8 with BYTE

use of com.sun.jna.platform.win32.WinDef.BYTE in project jna by java-native-access.

the class Kernel32NamedPipeTest method testMultiThreadedNamedPipe.

@Test
public void testMultiThreadedNamedPipe() {
    final String pipeName = "\\\\.\\pipe\\" + getCurrentTestName();
    final Logger logger = Logger.getLogger(getClass().getName());
    final int MAX_BUFFER_SIZE = 1024;
    ExecutorService executors = Executors.newFixedThreadPool(2);
    try {
        Future<?> server = executors.submit(new Runnable() {

            @Override
            public void run() {
                // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365588(v=vs.85).aspx
                HANDLE hNamedPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateNamedPipe(pipeName, // dwOpenMode
                WinBase.PIPE_ACCESS_DUPLEX, // dwPipeMode
                WinBase.PIPE_TYPE_MESSAGE | WinBase.PIPE_READMODE_MESSAGE | WinBase.PIPE_WAIT, // nMaxInstances,
                1, // nOutBufferSize,
                MAX_BUFFER_SIZE, // nInBufferSize,
                MAX_BUFFER_SIZE, // nDefaultTimeOut,
                (int) TimeUnit.SECONDS.toMillis(30L), // lpSecurityAttributes
                null));
                try {
                    logger.info("Await client connection");
                    assertCallSucceeded("ConnectNamedPipe", Kernel32.INSTANCE.ConnectNamedPipe(hNamedPipe, null));
                    logger.info("Client connected");
                    byte[] readBuffer = new byte[MAX_BUFFER_SIZE];
                    IntByReference lpNumberOfBytesRead = new IntByReference(0);
                    assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hNamedPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null));
                    int readSize = lpNumberOfBytesRead.getValue();
                    logger.info("Received client data - length=" + readSize);
                    assertTrue("No data receieved from client", readSize > 0);
                    IntByReference lpNumberOfBytesWritten = new IntByReference(0);
                    assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hNamedPipe, readBuffer, readSize, lpNumberOfBytesWritten, null));
                    logger.info("Echoed client data - length=" + lpNumberOfBytesWritten.getValue());
                    assertEquals("Mismatched write buffer size", readSize, lpNumberOfBytesWritten.getValue());
                    // Flush the pipe to allow the client to read the pipe's contents before disconnecting
                    assertCallSucceeded("FlushFileBuffers", Kernel32.INSTANCE.FlushFileBuffers(hNamedPipe));
                    logger.info("Disconnecting");
                    assertCallSucceeded("DisconnectNamedPipe", Kernel32.INSTANCE.DisconnectNamedPipe(hNamedPipe));
                    logger.info("Disconnected");
                } finally {
                    // clean up
                    assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hNamedPipe));
                }
            }
        });
        logger.info("Started server - handle=" + server);
        Future<?> client = executors.submit(new Runnable() {

            @Override
            public void run() {
                // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365592(v=vs.85).aspx
                assertCallSucceeded("WaitNamedPipe", Kernel32.INSTANCE.WaitNamedPipe(pipeName, (int) TimeUnit.SECONDS.toMillis(15L)));
                logger.info("Connected to server");
                HANDLE hPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateFile(pipeName, WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, // no sharing
                0, // default security attributes
                null, // opens existing pipe
                WinNT.OPEN_EXISTING, // default attributes
                0, // no template file
                null));
                try {
                    IntByReference lpMode = new IntByReference(WinBase.PIPE_READMODE_MESSAGE);
                    assertCallSucceeded("SetNamedPipeHandleState", Kernel32.INSTANCE.SetNamedPipeHandleState(hPipe, lpMode, null, null));
                    String expMessage = Thread.currentThread().getName() + " says hello";
                    byte[] expData = expMessage.getBytes();
                    IntByReference lpNumberOfBytesWritten = new IntByReference(0);
                    assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hPipe, expData, expData.length, lpNumberOfBytesWritten, null));
                    logger.info("Sent hello message");
                    assertEquals("Mismatched write buffer size", expData.length, lpNumberOfBytesWritten.getValue());
                    byte[] readBuffer = new byte[MAX_BUFFER_SIZE];
                    IntByReference lpNumberOfBytesRead = new IntByReference(0);
                    assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null));
                    int readSize = lpNumberOfBytesRead.getValue();
                    logger.info("Received server data - length=" + readSize);
                    assertTrue("No data receieved from server", readSize > 0);
                    String actMessage = new String(readBuffer, 0, readSize);
                    assertEquals("Mismatched server data", expMessage, actMessage);
                } finally {
                    // clean up
                    assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hPipe));
                }
            }
        });
        logger.info("Started client - handle=" + client);
        for (Future<?> f : Arrays.asList(client, server)) {
            try {
                f.get(30L, TimeUnit.SECONDS);
                logger.info("Finished " + f);
            } catch (Exception e) {
                logger.warning(e.getClass().getSimpleName() + " while await completion of " + f + ": " + e.getMessage());
            }
        }
    } finally {
        executors.shutdownNow();
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) ExecutorService(java.util.concurrent.ExecutorService) Logger(java.util.logging.Logger) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) Test(org.junit.Test)

Example 9 with BYTE

use of com.sun.jna.platform.win32.WinDef.BYTE in project jna by java-native-access.

the class Kernel32Test method testWriteProcessMemory.

public void testWriteProcessMemory() {
    Kernel32 kernel = Kernel32.INSTANCE;
    boolean successWrite = kernel.WriteProcessMemory(null, Pointer.NULL, Pointer.NULL, 1, null);
    assertFalse(successWrite);
    assertEquals(kernel.GetLastError(), WinError.ERROR_INVALID_HANDLE);
    ByteBuffer bufDest = ByteBuffer.allocateDirect(4);
    bufDest.put(new byte[] { 0, 1, 2, 3 });
    ByteBuffer bufSrc = ByteBuffer.allocateDirect(4);
    bufSrc.put(new byte[] { 5, 10, 15, 20 });
    Pointer ptrSrc = Native.getDirectBufferPointer(bufSrc);
    Pointer ptrDest = Native.getDirectBufferPointer(bufDest);
    HANDLE selfHandle = kernel.GetCurrentProcess();
    //Write only the first three
    kernel.WriteProcessMemory(selfHandle, ptrDest, ptrSrc, 3, null);
    assertEquals(bufDest.get(0), 5);
    assertEquals(bufDest.get(1), 10);
    assertEquals(bufDest.get(2), 15);
    assertEquals(bufDest.get(3), 3);
}
Also used : Pointer(com.sun.jna.Pointer) ByteBuffer(java.nio.ByteBuffer) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Example 10 with BYTE

use of com.sun.jna.platform.win32.WinDef.BYTE in project jna by java-native-access.

the class GuidTest method testGUIDFromString2.

/**
	 * Loads a GUID from string via the constructor and verify that the guid
	 * returned has the expected values in each byte.
	 */
public void testGUIDFromString2() {
    String sourceGuidStr = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}";
    // test loading via constructor
    GUID targetGuid = new GUID(sourceGuidStr);
    assertEquals(targetGuid.toGuidString(), sourceGuidStr);
}
Also used : GUID(com.sun.jna.platform.win32.Guid.GUID)

Aggregations

IntByReference (com.sun.jna.ptr.IntByReference)12 Pointer (com.sun.jna.Pointer)8 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)8 Advapi32 (com.sun.jna.platform.win32.Advapi32)6 HKEY (com.sun.jna.platform.win32.WinReg.HKEY)6 PointerByReference (com.sun.jna.ptr.PointerByReference)5 Memory (com.sun.jna.Memory)4 GUID (com.sun.jna.platform.win32.Guid.GUID)4 BSTR (com.sun.jna.platform.win32.WTypes.BSTR)4 File (java.io.File)4 Date (java.util.Date)4 Test (org.junit.Test)4 DATE (com.sun.jna.platform.win32.OaIdl.DATE)3 VARIANT (com.sun.jna.platform.win32.Variant.VARIANT)3 FE_EXPORT_FUNC (com.sun.jna.platform.win32.WinBase.FE_EXPORT_FUNC)3 BYTE (com.sun.jna.platform.win32.WinDef.BYTE)3 CHAR (com.sun.jna.platform.win32.WinDef.CHAR)3 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)3 LONG (com.sun.jna.platform.win32.WinDef.LONG)3 SHORT (com.sun.jna.platform.win32.WinDef.SHORT)3