Search in sources :

Example 26 with Kernel32

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

the class PsapiTest method testGetModuleFileNameEx.

@Test
public void testGetModuleFileNameEx() {
    final JFrame w = new JFrame();
    try {
        w.setVisible(true);
        final String searchSubStr = "\\bin\\java";
        final HWND hwnd = new HWND(Native.getComponentPointer(w));
        final IntByReference pid = new IntByReference();
        User32.INSTANCE.GetWindowThreadProcessId(hwnd, pid);
        final HANDLE process = Kernel32.INSTANCE.OpenProcess(0x0400 | 0x0010, false, pid.getValue());
        if (process == null)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        // check ANSI function
        final byte[] filePathAnsi = new byte[1025];
        int length = Psapi.INSTANCE.GetModuleFileNameExA(process, null, filePathAnsi, filePathAnsi.length - 1);
        if (length == 0)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        assertTrue("Path didn't contain '" + searchSubStr + "': " + Native.toString(filePathAnsi), Native.toString(filePathAnsi).toLowerCase().contains(searchSubStr));
        // check Unicode function
        final char[] filePathUnicode = new char[1025];
        length = Psapi.INSTANCE.GetModuleFileNameExW(process, null, filePathUnicode, filePathUnicode.length - 1);
        if (length == 0)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        assertTrue("Path didn't contain '" + searchSubStr + "': " + Native.toString(filePathUnicode), Native.toString(filePathUnicode).toLowerCase().contains(searchSubStr));
        // check default function
        final int memAllocSize = 1025 * Native.WCHAR_SIZE;
        final Memory filePathDefault = new Memory(memAllocSize);
        length = Psapi.INSTANCE.GetModuleFileNameEx(process, null, filePathDefault, (memAllocSize / Native.WCHAR_SIZE) - 1);
        if (length == 0)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        assertTrue("Path didn't contain '" + searchSubStr + "': " + Native.toString(filePathDefault.getCharArray(0, memAllocSize / Native.WCHAR_SIZE)), Native.toString(filePathDefault.getCharArray(0, memAllocSize / Native.WCHAR_SIZE)).toLowerCase().contains(searchSubStr));
    } finally {
        w.dispose();
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) JFrame(javax.swing.JFrame) Memory(com.sun.jna.Memory) HWND(com.sun.jna.platform.win32.WinDef.HWND) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) Test(org.junit.Test)

Example 27 with Kernel32

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

the class Win32SpoolMonitor method printJobInfo.

private void printJobInfo(JOB_INFO_1 jobInfo1) {
    FILETIME lpFileTime = new FILETIME();
    Kernel32.INSTANCE.SystemTimeToFileTime(jobInfo1.Submitted, lpFileTime);
    String info = "JobId: " + jobInfo1.JobId + "\n" + "pDatatype: " + jobInfo1.pDatatype + "\n" + "PagesPrinted: " + jobInfo1.PagesPrinted + "\n" + "pDocument: " + jobInfo1.pDocument + "\n" + "pMachineName: " + jobInfo1.pMachineName + "\n" + "Position: " + jobInfo1.Position + "\n" + "pPrinterName: " + jobInfo1.pPrinterName + "\n" + "Priority: " + jobInfo1.Priority + "\n" + "pStatus: " + jobInfo1.pStatus + "\n" + "pUserName: " + jobInfo1.pUserName + "\n" + "Status: " + jobInfo1.Status + "\n" + "TotalPages: " + jobInfo1.TotalPages + "\n" + "Submitted: " + DateFormat.getDateTimeInstance().format(lpFileTime.toDate());
    System.out.println(info);
}
Also used : FILETIME(com.sun.jna.platform.win32.WinBase.FILETIME)

Example 28 with Kernel32

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

the class Advapi32Util method getFileSecurity.

public static ACCESS_ACEStructure[] getFileSecurity(String fileName, boolean compact) {
    int infoType = WinNT.DACL_SECURITY_INFORMATION;
    int nLength = 1024;
    boolean repeat = false;
    Memory memory = null;
    do {
        repeat = false;
        memory = new Memory(nLength);
        IntByReference lpnSize = new IntByReference();
        boolean succeded = Advapi32.INSTANCE.GetFileSecurity(fileName, infoType, memory, nLength, lpnSize);
        if (!succeded) {
            int lastError = Kernel32.INSTANCE.GetLastError();
            memory.clear();
            if (W32Errors.ERROR_INSUFFICIENT_BUFFER != lastError) {
                throw new Win32Exception(lastError);
            }
        }
        int lengthNeeded = lpnSize.getValue();
        if (nLength < lengthNeeded) {
            repeat = true;
            nLength = lengthNeeded;
            memory.clear();
        }
    } while (repeat);
    SECURITY_DESCRIPTOR_RELATIVE sdr = new WinNT.SECURITY_DESCRIPTOR_RELATIVE(memory);
    memory.clear();
    ACL dacl = sdr.getDiscretionaryACL();
    ACCESS_ACEStructure[] aceStructures = dacl.getACEStructures();
    if (compact) {
        Map<String, ACCESS_ACEStructure> aceMap = new HashMap<String, ACCESS_ACEStructure>();
        for (ACCESS_ACEStructure aceStructure : aceStructures) {
            boolean inherted = ((aceStructure.AceFlags & WinNT.VALID_INHERIT_FLAGS) != 0);
            String key = aceStructure.getSidString() + "/" + inherted + "/" + aceStructure.getClass().getName();
            ACCESS_ACEStructure aceStructure2 = aceMap.get(key);
            if (aceStructure2 != null) {
                int accessMask = aceStructure2.Mask;
                accessMask = accessMask | aceStructure.Mask;
                aceStructure2.Mask = accessMask;
            } else {
                aceMap.put(key, aceStructure);
            }
        }
        return aceMap.values().toArray(new ACCESS_ACEStructure[aceMap.size()]);
    }
    return aceStructures;
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) HashMap(java.util.HashMap) Memory(com.sun.jna.Memory) SECURITY_DESCRIPTOR_RELATIVE(com.sun.jna.platform.win32.WinNT.SECURITY_DESCRIPTOR_RELATIVE) ACCESS_ACEStructure(com.sun.jna.platform.win32.WinNT.ACCESS_ACEStructure) ACL(com.sun.jna.platform.win32.WinNT.ACL)

