Search in sources :

Example 16 with CHAR

use of com.sun.jna.platform.win32.WinDef.CHAR in project intellij-community by JetBrains.

the class Restarter method restartOnWindows.

private static void restartOnWindows(String... beforeRestart) throws IOException {
    Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
    Shell32 shell32 = (Shell32) Native.loadLibrary("shell32", Shell32.class);
    int pid = kernel32.GetCurrentProcessId();
    IntByReference argc = new IntByReference();
    Pointer argvPtr = shell32.CommandLineToArgvW(kernel32.GetCommandLineW(), argc);
    String[] argv = getRestartArgv(argvPtr.getWideStringArray(0, argc.getValue()));
    kernel32.LocalFree(argvPtr);
    // See https://blogs.msdn.microsoft.com/oldnewthing/20060515-07/?p=31203
    // argv[0] as the program name is only a convention, i.e. there is no guarantee
    // the name is the full path to the executable.
    //
    // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197(v=vs.85).aspx
    // To retrieve the full path to the executable, use "GetModuleFileName(NULL, ...)".
    //
    // Note: We use 32,767 as buffer size to avoid limiting ourselves to MAX_PATH (260).
    char[] buffer = new char[32767];
    if (kernel32.GetModuleFileNameW(null, buffer, new WinDef.DWORD(buffer.length)).intValue() > 0) {
        argv[0] = Native.toString(buffer);
    }
    List<String> args = new ArrayList<>();
    args.add(String.valueOf(pid));
    args.add(String.valueOf(beforeRestart.length));
    Collections.addAll(args, beforeRestart);
    args.add(String.valueOf(argv.length));
    Collections.addAll(args, argv);
    runRestarter(new File(PathManager.getBinPath(), "restarter.exe"), args);
    // Since the process ID is passed through the command line, we want to make sure that we don't exit before the "restarter"
    // process has a chance to open the handle to our process, and that it doesn't wait for the termination of an unrelated
    // process which happened to have the same process ID.
    TimeoutUtil.sleep(500);
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) ArrayList(java.util.ArrayList) Pointer(com.sun.jna.Pointer) WString(com.sun.jna.WString) WinDef(com.sun.jna.platform.win32.WinDef) File(java.io.File)

Example 17 with CHAR

use of com.sun.jna.platform.win32.WinDef.CHAR in project gitblit by gitblit.

the class WindowsAuthProvider method authenticate.

@Override
public UserModel authenticate(String username, char[] password) {
    String defaultDomain = settings.getString(Keys.realm.windows.defaultDomain, null);
    if (StringUtils.isEmpty(defaultDomain)) {
        // ensure that default domain is null
        defaultDomain = null;
    }
    if (defaultDomain != null) {
        // sanitize username
        if (username.startsWith(defaultDomain + "\\")) {
            // strip default domain from domain\ username
            username = username.substring(defaultDomain.length() + 1);
        } else if (username.endsWith("@" + defaultDomain)) {
            // strip default domain from username@domain
            username = username.substring(0, username.lastIndexOf('@'));
        }
    }
    IWindowsIdentity identity = null;
    try {
        if (username.indexOf('@') > -1 || username.indexOf('\\') > -1) {
            // manually specified domain
            identity = waffle.logonUser(username, new String(password));
        } else {
            // no domain specified, use default domain
            identity = waffle.logonDomainUser(username, defaultDomain, new String(password));
        }
    } catch (Win32Exception e) {
        logger.error(e.getMessage());
        return null;
    }
    if (identity.isGuest() && !settings.getBoolean(Keys.realm.windows.allowGuests, false)) {
        logger.warn("Guest account access is disabled");
        identity.dispose();
        return null;
    }
    UserModel user = userManager.getUserModel(username);
    if (user == null) {
        // create user object for new authenticated user
        user = new UserModel(username.toLowerCase());
    }
    // create a user cookie
    setCookie(user);
    // update user attributes from Windows identity
    user.accountType = getAccountType();
    String fqn = identity.getFqn();
    if (fqn.indexOf('\\') > -1) {
        user.displayName = fqn.substring(fqn.lastIndexOf('\\') + 1);
    } else {
        user.displayName = fqn;
    }
    user.password = Constants.EXTERNAL_ACCOUNT;
    Set<String> groupNames = new TreeSet<String>();
    for (IWindowsAccount group : identity.getGroups()) {
        groupNames.add(group.getFqn());
    }
    if (settings.getBoolean(Keys.realm.windows.permitBuiltInAdministrators, true)) {
        if (groupNames.contains("BUILTIN\\Administrators")) {
            // local administrator
            user.canAdmin = true;
        }
    }
    // TODO consider mapping Windows groups to teams
    // push the changes to the backing user service
    updateUser(user);
    // cleanup resources
    identity.dispose();
    return user;
}
Also used : UserModel(com.gitblit.models.UserModel) TreeSet(java.util.TreeSet) IWindowsAccount(waffle.windows.auth.IWindowsAccount) IWindowsIdentity(waffle.windows.auth.IWindowsIdentity) Win32Exception(com.sun.jna.platform.win32.Win32Exception)

