From 3ec106afec880378174ba087044ac672b72e4bb9 Mon Sep 17 00:00:00 2001 From: Lyor Goldstein Date: Tue, 8 Mar 2016 20:34:49 +0200 Subject: [PATCH] Added standard Kernel32Util#closeHandle method that throws a Win32Exception if failed to close the handle --- CHANGES.md | 1 + .../sun/jna/platform/win32/Advapi32Util.java | 87 ++- .../com/sun/jna/platform/win32/Kernel32.java | 5 +- .../sun/jna/platform/win32/Kernel32Util.java | 145 +++- .../jna/platform/win32/W32FileMonitor.java | 68 +- .../sun/jna/platform/win32/Advapi32Test.java | 642 +++++++++--------- .../jna/platform/win32/Advapi32UtilTest.java | 178 ++--- .../sun/jna/platform/win32/Kernel32Test.java | 237 ++++--- .../jna/platform/win32/Kernel32UtilTest.java | 2 +- .../com/sun/jna/platform/win32/PsapiTest.java | 88 +-- .../sun/jna/platform/win32/Secur32Test.java | 194 +++--- 11 files changed, 910 insertions(+), 737 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 5fe462c080..f3674d508e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -42,6 +42,7 @@ Features * [#612](https://github.com/java-native-access/jna/pull/612): Kernel32Util#freeLocal/GlobalMemory always throws Win32Exception if failed [@lgoldstein](https://github.com/lgoldstein). * [#608](https://github.com/java-native-access/jna/pull/608): Mavenize the build process - change parent and native pom artifactId/name to differentiate in IDE and build tools. [@bhamail](https://github.com/bhamail) * [#613](https://github.com/java-native-access/jna/pull/613): Make Win32Exception extend LastErrorException [@lgoldstein](https://github.com/lgoldstein). +* [#613](https://github.com/java-native-access/jna/pull/614): Added standard Kernel32Util#closeHandle method that throws a eption if failed to close the handle [@lgoldstein](https://github.com/lgoldstein). Bug Fixes --------- diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Advapi32Util.java b/contrib/platform/src/com/sun/jna/platform/win32/Advapi32Util.java index 3ed91c6233..be7f370b54 100755 --- a/contrib/platform/src/com/sun/jna/platform/win32/Advapi32Util.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/Advapi32Util.java @@ -478,28 +478,45 @@ public static Account getTokenAccount(HANDLE hToken) { */ public static Account[] getCurrentUserGroups() { HANDLEByReference phToken = new HANDLEByReference(); + Win32Exception err = null; try { // open thread or process token HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle, TOKEN_DUPLICATE | TOKEN_QUERY, true, phToken)) { - if (W32Errors.ERROR_NO_TOKEN != Kernel32.INSTANCE - .GetLastError()) { - throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); + int rc = Kernel32.INSTANCE.GetLastError(); + if (rc != W32Errors.ERROR_NO_TOKEN) { + throw new Win32Exception(rc); } + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); if (!Advapi32.INSTANCE.OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_QUERY, phToken)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } } + return getTokenGroups(phToken.getValue()); + } catch(Win32Exception e) { + err = e; + throw err; // re-throw in order to invoke finally block } finally { - if (phToken.getValue() != WinBase.INVALID_HANDLE_VALUE) { - if (!Kernel32.INSTANCE.CloseHandle(phToken.getValue())) { - throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); + HANDLE hToken = phToken.getValue(); + if (!WinBase.INVALID_HANDLE_VALUE.equals(hToken)) { + try { + Kernel32Util.closeHandle(hToken); + } catch(Win32Exception e) { + if (err == null) { + err = e; + } else { + err.addSuppressed(e); + } } } + + if (err != null) { + throw err; + } } } @@ -2341,39 +2358,38 @@ else if ((securityDescriptor.Control & SE_SACL_PROTECTED) == 0) { * @return true if has access, otherwise false */ public static boolean accessCheck(File file, AccessCheckPermission permissionToCheck) { - boolean hasAccess = false; - final Memory securityDescriptorMemoryPointer = getSecurityDescriptorForFile(file.getAbsolutePath().replaceAll("/", "\\")); + Memory securityDescriptorMemoryPointer = getSecurityDescriptorForFile(file.getAbsolutePath().replace('/', '\\')); - HANDLEByReference openedAccessToken = null; - final HANDLEByReference duplicatedToken = new HANDLEByReference(); + HANDLEByReference openedAccessToken = new HANDLEByReference(); + HANDLEByReference duplicatedToken = new HANDLEByReference(); + Win32Exception err = null; try{ - openedAccessToken = new HANDLEByReference(); - - final int desireAccess = TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE | STANDARD_RIGHTS_READ; - if(!Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), desireAccess, openedAccessToken)) { + 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)) { + if (!Advapi32.INSTANCE.DuplicateToken(openedAccessToken.getValue(), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, duplicatedToken)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } - final GENERIC_MAPPING mapping = new GENERIC_MAPPING(); + 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); - final DWORDByReference rights = new DWORDByReference(new DWORD(permissionToCheck.getCode())); + DWORDByReference rights = new DWORDByReference(new DWORD(permissionToCheck.getCode())); Advapi32.INSTANCE.MapGenericMask(rights, mapping); - final PRIVILEGE_SET privileges = new PRIVILEGE_SET(1); + PRIVILEGE_SET privileges = new PRIVILEGE_SET(1); privileges.PrivilegeCount = new DWORD(0); - final DWORDByReference privilegeLength = new DWORDByReference(new DWORD(privileges.size())); + DWORDByReference privilegeLength = new DWORDByReference(new DWORD(privileges.size())); - final DWORDByReference grantedAccess = new DWORDByReference(); - final BOOLByReference result = new BOOLByReference(); - if(!Advapi32.INSTANCE.AccessCheck(securityDescriptorMemoryPointer, + DWORDByReference grantedAccess = new DWORDByReference(); + BOOLByReference result = new BOOLByReference(); + if (!Advapi32.INSTANCE.AccessCheck(securityDescriptorMemoryPointer, duplicatedToken.getValue(), rights.getValue(), mapping, @@ -2381,24 +2397,29 @@ public static boolean accessCheck(File file, AccessCheckPermission permissionToC throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } - hasAccess = result.getValue().booleanValue(); - + return result.getValue().booleanValue(); + } catch(Win32Exception e) { + err = e; + throw err; // re-throw so finally block executed } finally { - - if(openedAccessToken != null && openedAccessToken.getValue() != null) { - Kernel32.INSTANCE.CloseHandle(openedAccessToken.getValue()); + try { + Kernel32Util.closeHandleRefs(openedAccessToken, duplicatedToken); + } catch(Win32Exception e) { + if (err == null) { + err = e; + } else { + err.addSuppressed(e); + } } - if(duplicatedToken != null && duplicatedToken.getValue() != null) { - Kernel32.INSTANCE.CloseHandle(duplicatedToken.getValue()); + if (securityDescriptorMemoryPointer != null) { + securityDescriptorMemoryPointer.clear(); } - if(securityDescriptorMemoryPointer != null) { - securityDescriptorMemoryPointer.clear(); + if (err != null) { + throw err; } } - - return hasAccess; } /** diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java b/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java index 76c8b10d12..a2156ee3f3 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java @@ -735,14 +735,15 @@ boolean DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, int dwDesiredAccess, boolean bInheritHandle, int dwOptions); /** - * The CloseHandle function closes an open object handle. + * Closes an open object handle. * * @param hObject * Handle to an open object. This parameter can be a pseudo * handle or INVALID_HANDLE_VALUE. * @return If the function succeeds, the return value is nonzero. If the * function fails, the return value is zero. To get extended error - * information, call GetLastError. + * information, call {@code GetLastError}. + * @see CloseHandle */ boolean CloseHandle(HANDLE hObject); diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java b/contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java index 93ea3ac7b7..48ce6527ca 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java @@ -80,6 +80,90 @@ public static void freeGlobalMemory(Pointer ptr) { } } + /** + * Closes all referenced handles. If an exception is thrown for + * a specific handle, then it is accumulated until all + * handles have been closed. If more than one exception occurs, + * then it is added as a suppressed exception to the first one. + * Once closed all handles, the accumulated exception (if any) is thrown + * + * @param refs The references to close + * @see #closeHandleRef(HANDLEByReference) + */ + public static void closeHandleRefs(HANDLEByReference... refs) { + Win32Exception err = null; + for (HANDLEByReference r : refs) { + try { + closeHandleRef(r); + } catch(Win32Exception e) { + if (err == null) { + err = e; + } else { + err.addSuppressed(e); + } + } + } + + if (err != null) { + throw err; + } + } + /** + * Closes the handle in the reference + * + * @param ref The handle reference - ignored if {@code null} + * @see #closeHandle(HANDLE) + */ + public static void closeHandleRef(HANDLEByReference ref) { + closeHandle((ref == null) ? null : ref.getValue()); + } + + /** + * Invokes {@link #closeHandle(HANDLE)} on each handle. If an exception + * is thrown for a specific handle, then it is accumulated until all + * handles have been closed. If more than one exception occurs, then it + * is added as a suppressed exception to the first one. Once closed all + * handles, the accumulated exception (if any) is thrown + * + * @param handles The handles to be closed + * @see Throwable#getSuppressed() + */ + public static void closeHandles(HANDLE... handles) { + Win32Exception err = null; + for (HANDLE h : handles) { + try { + closeHandle(h); + } catch(Win32Exception e) { + if (err == null) { + err = e; + } else { + err.addSuppressed(e); + } + } + } + + if (err != null) { + throw err; + } + } + + /** + * Invokes {@link Kernel32#CloseHandle(HANDLE)} and checks the success code. + * If not successful, then throws a {@link Win32Exception} with the + * {@code GetLastError} value + * + * @param h The handle to be closed - ignored if {@code null} + */ + public static void closeHandle(HANDLE h) { + if (h == null) { + return; + } + + if (!Kernel32.INSTANCE.CloseHandle(h)) { + throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); + } + } + /** * Format a message from the value obtained from * {@link Kernel32#GetLastError()} or {@link Native#getLastError()}. @@ -220,6 +304,7 @@ public static int getFileType(String fileName) throws FileNotFoundException { } HANDLE hFile = null; + Win32Exception err = null; try { hFile = Kernel32.INSTANCE.CreateFile(fileName, WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), @@ -232,25 +317,36 @@ public static int getFileType(String fileName) throws FileNotFoundException { int type = Kernel32.INSTANCE.GetFileType(hFile); switch (type) { - case WinNT.FILE_TYPE_UNKNOWN: - int err = Kernel32.INSTANCE.GetLastError(); - switch (err) { - case WinError.NO_ERROR: - break; - default: - throw new Win32Exception(err); - } + case WinNT.FILE_TYPE_UNKNOWN: + int rc = Kernel32.INSTANCE.GetLastError(); + switch (rc) { + case WinError.NO_ERROR: + break; + default: + throw new Win32Exception(rc); + } // fall-thru default: return type; } + } catch(Win32Exception e) { + err = e; + throw err; // re-throw so finally block executed } finally { - if (hFile != null) { - if (!Kernel32.INSTANCE.CloseHandle(hFile)) { - throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); + try { + closeHandle(hFile); + } catch(Win32Exception e) { + if (err == null) { + err = e; + } else { + err.addSuppressed(e); } } + + if (err != null) { + throw err; + } } } @@ -942,16 +1038,17 @@ public static List getModules(int processID) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } - List modules = new ArrayList(); Win32Exception we = null; try { Tlhelp32.MODULEENTRY32W first = new Tlhelp32.MODULEENTRY32W(); - modules.add(first); if (!Kernel32.INSTANCE.Module32FirstW(snapshot, first)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } + List modules = new ArrayList(); + modules.add(first); + Tlhelp32.MODULEENTRY32W next = new Tlhelp32.MODULEENTRY32W(); while (Kernel32.INSTANCE.Module32NextW(snapshot, next)) { modules.add(next); @@ -965,23 +1062,25 @@ public static List getModules(int processID) { if (lastError != W32Errors.ERROR_SUCCESS && lastError != W32Errors.ERROR_NO_MORE_FILES) { throw new Win32Exception(lastError); } + + return modules; } catch (Win32Exception e) { we = e; + throw we; // re-throw so finally block is executed } finally { - if (snapshot != null) { - if (!Kernel32.INSTANCE.CloseHandle(snapshot)) { - Win32Exception e = new Win32Exception(Kernel32.INSTANCE.GetLastError()); - if (we != null) { - e.addSuppressed(we); - } + try { + closeHandle(snapshot); + } catch(Win32Exception e) { + if (we == null) { we = e; + } else { + we.addSuppressed(e); } } - } - if (we != null) { - throw we; + if (we != null) { + throw we; + } } - return modules; } } diff --git a/contrib/platform/src/com/sun/jna/platform/win32/W32FileMonitor.java b/contrib/platform/src/com/sun/jna/platform/win32/W32FileMonitor.java index fc9eddba0c..4ad1cbe442 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/W32FileMonitor.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/W32FileMonitor.java @@ -1,10 +1,10 @@ /* Copyright (c) 2007 Timothy Wall, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU @@ -27,9 +27,9 @@ import com.sun.jna.ptr.PointerByReference; public class W32FileMonitor extends FileMonitor { - + private static final int BUFFER_SIZE = 4096; - + private class FileInfo { public final File file; public final HANDLE handle; @@ -50,7 +50,7 @@ public FileInfo(File f, HANDLE h, int mask, boolean recurse) { private final Map fileMap = new HashMap(); private final Map handleMap = new HashMap(); private boolean disposing = false; - + private void handleChanges(FileInfo finfo) throws IOException { Kernel32 klib = Kernel32.INSTANCE; FILE_NOTIFY_INFORMATION fni = finfo.info; @@ -63,51 +63,51 @@ private void handleChanges(FileInfo finfo) throws IOException { case 0: break; case WinNT.FILE_ACTION_MODIFIED: - event = new FileEvent(file, FILE_MODIFIED); + event = new FileEvent(file, FILE_MODIFIED); break; case WinNT.FILE_ACTION_ADDED: - event = new FileEvent(file, FILE_CREATED); + event = new FileEvent(file, FILE_CREATED); break; case WinNT.FILE_ACTION_REMOVED: - event = new FileEvent(file, FILE_DELETED); + event = new FileEvent(file, FILE_DELETED); break; case WinNT.FILE_ACTION_RENAMED_OLD_NAME: - event = new FileEvent(file, FILE_NAME_CHANGED_OLD); + event = new FileEvent(file, FILE_NAME_CHANGED_OLD); break; case WinNT.FILE_ACTION_RENAMED_NEW_NAME: - event = new FileEvent(file, FILE_NAME_CHANGED_NEW); + event = new FileEvent(file, FILE_NAME_CHANGED_NEW); break; default: // TODO: other actions... System.err.println("Unrecognized file action '" + fni.Action + "'"); } - + if (event != null) { notify(event); } - + fni = fni.next(); } while (fni != null); - + // trigger the next read if (!finfo.file.exists()) { unwatch(finfo.file); return; } - - if (!klib.ReadDirectoryChangesW(finfo.handle, finfo.info, - finfo.info.size(), finfo.recursive, finfo.notifyMask, - finfo.infoLength, finfo.overlapped, null)) { + + if (!klib.ReadDirectoryChangesW(finfo.handle, finfo.info, + finfo.info.size(), finfo.recursive, finfo.notifyMask, + finfo.infoLength, finfo.overlapped, null)) { if (! disposing) { int err = klib.GetLastError(); throw new IOException("ReadDirectoryChangesW failed on " - + finfo.file + ": '" + + finfo.file + ": '" + Kernel32Util.formatMessageFromLastErrorCode(err) + "' (" + err + ")"); } } } - + private FileInfo waitForChange() { IntByReference rcount = new IntByReference(); ULONG_PTRByReference rkey = new ULONG_PTRByReference(); @@ -115,11 +115,11 @@ private FileInfo waitForChange() { if (! Kernel32.INSTANCE.GetQueuedCompletionStatus(port, rcount, rkey, roverlap, WinBase.INFINITE)) { return null; } - synchronized (this) { + synchronized (this) { return handleMap.get(new HANDLE(rkey.getValue().toPointer())); } } - + private int convertMask(int mask) { int result = 0; if ((mask & FILE_CREATED) != 0) { @@ -151,6 +151,7 @@ private int convertMask(int mask) { private static int watcherThreadID; + @Override protected synchronized void watch(File file, int eventMask, boolean recursive) throws IOException { File dir = file; if (!dir.isDirectory()) { @@ -169,12 +170,12 @@ protected synchronized void watch(File file, int eventMask, boolean recursive) t | WinNT.FILE_SHARE_WRITE | WinNT.FILE_SHARE_DELETE; int flags = WinNT.FILE_FLAG_BACKUP_SEMANTICS | WinNT.FILE_FLAG_OVERLAPPED; - HANDLE handle = klib.CreateFile(file.getAbsolutePath(), + HANDLE handle = klib.CreateFile(file.getAbsolutePath(), WinNT.FILE_LIST_DIRECTORY, mask, null, WinNT.OPEN_EXISTING, flags, null); if (WinBase.INVALID_HANDLE_VALUE.equals(handle)) { - throw new IOException("Unable to open " + file + " (" + throw new IOException("Unable to open " + file + " (" + klib.GetLastError() + ")"); } int notifyMask = convertMask(eventMask); @@ -188,10 +189,10 @@ protected synchronized void watch(File file, int eventMask, boolean recursive) t + "for " + file + " (" + klib.GetLastError() + ")"); } - // TODO: use FileIOCompletionRoutine callback method instead of a + // TODO: use FileIOCompletionRoutine callback method instead of a // dedicated thread - if (!klib.ReadDirectoryChangesW(handle, finfo.info, finfo.info.size(), - recursive, notifyMask, finfo.infoLength, + if (!klib.ReadDirectoryChangesW(handle, finfo.info, finfo.info.size(), + recursive, notifyMask, finfo.infoLength, finfo.overlapped, null)) { int err = klib.GetLastError(); throw new IOException("ReadDirectoryChangesW failed on " @@ -201,6 +202,7 @@ protected synchronized void watch(File file, int eventMask, boolean recursive) t } if (watcher == null) { watcher = new Thread("W32 File Monitor-" + (watcherThreadID++)) { + @Override public void run() { FileInfo finfo; while (true) { @@ -214,7 +216,7 @@ public void run() { } continue; } - + try { handleChanges(finfo); } @@ -230,28 +232,30 @@ public void run() { } } + @Override protected synchronized void unwatch(File file) { FileInfo finfo = fileMap.remove(file); if (finfo != null) { handleMap.remove(finfo.handle); Kernel32 klib = Kernel32.INSTANCE; // bug: the watcher may still be processing this file - klib.CloseHandle(finfo.handle); + klib.CloseHandle(finfo.handle); // TODO check error code if failed to close } } - + + @Override public synchronized void dispose() { disposing = true; - + // unwatch any remaining files in map, allows watcher thread to exit int i = 0; for (Object[] keys = fileMap.keySet().toArray(); !fileMap.isEmpty();) { unwatch((File)keys[i++]); } - + Kernel32 klib = Kernel32.INSTANCE; klib.PostQueuedCompletionStatus(port, 0, null, null); - klib.CloseHandle(port); + klib.CloseHandle(port); // TODO check error code if failed to close port = null; watcher = null; } diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java b/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java index 3f6763536f..48a51d3195 100755 --- a/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java @@ -236,176 +236,197 @@ public void testOpenThreadTokenNoToken() { public void testOpenProcessToken() { HANDLEByReference phToken = new HANDLEByReference(); - HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, - WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); - } - - public void testOpenThreadOrProcessToken() { - HANDLEByReference phToken = new HANDLEByReference(); - HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); - if (! Advapi32.INSTANCE.OpenThreadToken(threadHandle, - WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, true, phToken)) { - assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); + try { HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); + } finally { + Kernel32Util.closeHandleRef(phToken); } - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); + } + + public void testOpenThreadOrProcessToken() { + HANDLEByReference phToken = new HANDLEByReference(); + try { + HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); + if (! Advapi32.INSTANCE.OpenThreadToken(threadHandle, + WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, true, phToken)) { + assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); + } + } finally { + Kernel32Util.closeHandleRef(phToken); + } } public void testSetThreadTokenCurrentThread() { HANDLEByReference phToken = new HANDLEByReference(); HANDLEByReference phTokenDup = new HANDLEByReference(); - HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); - // See if thread has a token. If not, must duplicate process token and set thread token using that. - if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle, - WinNT.TOKEN_IMPERSONATE | WinNT.TOKEN_QUERY, false, phToken)) { - assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); - HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE, phToken)); - assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), - WinNT.TOKEN_IMPERSONATE, - null, - WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - WinNT.TOKEN_TYPE.TokenImpersonation, - phTokenDup)); - // Null sets on current thread - assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDup.getValue())); - } - else { - //Null sets on current thread - assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phToken.getValue())); + try { + HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); + // See if thread has a token. If not, must duplicate process token and set thread token using that. + if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle, + WinNT.TOKEN_IMPERSONATE | WinNT.TOKEN_QUERY, false, phToken)) { + assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE, phToken)); + assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), + WinNT.TOKEN_IMPERSONATE, + null, + WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + WinNT.TOKEN_TYPE.TokenImpersonation, + phTokenDup)); + // Null sets on current thread + assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDup.getValue())); + } + else { + //Null sets on current thread + assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phToken.getValue())); + } + // Revert and cleanup + assertTrue(Advapi32.INSTANCE.SetThreadToken(null, null)); + } finally { + Kernel32Util.closeHandleRefs(phToken, phTokenDup); } - // Revert and cleanup - assertTrue(Advapi32.INSTANCE.SetThreadToken(null, null)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); - if (phTokenDup.getValue() != null) - assertTrue(Kernel32.INSTANCE.CloseHandle(phTokenDup.getValue())); } public void testSetThreadTokenThisThread() { HANDLEByReference phToken = new HANDLEByReference(); HANDLEByReference phTokenDup = new HANDLEByReference(); - HANDLEByReference pthreadHandle = new HANDLEByReference(); - pthreadHandle.setValue(Kernel32.INSTANCE.GetCurrentThread()); - // See if thread has a token. If not, must duplicate process token and set thread token using that. - if (!Advapi32.INSTANCE.OpenThreadToken(pthreadHandle.getValue(), - WinNT.TOKEN_IMPERSONATE | WinNT.TOKEN_QUERY, false, phToken)) { - assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); - HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, - WinNT.TOKEN_DUPLICATE, phToken)); - assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), - WinNT.TOKEN_IMPERSONATE, - null, - WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - WinNT.TOKEN_TYPE.TokenImpersonation, - phTokenDup)); - // Use HANDLEByReference on this thread to test, should be good enough for API compatibility. - assertTrue(Advapi32.INSTANCE.SetThreadToken(pthreadHandle, phTokenDup.getValue())); - } - else { - // Use HANDLEByReference on this thread to test, should be good enough for API compatibility. - assertTrue(Advapi32.INSTANCE.SetThreadToken(pthreadHandle, phToken.getValue())); + try { + HANDLEByReference pthreadHandle = new HANDLEByReference(); + pthreadHandle.setValue(Kernel32.INSTANCE.GetCurrentThread()); + // See if thread has a token. If not, must duplicate process token and set thread token using that. + if (!Advapi32.INSTANCE.OpenThreadToken(pthreadHandle.getValue(), + WinNT.TOKEN_IMPERSONATE | WinNT.TOKEN_QUERY, false, phToken)) { + assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + WinNT.TOKEN_DUPLICATE, phToken)); + assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), + WinNT.TOKEN_IMPERSONATE, + null, + WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + WinNT.TOKEN_TYPE.TokenImpersonation, + phTokenDup)); + // Use HANDLEByReference on this thread to test, should be good enough for API compatibility. + assertTrue(Advapi32.INSTANCE.SetThreadToken(pthreadHandle, phTokenDup.getValue())); + } + else { + // Use HANDLEByReference on this thread to test, should be good enough for API compatibility. + assertTrue(Advapi32.INSTANCE.SetThreadToken(pthreadHandle, phToken.getValue())); + } + // Revert and cleanup + assertTrue(Advapi32.INSTANCE.SetThreadToken(null, null)); + } finally { + Kernel32Util.closeHandleRefs(phToken, phTokenDup); } - // Revert and cleanup - assertTrue(Advapi32.INSTANCE.SetThreadToken(null, null)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); - if (phTokenDup.getValue() != null) - assertTrue(Kernel32.INSTANCE.CloseHandle(phTokenDup.getValue())); } public void testDuplicateToken() { HANDLEByReference phToken = new HANDLEByReference(); HANDLEByReference phTokenDup = new HANDLEByReference(); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, - WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); - assertTrue(Advapi32.INSTANCE.DuplicateToken(phToken.getValue(), - WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, phTokenDup)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phTokenDup.getValue())); - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); + try { + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); + assertTrue(Advapi32.INSTANCE.DuplicateToken(phToken.getValue(), + WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, phTokenDup)); + } finally { + Kernel32Util.closeHandleRefs(phTokenDup, phToken); + } } public void testDuplicateTokenEx() { HANDLEByReference hExistingToken = new HANDLEByReference(); HANDLEByReference phNewToken = new HANDLEByReference(); - HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, - WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, hExistingToken)); - assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(hExistingToken.getValue(), - WinNT.GENERIC_READ, null, SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous, - TOKEN_TYPE.TokenPrimary, phNewToken)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phNewToken.getValue())); - assertTrue(Kernel32.INSTANCE.CloseHandle(hExistingToken.getValue())); + try { + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, hExistingToken)); + assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(hExistingToken.getValue(), + WinNT.GENERIC_READ, null, SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous, + TOKEN_TYPE.TokenPrimary, phNewToken)); + } finally { + Kernel32Util.closeHandleRefs(phNewToken, hExistingToken); + } } public void testGetTokenOwnerInformation() { HANDLEByReference phToken = new HANDLEByReference(); - HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, - WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); - IntByReference tokenInformationLength = new IntByReference(); - assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenOwner, null, 0, tokenInformationLength)); - assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); - WinNT.TOKEN_OWNER owner = new WinNT.TOKEN_OWNER(tokenInformationLength.getValue()); - assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenOwner, owner, - tokenInformationLength.getValue(), tokenInformationLength)); - assertTrue(tokenInformationLength.getValue() > 0); - assertTrue(Advapi32.INSTANCE.IsValidSid(owner.Owner)); - int sidLength = Advapi32.INSTANCE.GetLengthSid(owner.Owner); - assertTrue(sidLength < tokenInformationLength.getValue()); - assertTrue(sidLength > 0); - // System.out.println(Advapi32Util.convertSidToStringSid(owner.Owner)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); + try { + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); + IntByReference tokenInformationLength = new IntByReference(); + assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenOwner, null, 0, tokenInformationLength)); + assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); + WinNT.TOKEN_OWNER owner = new WinNT.TOKEN_OWNER(tokenInformationLength.getValue()); + assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenOwner, owner, + tokenInformationLength.getValue(), tokenInformationLength)); + assertTrue(tokenInformationLength.getValue() > 0); + assertTrue(Advapi32.INSTANCE.IsValidSid(owner.Owner)); + int sidLength = Advapi32.INSTANCE.GetLengthSid(owner.Owner); + assertTrue(sidLength < tokenInformationLength.getValue()); + assertTrue(sidLength > 0); + // System.out.println(Advapi32Util.convertSidToStringSid(owner.Owner)); + } finally { + Kernel32Util.closeHandleRef(phToken); + } } public void testGetTokenUserInformation() { HANDLEByReference phToken = new HANDLEByReference(); - HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, - WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); - IntByReference tokenInformationLength = new IntByReference(); - assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenUser, null, 0, tokenInformationLength)); - assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); - WinNT.TOKEN_USER user = new WinNT.TOKEN_USER(tokenInformationLength.getValue()); - assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user, - tokenInformationLength.getValue(), tokenInformationLength)); - assertTrue(tokenInformationLength.getValue() > 0); - assertTrue(Advapi32.INSTANCE.IsValidSid(user.User.Sid)); - int sidLength = Advapi32.INSTANCE.GetLengthSid(user.User.Sid); - assertTrue(sidLength > 0); - assertTrue(sidLength < tokenInformationLength.getValue()); - // System.out.println(Advapi32Util.convertSidToStringSid(user.User.Sid)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); + try { + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); + IntByReference tokenInformationLength = new IntByReference(); + assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenUser, null, 0, tokenInformationLength)); + assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); + WinNT.TOKEN_USER user = new WinNT.TOKEN_USER(tokenInformationLength.getValue()); + assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user, + tokenInformationLength.getValue(), tokenInformationLength)); + assertTrue(tokenInformationLength.getValue() > 0); + assertTrue(Advapi32.INSTANCE.IsValidSid(user.User.Sid)); + int sidLength = Advapi32.INSTANCE.GetLengthSid(user.User.Sid); + assertTrue(sidLength > 0); + assertTrue(sidLength < tokenInformationLength.getValue()); + // System.out.println(Advapi32Util.convertSidToStringSid(user.User.Sid)); + } finally { + Kernel32Util.closeHandleRef(phToken); + } } public void testGetTokenGroupsInformation() { HANDLEByReference phToken = new HANDLEByReference(); - HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, - WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); - IntByReference tokenInformationLength = new IntByReference(); - assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, null, 0, tokenInformationLength)); - assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); - WinNT.TOKEN_GROUPS groups = new WinNT.TOKEN_GROUPS(tokenInformationLength.getValue()); - assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, groups, - tokenInformationLength.getValue(), tokenInformationLength)); - assertTrue(tokenInformationLength.getValue() > 0); - assertTrue(groups.GroupCount > 0); - for (SID_AND_ATTRIBUTES sidAndAttribute : groups.getGroups()) { - assertTrue(Advapi32.INSTANCE.IsValidSid(sidAndAttribute.Sid)); - // System.out.println(Advapi32Util.convertSidToStringSid(sidAndAttribute.Sid)); + try { + HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); + IntByReference tokenInformationLength = new IntByReference(); + assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, null, 0, tokenInformationLength)); + assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); + WinNT.TOKEN_GROUPS groups = new WinNT.TOKEN_GROUPS(tokenInformationLength.getValue()); + assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, groups, + tokenInformationLength.getValue(), tokenInformationLength)); + assertTrue(tokenInformationLength.getValue() > 0); + assertTrue(groups.GroupCount > 0); + for (SID_AND_ATTRIBUTES sidAndAttribute : groups.getGroups()) { + assertTrue(Advapi32.INSTANCE.IsValidSid(sidAndAttribute.Sid)); + // System.out.println(Advapi32Util.convertSidToStringSid(sidAndAttribute.Sid)); + } + } finally { + Kernel32Util.closeHandleRef(phToken); } - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); } public void testImpersonateLoggedOnUser() { @@ -426,8 +447,9 @@ public void testImpersonateLoggedOnUser() { assertTrue(Advapi32.INSTANCE.ImpersonateLoggedOnUser(phUser.getValue())); assertTrue(Advapi32.INSTANCE.RevertToSelf()); } finally { - if (phUser.getValue() != WinBase.INVALID_HANDLE_VALUE) { - Kernel32.INSTANCE.CloseHandle(phUser.getValue()); + HANDLE hUser = phUser.getValue(); + if (!WinBase.INVALID_HANDLE_VALUE.equals(hUser)) { + Kernel32Util.closeHandle(hUser); } } } finally { @@ -916,12 +938,14 @@ public void testCreateProcessAsUser() { HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, hToken)); - - assertFalse(Advapi32.INSTANCE.CreateProcessAsUser(hToken.getValue(), null, "InvalidCmdLine.jna", - null, null, false, 0, null, null, new WinBase.STARTUPINFO(), - new WinBase.PROCESS_INFORMATION())); - assertEquals(W32Errors.ERROR_FILE_NOT_FOUND, Kernel32.INSTANCE.GetLastError()); - assertTrue(Kernel32.INSTANCE.CloseHandle(hToken.getValue())); + try { + assertFalse(Advapi32.INSTANCE.CreateProcessAsUser(hToken.getValue(), null, "InvalidCmdLine.jna", + null, null, false, 0, null, null, new WinBase.STARTUPINFO(), + new WinBase.PROCESS_INFORMATION())); + assertEquals(W32Errors.ERROR_FILE_NOT_FOUND, Kernel32.INSTANCE.GetLastError()); + } finally { + Kernel32Util.closeHandleRef(hToken); + } } /** @@ -948,27 +972,30 @@ public void testAdjustTokenPrivileges() { assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES | WinNT.TOKEN_QUERY, hToken)); - // Find an already enabled privilege - TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES(1024); - IntByReference returnLength = new IntByReference(); - assertTrue(Advapi32.INSTANCE.GetTokenInformation(hToken.getValue(), WinNT.TOKEN_INFORMATION_CLASS.TokenPrivileges, - tp, tp.size(), returnLength)); - assertTrue(tp.PrivilegeCount.intValue() > 0); - - WinNT.LUID luid = null; - for (int i=0; i 0) { - luid = tp.Privileges[i].Luid; - } - } - assertTrue(luid != null); + try { + // Find an already enabled privilege + TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES(1024); + IntByReference returnLength = new IntByReference(); + assertTrue(Advapi32.INSTANCE.GetTokenInformation(hToken.getValue(), WinNT.TOKEN_INFORMATION_CLASS.TokenPrivileges, + tp, tp.size(), returnLength)); + assertTrue(tp.PrivilegeCount.intValue() > 0); + + WinNT.LUID luid = null; + for (int i=0; i 0) { + luid = tp.Privileges[i].Luid; + } + } + assertTrue(luid != null); - // Re-enable it. That should succeed. - tp = new WinNT.TOKEN_PRIVILEGES(1); - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); + // Re-enable it. That should succeed. + tp = new WinNT.TOKEN_PRIVILEGES(1); + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); - assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tp, 0, null, null)); - assertTrue(Kernel32.INSTANCE.CloseHandle(hToken.getValue())); + assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tp, 0, null, null)); + } finally { + Kernel32Util.closeHandleRef(hToken); + } } public void testImpersonateSelf() { @@ -1015,80 +1042,77 @@ public void testGetNamedSecurityInfoForFileWithSACL() throws Exception { assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_SECURITY_NAME, pLuid)); - final HANDLEByReference phToken = new HANDLEByReference(); - final HANDLEByReference phTokenDuplicate = new HANDLEByReference(); - // open thread or process token, elevate - if (!Advapi32.INSTANCE.OpenThreadToken( - Kernel32.INSTANCE.GetCurrentThread(), - TOKEN_ADJUST_PRIVILEGES, - false, - phToken)) - { - assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); - // OpenThreadToken may fail with W32Errors.ERROR_NO_TOKEN if current thread is anonymous. When this happens, - // we need to open the process token to duplicate it, then set our thread token. - assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), TOKEN_DUPLICATE, phToken)); - // Process token opened, now duplicate - assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), - TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE, - null, - SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - TOKEN_TYPE.TokenImpersonation, - phTokenDuplicate)); - // And set thread token. - assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDuplicate.getValue())); - impersontating = true; - } + HANDLEByReference phToken = new HANDLEByReference(); + HANDLEByReference phTokenDuplicate = new HANDLEByReference(); + try { + // open thread or process token, elevate + if (!Advapi32.INSTANCE.OpenThreadToken( + Kernel32.INSTANCE.GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, false, phToken)) + { + assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); + // OpenThreadToken may fail with W32Errors.ERROR_NO_TOKEN if current thread is anonymous. When this happens, + // we need to open the process token to duplicate it, then set our thread token. + assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), TOKEN_DUPLICATE, phToken)); + // Process token opened, now duplicate + assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE, + null, + SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + TOKEN_TYPE.TokenImpersonation, + phTokenDuplicate)); + // And set thread token. + assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDuplicate.getValue())); + impersontating = true; + } - // Which token to adjust depends on whether we had to impersonate or not. - HANDLE tokenAdjust = impersontating ? phTokenDuplicate.getValue() : phToken.getValue(); + // Which token to adjust depends on whether we had to impersonate or not. + HANDLE tokenAdjust = impersontating ? phTokenDuplicate.getValue() : phToken.getValue(); - WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); - assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); + WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); + assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); - int infoType = OWNER_SECURITY_INFORMATION - | GROUP_SECURITY_INFORMATION - | DACL_SECURITY_INFORMATION - | SACL_SECURITY_INFORMATION; + int infoType = OWNER_SECURITY_INFORMATION + | GROUP_SECURITY_INFORMATION + | DACL_SECURITY_INFORMATION + | SACL_SECURITY_INFORMATION; - PointerByReference ppsidOwner = new PointerByReference(); - PointerByReference ppsidGroup = new PointerByReference(); - PointerByReference ppDacl = new PointerByReference(); - PointerByReference ppSacl = new PointerByReference(); - PointerByReference ppSecurityDescriptor = new PointerByReference(); + PointerByReference ppsidOwner = new PointerByReference(); + PointerByReference ppsidGroup = new PointerByReference(); + PointerByReference ppDacl = new PointerByReference(); + PointerByReference ppSacl = new PointerByReference(); + PointerByReference ppSecurityDescriptor = new PointerByReference(); - File file = createTempFile(); - String filePath = file.getAbsolutePath(); - try { + File file = createTempFile(); + String filePath = file.getAbsolutePath(); try { - assertEquals("GetNamedSecurityInfo(" + filePath + ")", 0, - Advapi32.INSTANCE.GetNamedSecurityInfo( - filePath, - AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, - infoType, - ppsidOwner, - ppsidGroup, - ppDacl, - ppSacl, - ppSecurityDescriptor)); + try { + assertEquals("GetNamedSecurityInfo(" + filePath + ")", 0, + Advapi32.INSTANCE.GetNamedSecurityInfo( + filePath, + AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, + infoType, + ppsidOwner, + ppsidGroup, + ppDacl, + ppSacl, + ppSecurityDescriptor)); + } finally { + file.delete(); + } } finally { - file.delete(); + Kernel32Util.freeLocalMemory(ppSecurityDescriptor.getValue()); + } + if (impersontating) { + Advapi32.INSTANCE.SetThreadToken(null, null); + } + else { + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(0)); + Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null); } } finally { - Kernel32Util.freeLocalMemory(ppSecurityDescriptor.getValue()); - } - if (impersontating) { - Advapi32.INSTANCE.SetThreadToken(null, null); - } - else { - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(0)); - Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null); + Kernel32Util.closeHandleRefs(phToken, phTokenDuplicate); } - if (phToken.getValue() != null) - Kernel32.INSTANCE.CloseHandle(phToken.getValue()); - if (phTokenDuplicate.getValue() != null) - Kernel32.INSTANCE.CloseHandle(phTokenDuplicate.getValue()); } public void testSetNamedSecurityInfoForFileNoSACL() throws Exception { @@ -1135,100 +1159,100 @@ public void testSetNamedSecurityInfoForFileNoSACL() throws Exception { public void testSetNamedSecurityInfoForFileWithSACL() throws Exception { boolean impersontating = false; - final HANDLEByReference phToken = new HANDLEByReference(); - final HANDLEByReference phTokenDuplicate = new HANDLEByReference(); - // open thread or process token, elevate - if (!Advapi32.INSTANCE.OpenThreadToken( - Kernel32.INSTANCE.GetCurrentThread(), - TOKEN_ADJUST_PRIVILEGES, - false, - phToken)) - { - assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); - // OpenThreadToken may fail with W32Errors.ERROR_NO_TOKEN if current thread is anonymous. When this happens, - // we need to open the process token to duplicate it, then set our thread token. - assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), TOKEN_DUPLICATE, phToken)); - // Process token opened, now duplicate - assertTrue(Advapi32.INSTANCE.DuplicateTokenEx( - phToken.getValue(), - TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE, - null, - SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, - TOKEN_TYPE.TokenImpersonation, - phTokenDuplicate)); - // And set thread token. - assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDuplicate.getValue())); - impersontating = true; - } - - // Which token to adjust depends on whether we had to impersonate or not. - HANDLE tokenAdjust = impersontating ? phTokenDuplicate.getValue() : phToken.getValue(); - - WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); - WinNT.LUID pLuid = new WinNT.LUID(); - - assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_SECURITY_NAME, pLuid)); - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); - assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); - - assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_RESTORE_NAME, pLuid)); - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); - assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); - - // create a temp file - File file = createTempFile(); - int infoType = OWNER_SECURITY_INFORMATION - | GROUP_SECURITY_INFORMATION - | DACL_SECURITY_INFORMATION - | SACL_SECURITY_INFORMATION; - - PointerByReference ppsidOwner = new PointerByReference(); - PointerByReference ppsidGroup = new PointerByReference(); - PointerByReference ppDacl = new PointerByReference(); - PointerByReference ppSacl = new PointerByReference(); - PointerByReference ppSecurityDescriptor = new PointerByReference(); - String filePath = file.getAbsolutePath(); + HANDLEByReference phToken = new HANDLEByReference(); + HANDLEByReference phTokenDuplicate = new HANDLEByReference(); try { - try { - assertEquals("GetNamedSecurityInfo(" + filePath + ")", 0, - Advapi32.INSTANCE.GetNamedSecurityInfo( - filePath, - AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, - infoType, - ppsidOwner, - ppsidGroup, - ppDacl, - ppSacl, - ppSecurityDescriptor)); + // open thread or process token, elevate + if (!Advapi32.INSTANCE.OpenThreadToken( + Kernel32.INSTANCE.GetCurrentThread(), + TOKEN_ADJUST_PRIVILEGES, + false, + phToken)) + { + assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); + // OpenThreadToken may fail with W32Errors.ERROR_NO_TOKEN if current thread is anonymous. When this happens, + // we need to open the process token to duplicate it, then set our thread token. + assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), TOKEN_DUPLICATE, phToken)); + // Process token opened, now duplicate + assertTrue(Advapi32.INSTANCE.DuplicateTokenEx( + phToken.getValue(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE, + null, + SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, + TOKEN_TYPE.TokenImpersonation, + phTokenDuplicate)); + // And set thread token. + assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDuplicate.getValue())); + impersontating = true; + } - // Send the DACL as a SACL - assertEquals("SetNamedSecurityInfo(" + filePath + ")", 0, - Advapi32.INSTANCE.SetNamedSecurityInfo( - filePath, - AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, - infoType, - ppsidOwner.getValue(), - ppsidGroup.getValue(), - ppDacl.getValue(), - ppDacl.getValue())); + // Which token to adjust depends on whether we had to impersonate or not. + HANDLE tokenAdjust = impersontating ? phTokenDuplicate.getValue() : phToken.getValue(); + + WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); + WinNT.LUID pLuid = new WinNT.LUID(); + + assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_SECURITY_NAME, pLuid)); + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); + assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); + + assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_RESTORE_NAME, pLuid)); + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); + assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); + + // create a temp file + File file = createTempFile(); + int infoType = OWNER_SECURITY_INFORMATION + | GROUP_SECURITY_INFORMATION + | DACL_SECURITY_INFORMATION + | SACL_SECURITY_INFORMATION; + + PointerByReference ppsidOwner = new PointerByReference(); + PointerByReference ppsidGroup = new PointerByReference(); + PointerByReference ppDacl = new PointerByReference(); + PointerByReference ppSacl = new PointerByReference(); + PointerByReference ppSecurityDescriptor = new PointerByReference(); + String filePath = file.getAbsolutePath(); + try { + try { + assertEquals("GetNamedSecurityInfo(" + filePath + ")", 0, + Advapi32.INSTANCE.GetNamedSecurityInfo( + filePath, + AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, + infoType, + ppsidOwner, + ppsidGroup, + ppDacl, + ppSacl, + ppSecurityDescriptor)); + + // Send the DACL as a SACL + assertEquals("SetNamedSecurityInfo(" + filePath + ")", 0, + Advapi32.INSTANCE.SetNamedSecurityInfo( + filePath, + AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, + infoType, + ppsidOwner.getValue(), + ppsidGroup.getValue(), + ppDacl.getValue(), + ppDacl.getValue())); + } finally { + file.delete(); + } } finally { - file.delete(); + Kernel32Util.freeLocalMemory(ppSecurityDescriptor.getValue()); } - } finally { - Kernel32Util.freeLocalMemory(ppSecurityDescriptor.getValue()); - } - if (impersontating) { - assertTrue("SetThreadToken", Advapi32.INSTANCE.SetThreadToken(null, null)); - } - else { - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(0)); - assertTrue("AdjustTokenPrivileges", Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); + if (impersontating) { + assertTrue("SetThreadToken", Advapi32.INSTANCE.SetThreadToken(null, null)); + } + else { + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(0)); + assertTrue("AdjustTokenPrivileges", Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); + } + } finally { + Kernel32Util.closeHandleRefs(phToken, phTokenDuplicate); } - if (phToken.getValue() != null) - Kernel32.INSTANCE.CloseHandle(phToken.getValue()); - if (phTokenDuplicate.getValue() != null) - Kernel32.INSTANCE.CloseHandle(phTokenDuplicate.getValue()); } public void testGetSecurityDescriptorLength() throws Exception { diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Advapi32UtilTest.java b/contrib/platform/test/com/sun/jna/platform/win32/Advapi32UtilTest.java index 0aa0aa6d3f..f6488d7105 100755 --- a/contrib/platform/test/com/sun/jna/platform/win32/Advapi32UtilTest.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Advapi32UtilTest.java @@ -1,28 +1,31 @@ /* Copyright (c) 2010 Daniel Doubrovkine, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna.platform.win32; +import static com.sun.jna.platform.win32.WinBase.FILE_DIR_DISALOWED; +import static com.sun.jna.platform.win32.WinBase.FILE_ENCRYPTABLE; +import static com.sun.jna.platform.win32.WinBase.FILE_IS_ENCRYPTED; + import java.io.File; import java.io.FileWriter; import java.util.Map; import java.util.TreeMap; -import junit.framework.TestCase; - import com.sun.jna.platform.win32.Advapi32Util.Account; import com.sun.jna.platform.win32.Advapi32Util.EventLogIterator; import com.sun.jna.platform.win32.Advapi32Util.EventLogRecord; import com.sun.jna.platform.win32.LMAccess.USER_INFO_1; +import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.platform.win32.WinNT.HANDLEByReference; import com.sun.jna.platform.win32.WinNT.PSID; import com.sun.jna.platform.win32.WinNT.SECURITY_DESCRIPTOR_RELATIVE; @@ -31,7 +34,7 @@ import com.sun.jna.platform.win32.WinReg.HKEY; import com.sun.jna.platform.win32.WinReg.HKEYByReference; -import static com.sun.jna.platform.win32.WinBase.*; +import junit.framework.TestCase; /** * @author dblock[at]dblock[dot]org @@ -42,17 +45,17 @@ public static void main(String[] args) { junit.textui.TestRunner.run(Advapi32UtilTest.class); String currentUserName = Advapi32Util.getUserName(); System.out.println("GetUserName: " + currentUserName); - + for(Account group : Advapi32Util.getCurrentUserGroups()) { System.out.println(" " + group.fqn + " [" + group.sidString + "]"); } - + Account accountByName = Advapi32Util.getAccountByName(currentUserName); System.out.println("AccountByName: " + currentUserName); System.out.println(" Fqn: " + accountByName.fqn); System.out.println(" Domain: " + accountByName.domain); System.out.println(" Sid: " + accountByName.sidString); - + Account accountBySid = Advapi32Util.getAccountBySid(new PSID(accountByName.sid)); System.out.println("AccountBySid: " + accountByName.sidString); System.out.println(" Fqn: " + accountBySid.fqn); @@ -75,13 +78,13 @@ public void testExecuteAccess() { final boolean access = Advapi32Util.accessCheck(new File(System.getProperty("java.io.tmpdir")), Advapi32Util.AccessCheckPermission.EXECUTE); assertTrue(access); } - + public void testGetUsername() { String username = Advapi32Util.getUserName(); assertTrue(username.length() > 0); } - - public void testGetAccountBySid() { + + public void testGetAccountBySid() { String accountName = Advapi32Util.getUserName(); Account currentUser = Advapi32Util.getAccountByName(accountName); Account account = Advapi32Util.getAccountBySid(new PSID(currentUser.sid)); @@ -89,23 +92,23 @@ public void testGetAccountBySid() { assertEquals(currentUser.fqn.toLowerCase(), account.fqn.toLowerCase()); assertEquals(currentUser.name.toLowerCase(), account.name.toLowerCase()); assertEquals(currentUser.domain.toLowerCase(), account.domain.toLowerCase()); - assertEquals(currentUser.sidString, account.sidString); + assertEquals(currentUser.sidString, account.sidString); } - public void testGetAccountByName() { + public void testGetAccountByName() { String accountName = Advapi32Util.getUserName(); Account account = Advapi32Util.getAccountByName(accountName); assertEquals(SID_NAME_USE.SidTypeUser, account.accountType); } - + public void testGetAccountNameFromSid() { - assertEquals("Everyone", Advapi32Util.getAccountBySid("S-1-1-0").name); + assertEquals("Everyone", Advapi32Util.getAccountBySid("S-1-1-0").name); } public void testGetAccountSidFromName() { assertEquals("S-1-1-0", Advapi32Util.getAccountByName("Everyone").sidString); } - + public void testConvertSid() { String sidString = "S-1-1-0"; // Everyone byte[] sidBytes = Advapi32Util.convertStringSidToSid(sidString); @@ -113,7 +116,7 @@ public void testConvertSid() { String convertedSidString = Advapi32Util.convertSidToStringSid(new PSID(sidBytes)); assertEquals(convertedSidString, sidString); } - + public void testGetCurrentUserGroups() { Account[] groups = Advapi32Util.getCurrentUserGroups(); assertTrue(groups.length > 0); @@ -123,7 +126,7 @@ public void testGetCurrentUserGroups() { assertTrue(group.sid.length > 0); } } - + public void testGetUserGroups() { USER_INFO_1 userInfo = new USER_INFO_1(); userInfo.usri1_name = "JNANetapi32TestUser"; @@ -137,7 +140,7 @@ public void testGetUserGroups() { HANDLEByReference phUser = new HANDLEByReference(); try { assertTrue(Advapi32.INSTANCE.LogonUser(userInfo.usri1_name.toString(), - null, userInfo.usri1_password.toString(), WinBase.LOGON32_LOGON_NETWORK, + null, userInfo.usri1_password.toString(), WinBase.LOGON32_LOGON_NETWORK, WinBase.LOGON32_PROVIDER_DEFAULT, phUser)); Account[] groups = Advapi32Util.getTokenGroups(phUser.getValue()); assertTrue(groups.length > 0); @@ -147,17 +150,18 @@ public void testGetUserGroups() { assertTrue(group.sid.length > 0); } } finally { - if (phUser.getValue() != WinBase.INVALID_HANDLE_VALUE) { - Kernel32.INSTANCE.CloseHandle(phUser.getValue()); - } + HANDLE hUser = phUser.getValue(); + if (!WinBase.INVALID_HANDLE_VALUE.equals(hUser)) { + Kernel32Util.closeHandle(hUser); + } } } finally { assertEquals("Error in NetUserDel", LMErr.NERR_Success, - Netapi32.INSTANCE.NetUserDel(null, userInfo.usri1_name.toString())); + Netapi32.INSTANCE.NetUserDel(null, userInfo.usri1_name.toString())); } } - + public void testGetUserAccount() { USER_INFO_1 userInfo = new USER_INFO_1(); userInfo.usri1_name = "JNANetapi32TestUser"; @@ -171,47 +175,47 @@ public void testGetUserAccount() { HANDLEByReference phUser = new HANDLEByReference(); try { assertTrue(Advapi32.INSTANCE.LogonUser(userInfo.usri1_name.toString(), - null, userInfo.usri1_password.toString(), WinBase.LOGON32_LOGON_NETWORK, + null, userInfo.usri1_password.toString(), WinBase.LOGON32_LOGON_NETWORK, WinBase.LOGON32_PROVIDER_DEFAULT, phUser)); Advapi32Util.Account account = Advapi32Util.getTokenAccount(phUser.getValue()); assertTrue(account.name.length() > 0); assertEquals(userInfo.usri1_name.toString(), account.name); } finally { - if (phUser.getValue() != WinBase.INVALID_HANDLE_VALUE) { - Kernel32.INSTANCE.CloseHandle(phUser.getValue()); + HANDLE hUser = phUser.getValue(); + if (!WinBase.INVALID_HANDLE_VALUE.equals(hUser)) { + Kernel32Util.closeHandle(hUser); } } } finally { - assertEquals(LMErr.NERR_Success, Netapi32.INSTANCE.NetUserDel( - null, userInfo.usri1_name.toString())); + assertEquals(LMErr.NERR_Success, Netapi32.INSTANCE.NetUserDel(null, userInfo.usri1_name.toString())); } - } - + } + public void testRegistryKeyExists() { - assertTrue(Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, + assertTrue(Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, "")); - assertTrue(Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, + assertTrue(Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, "Software\\Microsoft")); - assertFalse(Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, + assertFalse(Advapi32Util.registryKeyExists(WinReg.HKEY_LOCAL_MACHINE, "KeyDoesNotExist\\SubKeyDoesNotExist")); } - + public void testRegistryValueExists() { - assertFalse(Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, + assertFalse(Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, "Software\\Microsoft", "")); - assertFalse(Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, + assertFalse(Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, "Software\\Microsoft", "KeyDoesNotExist")); - assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, + assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control", "SystemBootDevice")); - } - + } + public void testRegistryCreateDeleteKey() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); assertTrue(Advapi32Util.registryKeyExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA")); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); assertFalse(Advapi32Util.registryKeyExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA")); } - + public void testRegistryCreateKeyDisposition() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); @@ -225,47 +229,47 @@ public void testRegistryDeleteValue() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registrySetIntValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue", 42); assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue")); - Advapi32Util.registryDeleteValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue"); + Advapi32Util.registryDeleteValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue"); assertFalse(Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue")); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } - + public void testRegistrySetGetIntValue() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registrySetIntValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue", 42); - assertEquals(42, Advapi32Util.registryGetIntValue(WinReg.HKEY_CURRENT_USER, + assertEquals(42, Advapi32Util.registryGetIntValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue")); assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "IntValue")); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } - + public void testRegistrySetGetLongValue() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registrySetLongValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "LongValue", 1234L); - assertEquals(1234L, Advapi32Util.registryGetLongValue(WinReg.HKEY_CURRENT_USER, + assertEquals(1234L, Advapi32Util.registryGetLongValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "LongValue")); assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "LongValue")); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } - + public void testRegistrySetGetStringValue() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "StringValue", "Hello World"); - assertEquals("Hello World", Advapi32Util.registryGetStringValue(WinReg.HKEY_CURRENT_USER, + assertEquals("Hello World", Advapi32Util.registryGetStringValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "StringValue")); assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "StringValue")); - Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); + Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } public void testRegistrySetGetExpandableStringValue() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registrySetExpandableStringValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "StringValue", "Temp is %TEMP%"); - assertEquals("Temp is %TEMP%", Advapi32Util.registryGetExpandableStringValue(WinReg.HKEY_CURRENT_USER, + assertEquals("Temp is %TEMP%", Advapi32Util.registryGetExpandableStringValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "StringValue")); assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "StringValue")); - Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); + Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } - + public void testRegistrySetGetStringArray() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); String[] dataWritten = { "Hello", "World" }; @@ -288,14 +292,14 @@ public void testRegistrySetGetBinaryValue() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registrySetBinaryValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "BinaryValue", data); byte[] read = Advapi32Util.registryGetBinaryValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "BinaryValue"); - assertEquals(data.length, read.length); + assertEquals(data.length, read.length); for(int i = 0; i < data.length; i++) { assertEquals(data[i], read[i]); } assertTrue(Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "BinaryValue")); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } - + public void testRegistryGetKeys() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "Key1"); @@ -306,9 +310,9 @@ public void testRegistryGetKeys() { assertEquals(subKeys[1], "Key2"); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "Key1"); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "Key2"); - Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); + Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } - + public void testRegistryGetCloseKey() { Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "Key1"); @@ -323,14 +327,14 @@ public void testRegistryGetCloseKey() { Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "Key2"); Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } - + public void testRegistryGetValues() { String uu = new String("A" + "\\u00ea" + "\\u00f1" + "\\u00fc" + "C"); Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); Advapi32Util.registrySetIntValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "FourtyTwo" + uu, 42); Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "42" + uu, "FourtyTwo" + uu); Advapi32Util.registrySetExpandableStringValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "ExpandableString", "%TEMP%"); - byte[] dataWritten = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF }; + byte[] dataWritten = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF }; Advapi32Util.registrySetBinaryValue(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "DeadBeef", dataWritten); String[] stringsWritten = { "Hello", "World", "Hello World", uu }; Advapi32Util.registrySetStringArray(WinReg.HKEY_CURRENT_USER, "Software\\JNA", "StringArray", stringsWritten); @@ -354,7 +358,7 @@ public void testRegistryGetValues() { } stringsRead = (String[]) values.get("EmptyStringArray"); assertEquals(0, stringsRead.length); - Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); + Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "Software", "JNA"); } public void testRegistryGetEmptyValues() { @@ -396,16 +400,16 @@ private static void registrySetEmptyValue(HKEY root, String keyPath, String name } } } - - public void testIsWellKnownSid() { + + public void testIsWellKnownSid() { String everyoneString = "S-1-1-0"; - assertTrue(Advapi32Util.isWellKnownSid(everyoneString, WELL_KNOWN_SID_TYPE.WinWorldSid)); + assertTrue(Advapi32Util.isWellKnownSid(everyoneString, WELL_KNOWN_SID_TYPE.WinWorldSid)); assertFalse(Advapi32Util.isWellKnownSid(everyoneString, WELL_KNOWN_SID_TYPE.WinAccountAdministratorSid)); byte[] everyoneBytes = Advapi32Util.convertStringSidToSid(everyoneString); - assertTrue(Advapi32Util.isWellKnownSid(everyoneBytes, WELL_KNOWN_SID_TYPE.WinWorldSid)); + assertTrue(Advapi32Util.isWellKnownSid(everyoneBytes, WELL_KNOWN_SID_TYPE.WinWorldSid)); assertFalse(Advapi32Util.isWellKnownSid(everyoneBytes, WELL_KNOWN_SID_TYPE.WinAccountAdministratorSid)); } - + public void testEventLogIteratorForwards() { EventLogIterator iter = new EventLogIterator("Application"); try { @@ -418,18 +422,18 @@ public void testEventLogIteratorForwards() { assertNotNull(record.getType().name()); assertNotNull(record.getSource()); if (record.getRecord().DataLength.intValue() > 0) { - assertEquals(record.getData().length, + assertEquals(record.getData().length, record.getRecord().DataLength.intValue()); } else { assertNull(record.getData()); } if (record.getRecord().NumStrings.intValue() > 0) { - assertEquals(record.getStrings().length, + assertEquals(record.getStrings().length, record.getRecord().NumStrings.intValue()); } else { assertNull(record.getStrings()); } - + if (max-- <= 0) { break; // shorten test } @@ -444,9 +448,9 @@ public void testEventLogIteratorForwards() { iter.close(); } } - + public void testEventLogIteratorBackwards() { - EventLogIterator iter = new EventLogIterator(null, + EventLogIterator iter = new EventLogIterator(null, "Application", WinNT.EVENTLOG_BACKWARDS_READ); try { int max = 100; @@ -469,10 +473,10 @@ public void testEventLogIteratorBackwards() { iter.close(); } } - + public void testGetEnvironmentBlock() { String expected = "KEY=value\0" - + "KEY_EMPTY=\0" + + "KEY_EMPTY=\0" + "KEY_NUMBER=2\0" + "\0"; @@ -481,28 +485,28 @@ public void testGetEnvironmentBlock() { mockEnvironment.put("KEY", "value"); mockEnvironment.put("KEY_EMPTY", ""); mockEnvironment.put("KEY_NUMBER", "2"); - mockEnvironment.put("KEY_NULL", null); + mockEnvironment.put("KEY_NULL", null); String block = Advapi32Util.getEnvironmentBlock(mockEnvironment); assertEquals("Environment block must comprise key=value pairs separated by NUL characters", expected, block); } - + public void testGetFileSecurityDescriptor() throws Exception { - File file = createTempFile(); + File file = createTempFile(); SECURITY_DESCRIPTOR_RELATIVE sdr = Advapi32Util.getFileSecurityDescriptor(file, false); assertTrue(Advapi32.INSTANCE.IsValidSecurityDescriptor(sdr.getPointer())); file.delete(); } - + public void testSetFileSecurityDescriptor() throws Exception { - File file = createTempFile(); - SECURITY_DESCRIPTOR_RELATIVE sdr = Advapi32Util.getFileSecurityDescriptor(file, false); + File file = createTempFile(); + SECURITY_DESCRIPTOR_RELATIVE sdr = Advapi32Util.getFileSecurityDescriptor(file, false); Advapi32Util.setFileSecurityDescriptor(file, sdr, false, true, true, false, true, false); sdr = Advapi32Util.getFileSecurityDescriptor(file, false); - assertTrue(Advapi32.INSTANCE.IsValidSecurityDescriptor(sdr.getPointer())); + assertTrue(Advapi32.INSTANCE.IsValidSecurityDescriptor(sdr.getPointer())); file.delete(); } - + public void testEncryptFile() throws Exception { File file = createTempFile(); assertEquals(FILE_ENCRYPTABLE, Advapi32Util.fileEncryptionStatus(file)); @@ -521,7 +525,7 @@ public void testDecryptFile() throws Exception { } public void testDisableEncryption() throws Exception { - File dir = new File(System.getProperty("java.io.tmpdir") + File.separator + File dir = new File(System.getProperty("java.io.tmpdir") + File.separator + System.nanoTime()); dir.mkdir(); assertEquals(FILE_ENCRYPTABLE, Advapi32Util.fileEncryptionStatus(dir)); @@ -534,29 +538,29 @@ public void testDisableEncryption() throws Exception { } dir.delete(); } - + public void testBackupEncryptedFile() throws Exception { // backup an encrypted file File srcFile = createTempFile(); Advapi32Util.encryptFile(srcFile); - File dest = new File(System.getProperty("java.io.tmpdir") + File.separator + File dest = new File(System.getProperty("java.io.tmpdir") + File.separator + "backup" + System.nanoTime()); dest.mkdir(); Advapi32Util.backupEncryptedFile(srcFile, dest); // simple check to see if a backup file exist - File backupFile = new File(dest.getAbsolutePath() + File.separator + + File backupFile = new File(dest.getAbsolutePath() + File.separator + srcFile.getName()); assertTrue(backupFile.exists()); assertEquals(srcFile.length(), backupFile.length()); // backup an encrypted directory - File srcDir = new File(System.getProperty("java.io.tmpdir") + File.separator + File srcDir = new File(System.getProperty("java.io.tmpdir") + File.separator + System.nanoTime()); srcDir.mkdir(); Advapi32Util.encryptFile(srcDir); - + Advapi32Util.backupEncryptedFile(srcDir, dest); // Check to see if a backup directory exist @@ -576,7 +580,7 @@ public void testBackupEncryptedFile() throws Exception { } private File createTempFile() throws Exception{ - String filePath = System.getProperty("java.io.tmpdir") + System.nanoTime() + String filePath = System.getProperty("java.io.tmpdir") + System.nanoTime() + ".text"; File file = new File(filePath); file.createNewFile(); diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java index 57cbb19090..fca801832f 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java @@ -240,59 +240,68 @@ public void testGetComputerNameExSameAsGetComputerName() { public void testWaitForSingleObject() { HANDLE handle = Kernel32.INSTANCE.CreateEvent(null, false, false, null); + assertNotNull("Failed to create event: " + Kernel32.INSTANCE.GetLastError(), handle); - // handle runs into timeout since it is not triggered - // WAIT_TIMEOUT = 0x00000102 - assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForSingleObject( - handle, 1000)); - - Kernel32.INSTANCE.CloseHandle(handle); + try { + // handle runs into timeout since it is not triggered + // WAIT_TIMEOUT = 0x00000102 + assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForSingleObject(handle, 1000)); + } finally { + Kernel32Util.closeHandle(handle); + } } public void testResetEvent() { HANDLE handle = Kernel32.INSTANCE.CreateEvent(null, true, false, null); + assertNotNull("Failed to create event: " + Kernel32.INSTANCE.GetLastError(), handle); - // set the event to the signaled state - Kernel32.INSTANCE.SetEvent(handle); - - // This should return successfully - assertEquals(WinBase.WAIT_OBJECT_0, Kernel32.INSTANCE.WaitForSingleObject( - handle, 1000)); + try { + // set the event to the signaled state + Kernel32.INSTANCE.SetEvent(handle); - // now reset it to not signaled - Kernel32.INSTANCE.ResetEvent(handle); + // This should return successfully + assertEquals(WinBase.WAIT_OBJECT_0, Kernel32.INSTANCE.WaitForSingleObject( + handle, 1000)); - // handle runs into timeout since it is not triggered - // WAIT_TIMEOUT = 0x00000102 - assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForSingleObject( - handle, 1000)); + // now reset it to not signaled + Kernel32.INSTANCE.ResetEvent(handle); - Kernel32.INSTANCE.CloseHandle(handle); + // handle runs into timeout since it is not triggered + // WAIT_TIMEOUT = 0x00000102 + assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForSingleObject(handle, 1000)); + } finally { + Kernel32Util.closeHandle(handle); + } } public void testWaitForMultipleObjects(){ HANDLE[] handles = new HANDLE[2]; - - handles[0] = Kernel32.INSTANCE.CreateEvent(null, false, false, null); - handles[1] = Kernel32.INSTANCE.CreateEvent(null, false, false, null); - - // handle runs into timeout since it is not triggered - // WAIT_TIMEOUT = 0x00000102 - assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForMultipleObjects( - handles.length, handles, false, 1000)); - - Kernel32.INSTANCE.CloseHandle(handles[0]); - Kernel32.INSTANCE.CloseHandle(handles[1]); + try { + for (int index = 0; index < handles.length; index++) { + HANDLE h = Kernel32.INSTANCE.CreateEvent(null, false, false, null); + assertNotNull("Failed to create event #" + index + ": " + Kernel32.INSTANCE.GetLastError(), h); + handles[index] = h; + } + // handle runs into timeout since it is not triggered + // WAIT_TIMEOUT = 0x00000102 + assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForMultipleObjects( + handles.length, handles, false, 1000)); + } finally { + Kernel32Util.closeHandles(handles); + } // invalid Handle handles[0] = WinBase.INVALID_HANDLE_VALUE; handles[1] = Kernel32.INSTANCE.CreateEvent(null, false, false, null); + assertNotNull("Failed to create valid event: " + Kernel32.INSTANCE.GetLastError(), handles[1]); + try { + // returns WAIT_FAILED since handle is invalid + assertEquals(WinBase.WAIT_FAILED, Kernel32.INSTANCE.WaitForMultipleObjects( + handles.length, handles, false, 5000)); - // returns WAIT_FAILED since handle is invalid - assertEquals(WinBase.WAIT_FAILED, Kernel32.INSTANCE.WaitForMultipleObjects( - handles.length, handles, false, 5000)); - - Kernel32.INSTANCE.CloseHandle(handles[1]); + } finally { + Kernel32Util.closeHandle(handles[1]); + } } public void testGetCurrentThreadId() { @@ -304,7 +313,7 @@ public void testGetCurrentThread() { assertNotNull("No current thread handle", h); assertFalse("Null current thread handle", h.equals(0)); // Calling the CloseHandle function with this handle has no effect - assertTrue(Kernel32.INSTANCE.CloseHandle(h)); + Kernel32Util.closeHandle(h); } public void testOpenThread() { @@ -312,7 +321,7 @@ public void testOpenThread() { Kernel32.INSTANCE.GetCurrentThreadId()); assertNotNull(h); assertFalse(h.equals(0)); - assertTrue(Kernel32.INSTANCE.CloseHandle(h)); + Kernel32Util.closeHandle(h); } public void testGetCurrentProcessId() { @@ -324,7 +333,7 @@ public void testGetCurrentProcess() { assertNotNull("No current process handle", h); assertFalse("Null current process handle", h.equals(0)); // Calling the CloseHandle function with a pseudo handle has no effect - assertTrue(Kernel32.INSTANCE.CloseHandle(h)); + Kernel32Util.closeHandle(h); } public void testOpenProcess() { @@ -347,7 +356,7 @@ public void testQueryFullProcessImageName() { assertTrue("Failed (" + Kernel32.INSTANCE.GetLastError() + ") to query process image name", b); assertTrue("Failed to query process image name, empty path returned", lpdwSize.getValue() > 0); } finally { - assertTrue("CloseHandle", Kernel32.INSTANCE.CloseHandle(h)); + Kernel32Util.closeHandle(h); } } @@ -483,7 +492,7 @@ public void testReadFile() throws IOException { assertEquals("Mismatched read content", expected, new String(readBuffer, 0, read)); } finally { - assertTrue("Failed to close file", Kernel32.INSTANCE.CloseHandle(hFile)); + Kernel32Util.closeHandle(hFile); } } @@ -493,19 +502,22 @@ public void testSetHandleInformation() throws IOException { HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); - assertFalse(hFile == WinBase.INVALID_HANDLE_VALUE); - - assertTrue(Kernel32.INSTANCE.SetHandleInformation(hFile, WinBase.HANDLE_FLAG_PROTECT_FROM_CLOSE, 0)); - assertTrue(Kernel32.INSTANCE.CloseHandle(hFile)); + assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); + try { + assertTrue(Kernel32.INSTANCE.SetHandleInformation(hFile, WinBase.HANDLE_FLAG_PROTECT_FROM_CLOSE, 0)); + } finally { + Kernel32Util.closeHandle(hFile); + } } public void testCreatePipe() { HANDLEByReference hReadPipe = new HANDLEByReference(); HANDLEByReference hWritePipe = new HANDLEByReference(); - - assertTrue(Kernel32.INSTANCE.CreatePipe(hReadPipe, hWritePipe, null, 0)); - assertTrue(Kernel32.INSTANCE.CloseHandle(hReadPipe.getValue())); - assertTrue(Kernel32.INSTANCE.CloseHandle(hWritePipe.getValue())); + try { + assertTrue(Kernel32.INSTANCE.CreatePipe(hReadPipe, hWritePipe, null, 0)); + } finally { + Kernel32Util.closeHandleRefs(hReadPipe, hWritePipe); + } } public void testGetExitCodeProcess() { @@ -519,10 +531,13 @@ public void testTerminateProcess() throws IOException { tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); - - assertFalse(Kernel32.INSTANCE.TerminateProcess(hFile, 1)); - assertEquals(WinError.ERROR_INVALID_HANDLE, Kernel32.INSTANCE.GetLastError()); - assertTrue(Kernel32.INSTANCE.CloseHandle(hFile)); + assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); + try { + assertFalse(Kernel32.INSTANCE.TerminateProcess(hFile, 1)); + assertEquals(WinError.ERROR_INVALID_HANDLE, Kernel32.INSTANCE.GetLastError()); + } finally { + Kernel32Util.closeHandle(hFile); + } } public void testGetFileAttributes() { @@ -587,22 +602,22 @@ public void testGetSetFileTime() throws IOException { HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_WRITE, WinNT.FILE_SHARE_WRITE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); - assertFalse(hFile == WinBase.INVALID_HANDLE_VALUE); - - WinBase.FILETIME.ByReference creationTime = new WinBase.FILETIME.ByReference(); - WinBase.FILETIME.ByReference accessTime = new WinBase.FILETIME.ByReference(); - WinBase.FILETIME.ByReference modifiedTime = new WinBase.FILETIME.ByReference(); - Kernel32.INSTANCE.GetFileTime(hFile, creationTime, accessTime, modifiedTime); - - assertEquals(creationTime.toDate().getYear(), new Date().getYear()); - assertEquals(accessTime.toDate().getYear(), new Date().getYear()); - assertEquals(modifiedTime.toDate().getYear(), new Date().getYear()); - - Kernel32.INSTANCE.SetFileTime(hFile, null, null, new WinBase.FILETIME(new Date(2010, 1, 1))); + assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); + try { + WinBase.FILETIME.ByReference creationTime = new WinBase.FILETIME.ByReference(); + WinBase.FILETIME.ByReference accessTime = new WinBase.FILETIME.ByReference(); + WinBase.FILETIME.ByReference modifiedTime = new WinBase.FILETIME.ByReference(); + Kernel32.INSTANCE.GetFileTime(hFile, creationTime, accessTime, modifiedTime); - assertTrue(Kernel32.INSTANCE.CloseHandle(hFile)); + assertEquals(creationTime.toDate().getYear(), new Date().getYear()); + assertEquals(accessTime.toDate().getYear(), new Date().getYear()); + assertEquals(modifiedTime.toDate().getYear(), new Date().getYear()); - assertEquals(2010, new Date(tmp.lastModified()).getYear()); + Kernel32.INSTANCE.SetFileTime(hFile, null, null, new WinBase.FILETIME(new Date(2010, 1, 1))); + assertEquals(2010, new Date(tmp.lastModified()).getYear()); + } finally { + Kernel32Util.closeHandle(hFile); + } } public void testSetFileAttributes() throws IOException { @@ -616,23 +631,24 @@ public void testSetFileAttributes() throws IOException { } public void testGetProcessList() throws IOException { - WinNT.HANDLE processEnumHandle = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL, new WinDef.DWORD(0)); + HANDLE processEnumHandle = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL, new WinDef.DWORD(0)); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(processEnumHandle)); + try { + Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); - Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); + assertTrue(Kernel32.INSTANCE.Process32First(processEnumHandle, processEntry)); - assertTrue(Kernel32.INSTANCE.Process32First(processEnumHandle, processEntry)); + List processIdList = new ArrayList(); + processIdList.add(processEntry.th32ProcessID.longValue()); - List processIdList = new ArrayList(); - processIdList.add(processEntry.th32ProcessID.longValue()); + while (Kernel32.INSTANCE.Process32Next(processEnumHandle, processEntry)) { + processIdList.add(processEntry.th32ProcessID.longValue()); + } - while (Kernel32.INSTANCE.Process32Next(processEnumHandle, processEntry)) - { - processIdList.add(processEntry.th32ProcessID.longValue()); + assertTrue(processIdList.size() > 4); + } finally { + Kernel32Util.closeHandle(processEnumHandle); } - - assertTrue(Kernel32.INSTANCE.CloseHandle(processEnumHandle)); - assertTrue(processIdList.size() > 4); } public final void testGetPrivateProfileInt() throws IOException { @@ -848,7 +864,7 @@ public void testGetCommState() { fail("Received value of WinBase.DCB.BaudRate is not valid"); } } finally { - Kernel32.INSTANCE.CloseHandle(handleSerialPort); + Kernel32Util.closeHandle(handleSerialPort); } } } @@ -889,7 +905,7 @@ public void testSetCommState() { assertTrue(Kernel32.INSTANCE.SetCommState(handleSerialPort, lpDCB)); } finally { - Kernel32.INSTANCE.CloseHandle(handleSerialPort); + Kernel32Util.closeHandle(handleSerialPort); } } } @@ -919,7 +935,7 @@ public void testGetCommTimeouts() { lpCommTimeouts = new WinBase.COMMTIMEOUTS(); assertTrue(Kernel32.INSTANCE.GetCommTimeouts(handleSerialPort, lpCommTimeouts)); } finally { - Kernel32.INSTANCE.CloseHandle(handleSerialPort); + Kernel32Util.closeHandle(handleSerialPort); } } } @@ -965,7 +981,7 @@ public void testSetCommTimeouts() { assertTrue(Kernel32.INSTANCE.SetCommTimeouts(handleSerialPort, lpCommTimeouts)); } finally { - Kernel32.INSTANCE.CloseHandle(handleSerialPort); + Kernel32Util.closeHandle(handleSerialPort); } } } @@ -1065,28 +1081,30 @@ public void testModule32FirstW() { if (!Kernel32.INSTANCE.Module32FirstW(snapshot, first)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } + + + // not sure if this will be run against java.exe or javaw.exe but this + // check tests both + assertTrue("The first module in the current process should be java.exe or javaw.exe", first.szModule().startsWith("java")); + assertEquals("The process ID of the module ID should be our process ID", Kernel32.INSTANCE.GetCurrentProcessId(), first.th32ProcessID.intValue()); } catch (Win32Exception e) { we = e; + throw we; // re-throw so finally block is executed } finally { - if (snapshot != null) { - if (!Kernel32.INSTANCE.CloseHandle(snapshot)) { - Win32Exception e = new Win32Exception(Kernel32.INSTANCE.GetLastError()); - if (we != null) { - e.addSuppressed(we); - } + try { + Kernel32Util.closeHandle(snapshot); + } catch(Win32Exception e) { + if (we == null) { we = e; + } else { + we.addSuppressed(e); } } - } - if (we != null) { - throw we; + if (we != null) { + throw we; + } } - - // not sure if this will be run against java.exe or javaw.exe but this - // check tests both - assertTrue("The first module in the current process should be java.exe or javaw.exe", first.szModule().startsWith("java")); - assertEquals("The process ID of the module ID should be our process ID", Kernel32.INSTANCE.GetCurrentProcessId(), first.th32ProcessID.intValue()); } public void testModule32NextW() { @@ -1101,27 +1119,28 @@ public void testModule32NextW() { if (!Kernel32.INSTANCE.Module32NextW(snapshot, first)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } + + // not sure if this will be run against java.exe or javaw.exe but this + // check tests both + assertTrue("The first module in the current process should be java.exe or javaw.exe", first.szModule().startsWith("java")); + assertEquals("The process ID of the module ID should be our process ID", Kernel32.INSTANCE.GetCurrentProcessId(), first.th32ProcessID.intValue()); } catch (Win32Exception e) { we = e; + throw we; // re-throw so finally block is executed } finally { - if (snapshot != null) { - if (!Kernel32.INSTANCE.CloseHandle(snapshot)) { - Win32Exception e = new Win32Exception(Kernel32.INSTANCE.GetLastError()); - if (we != null) { - e.addSuppressed(we); - } + try { + Kernel32Util.closeHandle(snapshot); + } catch(Win32Exception e) { + if (we == null) { we = e; + } else { + we.addSuppressed(e); } } - } - if (we != null) { - throw we; + if (we != null) { + throw we; + } } - - // not sure if this will be run against java.exe or javaw.exe but this - // check tests both - assertTrue("The first module in the current process should be java.exe or javaw.exe", first.szModule().startsWith("java")); - assertEquals("The process ID of the module ID should be our process ID", Kernel32.INSTANCE.GetCurrentProcessId(), first.th32ProcessID.intValue()); } } diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32UtilTest.java b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32UtilTest.java index d6106e449b..0ecbbfbeaf 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32UtilTest.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32UtilTest.java @@ -291,7 +291,7 @@ public final void testQueryFullProcessImageName() { String name = Kernel32Util.QueryFullProcessImageName(h, 0); assertTrue("Failed to query process image name, empty path returned", name.length() > 0); } finally { - assertTrue("CloseHandle", Kernel32.INSTANCE.CloseHandle(h)); + Kernel32Util.closeHandle(h); } } diff --git a/contrib/platform/test/com/sun/jna/platform/win32/PsapiTest.java b/contrib/platform/test/com/sun/jna/platform/win32/PsapiTest.java index c77e2e9316..bd434194e7 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/PsapiTest.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/PsapiTest.java @@ -1,14 +1,14 @@ /* Copyright (c) 2015 Andreas "PAX" L\u00FCck, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna.platform.win32; @@ -31,7 +31,7 @@ /** * Applies API tests on {@link Psapi}. - * + * * @author Andreas "PAX" Lück, onkelpax-git[at]yahoo.de */ public class PsapiTest { @@ -99,7 +99,7 @@ public void testGetModuleFileNameEx() { w.dispose(); } } - + @Test public void testEnumProcessModules() { HANDLE me = null; @@ -108,7 +108,7 @@ public void testEnumProcessModules() { try { me = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_ALL_ACCESS, false, Kernel32.INSTANCE.GetCurrentProcessId()); assertTrue("Handle to my process should not be null", me != null); - + List list = new LinkedList(); HMODULE[] lphModule = new HMODULE[100 * 4]; @@ -125,23 +125,23 @@ public void testEnumProcessModules() { assertTrue("List should have at least 1 item in it.", list.size() > 0); } catch (Win32Exception e) { we = e; + throw we; // re-throw to invoke finally block } finally { - if (me != null) { - if (!Kernel32.INSTANCE.CloseHandle(me)) { - Win32Exception e = new Win32Exception(Native.getLastError()); - if (we != null) { - e.addSuppressed(we); - } + try { + Kernel32Util.closeHandle(me); + } catch(Win32Exception e) { + if (we == null) { we = e; + } else { + we.addSuppressed(e); } } + if (we != null) { + throw we; + } } - if (we != null) { - throw we; - } - } - + @Test public void testGetModuleInformation() { HANDLE me = null; @@ -150,7 +150,7 @@ public void testGetModuleInformation() { try { me = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_ALL_ACCESS, false, Kernel32.INSTANCE.GetCurrentProcessId()); assertTrue("Handle to my process should not be null", me != null); - + List list = new LinkedList(); HMODULE[] lphModule = new HMODULE[100 * 4]; @@ -165,34 +165,34 @@ public void testGetModuleInformation() { } assertTrue("List should have at least 1 item in it.", list.size() > 0); - + MODULEINFO lpmodinfo = new MODULEINFO(); - + if (!Psapi.INSTANCE.GetModuleInformation(me, list.get(0), lpmodinfo, lpmodinfo.size())) { throw new Win32Exception(Native.getLastError()); } - + assertTrue("MODULEINFO.EntryPoint should not be null.", lpmodinfo.EntryPoint != null); - + } catch (Win32Exception e) { we = e; + throw we; // re-throw to invoke finally block } finally { - if (me != null) { - if (!Kernel32.INSTANCE.CloseHandle(me)) { - Win32Exception e = new Win32Exception(Native.getLastError()); - if (we != null) { - e.addSuppressed(we); - } + try { + Kernel32Util.closeHandle(me); + } catch(Win32Exception e) { + if (we == null) { we = e; + } else { + we.addSuppressed(e); } } + if (we != null) { + throw we; + } } - if (we != null) { - throw we; - } - } - + @Test public void testGetProcessImageFileName() { HANDLE me = null; @@ -201,27 +201,27 @@ public void testGetProcessImageFileName() { try { me = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_ALL_ACCESS, false, Kernel32.INSTANCE.GetCurrentProcessId()); assertTrue("Handle to my process should not be null", me != null); - + char[] buffer = new char[256]; Psapi.INSTANCE.GetProcessImageFileName(me, buffer, 256); String path = new String(buffer); assertTrue("Image path should contain 'java' and '.exe'", path.contains("java") && path.contains(".exe")); } catch (Win32Exception e) { we = e; + throw we; // re-throw to invoke finally block } finally { - if (me != null) { - if (!Kernel32.INSTANCE.CloseHandle(me)) { - Win32Exception e = new Win32Exception(Native.getLastError()); - if (we != null) { - e.addSuppressed(we); - } + try { + Kernel32Util.closeHandle(me); + } catch(Win32Exception e) { + if (we == null) { we = e; + } else { + we.addSuppressed(e); } } + if (we != null) { + throw we; + } } - if (we != null) { - throw we; - } - } } diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Secur32Test.java b/contrib/platform/test/com/sun/jna/platform/win32/Secur32Test.java index 2af202aa52..8bf068bbed 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/Secur32Test.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Secur32Test.java @@ -1,19 +1,17 @@ /* Copyright (c) 2010 Daniel Doubrovkine, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna.platform.win32; -import junit.framework.TestCase; - import com.sun.jna.Native; import com.sun.jna.platform.win32.Sspi.CredHandle; import com.sun.jna.platform.win32.Sspi.CtxtHandle; @@ -24,6 +22,8 @@ import com.sun.jna.platform.win32.WinNT.HANDLEByReference; import com.sun.jna.ptr.IntByReference; +import junit.framework.TestCase; + /** * @author dblock[at]dblock[dot]org */ @@ -32,7 +32,7 @@ public class Secur32Test extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(Secur32Test.class); } - + public void testGetUserNameEx() { IntByReference len = new IntByReference(); Secur32.INSTANCE.GetUserNameEx( @@ -44,59 +44,59 @@ public void testGetUserNameEx() { String username = Native.toString(buffer); assertTrue(username.length() > 0); } - + public void testAcquireCredentialsHandle() { CredHandle phCredential = new CredHandle(); TimeStamp ptsExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, null, phCredential, ptsExpiry)); assertTrue(phCredential.dwLower != null); assertTrue(phCredential.dwUpper != null); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.FreeCredentialsHandle( - phCredential)); + phCredential)); } - + public void testAcquireCredentialsHandleInvalidPackage() { CredHandle phCredential = new CredHandle(); TimeStamp ptsExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_SECPKG_NOT_FOUND, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "PackageDoesntExist", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, + null, "PackageDoesntExist", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, null, phCredential, ptsExpiry)); } - + public void testInitializeSecurityContext() { CredHandle phCredential = new CredHandle(); TimeStamp ptsExpiry = new TimeStamp(); // acquire a credentials handle assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, null, phCredential, ptsExpiry)); // initialize security context CtxtHandle phNewContext = new CtxtHandle(); SecBufferDesc pbToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE); IntByReference pfContextAttr = new IntByReference(); - int rc = Secur32.INSTANCE.InitializeSecurityContext(phCredential, null, - Advapi32Util.getUserName(), Sspi.ISC_REQ_CONNECTION, 0, - Sspi.SECURITY_NATIVE_DREP, null, 0, phNewContext, pbToken, - pfContextAttr, null); + int rc = Secur32.INSTANCE.InitializeSecurityContext(phCredential, null, + Advapi32Util.getUserName(), Sspi.ISC_REQ_CONNECTION, 0, + Sspi.SECURITY_NATIVE_DREP, null, 0, phNewContext, pbToken, + pfContextAttr, null); assertTrue(rc == W32Errors.SEC_I_CONTINUE_NEEDED || rc == W32Errors.SEC_E_OK); assertTrue(phNewContext.dwLower != null); assertTrue(phNewContext.dwUpper != null); assertTrue(pbToken.pBuffers[0].getBytes().length > 0); - // release + // release assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.DeleteSecurityContext( phNewContext)); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.FreeCredentialsHandle( phCredential)); } - + public void testAcceptSecurityContext() { // client ----------- acquire outbound credential handle CredHandle phClientCredential = new CredHandle(); TimeStamp ptsClientExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, null, phClientCredential, ptsClientExpiry)); // client ----------- security context CtxtHandle phClientContext = new CtxtHandle(); @@ -105,7 +105,7 @@ public void testAcceptSecurityContext() { CredHandle phServerCredential = new CredHandle(); TimeStamp ptsServerExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_INBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_INBOUND, null, null, null, null, phServerCredential, ptsServerExpiry)); // server ----------- security context CtxtHandle phServerContext = new CtxtHandle(); @@ -119,37 +119,37 @@ public void testAcceptSecurityContext() { SecBufferDesc pbClientToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE); if (clientRc == W32Errors.SEC_I_CONTINUE_NEEDED) { // server token is empty the first time - SecBufferDesc pbServerTokenCopy = pbServerToken == null + SecBufferDesc pbServerTokenCopy = pbServerToken == null ? null : new SecBufferDesc(Sspi.SECBUFFER_TOKEN, pbServerToken.getBytes()); clientRc = Secur32.INSTANCE.InitializeSecurityContext( - phClientCredential, - phClientContext.isNull() ? null : phClientContext, - Advapi32Util.getUserName(), - Sspi.ISC_REQ_CONNECTION, - 0, - Sspi.SECURITY_NATIVE_DREP, - pbServerTokenCopy, - 0, - phClientContext, - pbClientToken, - pfClientContextAttr, - null); + phClientCredential, + phClientContext.isNull() ? null : phClientContext, + Advapi32Util.getUserName(), + Sspi.ISC_REQ_CONNECTION, + 0, + Sspi.SECURITY_NATIVE_DREP, + pbServerTokenCopy, + 0, + phClientContext, + pbClientToken, + pfClientContextAttr, + null); assertTrue(clientRc == W32Errors.SEC_I_CONTINUE_NEEDED || clientRc == W32Errors.SEC_E_OK); } // server ----------- accept security context, produce a server token if (serverRc == W32Errors.SEC_I_CONTINUE_NEEDED) { pbServerToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE); SecBufferDesc pbClientTokenByValue = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, pbClientToken.getBytes()); - serverRc = Secur32.INSTANCE.AcceptSecurityContext(phServerCredential, - phServerContext.isNull() ? null : phServerContext, + serverRc = Secur32.INSTANCE.AcceptSecurityContext(phServerCredential, + phServerContext.isNull() ? null : phServerContext, pbClientTokenByValue, - Sspi.ISC_REQ_CONNECTION, - Sspi.SECURITY_NATIVE_DREP, + Sspi.ISC_REQ_CONNECTION, + Sspi.SECURITY_NATIVE_DREP, phServerContext, - pbServerToken, - pfServerContextAttr, - ptsServerExpiry); - assertTrue(serverRc == W32Errors.SEC_I_CONTINUE_NEEDED || serverRc == W32Errors.SEC_E_OK); + pbServerToken, + pfServerContextAttr, + ptsServerExpiry); + assertTrue(serverRc == W32Errors.SEC_I_CONTINUE_NEEDED || serverRc == W32Errors.SEC_E_OK); } } while(serverRc != W32Errors.SEC_E_OK || clientRc != W32Errors.SEC_E_OK); // release server context @@ -163,13 +163,13 @@ public void testAcceptSecurityContext() { assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.FreeCredentialsHandle( phClientCredential)); } - + public void testImpersonateRevertSecurityContext() { // client ----------- acquire outbound credential handle CredHandle phClientCredential = new CredHandle(); TimeStamp ptsClientExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, null, phClientCredential, ptsClientExpiry)); // client ----------- security context CtxtHandle phClientContext = new CtxtHandle(); @@ -178,7 +178,7 @@ public void testImpersonateRevertSecurityContext() { CredHandle phServerCredential = new CredHandle(); TimeStamp ptsServerExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_INBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_INBOUND, null, null, null, null, phServerCredential, ptsServerExpiry)); // server ----------- security context CtxtHandle phServerContext = new CtxtHandle(); @@ -192,37 +192,37 @@ public void testImpersonateRevertSecurityContext() { SecBufferDesc pbClientToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE); if (clientRc == W32Errors.SEC_I_CONTINUE_NEEDED) { // server token is empty the first time - SecBufferDesc pbServerTokenCopy = pbServerToken == null + SecBufferDesc pbServerTokenCopy = pbServerToken == null ? null : new SecBufferDesc(Sspi.SECBUFFER_TOKEN, pbServerToken.getBytes()); clientRc = Secur32.INSTANCE.InitializeSecurityContext( - phClientCredential, - phClientContext.isNull() ? null : phClientContext, - Advapi32Util.getUserName(), - Sspi.ISC_REQ_CONNECTION, - 0, - Sspi.SECURITY_NATIVE_DREP, - pbServerTokenCopy, - 0, - phClientContext, - pbClientToken, - pfClientContextAttr, - null); + phClientCredential, + phClientContext.isNull() ? null : phClientContext, + Advapi32Util.getUserName(), + Sspi.ISC_REQ_CONNECTION, + 0, + Sspi.SECURITY_NATIVE_DREP, + pbServerTokenCopy, + 0, + phClientContext, + pbClientToken, + pfClientContextAttr, + null); assertTrue(clientRc == W32Errors.SEC_I_CONTINUE_NEEDED || clientRc == W32Errors.SEC_E_OK); } // server ----------- accept security context, produce a server token if (serverRc == W32Errors.SEC_I_CONTINUE_NEEDED) { pbServerToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE); SecBufferDesc pbClientTokenByValue = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, pbClientToken.getBytes()); - serverRc = Secur32.INSTANCE.AcceptSecurityContext(phServerCredential, - phServerContext.isNull() ? null : phServerContext, + serverRc = Secur32.INSTANCE.AcceptSecurityContext(phServerCredential, + phServerContext.isNull() ? null : phServerContext, pbClientTokenByValue, - Sspi.ISC_REQ_CONNECTION, - Sspi.SECURITY_NATIVE_DREP, + Sspi.ISC_REQ_CONNECTION, + Sspi.SECURITY_NATIVE_DREP, phServerContext, - pbServerToken, - pfServerContextAttr, - ptsServerExpiry); - assertTrue(serverRc == W32Errors.SEC_I_CONTINUE_NEEDED || serverRc == W32Errors.SEC_E_OK); + pbServerToken, + pfServerContextAttr, + ptsServerExpiry); + assertTrue(serverRc == W32Errors.SEC_I_CONTINUE_NEEDED || serverRc == W32Errors.SEC_E_OK); } } while(serverRc != W32Errors.SEC_E_OK || clientRc != W32Errors.SEC_E_OK); // impersonate @@ -241,14 +241,14 @@ public void testImpersonateRevertSecurityContext() { assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.FreeCredentialsHandle( phClientCredential)); } - + public void testEnumerateSecurityPackages() { IntByReference pcPackages = new IntByReference(); PSecPkgInfo.ByReference pPackageInfo = new PSecPkgInfo.ByReference(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.EnumerateSecurityPackages( pcPackages, pPackageInfo)); SecPkgInfo.ByReference[] packagesInfo = pPackageInfo.toArray( - pcPackages.getValue()); + pcPackages.getValue()); for(SecPkgInfo.ByReference packageInfo : packagesInfo) { assertTrue(packageInfo.Name.length() > 0); assertTrue(packageInfo.Comment.length() >= 0); @@ -256,13 +256,13 @@ public void testEnumerateSecurityPackages() { assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.FreeContextBuffer( pPackageInfo.getPointer())); } - + public void testQuerySecurityContextToken() { // client ----------- acquire outbound credential handle CredHandle phClientCredential = new CredHandle(); TimeStamp ptsClientExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_OUTBOUND, null, null, null, null, phClientCredential, ptsClientExpiry)); // client ----------- security context CtxtHandle phClientContext = new CtxtHandle(); @@ -271,7 +271,7 @@ public void testQuerySecurityContextToken() { CredHandle phServerCredential = new CredHandle(); TimeStamp ptsServerExpiry = new TimeStamp(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.AcquireCredentialsHandle( - null, "Negotiate", Sspi.SECPKG_CRED_INBOUND, null, null, null, + null, "Negotiate", Sspi.SECPKG_CRED_INBOUND, null, null, null, null, phServerCredential, ptsServerExpiry)); // server ----------- security context CtxtHandle phServerContext = new CtxtHandle(); @@ -286,40 +286,40 @@ public void testQuerySecurityContextToken() { if (clientRc == W32Errors.SEC_I_CONTINUE_NEEDED) { // server token is empty the first time clientRc = Secur32.INSTANCE.InitializeSecurityContext( - phClientCredential, - phClientContext.isNull() ? null : phClientContext, - Advapi32Util.getUserName(), - Sspi.ISC_REQ_CONNECTION, - 0, - Sspi.SECURITY_NATIVE_DREP, - pbServerToken, - 0, - phClientContext, - pbClientToken, - pfClientContextAttr, - null); - assertTrue(clientRc == W32Errors.SEC_I_CONTINUE_NEEDED || clientRc == W32Errors.SEC_E_OK); - } + phClientCredential, + phClientContext.isNull() ? null : phClientContext, + Advapi32Util.getUserName(), + Sspi.ISC_REQ_CONNECTION, + 0, + Sspi.SECURITY_NATIVE_DREP, + pbServerToken, + 0, + phClientContext, + pbClientToken, + pfClientContextAttr, + null); + assertTrue(clientRc == W32Errors.SEC_I_CONTINUE_NEEDED || clientRc == W32Errors.SEC_E_OK); + } // server ----------- accept security context, produce a server token if (serverRc == W32Errors.SEC_I_CONTINUE_NEEDED) { - serverRc = Secur32.INSTANCE.AcceptSecurityContext(phServerCredential, - phServerContext.isNull() ? null : phServerContext, - pbClientToken, - Sspi.ISC_REQ_CONNECTION, - Sspi.SECURITY_NATIVE_DREP, + serverRc = Secur32.INSTANCE.AcceptSecurityContext(phServerCredential, + phServerContext.isNull() ? null : phServerContext, + pbClientToken, + Sspi.ISC_REQ_CONNECTION, + Sspi.SECURITY_NATIVE_DREP, phServerContext, - pbServerToken, - pfServerContextAttr, + pbServerToken, + pfServerContextAttr, ptsServerExpiry); assertTrue(serverRc == W32Errors.SEC_I_CONTINUE_NEEDED || serverRc == W32Errors.SEC_E_OK); - } - } while(serverRc != W32Errors.SEC_E_OK || clientRc != W32Errors.SEC_E_OK); + } + } while(serverRc != W32Errors.SEC_E_OK || clientRc != W32Errors.SEC_E_OK); // query security context token HANDLEByReference phContextToken = new HANDLEByReference(); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.QuerySecurityContextToken( phServerContext, phContextToken)); // release security context token - assertTrue(Kernel32.INSTANCE.CloseHandle(phContextToken.getValue())); + Kernel32Util.closeHandleRef(phContextToken); // release server context assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.DeleteSecurityContext( phServerContext)); @@ -329,9 +329,9 @@ public void testQuerySecurityContextToken() { assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.DeleteSecurityContext( phClientContext)); assertEquals(W32Errors.SEC_E_OK, Secur32.INSTANCE.FreeCredentialsHandle( - phClientCredential)); + phClientCredential)); } - + public void testCreateEmptyToken() { SecBufferDesc token = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE); assertEquals(1, token.pBuffers.length);