Example 29 with Kernel32

use of com.sun.jna.platform.win32.Kernel32 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 30 with Kernel32

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

the class Advapi32Util method accessCheck.

/**
     * Checks if the current process has the given permission for the file.
     * @param file the file to check
     * @param permissionToCheck the permission to check for the file
     * @return true if has access, otherwise false
     */
public static boolean accessCheck(File file, AccessCheckPermission permissionToCheck) {
    Memory securityDescriptorMemoryPointer = getSecurityDescriptorForFile(file.getAbsolutePath().replace('/', '\\'));
    HANDLEByReference openedAccessToken = new HANDLEByReference();
    HANDLEByReference duplicatedToken = new HANDLEByReference();
    Win32Exception err = null;
    try {
        int desireAccess = TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE | STANDARD_RIGHTS_READ;
        HANDLE hProcess = Kernel32.INSTANCE.GetCurrentProcess();
        if (!Advapi32.INSTANCE.OpenProcessToken(hProcess, desireAccess, openedAccessToken)) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        if (!Advapi32.INSTANCE.DuplicateToken(openedAccessToken.getValue(), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, duplicatedToken)) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        GENERIC_MAPPING mapping = new GENERIC_MAPPING();
        mapping.genericRead = new DWORD(FILE_GENERIC_READ);
        mapping.genericWrite = new DWORD(FILE_GENERIC_WRITE);
        mapping.genericExecute = new DWORD(FILE_GENERIC_EXECUTE);
        mapping.genericAll = new DWORD(FILE_ALL_ACCESS);
        DWORDByReference rights = new DWORDByReference(new DWORD(permissionToCheck.getCode()));
        Advapi32.INSTANCE.MapGenericMask(rights, mapping);
        PRIVILEGE_SET privileges = new PRIVILEGE_SET(1);
        privileges.PrivilegeCount = new DWORD(0);
        DWORDByReference privilegeLength = new DWORDByReference(new DWORD(privileges.size()));
        DWORDByReference grantedAccess = new DWORDByReference();
        BOOLByReference result = new BOOLByReference();
        if (!Advapi32.INSTANCE.AccessCheck(securityDescriptorMemoryPointer, duplicatedToken.getValue(), rights.getValue(), mapping, privileges, privilegeLength, grantedAccess, result)) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        return result.getValue().booleanValue();
    } catch (Win32Exception e) {
        err = e;
        // re-throw so finally block executed
        throw err;
    } finally {
        try {
            Kernel32Util.closeHandleRefs(openedAccessToken, duplicatedToken);
        } catch (Win32Exception e) {
            if (err == null) {
                err = e;
            } else {
                err.addSuppressed(e);
            }
        }
        if (securityDescriptorMemoryPointer != null) {
            securityDescriptorMemoryPointer.clear();
        }
        if (err != null) {
            throw err;
        }
    }
}
Also used : BOOLByReference(com.sun.jna.platform.win32.WinDef.BOOLByReference) PRIVILEGE_SET(com.sun.jna.platform.win32.WinNT.PRIVILEGE_SET) GENERIC_MAPPING(com.sun.jna.platform.win32.WinNT.GENERIC_MAPPING) DWORDByReference(com.sun.jna.platform.win32.WinDef.DWORDByReference) Memory(com.sun.jna.Memory) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) HANDLEByReference(com.sun.jna.platform.win32.WinNT.HANDLEByReference) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Aggregations

HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)74 IntByReference (com.sun.jna.ptr.IntByReference)47 File (java.io.File)33 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)30 SC_HANDLE (com.sun.jna.platform.win32.Winsvc.SC_HANDLE)27 HANDLEByReference (com.sun.jna.platform.win32.WinNT.HANDLEByReference)26 Memory (com.sun.jna.Memory)25 PointerByReference (com.sun.jna.ptr.PointerByReference)14 Pointer (com.sun.jna.Pointer)12 EVT_HANDLE (com.sun.jna.platform.win32.Winevt.EVT_HANDLE)7 Test (org.junit.Test)7 SYSTEMTIME (com.sun.jna.platform.win32.WinBase.SYSTEMTIME)6 ArrayList (java.util.ArrayList)6 FILETIME (com.sun.jna.platform.win32.WinBase.FILETIME)5 HMODULE (com.sun.jna.platform.win32.WinDef.HMODULE)5 PSID (com.sun.jna.platform.win32.WinNT.PSID)5 TOKEN_PRIVILEGES (com.sun.jna.platform.win32.WinNT.TOKEN_PRIVILEGES)5 WString (com.sun.jna.WString)4 DWORDByReference (com.sun.jna.platform.win32.WinDef.DWORDByReference)4 ShortByReference (com.sun.jna.ptr.ShortByReference)4