Example 18 with CHAR

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

the class Advapi32Util method getAccountByName.

/**
	 * Retrieves a security identifier (SID) for a given account.
	 *
	 * @param systemName
	 *            Name of the system.
	 * @param accountName
	 *            Account name.
	 * @return A structure containing the account SID.
	 */
public static Account getAccountByName(String systemName, String accountName) {
    IntByReference pSid = new IntByReference(0);
    IntByReference cchDomainName = new IntByReference(0);
    PointerByReference peUse = new PointerByReference();
    if (Advapi32.INSTANCE.LookupAccountName(systemName, accountName, null, pSid, null, cchDomainName, peUse)) {
        throw new RuntimeException("LookupAccountNameW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
    }
    int rc = Kernel32.INSTANCE.GetLastError();
    if (pSid.getValue() == 0 || rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
        throw new Win32Exception(rc);
    }
    Memory sidMemory = new Memory(pSid.getValue());
    PSID result = new PSID(sidMemory);
    char[] referencedDomainName = new char[cchDomainName.getValue() + 1];
    if (!Advapi32.INSTANCE.LookupAccountName(systemName, accountName, result, pSid, referencedDomainName, cchDomainName, peUse)) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    Account account = new Account();
    account.accountType = peUse.getPointer().getInt(0);
    account.name = accountName;
    String[] accountNamePartsBs = accountName.split("\\\\", 2);
    String[] accountNamePartsAt = accountName.split("@", 2);
    if (accountNamePartsBs.length == 2) {
        account.name = accountNamePartsBs[1];
    } else if (accountNamePartsAt.length == 2) {
        account.name = accountNamePartsAt[0];
    } else {
        account.name = accountName;
    }
    if (cchDomainName.getValue() > 0) {
        account.domain = Native.toString(referencedDomainName);
        account.fqn = account.domain + "\\" + account.name;
    } else {
        account.fqn = account.name;
    }
    account.sid = result.getBytes();
    account.sidString = convertSidToStringSid(new PSID(account.sid));
    return account;
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) Memory(com.sun.jna.Memory) PointerByReference(com.sun.jna.ptr.PointerByReference) PSID(com.sun.jna.platform.win32.WinNT.PSID)

Example 19 with CHAR

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

the class Advapi32Util method registryValueExists.

/**
	 * Checks whether a registry value exists.
	 *
	 * @param root
	 *            HKEY_LOCAL_MACHINE, etc.
	 * @param key
	 *            Registry key path.
	 * @param value
	 *            Value name.
	 * @return True if the value exists.
	 */
public static boolean registryValueExists(HKEY root, String key, String value) {
    HKEYByReference phkKey = new HKEYByReference();
    int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ, phkKey);
    try {
        switch(rc) {
            case W32Errors.ERROR_SUCCESS:
                break;
            case W32Errors.ERROR_FILE_NOT_FOUND:
                return false;
            default:
                throw new Win32Exception(rc);
        }
        IntByReference lpcbData = new IntByReference();
        IntByReference lpType = new IntByReference();
        rc = Advapi32.INSTANCE.RegQueryValueEx(phkKey.getValue(), value, 0, lpType, (char[]) null, lpcbData);
        switch(rc) {
            case W32Errors.ERROR_SUCCESS:
            case W32Errors.ERROR_MORE_DATA:
            case W32Errors.ERROR_INSUFFICIENT_BUFFER:
                return true;
            case W32Errors.ERROR_FILE_NOT_FOUND:
                return false;
            default:
                throw new Win32Exception(rc);
        }
    } finally {
        if (phkKey.getValue() != WinBase.INVALID_HANDLE_VALUE) {
            rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
            if (rc != W32Errors.ERROR_SUCCESS) {
                throw new Win32Exception(rc);
            }
        }
    }
}
Also used : HKEYByReference(com.sun.jna.platform.win32.WinReg.HKEYByReference) IntByReference(com.sun.jna.ptr.IntByReference)

Example 20 with CHAR

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

the class Convert method toJavaObject.

public static Object toJavaObject(VARIANT value, Class<?> targetClass, ObjectFactory factory, boolean addReference, boolean freeValue) {
    if (null == value || value.getVarType().intValue() == VT_EMPTY || value.getVarType().intValue() == VT_NULL) {
        return null;
    }
    if (targetClass != null && (!targetClass.isAssignableFrom(Object.class))) {
        if (targetClass.isAssignableFrom(value.getClass())) {
            return value;
        }
        Object vobj = value.getValue();
        if (vobj != null && (targetClass.isAssignableFrom(vobj.getClass()))) {
            return vobj;
        }
    }
    VARIANT inputValue = value;
    if (value.getVarType().intValue() == (VT_BYREF | VT_VARIANT)) {
        value = (VARIANT) value.getValue();
    }
    // handling
    if (targetClass == null || (targetClass.isAssignableFrom(Object.class))) {
        targetClass = null;
        int varType = value.getVarType().intValue();
        switch(value.getVarType().intValue()) {
            case VT_UI1:
            case VT_I1:
            case VT_BYREF | VT_UI1:
            case VT_BYREF | VT_I1:
                targetClass = Byte.class;
                break;
            case VT_I2:
            case VT_BYREF | VT_I2:
                targetClass = Short.class;
                break;
            case VT_UI2:
            case VT_BYREF | VT_UI2:
                targetClass = Character.class;
                break;
            case VT_INT:
            case VT_UINT:
            case VT_UI4:
            case VT_I4:
            case VT_BYREF | VT_I4:
            case VT_BYREF | VT_UI4:
            case VT_BYREF | VT_INT:
            case VT_BYREF | VT_UINT:
                targetClass = Integer.class;
                break;
            case VT_UI8:
            case VT_I8:
            case VT_BYREF | VT_I8:
            case VT_BYREF | VT_UI8:
                targetClass = Long.class;
                break;
            case VT_R4:
            case VT_BYREF | VT_R4:
                targetClass = Float.class;
                break;
            case VT_R8:
            case VT_BYREF | VT_R8:
                targetClass = Double.class;
                break;
            case VT_BOOL:
            case VT_BYREF | VT_BOOL:
                targetClass = Boolean.class;
                break;
            case VT_ERROR:
            case VT_BYREF | VT_ERROR:
                targetClass = WinDef.SCODE.class;
                break;
            case VT_CY:
            case VT_BYREF | VT_CY:
                targetClass = OaIdl.CURRENCY.class;
                break;
            case VT_DATE:
            case VT_BYREF | VT_DATE:
                targetClass = Date.class;
                break;
            case VT_BSTR:
            case VT_BYREF | VT_BSTR:
                targetClass = String.class;
                break;
            case VT_UNKNOWN:
            case VT_BYREF | VT_UNKNOWN:
                targetClass = com.sun.jna.platform.win32.COM.IUnknown.class;
                break;
            case VT_DISPATCH:
            case VT_BYREF | VT_DISPATCH:
                targetClass = IDispatch.class;
                break;
            case VT_BYREF | VT_VARIANT:
                targetClass = Variant.class;
                break;
            case VT_BYREF:
                targetClass = PVOID.class;
                break;
            case VT_BYREF | VT_DECIMAL:
                targetClass = OaIdl.DECIMAL.class;
                break;
            case VT_RECORD:
            default:
                if ((varType & VT_ARRAY) > 0) {
                    targetClass = OaIdl.SAFEARRAY.class;
                }
        }
    }
    Object result;
    if (Byte.class.equals(targetClass) || byte.class.equals(targetClass)) {
        result = value.byteValue();
    } else if (Short.class.equals(targetClass) || short.class.equals(targetClass)) {
        result = value.shortValue();
    } else if (Character.class.equals(targetClass) || char.class.equals(targetClass)) {
        result = (char) value.intValue();
    } else if (Integer.class.equals(targetClass) || int.class.equals(targetClass)) {
        result = value.intValue();
    } else if (Long.class.equals(targetClass) || long.class.equals(targetClass) || IComEnum.class.isAssignableFrom(targetClass)) {
        result = value.longValue();
    } else if (Float.class.equals(targetClass) || float.class.equals(targetClass)) {
        result = value.floatValue();
    } else if (Double.class.equals(targetClass) || double.class.equals(targetClass)) {
        result = value.doubleValue();
    } else if (Boolean.class.equals(targetClass) || boolean.class.equals(targetClass)) {
        result = value.booleanValue();
    } else if (Date.class.equals(targetClass)) {
        result = value.dateValue();
    } else if (String.class.equals(targetClass)) {
        result = value.stringValue();
    } else if (value.getValue() instanceof com.sun.jna.platform.win32.COM.IDispatch) {
        com.sun.jna.platform.win32.COM.IDispatch d = (com.sun.jna.platform.win32.COM.IDispatch) value.getValue();
        Object proxy = factory.createProxy(targetClass, d);
        // call
        if (!addReference) {
            int n = d.Release();
        }
        result = proxy;
    } else {
        /*
                    WinDef.SCODE.class.equals(targetClass) 
                        || OaIdl.CURRENCY.class.equals(targetClass)
                        || OaIdl.DECIMAL.class.equals(targetClass)
                        || OaIdl.SAFEARRAY.class.equals(targetClass)
                        || com.sun.jna.platform.win32.COM.IUnknown.class.equals(targetClass)
                        || Variant.class.equals(targetClass)
                        || PVOID.class.equals(targetClass
                    */
        result = value.getValue();
    }
    if (IComEnum.class.isAssignableFrom(targetClass)) {
        result = targetClass.cast(Convert.toComEnum((Class<? extends IComEnum>) targetClass, result));
    }
    if (freeValue) {
        free(inputValue, result);
    }
    return result;
}
Also used : VARIANT(com.sun.jna.platform.win32.Variant.VARIANT) VT_VARIANT(com.sun.jna.platform.win32.Variant.VT_VARIANT) WinDef(com.sun.jna.platform.win32.WinDef) OaIdl(com.sun.jna.platform.win32.OaIdl)

Aggregations

IntByReference (com.sun.jna.ptr.IntByReference)15 HKEYByReference (com.sun.jna.platform.win32.WinReg.HKEYByReference)7 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)5 VARIANT (com.sun.jna.platform.win32.Variant.VARIANT)4 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)4 File (java.io.File)4 Test (org.junit.Test)4 Memory (com.sun.jna.Memory)3 BSTR (com.sun.jna.platform.win32.WTypes.BSTR)3 BYTE (com.sun.jna.platform.win32.WinDef.BYTE)3 CHAR (com.sun.jna.platform.win32.WinDef.CHAR)3 LONG (com.sun.jna.platform.win32.WinDef.LONG)3 SHORT (com.sun.jna.platform.win32.WinDef.SHORT)3 PSID (com.sun.jna.platform.win32.WinNT.PSID)3 PointerByReference (com.sun.jna.ptr.PointerByReference)3 BufferedWriter (java.io.BufferedWriter)3 FileWriter (java.io.FileWriter)3 PrintWriter (java.io.PrintWriter)3 Pointer (com.sun.jna.Pointer)2 Advapi32 (com.sun.jna.platform.win32.Advapi32)2